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/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/IntrinsicsRISCV.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "riscv-lower"
44 
45 STATISTIC(NumTailCalls, "Number of tail calls");
46 
47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
48                                          const RISCVSubtarget &STI)
49     : TargetLowering(TM), Subtarget(STI) {
50 
51   if (Subtarget.isRV32E())
52     report_fatal_error("Codegen not yet implemented for RV32E");
53 
54   RISCVABI::ABI ABI = Subtarget.getTargetABI();
55   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
56 
57   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
58       !Subtarget.hasStdExtF()) {
59     errs() << "Hard-float 'f' ABI can't be used for a target that "
60                 "doesn't support the F instruction set extension (ignoring "
61                           "target-abi)\n";
62     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
63   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
64              !Subtarget.hasStdExtD()) {
65     errs() << "Hard-float 'd' ABI can't be used for a target that "
66               "doesn't support the D instruction set extension (ignoring "
67               "target-abi)\n";
68     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
69   }
70 
71   switch (ABI) {
72   default:
73     report_fatal_error("Don't know how to lower this ABI");
74   case RISCVABI::ABI_ILP32:
75   case RISCVABI::ABI_ILP32F:
76   case RISCVABI::ABI_ILP32D:
77   case RISCVABI::ABI_LP64:
78   case RISCVABI::ABI_LP64F:
79   case RISCVABI::ABI_LP64D:
80     break;
81   }
82 
83   MVT XLenVT = Subtarget.getXLenVT();
84 
85   // Set up the register classes.
86   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
87 
88   if (Subtarget.hasStdExtZfh())
89     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
90   if (Subtarget.hasStdExtF())
91     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
92   if (Subtarget.hasStdExtD())
93     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
94 
95   static const MVT::SimpleValueType BoolVecVTs[] = {
96       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
97       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
98   static const MVT::SimpleValueType IntVecVTs[] = {
99       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
100       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
101       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
102       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
103       MVT::nxv4i64, MVT::nxv8i64};
104   static const MVT::SimpleValueType F16VecVTs[] = {
105       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
106       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
107   static const MVT::SimpleValueType F32VecVTs[] = {
108       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
109   static const MVT::SimpleValueType F64VecVTs[] = {
110       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
111 
112   if (Subtarget.hasVInstructions()) {
113     auto addRegClassForRVV = [this](MVT VT) {
114       unsigned Size = VT.getSizeInBits().getKnownMinValue();
115       assert(Size <= 512 && isPowerOf2_32(Size));
116       const TargetRegisterClass *RC;
117       if (Size <= 64)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 128)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 256)
122         RC = &RISCV::VRM4RegClass;
123       else
124         RC = &RISCV::VRM8RegClass;
125 
126       addRegisterClass(VT, RC);
127     };
128 
129     for (MVT VT : BoolVecVTs)
130       addRegClassForRVV(VT);
131     for (MVT VT : IntVecVTs) {
132       if (VT.getVectorElementType() == MVT::i64 &&
133           !Subtarget.hasVInstructionsI64())
134         continue;
135       addRegClassForRVV(VT);
136     }
137 
138     if (Subtarget.hasVInstructionsF16())
139       for (MVT VT : F16VecVTs)
140         addRegClassForRVV(VT);
141 
142     if (Subtarget.hasVInstructionsF32())
143       for (MVT VT : F32VecVTs)
144         addRegClassForRVV(VT);
145 
146     if (Subtarget.hasVInstructionsF64())
147       for (MVT VT : F64VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.useRVVForFixedLengthVectors()) {
151       auto addRegClassForFixedVectors = [this](MVT VT) {
152         MVT ContainerVT = getContainerForFixedLengthVector(VT);
153         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
154         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
155         addRegisterClass(VT, TRI.getRegClass(RCID));
156       };
157       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
158         if (useRVVForFixedLengthVectorVT(VT))
159           addRegClassForFixedVectors(VT);
160 
161       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
162         if (useRVVForFixedLengthVectorVT(VT))
163           addRegClassForFixedVectors(VT);
164     }
165   }
166 
167   // Compute derived properties from the register classes.
168   computeRegisterProperties(STI.getRegisterInfo());
169 
170   setStackPointerRegisterToSaveRestore(RISCV::X2);
171 
172   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
173     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
174 
175   // TODO: add all necessary setOperationAction calls.
176   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
177 
178   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
179   setOperationAction(ISD::BR_CC, XLenVT, Expand);
180   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
181   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
182 
183   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
184   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
185 
186   setOperationAction(ISD::VASTART, MVT::Other, Custom);
187   setOperationAction(ISD::VAARG, MVT::Other, Expand);
188   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
189   setOperationAction(ISD::VAEND, MVT::Other, Expand);
190 
191   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
192   if (!Subtarget.hasStdExtZbb()) {
193     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
195   }
196 
197   if (Subtarget.is64Bit()) {
198     setOperationAction(ISD::ADD, MVT::i32, Custom);
199     setOperationAction(ISD::SUB, MVT::i32, Custom);
200     setOperationAction(ISD::SHL, MVT::i32, Custom);
201     setOperationAction(ISD::SRA, MVT::i32, Custom);
202     setOperationAction(ISD::SRL, MVT::i32, Custom);
203 
204     setOperationAction(ISD::UADDO, MVT::i32, Custom);
205     setOperationAction(ISD::USUBO, MVT::i32, Custom);
206     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
207     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
208   } else {
209     setLibcallName(RTLIB::SHL_I128, nullptr);
210     setLibcallName(RTLIB::SRL_I128, nullptr);
211     setLibcallName(RTLIB::SRA_I128, nullptr);
212     setLibcallName(RTLIB::MUL_I128, nullptr);
213     setLibcallName(RTLIB::MULO_I64, nullptr);
214   }
215 
216   if (!Subtarget.hasStdExtM()) {
217     setOperationAction(ISD::MUL, XLenVT, Expand);
218     setOperationAction(ISD::MULHS, XLenVT, Expand);
219     setOperationAction(ISD::MULHU, XLenVT, Expand);
220     setOperationAction(ISD::SDIV, XLenVT, Expand);
221     setOperationAction(ISD::UDIV, XLenVT, Expand);
222     setOperationAction(ISD::SREM, XLenVT, Expand);
223     setOperationAction(ISD::UREM, XLenVT, Expand);
224   } else {
225     if (Subtarget.is64Bit()) {
226       setOperationAction(ISD::MUL, MVT::i32, Custom);
227       setOperationAction(ISD::MUL, MVT::i128, Custom);
228 
229       setOperationAction(ISD::SDIV, MVT::i8, Custom);
230       setOperationAction(ISD::UDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UREM, MVT::i8, Custom);
232       setOperationAction(ISD::SDIV, MVT::i16, Custom);
233       setOperationAction(ISD::UDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UREM, MVT::i16, Custom);
235       setOperationAction(ISD::SDIV, MVT::i32, Custom);
236       setOperationAction(ISD::UDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UREM, MVT::i32, Custom);
238     } else {
239       setOperationAction(ISD::MUL, MVT::i64, Custom);
240     }
241   }
242 
243   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
244   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
246   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
247 
248   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
249   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
251 
252   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
253     if (Subtarget.is64Bit()) {
254       setOperationAction(ISD::ROTL, MVT::i32, Custom);
255       setOperationAction(ISD::ROTR, MVT::i32, Custom);
256     }
257   } else {
258     setOperationAction(ISD::ROTL, XLenVT, Expand);
259     setOperationAction(ISD::ROTR, XLenVT, Expand);
260   }
261 
262   if (Subtarget.hasStdExtZbp()) {
263     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
264     // more combining.
265     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
266     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
267     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
268     // BSWAP i8 doesn't exist.
269     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
270     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
271 
272     if (Subtarget.is64Bit()) {
273       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
274       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
275     }
276   } else {
277     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
278     // pattern match it directly in isel.
279     setOperationAction(ISD::BSWAP, XLenVT,
280                        Subtarget.hasStdExtZbb() ? Legal : Expand);
281   }
282 
283   if (Subtarget.hasStdExtZbb()) {
284     setOperationAction(ISD::SMIN, XLenVT, Legal);
285     setOperationAction(ISD::SMAX, XLenVT, Legal);
286     setOperationAction(ISD::UMIN, XLenVT, Legal);
287     setOperationAction(ISD::UMAX, XLenVT, Legal);
288 
289     if (Subtarget.is64Bit()) {
290       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
291       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
292       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
293       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
294     }
295   } else {
296     setOperationAction(ISD::CTTZ, XLenVT, Expand);
297     setOperationAction(ISD::CTLZ, XLenVT, Expand);
298     setOperationAction(ISD::CTPOP, XLenVT, Expand);
299   }
300 
301   if (Subtarget.hasStdExtZbt()) {
302     setOperationAction(ISD::FSHL, XLenVT, Custom);
303     setOperationAction(ISD::FSHR, XLenVT, Custom);
304     setOperationAction(ISD::SELECT, XLenVT, Legal);
305 
306     if (Subtarget.is64Bit()) {
307       setOperationAction(ISD::FSHL, MVT::i32, Custom);
308       setOperationAction(ISD::FSHR, MVT::i32, Custom);
309     }
310   } else {
311     setOperationAction(ISD::SELECT, XLenVT, Custom);
312   }
313 
314   static const ISD::CondCode FPCCToExpand[] = {
315       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
316       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
317       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
318 
319   static const ISD::NodeType FPOpToExpand[] = {
320       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
321       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
322 
323   if (Subtarget.hasStdExtZfh())
324     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
325 
326   if (Subtarget.hasStdExtZfh()) {
327     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
328     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
329     setOperationAction(ISD::LRINT, MVT::f16, Legal);
330     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
331     setOperationAction(ISD::LROUND, MVT::f16, Legal);
332     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
333     setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal);
334     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
335     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
336     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
337     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
338     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
339     for (auto CC : FPCCToExpand)
340       setCondCodeAction(CC, MVT::f16, Expand);
341     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
342     setOperationAction(ISD::SELECT, MVT::f16, Custom);
343     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
344 
345     setOperationAction(ISD::FREM,       MVT::f16, Promote);
346     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
347     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
348     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
349     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
350     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
351     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
352     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
353     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
354     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
355     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
356     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
357     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
358     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
359     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
360     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
361     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
362     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
363 
364     // We need to custom promote this.
365     if (Subtarget.is64Bit())
366       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
367   }
368 
369   if (Subtarget.hasStdExtF()) {
370     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
371     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
372     setOperationAction(ISD::LRINT, MVT::f32, Legal);
373     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
374     setOperationAction(ISD::LROUND, MVT::f32, Legal);
375     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
376     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
377     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
378     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
379     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
380     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
381     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
382     for (auto CC : FPCCToExpand)
383       setCondCodeAction(CC, MVT::f32, Expand);
384     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
385     setOperationAction(ISD::SELECT, MVT::f32, Custom);
386     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
387     for (auto Op : FPOpToExpand)
388       setOperationAction(Op, MVT::f32, Expand);
389     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
390     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
391   }
392 
393   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
394     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
395 
396   if (Subtarget.hasStdExtD()) {
397     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
398     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
399     setOperationAction(ISD::LRINT, MVT::f64, Legal);
400     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
401     setOperationAction(ISD::LROUND, MVT::f64, Legal);
402     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
403     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
404     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
405     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
406     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
407     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
408     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
409     for (auto CC : FPCCToExpand)
410       setCondCodeAction(CC, MVT::f64, Expand);
411     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
412     setOperationAction(ISD::SELECT, MVT::f64, Custom);
413     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
414     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
415     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
416     for (auto Op : FPOpToExpand)
417       setOperationAction(Op, MVT::f64, Expand);
418     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
419     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
420   }
421 
422   if (Subtarget.is64Bit()) {
423     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
424     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
425     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
426     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
427   }
428 
429   if (Subtarget.hasStdExtF()) {
430     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
431     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
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_SELECT};
494 
495     static const unsigned FloatingPointVPOps[] = {
496         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
497         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
498         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT};
499 
500     if (!Subtarget.is64Bit()) {
501       // We must custom-lower certain vXi64 operations on RV32 due to the vector
502       // element type being illegal.
503       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
504       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
505 
506       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
507       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
508       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
509       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
510       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
511       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
512       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
513       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
514 
515       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
516       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
517       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
518       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
519       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
520       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
521       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
522       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
523     }
524 
525     for (MVT VT : BoolVecVTs) {
526       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
527 
528       // Mask VTs are custom-expanded into a series of standard nodes
529       setOperationAction(ISD::TRUNCATE, VT, Custom);
530       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
531       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
532       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
533 
534       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
535       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
536 
537       setOperationAction(ISD::SELECT, VT, Custom);
538       setOperationAction(ISD::SELECT_CC, VT, Expand);
539       setOperationAction(ISD::VSELECT, VT, Expand);
540 
541       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
542       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
543       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
544 
545       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
546       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
547       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
548 
549       // RVV has native int->float & float->int conversions where the
550       // element type sizes are within one power-of-two of each other. Any
551       // wider distances between type sizes have to be lowered as sequences
552       // which progressively narrow the gap in stages.
553       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
554       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
555       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
556       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
557 
558       // Expand all extending loads to types larger than this, and truncating
559       // stores from types larger than this.
560       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
561         setTruncStoreAction(OtherVT, VT, Expand);
562         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
563         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
564         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
565       }
566     }
567 
568     for (MVT VT : IntVecVTs) {
569       if (VT.getVectorElementType() == MVT::i64 &&
570           !Subtarget.hasVInstructionsI64())
571         continue;
572 
573       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
574       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
575 
576       // Vectors implement MULHS/MULHU.
577       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
578       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
579 
580       setOperationAction(ISD::SMIN, VT, Legal);
581       setOperationAction(ISD::SMAX, VT, Legal);
582       setOperationAction(ISD::UMIN, VT, Legal);
583       setOperationAction(ISD::UMAX, VT, Legal);
584 
585       setOperationAction(ISD::ROTL, VT, Expand);
586       setOperationAction(ISD::ROTR, VT, Expand);
587 
588       setOperationAction(ISD::CTTZ, VT, Expand);
589       setOperationAction(ISD::CTLZ, VT, Expand);
590       setOperationAction(ISD::CTPOP, VT, Expand);
591 
592       setOperationAction(ISD::BSWAP, VT, Expand);
593 
594       // Custom-lower extensions and truncations from/to mask types.
595       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
596       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
597       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
598 
599       // RVV has native int->float & float->int conversions where the
600       // element type sizes are within one power-of-two of each other. Any
601       // wider distances between type sizes have to be lowered as sequences
602       // which progressively narrow the gap in stages.
603       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
604       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
605       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
606       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
607 
608       setOperationAction(ISD::SADDSAT, VT, Legal);
609       setOperationAction(ISD::UADDSAT, VT, Legal);
610       setOperationAction(ISD::SSUBSAT, VT, Legal);
611       setOperationAction(ISD::USUBSAT, VT, Legal);
612 
613       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
614       // nodes which truncate by one power of two at a time.
615       setOperationAction(ISD::TRUNCATE, VT, Custom);
616 
617       // Custom-lower insert/extract operations to simplify patterns.
618       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
619       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
620 
621       // Custom-lower reduction operations to set up the corresponding custom
622       // nodes' operands.
623       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
624       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
625       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
626       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
627       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
628       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
629       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
630       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
631 
632       for (unsigned VPOpc : IntegerVPOps)
633         setOperationAction(VPOpc, VT, Custom);
634 
635       setOperationAction(ISD::LOAD, VT, Custom);
636       setOperationAction(ISD::STORE, VT, Custom);
637 
638       setOperationAction(ISD::MLOAD, VT, Custom);
639       setOperationAction(ISD::MSTORE, VT, Custom);
640       setOperationAction(ISD::MGATHER, VT, Custom);
641       setOperationAction(ISD::MSCATTER, VT, Custom);
642 
643       setOperationAction(ISD::VP_LOAD, VT, Custom);
644       setOperationAction(ISD::VP_STORE, VT, Custom);
645       setOperationAction(ISD::VP_GATHER, VT, Custom);
646       setOperationAction(ISD::VP_SCATTER, VT, Custom);
647 
648       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
649       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
650       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
651 
652       setOperationAction(ISD::SELECT, VT, Custom);
653       setOperationAction(ISD::SELECT_CC, VT, Expand);
654 
655       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
656       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
657 
658       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
659         setTruncStoreAction(VT, OtherVT, Expand);
660         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
661         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
662         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
663       }
664 
665       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
666       // type that can represent the value exactly.
667       if (VT.getVectorElementType() != MVT::i64) {
668         MVT FloatEltVT =
669             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
670         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
671         if (isTypeLegal(FloatVT)) {
672           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
673           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
674         }
675       }
676     }
677 
678     // Expand various CCs to best match the RVV ISA, which natively supports UNE
679     // but no other unordered comparisons, and supports all ordered comparisons
680     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
681     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
682     // and we pattern-match those back to the "original", swapping operands once
683     // more. This way we catch both operations and both "vf" and "fv" forms with
684     // fewer patterns.
685     static const ISD::CondCode VFPCCToExpand[] = {
686         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
687         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
688         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
689     };
690 
691     // Sets common operation actions on RVV floating-point vector types.
692     const auto SetCommonVFPActions = [&](MVT VT) {
693       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
694       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
695       // sizes are within one power-of-two of each other. Therefore conversions
696       // between vXf16 and vXf64 must be lowered as sequences which convert via
697       // vXf32.
698       setOperationAction(ISD::FP_ROUND, VT, Custom);
699       setOperationAction(ISD::FP_EXTEND, VT, Custom);
700       // Custom-lower insert/extract operations to simplify patterns.
701       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
702       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
703       // Expand various condition codes (explained above).
704       for (auto CC : VFPCCToExpand)
705         setCondCodeAction(CC, VT, Expand);
706 
707       setOperationAction(ISD::FMINNUM, VT, Legal);
708       setOperationAction(ISD::FMAXNUM, VT, Legal);
709 
710       setOperationAction(ISD::FTRUNC, VT, Custom);
711       setOperationAction(ISD::FCEIL, VT, Custom);
712       setOperationAction(ISD::FFLOOR, VT, Custom);
713 
714       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
715       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
716       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
717       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
718 
719       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
720 
721       setOperationAction(ISD::LOAD, VT, Custom);
722       setOperationAction(ISD::STORE, VT, Custom);
723 
724       setOperationAction(ISD::MLOAD, VT, Custom);
725       setOperationAction(ISD::MSTORE, VT, Custom);
726       setOperationAction(ISD::MGATHER, VT, Custom);
727       setOperationAction(ISD::MSCATTER, VT, Custom);
728 
729       setOperationAction(ISD::VP_LOAD, VT, Custom);
730       setOperationAction(ISD::VP_STORE, VT, Custom);
731       setOperationAction(ISD::VP_GATHER, VT, Custom);
732       setOperationAction(ISD::VP_SCATTER, VT, Custom);
733 
734       setOperationAction(ISD::SELECT, VT, Custom);
735       setOperationAction(ISD::SELECT_CC, VT, Expand);
736 
737       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
738       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
739       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
740 
741       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
742 
743       for (unsigned VPOpc : FloatingPointVPOps)
744         setOperationAction(VPOpc, VT, Custom);
745     };
746 
747     // Sets common extload/truncstore actions on RVV floating-point vector
748     // types.
749     const auto SetCommonVFPExtLoadTruncStoreActions =
750         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
751           for (auto SmallVT : SmallerVTs) {
752             setTruncStoreAction(VT, SmallVT, Expand);
753             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
754           }
755         };
756 
757     if (Subtarget.hasVInstructionsF16())
758       for (MVT VT : F16VecVTs)
759         SetCommonVFPActions(VT);
760 
761     for (MVT VT : F32VecVTs) {
762       if (Subtarget.hasVInstructionsF32())
763         SetCommonVFPActions(VT);
764       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
765     }
766 
767     for (MVT VT : F64VecVTs) {
768       if (Subtarget.hasVInstructionsF64())
769         SetCommonVFPActions(VT);
770       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
771       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
772     }
773 
774     if (Subtarget.useRVVForFixedLengthVectors()) {
775       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
776         if (!useRVVForFixedLengthVectorVT(VT))
777           continue;
778 
779         // By default everything must be expanded.
780         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
781           setOperationAction(Op, VT, Expand);
782         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
783           setTruncStoreAction(VT, OtherVT, Expand);
784           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
785           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
786           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
787         }
788 
789         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
790         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
791         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
792 
793         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
794         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
795 
796         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
797         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
798 
799         setOperationAction(ISD::LOAD, VT, Custom);
800         setOperationAction(ISD::STORE, VT, Custom);
801 
802         setOperationAction(ISD::SETCC, VT, Custom);
803 
804         setOperationAction(ISD::SELECT, VT, Custom);
805 
806         setOperationAction(ISD::TRUNCATE, VT, Custom);
807 
808         setOperationAction(ISD::BITCAST, VT, Custom);
809 
810         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
811         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
812         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
813 
814         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
815         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
816         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
817 
818         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
819         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
820         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
821         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
822 
823         // Operations below are different for between masks and other vectors.
824         if (VT.getVectorElementType() == MVT::i1) {
825           setOperationAction(ISD::AND, VT, Custom);
826           setOperationAction(ISD::OR, VT, Custom);
827           setOperationAction(ISD::XOR, VT, Custom);
828           continue;
829         }
830 
831         // Use SPLAT_VECTOR to prevent type legalization from destroying the
832         // splats when type legalizing i64 scalar on RV32.
833         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
834         // improvements first.
835         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
836           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
837           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
838         }
839 
840         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
841         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
842 
843         setOperationAction(ISD::MLOAD, VT, Custom);
844         setOperationAction(ISD::MSTORE, VT, Custom);
845         setOperationAction(ISD::MGATHER, VT, Custom);
846         setOperationAction(ISD::MSCATTER, VT, Custom);
847 
848         setOperationAction(ISD::VP_LOAD, VT, Custom);
849         setOperationAction(ISD::VP_STORE, VT, Custom);
850         setOperationAction(ISD::VP_GATHER, VT, Custom);
851         setOperationAction(ISD::VP_SCATTER, VT, Custom);
852 
853         setOperationAction(ISD::ADD, VT, Custom);
854         setOperationAction(ISD::MUL, VT, Custom);
855         setOperationAction(ISD::SUB, VT, Custom);
856         setOperationAction(ISD::AND, VT, Custom);
857         setOperationAction(ISD::OR, VT, Custom);
858         setOperationAction(ISD::XOR, VT, Custom);
859         setOperationAction(ISD::SDIV, VT, Custom);
860         setOperationAction(ISD::SREM, VT, Custom);
861         setOperationAction(ISD::UDIV, VT, Custom);
862         setOperationAction(ISD::UREM, VT, Custom);
863         setOperationAction(ISD::SHL, VT, Custom);
864         setOperationAction(ISD::SRA, VT, Custom);
865         setOperationAction(ISD::SRL, VT, Custom);
866 
867         setOperationAction(ISD::SMIN, VT, Custom);
868         setOperationAction(ISD::SMAX, VT, Custom);
869         setOperationAction(ISD::UMIN, VT, Custom);
870         setOperationAction(ISD::UMAX, VT, Custom);
871         setOperationAction(ISD::ABS,  VT, Custom);
872 
873         setOperationAction(ISD::MULHS, VT, Custom);
874         setOperationAction(ISD::MULHU, VT, Custom);
875 
876         setOperationAction(ISD::SADDSAT, VT, Custom);
877         setOperationAction(ISD::UADDSAT, VT, Custom);
878         setOperationAction(ISD::SSUBSAT, VT, Custom);
879         setOperationAction(ISD::USUBSAT, VT, Custom);
880 
881         setOperationAction(ISD::VSELECT, VT, Custom);
882         setOperationAction(ISD::SELECT_CC, VT, Expand);
883 
884         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
885         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
886         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
887 
888         // Custom-lower reduction operations to set up the corresponding custom
889         // nodes' operands.
890         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
891         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
892         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
893         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
894         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
895 
896         for (unsigned VPOpc : IntegerVPOps)
897           setOperationAction(VPOpc, VT, Custom);
898 
899         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
900         // type that can represent the value exactly.
901         if (VT.getVectorElementType() != MVT::i64) {
902           MVT FloatEltVT =
903               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
904           EVT FloatVT =
905               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
906           if (isTypeLegal(FloatVT)) {
907             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
908             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
909           }
910         }
911       }
912 
913       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
914         if (!useRVVForFixedLengthVectorVT(VT))
915           continue;
916 
917         // By default everything must be expanded.
918         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
919           setOperationAction(Op, VT, Expand);
920         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
921           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
922           setTruncStoreAction(VT, OtherVT, Expand);
923         }
924 
925         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
926         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
927         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
928 
929         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
930         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
931         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
932         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
933         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
934 
935         setOperationAction(ISD::LOAD, VT, Custom);
936         setOperationAction(ISD::STORE, VT, Custom);
937         setOperationAction(ISD::MLOAD, VT, Custom);
938         setOperationAction(ISD::MSTORE, VT, Custom);
939         setOperationAction(ISD::MGATHER, VT, Custom);
940         setOperationAction(ISD::MSCATTER, VT, Custom);
941 
942         setOperationAction(ISD::VP_LOAD, VT, Custom);
943         setOperationAction(ISD::VP_STORE, VT, Custom);
944         setOperationAction(ISD::VP_GATHER, VT, Custom);
945         setOperationAction(ISD::VP_SCATTER, VT, Custom);
946 
947         setOperationAction(ISD::FADD, VT, Custom);
948         setOperationAction(ISD::FSUB, VT, Custom);
949         setOperationAction(ISD::FMUL, VT, Custom);
950         setOperationAction(ISD::FDIV, VT, Custom);
951         setOperationAction(ISD::FNEG, VT, Custom);
952         setOperationAction(ISD::FABS, VT, Custom);
953         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
954         setOperationAction(ISD::FSQRT, VT, Custom);
955         setOperationAction(ISD::FMA, VT, Custom);
956         setOperationAction(ISD::FMINNUM, VT, Custom);
957         setOperationAction(ISD::FMAXNUM, VT, Custom);
958 
959         setOperationAction(ISD::FP_ROUND, VT, Custom);
960         setOperationAction(ISD::FP_EXTEND, VT, Custom);
961 
962         setOperationAction(ISD::FTRUNC, VT, Custom);
963         setOperationAction(ISD::FCEIL, VT, Custom);
964         setOperationAction(ISD::FFLOOR, VT, Custom);
965 
966         for (auto CC : VFPCCToExpand)
967           setCondCodeAction(CC, VT, Expand);
968 
969         setOperationAction(ISD::VSELECT, VT, Custom);
970         setOperationAction(ISD::SELECT, VT, Custom);
971         setOperationAction(ISD::SELECT_CC, VT, Expand);
972 
973         setOperationAction(ISD::BITCAST, VT, Custom);
974 
975         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
976         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
977         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
978         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
979 
980         for (unsigned VPOpc : FloatingPointVPOps)
981           setOperationAction(VPOpc, VT, Custom);
982       }
983 
984       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
985       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
986       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
987       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
988       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
989       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
990       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
991       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
992     }
993   }
994 
995   // Function alignments.
996   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
997   setMinFunctionAlignment(FunctionAlignment);
998   setPrefFunctionAlignment(FunctionAlignment);
999 
1000   setMinimumJumpTableEntries(5);
1001 
1002   // Jumps are expensive, compared to logic
1003   setJumpIsExpensive();
1004 
1005   setTargetDAGCombine(ISD::ADD);
1006   setTargetDAGCombine(ISD::SUB);
1007   setTargetDAGCombine(ISD::AND);
1008   setTargetDAGCombine(ISD::OR);
1009   setTargetDAGCombine(ISD::XOR);
1010   setTargetDAGCombine(ISD::ANY_EXTEND);
1011   setTargetDAGCombine(ISD::ZERO_EXTEND);
1012   if (Subtarget.hasVInstructions()) {
1013     setTargetDAGCombine(ISD::FCOPYSIGN);
1014     setTargetDAGCombine(ISD::MGATHER);
1015     setTargetDAGCombine(ISD::MSCATTER);
1016     setTargetDAGCombine(ISD::VP_GATHER);
1017     setTargetDAGCombine(ISD::VP_SCATTER);
1018     setTargetDAGCombine(ISD::SRA);
1019     setTargetDAGCombine(ISD::SRL);
1020     setTargetDAGCombine(ISD::SHL);
1021     setTargetDAGCombine(ISD::STORE);
1022   }
1023 }
1024 
1025 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1026                                             LLVMContext &Context,
1027                                             EVT VT) const {
1028   if (!VT.isVector())
1029     return getPointerTy(DL);
1030   if (Subtarget.hasVInstructions() &&
1031       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1032     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1033   return VT.changeVectorElementTypeToInteger();
1034 }
1035 
1036 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1037   return Subtarget.getXLenVT();
1038 }
1039 
1040 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1041                                              const CallInst &I,
1042                                              MachineFunction &MF,
1043                                              unsigned Intrinsic) const {
1044   auto &DL = I.getModule()->getDataLayout();
1045   switch (Intrinsic) {
1046   default:
1047     return false;
1048   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1049   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1050   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1051   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1052   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1053   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1054   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1055   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1056   case Intrinsic::riscv_masked_cmpxchg_i32: {
1057     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1058     Info.opc = ISD::INTRINSIC_W_CHAIN;
1059     Info.memVT = MVT::getVT(PtrTy->getElementType());
1060     Info.ptrVal = I.getArgOperand(0);
1061     Info.offset = 0;
1062     Info.align = Align(4);
1063     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1064                  MachineMemOperand::MOVolatile;
1065     return true;
1066   }
1067   case Intrinsic::riscv_masked_strided_load:
1068     Info.opc = ISD::INTRINSIC_W_CHAIN;
1069     Info.ptrVal = I.getArgOperand(1);
1070     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1071     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1072     Info.size = MemoryLocation::UnknownSize;
1073     Info.flags |= MachineMemOperand::MOLoad;
1074     return true;
1075   case Intrinsic::riscv_masked_strided_store:
1076     Info.opc = ISD::INTRINSIC_VOID;
1077     Info.ptrVal = I.getArgOperand(1);
1078     Info.memVT =
1079         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1080     Info.align = Align(
1081         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1082         8);
1083     Info.size = MemoryLocation::UnknownSize;
1084     Info.flags |= MachineMemOperand::MOStore;
1085     return true;
1086   }
1087 }
1088 
1089 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1090                                                 const AddrMode &AM, Type *Ty,
1091                                                 unsigned AS,
1092                                                 Instruction *I) const {
1093   // No global is ever allowed as a base.
1094   if (AM.BaseGV)
1095     return false;
1096 
1097   // Require a 12-bit signed offset.
1098   if (!isInt<12>(AM.BaseOffs))
1099     return false;
1100 
1101   switch (AM.Scale) {
1102   case 0: // "r+i" or just "i", depending on HasBaseReg.
1103     break;
1104   case 1:
1105     if (!AM.HasBaseReg) // allow "r+i".
1106       break;
1107     return false; // disallow "r+r" or "r+r+i".
1108   default:
1109     return false;
1110   }
1111 
1112   return true;
1113 }
1114 
1115 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1116   return isInt<12>(Imm);
1117 }
1118 
1119 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1120   return isInt<12>(Imm);
1121 }
1122 
1123 // On RV32, 64-bit integers are split into their high and low parts and held
1124 // in two different registers, so the trunc is free since the low register can
1125 // just be used.
1126 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1127   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1128     return false;
1129   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1130   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1131   return (SrcBits == 64 && DestBits == 32);
1132 }
1133 
1134 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1135   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1136       !SrcVT.isInteger() || !DstVT.isInteger())
1137     return false;
1138   unsigned SrcBits = SrcVT.getSizeInBits();
1139   unsigned DestBits = DstVT.getSizeInBits();
1140   return (SrcBits == 64 && DestBits == 32);
1141 }
1142 
1143 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1144   // Zexts are free if they can be combined with a load.
1145   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1146     EVT MemVT = LD->getMemoryVT();
1147     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1148          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1149         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1150          LD->getExtensionType() == ISD::ZEXTLOAD))
1151       return true;
1152   }
1153 
1154   return TargetLowering::isZExtFree(Val, VT2);
1155 }
1156 
1157 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1158   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1159 }
1160 
1161 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1162   return Subtarget.hasStdExtZbb();
1163 }
1164 
1165 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1166   return Subtarget.hasStdExtZbb();
1167 }
1168 
1169 bool RISCVTargetLowering::hasAndNot(SDValue Y) const {
1170   EVT VT = Y.getValueType();
1171 
1172   // FIXME: Support vectors once we have tests.
1173   if (VT.isVector())
1174     return false;
1175 
1176   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1177 }
1178 
1179 /// Check if sinking \p I's operands to I's basic block is profitable, because
1180 /// the operands can be folded into a target instruction, e.g.
1181 /// splats of scalars can fold into vector instructions.
1182 bool RISCVTargetLowering::shouldSinkOperands(
1183     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1184   using namespace llvm::PatternMatch;
1185 
1186   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1187     return false;
1188 
1189   auto IsSinker = [&](Instruction *I, int Operand) {
1190     switch (I->getOpcode()) {
1191     case Instruction::Add:
1192     case Instruction::Sub:
1193     case Instruction::Mul:
1194     case Instruction::And:
1195     case Instruction::Or:
1196     case Instruction::Xor:
1197     case Instruction::FAdd:
1198     case Instruction::FSub:
1199     case Instruction::FMul:
1200     case Instruction::FDiv:
1201     case Instruction::ICmp:
1202     case Instruction::FCmp:
1203       return true;
1204     case Instruction::Shl:
1205     case Instruction::LShr:
1206     case Instruction::AShr:
1207     case Instruction::UDiv:
1208     case Instruction::SDiv:
1209     case Instruction::URem:
1210     case Instruction::SRem:
1211       return Operand == 1;
1212     case Instruction::Call:
1213       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1214         switch (II->getIntrinsicID()) {
1215         case Intrinsic::fma:
1216           return Operand == 0 || Operand == 1;
1217         default:
1218           return false;
1219         }
1220       }
1221       return false;
1222     default:
1223       return false;
1224     }
1225   };
1226 
1227   for (auto OpIdx : enumerate(I->operands())) {
1228     if (!IsSinker(I, OpIdx.index()))
1229       continue;
1230 
1231     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1232     // Make sure we are not already sinking this operand
1233     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1234       continue;
1235 
1236     // We are looking for a splat that can be sunk.
1237     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1238                              m_Undef(), m_ZeroMask())))
1239       continue;
1240 
1241     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1242     // and vector registers
1243     for (Use &U : Op->uses()) {
1244       Instruction *Insn = cast<Instruction>(U.getUser());
1245       if (!IsSinker(Insn, U.getOperandNo()))
1246         return false;
1247     }
1248 
1249     Ops.push_back(&Op->getOperandUse(0));
1250     Ops.push_back(&OpIdx.value());
1251   }
1252   return true;
1253 }
1254 
1255 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1256                                        bool ForCodeSize) const {
1257   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1258   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1259     return false;
1260   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1261     return false;
1262   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1263     return false;
1264   if (Imm.isNegZero())
1265     return false;
1266   return Imm.isZero();
1267 }
1268 
1269 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1270   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1271          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1272          (VT == MVT::f64 && Subtarget.hasStdExtD());
1273 }
1274 
1275 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1276                                                       CallingConv::ID CC,
1277                                                       EVT VT) const {
1278   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1279   // We might still end up using a GPR but that will be decided based on ABI.
1280   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1281   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1282     return MVT::f32;
1283 
1284   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1285 }
1286 
1287 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1288                                                            CallingConv::ID CC,
1289                                                            EVT VT) const {
1290   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1291   // We might still end up using a GPR but that will be decided based on ABI.
1292   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1293   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1294     return 1;
1295 
1296   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1297 }
1298 
1299 // Changes the condition code and swaps operands if necessary, so the SetCC
1300 // operation matches one of the comparisons supported directly by branches
1301 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1302 // with 1/-1.
1303 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1304                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1305   // Convert X > -1 to X >= 0.
1306   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1307     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1308     CC = ISD::SETGE;
1309     return;
1310   }
1311   // Convert X < 1 to 0 >= X.
1312   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1313     RHS = LHS;
1314     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1315     CC = ISD::SETGE;
1316     return;
1317   }
1318 
1319   switch (CC) {
1320   default:
1321     break;
1322   case ISD::SETGT:
1323   case ISD::SETLE:
1324   case ISD::SETUGT:
1325   case ISD::SETULE:
1326     CC = ISD::getSetCCSwappedOperands(CC);
1327     std::swap(LHS, RHS);
1328     break;
1329   }
1330 }
1331 
1332 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1333   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1334   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1335   if (VT.getVectorElementType() == MVT::i1)
1336     KnownSize *= 8;
1337 
1338   switch (KnownSize) {
1339   default:
1340     llvm_unreachable("Invalid LMUL.");
1341   case 8:
1342     return RISCVII::VLMUL::LMUL_F8;
1343   case 16:
1344     return RISCVII::VLMUL::LMUL_F4;
1345   case 32:
1346     return RISCVII::VLMUL::LMUL_F2;
1347   case 64:
1348     return RISCVII::VLMUL::LMUL_1;
1349   case 128:
1350     return RISCVII::VLMUL::LMUL_2;
1351   case 256:
1352     return RISCVII::VLMUL::LMUL_4;
1353   case 512:
1354     return RISCVII::VLMUL::LMUL_8;
1355   }
1356 }
1357 
1358 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1359   switch (LMul) {
1360   default:
1361     llvm_unreachable("Invalid LMUL.");
1362   case RISCVII::VLMUL::LMUL_F8:
1363   case RISCVII::VLMUL::LMUL_F4:
1364   case RISCVII::VLMUL::LMUL_F2:
1365   case RISCVII::VLMUL::LMUL_1:
1366     return RISCV::VRRegClassID;
1367   case RISCVII::VLMUL::LMUL_2:
1368     return RISCV::VRM2RegClassID;
1369   case RISCVII::VLMUL::LMUL_4:
1370     return RISCV::VRM4RegClassID;
1371   case RISCVII::VLMUL::LMUL_8:
1372     return RISCV::VRM8RegClassID;
1373   }
1374 }
1375 
1376 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1377   RISCVII::VLMUL LMUL = getLMUL(VT);
1378   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1379       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1380       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1381       LMUL == RISCVII::VLMUL::LMUL_1) {
1382     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1383                   "Unexpected subreg numbering");
1384     return RISCV::sub_vrm1_0 + Index;
1385   }
1386   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1387     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1388                   "Unexpected subreg numbering");
1389     return RISCV::sub_vrm2_0 + Index;
1390   }
1391   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1392     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1393                   "Unexpected subreg numbering");
1394     return RISCV::sub_vrm4_0 + Index;
1395   }
1396   llvm_unreachable("Invalid vector type.");
1397 }
1398 
1399 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1400   if (VT.getVectorElementType() == MVT::i1)
1401     return RISCV::VRRegClassID;
1402   return getRegClassIDForLMUL(getLMUL(VT));
1403 }
1404 
1405 // Attempt to decompose a subvector insert/extract between VecVT and
1406 // SubVecVT via subregister indices. Returns the subregister index that
1407 // can perform the subvector insert/extract with the given element index, as
1408 // well as the index corresponding to any leftover subvectors that must be
1409 // further inserted/extracted within the register class for SubVecVT.
1410 std::pair<unsigned, unsigned>
1411 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1412     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1413     const RISCVRegisterInfo *TRI) {
1414   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1415                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1416                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1417                 "Register classes not ordered");
1418   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1419   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1420   // Try to compose a subregister index that takes us from the incoming
1421   // LMUL>1 register class down to the outgoing one. At each step we half
1422   // the LMUL:
1423   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1424   // Note that this is not guaranteed to find a subregister index, such as
1425   // when we are extracting from one VR type to another.
1426   unsigned SubRegIdx = RISCV::NoSubRegister;
1427   for (const unsigned RCID :
1428        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1429     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1430       VecVT = VecVT.getHalfNumVectorElementsVT();
1431       bool IsHi =
1432           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1433       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1434                                             getSubregIndexByMVT(VecVT, IsHi));
1435       if (IsHi)
1436         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1437     }
1438   return {SubRegIdx, InsertExtractIdx};
1439 }
1440 
1441 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1442 // stores for those types.
1443 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1444   return !Subtarget.useRVVForFixedLengthVectors() ||
1445          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1446 }
1447 
1448 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1449   if (ScalarTy->isPointerTy())
1450     return true;
1451 
1452   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1453       ScalarTy->isIntegerTy(32))
1454     return true;
1455 
1456   if (ScalarTy->isIntegerTy(64))
1457     return Subtarget.hasVInstructionsI64();
1458 
1459   if (ScalarTy->isHalfTy())
1460     return Subtarget.hasVInstructionsF16();
1461   if (ScalarTy->isFloatTy())
1462     return Subtarget.hasVInstructionsF32();
1463   if (ScalarTy->isDoubleTy())
1464     return Subtarget.hasVInstructionsF64();
1465 
1466   return false;
1467 }
1468 
1469 static bool useRVVForFixedLengthVectorVT(MVT VT,
1470                                          const RISCVSubtarget &Subtarget) {
1471   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1472   if (!Subtarget.useRVVForFixedLengthVectors())
1473     return false;
1474 
1475   // We only support a set of vector types with a consistent maximum fixed size
1476   // across all supported vector element types to avoid legalization issues.
1477   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1478   // fixed-length vector type we support is 1024 bytes.
1479   if (VT.getFixedSizeInBits() > 1024 * 8)
1480     return false;
1481 
1482   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1483 
1484   MVT EltVT = VT.getVectorElementType();
1485 
1486   // Don't use RVV for vectors we cannot scalarize if required.
1487   switch (EltVT.SimpleTy) {
1488   // i1 is supported but has different rules.
1489   default:
1490     return false;
1491   case MVT::i1:
1492     // Masks can only use a single register.
1493     if (VT.getVectorNumElements() > MinVLen)
1494       return false;
1495     MinVLen /= 8;
1496     break;
1497   case MVT::i8:
1498   case MVT::i16:
1499   case MVT::i32:
1500     break;
1501   case MVT::i64:
1502     if (!Subtarget.hasVInstructionsI64())
1503       return false;
1504     break;
1505   case MVT::f16:
1506     if (!Subtarget.hasVInstructionsF16())
1507       return false;
1508     break;
1509   case MVT::f32:
1510     if (!Subtarget.hasVInstructionsF32())
1511       return false;
1512     break;
1513   case MVT::f64:
1514     if (!Subtarget.hasVInstructionsF64())
1515       return false;
1516     break;
1517   }
1518 
1519   // Reject elements larger than ELEN.
1520   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1521     return false;
1522 
1523   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1524   // Don't use RVV for types that don't fit.
1525   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1526     return false;
1527 
1528   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1529   // the base fixed length RVV support in place.
1530   if (!VT.isPow2VectorType())
1531     return false;
1532 
1533   return true;
1534 }
1535 
1536 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1537   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1538 }
1539 
1540 // Return the largest legal scalable vector type that matches VT's element type.
1541 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1542                                             const RISCVSubtarget &Subtarget) {
1543   // This may be called before legal types are setup.
1544   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1545           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1546          "Expected legal fixed length vector!");
1547 
1548   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1549   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1550 
1551   MVT EltVT = VT.getVectorElementType();
1552   switch (EltVT.SimpleTy) {
1553   default:
1554     llvm_unreachable("unexpected element type for RVV container");
1555   case MVT::i1:
1556   case MVT::i8:
1557   case MVT::i16:
1558   case MVT::i32:
1559   case MVT::i64:
1560   case MVT::f16:
1561   case MVT::f32:
1562   case MVT::f64: {
1563     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1564     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1565     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1566     unsigned NumElts =
1567         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1568     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1569     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1570     return MVT::getScalableVectorVT(EltVT, NumElts);
1571   }
1572   }
1573 }
1574 
1575 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1576                                             const RISCVSubtarget &Subtarget) {
1577   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1578                                           Subtarget);
1579 }
1580 
1581 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1582   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1583 }
1584 
1585 // Grow V to consume an entire RVV register.
1586 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1587                                        const RISCVSubtarget &Subtarget) {
1588   assert(VT.isScalableVector() &&
1589          "Expected to convert into a scalable vector!");
1590   assert(V.getValueType().isFixedLengthVector() &&
1591          "Expected a fixed length vector operand!");
1592   SDLoc DL(V);
1593   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1594   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1595 }
1596 
1597 // Shrink V so it's just big enough to maintain a VT's worth of data.
1598 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1599                                          const RISCVSubtarget &Subtarget) {
1600   assert(VT.isFixedLengthVector() &&
1601          "Expected to convert into a fixed length vector!");
1602   assert(V.getValueType().isScalableVector() &&
1603          "Expected a scalable vector operand!");
1604   SDLoc DL(V);
1605   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1606   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1607 }
1608 
1609 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1610 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1611 // the vector type that it is contained in.
1612 static std::pair<SDValue, SDValue>
1613 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1614                 const RISCVSubtarget &Subtarget) {
1615   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1616   MVT XLenVT = Subtarget.getXLenVT();
1617   SDValue VL = VecVT.isFixedLengthVector()
1618                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1619                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1620   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1621   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1622   return {Mask, VL};
1623 }
1624 
1625 // As above but assuming the given type is a scalable vector type.
1626 static std::pair<SDValue, SDValue>
1627 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1628                         const RISCVSubtarget &Subtarget) {
1629   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1630   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1631 }
1632 
1633 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1634 // of either is (currently) supported. This can get us into an infinite loop
1635 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1636 // as a ..., etc.
1637 // Until either (or both) of these can reliably lower any node, reporting that
1638 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1639 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1640 // which is not desirable.
1641 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1642     EVT VT, unsigned DefinedValues) const {
1643   return false;
1644 }
1645 
1646 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1647   // Only splats are currently supported.
1648   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1649     return true;
1650 
1651   return false;
1652 }
1653 
1654 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1655   // RISCV FP-to-int conversions saturate to the destination register size, but
1656   // don't produce 0 for nan. We can use a conversion instruction and fix the
1657   // nan case with a compare and a select.
1658   SDValue Src = Op.getOperand(0);
1659 
1660   EVT DstVT = Op.getValueType();
1661   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1662 
1663   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1664   unsigned Opc;
1665   if (SatVT == DstVT)
1666     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1667   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1668     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1669   else
1670     return SDValue();
1671   // FIXME: Support other SatVTs by clamping before or after the conversion.
1672 
1673   SDLoc DL(Op);
1674   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1675 
1676   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1677   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1678 }
1679 
1680 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1681 // and back. Taking care to avoid converting values that are nan or already
1682 // correct.
1683 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1684 // have FRM dependencies modeled yet.
1685 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1686   MVT VT = Op.getSimpleValueType();
1687   assert(VT.isVector() && "Unexpected type");
1688 
1689   SDLoc DL(Op);
1690 
1691   // Freeze the source since we are increasing the number of uses.
1692   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1693 
1694   // Truncate to integer and convert back to FP.
1695   MVT IntVT = VT.changeVectorElementTypeToInteger();
1696   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1697   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1698 
1699   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1700 
1701   if (Op.getOpcode() == ISD::FCEIL) {
1702     // If the truncated value is the greater than or equal to the original
1703     // value, we've computed the ceil. Otherwise, we went the wrong way and
1704     // need to increase by 1.
1705     // FIXME: This should use a masked operation. Handle here or in isel?
1706     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1707                                  DAG.getConstantFP(1.0, DL, VT));
1708     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1709     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1710   } else if (Op.getOpcode() == ISD::FFLOOR) {
1711     // If the truncated value is the less than or equal to the original value,
1712     // we've computed the floor. Otherwise, we went the wrong way and need to
1713     // decrease by 1.
1714     // FIXME: This should use a masked operation. Handle here or in isel?
1715     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1716                                  DAG.getConstantFP(1.0, DL, VT));
1717     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1718     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1719   }
1720 
1721   // Restore the original sign so that -0.0 is preserved.
1722   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1723 
1724   // Determine the largest integer that can be represented exactly. This and
1725   // values larger than it don't have any fractional bits so don't need to
1726   // be converted.
1727   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1728   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1729   APFloat MaxVal = APFloat(FltSem);
1730   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1731                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1732   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1733 
1734   // If abs(Src) was larger than MaxVal or nan, keep it.
1735   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1736   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1737   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1738 }
1739 
1740 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1741                                  const RISCVSubtarget &Subtarget) {
1742   MVT VT = Op.getSimpleValueType();
1743   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1744 
1745   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1746 
1747   SDLoc DL(Op);
1748   SDValue Mask, VL;
1749   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1750 
1751   unsigned Opc =
1752       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1753   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1754   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1755 }
1756 
1757 struct VIDSequence {
1758   int64_t StepNumerator;
1759   unsigned StepDenominator;
1760   int64_t Addend;
1761 };
1762 
1763 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1764 // to the (non-zero) step S and start value X. This can be then lowered as the
1765 // RVV sequence (VID * S) + X, for example.
1766 // The step S is represented as an integer numerator divided by a positive
1767 // denominator. Note that the implementation currently only identifies
1768 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1769 // cannot detect 2/3, for example.
1770 // Note that this method will also match potentially unappealing index
1771 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1772 // determine whether this is worth generating code for.
1773 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1774   unsigned NumElts = Op.getNumOperands();
1775   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1776   if (!Op.getValueType().isInteger())
1777     return None;
1778 
1779   Optional<unsigned> SeqStepDenom;
1780   Optional<int64_t> SeqStepNum, SeqAddend;
1781   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1782   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1783   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1784     // Assume undef elements match the sequence; we just have to be careful
1785     // when interpolating across them.
1786     if (Op.getOperand(Idx).isUndef())
1787       continue;
1788     // The BUILD_VECTOR must be all constants.
1789     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1790       return None;
1791 
1792     uint64_t Val = Op.getConstantOperandVal(Idx) &
1793                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1794 
1795     if (PrevElt) {
1796       // Calculate the step since the last non-undef element, and ensure
1797       // it's consistent across the entire sequence.
1798       unsigned IdxDiff = Idx - PrevElt->second;
1799       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1800 
1801       // A zero-value value difference means that we're somewhere in the middle
1802       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1803       // step change before evaluating the sequence.
1804       if (ValDiff != 0) {
1805         int64_t Remainder = ValDiff % IdxDiff;
1806         // Normalize the step if it's greater than 1.
1807         if (Remainder != ValDiff) {
1808           // The difference must cleanly divide the element span.
1809           if (Remainder != 0)
1810             return None;
1811           ValDiff /= IdxDiff;
1812           IdxDiff = 1;
1813         }
1814 
1815         if (!SeqStepNum)
1816           SeqStepNum = ValDiff;
1817         else if (ValDiff != SeqStepNum)
1818           return None;
1819 
1820         if (!SeqStepDenom)
1821           SeqStepDenom = IdxDiff;
1822         else if (IdxDiff != *SeqStepDenom)
1823           return None;
1824       }
1825     }
1826 
1827     // Record and/or check any addend.
1828     if (SeqStepNum && SeqStepDenom) {
1829       uint64_t ExpectedVal =
1830           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1831       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1832       if (!SeqAddend)
1833         SeqAddend = Addend;
1834       else if (SeqAddend != Addend)
1835         return None;
1836     }
1837 
1838     // Record this non-undef element for later.
1839     if (!PrevElt || PrevElt->first != Val)
1840       PrevElt = std::make_pair(Val, Idx);
1841   }
1842   // We need to have logged both a step and an addend for this to count as
1843   // a legal index sequence.
1844   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1845     return None;
1846 
1847   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1848 }
1849 
1850 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1851                                  const RISCVSubtarget &Subtarget) {
1852   MVT VT = Op.getSimpleValueType();
1853   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1854 
1855   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1856 
1857   SDLoc DL(Op);
1858   SDValue Mask, VL;
1859   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1860 
1861   MVT XLenVT = Subtarget.getXLenVT();
1862   unsigned NumElts = Op.getNumOperands();
1863 
1864   if (VT.getVectorElementType() == MVT::i1) {
1865     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1866       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1867       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1868     }
1869 
1870     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1871       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1872       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1873     }
1874 
1875     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1876     // scalar integer chunks whose bit-width depends on the number of mask
1877     // bits and XLEN.
1878     // First, determine the most appropriate scalar integer type to use. This
1879     // is at most XLenVT, but may be shrunk to a smaller vector element type
1880     // according to the size of the final vector - use i8 chunks rather than
1881     // XLenVT if we're producing a v8i1. This results in more consistent
1882     // codegen across RV32 and RV64.
1883     unsigned NumViaIntegerBits =
1884         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1885     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1886       // If we have to use more than one INSERT_VECTOR_ELT then this
1887       // optimization is likely to increase code size; avoid peforming it in
1888       // such a case. We can use a load from a constant pool in this case.
1889       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1890         return SDValue();
1891       // Now we can create our integer vector type. Note that it may be larger
1892       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1893       MVT IntegerViaVecVT =
1894           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1895                            divideCeil(NumElts, NumViaIntegerBits));
1896 
1897       uint64_t Bits = 0;
1898       unsigned BitPos = 0, IntegerEltIdx = 0;
1899       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1900 
1901       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1902         // Once we accumulate enough bits to fill our scalar type, insert into
1903         // our vector and clear our accumulated data.
1904         if (I != 0 && I % NumViaIntegerBits == 0) {
1905           if (NumViaIntegerBits <= 32)
1906             Bits = SignExtend64(Bits, 32);
1907           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1908           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1909                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1910           Bits = 0;
1911           BitPos = 0;
1912           IntegerEltIdx++;
1913         }
1914         SDValue V = Op.getOperand(I);
1915         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1916         Bits |= ((uint64_t)BitValue << BitPos);
1917       }
1918 
1919       // Insert the (remaining) scalar value into position in our integer
1920       // vector type.
1921       if (NumViaIntegerBits <= 32)
1922         Bits = SignExtend64(Bits, 32);
1923       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1924       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1925                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1926 
1927       if (NumElts < NumViaIntegerBits) {
1928         // If we're producing a smaller vector than our minimum legal integer
1929         // type, bitcast to the equivalent (known-legal) mask type, and extract
1930         // our final mask.
1931         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1932         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1933         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1934                           DAG.getConstant(0, DL, XLenVT));
1935       } else {
1936         // Else we must have produced an integer type with the same size as the
1937         // mask type; bitcast for the final result.
1938         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1939         Vec = DAG.getBitcast(VT, Vec);
1940       }
1941 
1942       return Vec;
1943     }
1944 
1945     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1946     // vector type, we have a legal equivalently-sized i8 type, so we can use
1947     // that.
1948     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1949     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1950 
1951     SDValue WideVec;
1952     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1953       // For a splat, perform a scalar truncate before creating the wider
1954       // vector.
1955       assert(Splat.getValueType() == XLenVT &&
1956              "Unexpected type for i1 splat value");
1957       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1958                           DAG.getConstant(1, DL, XLenVT));
1959       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1960     } else {
1961       SmallVector<SDValue, 8> Ops(Op->op_values());
1962       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1963       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1964       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1965     }
1966 
1967     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1968   }
1969 
1970   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1971     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1972                                         : RISCVISD::VMV_V_X_VL;
1973     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1974     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1975   }
1976 
1977   // Try and match index sequences, which we can lower to the vid instruction
1978   // with optional modifications. An all-undef vector is matched by
1979   // getSplatValue, above.
1980   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1981     int64_t StepNumerator = SimpleVID->StepNumerator;
1982     unsigned StepDenominator = SimpleVID->StepDenominator;
1983     int64_t Addend = SimpleVID->Addend;
1984 
1985     assert(StepNumerator != 0 && "Invalid step");
1986     bool Negate = false;
1987     int64_t SplatStepVal = StepNumerator;
1988     unsigned StepOpcode = ISD::MUL;
1989     if (StepNumerator != 1) {
1990       if (isPowerOf2_64(std::abs(StepNumerator))) {
1991         Negate = StepNumerator < 0;
1992         StepOpcode = ISD::SHL;
1993         SplatStepVal = Log2_64(std::abs(StepNumerator));
1994       }
1995     }
1996 
1997     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1998     // threshold since it's the immediate value many RVV instructions accept.
1999     // There is no vmul.vi instruction so ensure multiply constant can fit in
2000     // a single addi instruction.
2001     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2002          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2003         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2004       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2005       // Convert right out of the scalable type so we can use standard ISD
2006       // nodes for the rest of the computation. If we used scalable types with
2007       // these, we'd lose the fixed-length vector info and generate worse
2008       // vsetvli code.
2009       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2010       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2011           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2012         SDValue SplatStep = DAG.getSplatVector(
2013             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2014         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2015       }
2016       if (StepDenominator != 1) {
2017         SDValue SplatStep = DAG.getSplatVector(
2018             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2019         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2020       }
2021       if (Addend != 0 || Negate) {
2022         SDValue SplatAddend =
2023             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2024         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2025       }
2026       return VID;
2027     }
2028   }
2029 
2030   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2031   // when re-interpreted as a vector with a larger element type. For example,
2032   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2033   // could be instead splat as
2034   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2035   // TODO: This optimization could also work on non-constant splats, but it
2036   // would require bit-manipulation instructions to construct the splat value.
2037   SmallVector<SDValue> Sequence;
2038   unsigned EltBitSize = VT.getScalarSizeInBits();
2039   const auto *BV = cast<BuildVectorSDNode>(Op);
2040   if (VT.isInteger() && EltBitSize < 64 &&
2041       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2042       BV->getRepeatedSequence(Sequence) &&
2043       (Sequence.size() * EltBitSize) <= 64) {
2044     unsigned SeqLen = Sequence.size();
2045     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2046     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2047     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2048             ViaIntVT == MVT::i64) &&
2049            "Unexpected sequence type");
2050 
2051     unsigned EltIdx = 0;
2052     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2053     uint64_t SplatValue = 0;
2054     // Construct the amalgamated value which can be splatted as this larger
2055     // vector type.
2056     for (const auto &SeqV : Sequence) {
2057       if (!SeqV.isUndef())
2058         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2059                        << (EltIdx * EltBitSize));
2060       EltIdx++;
2061     }
2062 
2063     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2064     // achieve better constant materializion.
2065     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2066       SplatValue = SignExtend64(SplatValue, 32);
2067 
2068     // Since we can't introduce illegal i64 types at this stage, we can only
2069     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2070     // way we can use RVV instructions to splat.
2071     assert((ViaIntVT.bitsLE(XLenVT) ||
2072             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2073            "Unexpected bitcast sequence");
2074     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2075       SDValue ViaVL =
2076           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2077       MVT ViaContainerVT =
2078           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2079       SDValue Splat =
2080           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2081                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2082       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2083       return DAG.getBitcast(VT, Splat);
2084     }
2085   }
2086 
2087   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2088   // which constitute a large proportion of the elements. In such cases we can
2089   // splat a vector with the dominant element and make up the shortfall with
2090   // INSERT_VECTOR_ELTs.
2091   // Note that this includes vectors of 2 elements by association. The
2092   // upper-most element is the "dominant" one, allowing us to use a splat to
2093   // "insert" the upper element, and an insert of the lower element at position
2094   // 0, which improves codegen.
2095   SDValue DominantValue;
2096   unsigned MostCommonCount = 0;
2097   DenseMap<SDValue, unsigned> ValueCounts;
2098   unsigned NumUndefElts =
2099       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2100 
2101   // Track the number of scalar loads we know we'd be inserting, estimated as
2102   // any non-zero floating-point constant. Other kinds of element are either
2103   // already in registers or are materialized on demand. The threshold at which
2104   // a vector load is more desirable than several scalar materializion and
2105   // vector-insertion instructions is not known.
2106   unsigned NumScalarLoads = 0;
2107 
2108   for (SDValue V : Op->op_values()) {
2109     if (V.isUndef())
2110       continue;
2111 
2112     ValueCounts.insert(std::make_pair(V, 0));
2113     unsigned &Count = ValueCounts[V];
2114 
2115     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2116       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2117 
2118     // Is this value dominant? In case of a tie, prefer the highest element as
2119     // it's cheaper to insert near the beginning of a vector than it is at the
2120     // end.
2121     if (++Count >= MostCommonCount) {
2122       DominantValue = V;
2123       MostCommonCount = Count;
2124     }
2125   }
2126 
2127   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2128   unsigned NumDefElts = NumElts - NumUndefElts;
2129   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2130 
2131   // Don't perform this optimization when optimizing for size, since
2132   // materializing elements and inserting them tends to cause code bloat.
2133   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2134       ((MostCommonCount > DominantValueCountThreshold) ||
2135        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2136     // Start by splatting the most common element.
2137     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2138 
2139     DenseSet<SDValue> Processed{DominantValue};
2140     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2141     for (const auto &OpIdx : enumerate(Op->ops())) {
2142       const SDValue &V = OpIdx.value();
2143       if (V.isUndef() || !Processed.insert(V).second)
2144         continue;
2145       if (ValueCounts[V] == 1) {
2146         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2147                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2148       } else {
2149         // Blend in all instances of this value using a VSELECT, using a
2150         // mask where each bit signals whether that element is the one
2151         // we're after.
2152         SmallVector<SDValue> Ops;
2153         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2154           return DAG.getConstant(V == V1, DL, XLenVT);
2155         });
2156         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2157                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2158                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2159       }
2160     }
2161 
2162     return Vec;
2163   }
2164 
2165   return SDValue();
2166 }
2167 
2168 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2169                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2170   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2171     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2172     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2173     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2174     // node in order to try and match RVV vector/scalar instructions.
2175     if ((LoC >> 31) == HiC)
2176       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2177   }
2178 
2179   // Fall back to a stack store and stride x0 vector load.
2180   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2181 }
2182 
2183 // Called by type legalization to handle splat of i64 on RV32.
2184 // FIXME: We can optimize this when the type has sign or zero bits in one
2185 // of the halves.
2186 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2187                                    SDValue VL, SelectionDAG &DAG) {
2188   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2189   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2190                            DAG.getConstant(0, DL, MVT::i32));
2191   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2192                            DAG.getConstant(1, DL, MVT::i32));
2193   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2194 }
2195 
2196 // This function lowers a splat of a scalar operand Splat with the vector
2197 // length VL. It ensures the final sequence is type legal, which is useful when
2198 // lowering a splat after type legalization.
2199 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2200                                 SelectionDAG &DAG,
2201                                 const RISCVSubtarget &Subtarget) {
2202   if (VT.isFloatingPoint())
2203     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2204 
2205   MVT XLenVT = Subtarget.getXLenVT();
2206 
2207   // Simplest case is that the operand needs to be promoted to XLenVT.
2208   if (Scalar.getValueType().bitsLE(XLenVT)) {
2209     // If the operand is a constant, sign extend to increase our chances
2210     // of being able to use a .vi instruction. ANY_EXTEND would become a
2211     // a zero extend and the simm5 check in isel would fail.
2212     // FIXME: Should we ignore the upper bits in isel instead?
2213     unsigned ExtOpc =
2214         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2215     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2216     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2217   }
2218 
2219   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2220          "Unexpected scalar for splat lowering!");
2221 
2222   // Otherwise use the more complicated splatting algorithm.
2223   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2224 }
2225 
2226 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2227                                    const RISCVSubtarget &Subtarget) {
2228   SDValue V1 = Op.getOperand(0);
2229   SDValue V2 = Op.getOperand(1);
2230   SDLoc DL(Op);
2231   MVT XLenVT = Subtarget.getXLenVT();
2232   MVT VT = Op.getSimpleValueType();
2233   unsigned NumElts = VT.getVectorNumElements();
2234   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2235 
2236   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2237 
2238   SDValue TrueMask, VL;
2239   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2240 
2241   if (SVN->isSplat()) {
2242     const int Lane = SVN->getSplatIndex();
2243     if (Lane >= 0) {
2244       MVT SVT = VT.getVectorElementType();
2245 
2246       // Turn splatted vector load into a strided load with an X0 stride.
2247       SDValue V = V1;
2248       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2249       // with undef.
2250       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2251       int Offset = Lane;
2252       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2253         int OpElements =
2254             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2255         V = V.getOperand(Offset / OpElements);
2256         Offset %= OpElements;
2257       }
2258 
2259       // We need to ensure the load isn't atomic or volatile.
2260       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2261         auto *Ld = cast<LoadSDNode>(V);
2262         Offset *= SVT.getStoreSize();
2263         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2264                                                    TypeSize::Fixed(Offset), DL);
2265 
2266         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2267         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2268           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2269           SDValue IntID =
2270               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2271           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2272                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2273           SDValue NewLoad = DAG.getMemIntrinsicNode(
2274               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2275               DAG.getMachineFunction().getMachineMemOperand(
2276                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2277           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2278           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2279         }
2280 
2281         // Otherwise use a scalar load and splat. This will give the best
2282         // opportunity to fold a splat into the operation. ISel can turn it into
2283         // the x0 strided load if we aren't able to fold away the select.
2284         if (SVT.isFloatingPoint())
2285           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2286                           Ld->getPointerInfo().getWithOffset(Offset),
2287                           Ld->getOriginalAlign(),
2288                           Ld->getMemOperand()->getFlags());
2289         else
2290           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2291                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2292                              Ld->getOriginalAlign(),
2293                              Ld->getMemOperand()->getFlags());
2294         DAG.makeEquivalentMemoryOrdering(Ld, V);
2295 
2296         unsigned Opc =
2297             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2298         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2299         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2300       }
2301 
2302       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2303       assert(Lane < (int)NumElts && "Unexpected lane!");
2304       SDValue Gather =
2305           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2306                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2307       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2308     }
2309   }
2310 
2311   // Detect shuffles which can be re-expressed as vector selects; these are
2312   // shuffles in which each element in the destination is taken from an element
2313   // at the corresponding index in either source vectors.
2314   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2315     int MaskIndex = MaskIdx.value();
2316     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2317   });
2318 
2319   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2320 
2321   SmallVector<SDValue> MaskVals;
2322   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2323   // merged with a second vrgather.
2324   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2325 
2326   // By default we preserve the original operand order, and use a mask to
2327   // select LHS as true and RHS as false. However, since RVV vector selects may
2328   // feature splats but only on the LHS, we may choose to invert our mask and
2329   // instead select between RHS and LHS.
2330   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2331   bool InvertMask = IsSelect == SwapOps;
2332 
2333   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2334   // half.
2335   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2336 
2337   // Now construct the mask that will be used by the vselect or blended
2338   // vrgather operation. For vrgathers, construct the appropriate indices into
2339   // each vector.
2340   for (int MaskIndex : SVN->getMask()) {
2341     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2342     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2343     if (!IsSelect) {
2344       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2345       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2346                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2347                                      : DAG.getUNDEF(XLenVT));
2348       GatherIndicesRHS.push_back(
2349           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2350                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2351       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2352         ++LHSIndexCounts[MaskIndex];
2353       if (!IsLHSOrUndefIndex)
2354         ++RHSIndexCounts[MaskIndex - NumElts];
2355     }
2356   }
2357 
2358   if (SwapOps) {
2359     std::swap(V1, V2);
2360     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2361   }
2362 
2363   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2364   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2365   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2366 
2367   if (IsSelect)
2368     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2369 
2370   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2371     // On such a large vector we're unable to use i8 as the index type.
2372     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2373     // may involve vector splitting if we're already at LMUL=8, or our
2374     // user-supplied maximum fixed-length LMUL.
2375     return SDValue();
2376   }
2377 
2378   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2379   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2380   MVT IndexVT = VT.changeTypeToInteger();
2381   // Since we can't introduce illegal index types at this stage, use i16 and
2382   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2383   // than XLenVT.
2384   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2385     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2386     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2387   }
2388 
2389   MVT IndexContainerVT =
2390       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2391 
2392   SDValue Gather;
2393   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2394   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2395   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2396     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2397   } else {
2398     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2399     // If only one index is used, we can use a "splat" vrgather.
2400     // TODO: We can splat the most-common index and fix-up any stragglers, if
2401     // that's beneficial.
2402     if (LHSIndexCounts.size() == 1) {
2403       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2404       Gather =
2405           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2406                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2407     } else {
2408       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2409       LHSIndices =
2410           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2411 
2412       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2413                            TrueMask, VL);
2414     }
2415   }
2416 
2417   // If a second vector operand is used by this shuffle, blend it in with an
2418   // additional vrgather.
2419   if (!V2.isUndef()) {
2420     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2421     // If only one index is used, we can use a "splat" vrgather.
2422     // TODO: We can splat the most-common index and fix-up any stragglers, if
2423     // that's beneficial.
2424     if (RHSIndexCounts.size() == 1) {
2425       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2426       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2427                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2428     } else {
2429       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2430       RHSIndices =
2431           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2432       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2433                        VL);
2434     }
2435 
2436     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2437     SelectMask =
2438         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2439 
2440     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2441                          Gather, VL);
2442   }
2443 
2444   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2445 }
2446 
2447 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2448                                      SDLoc DL, SelectionDAG &DAG,
2449                                      const RISCVSubtarget &Subtarget) {
2450   if (VT.isScalableVector())
2451     return DAG.getFPExtendOrRound(Op, DL, VT);
2452   assert(VT.isFixedLengthVector() &&
2453          "Unexpected value type for RVV FP extend/round lowering");
2454   SDValue Mask, VL;
2455   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2456   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2457                         ? RISCVISD::FP_EXTEND_VL
2458                         : RISCVISD::FP_ROUND_VL;
2459   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2460 }
2461 
2462 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2463 // the exponent.
2464 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2465   MVT VT = Op.getSimpleValueType();
2466   unsigned EltSize = VT.getScalarSizeInBits();
2467   SDValue Src = Op.getOperand(0);
2468   SDLoc DL(Op);
2469 
2470   // We need a FP type that can represent the value.
2471   // TODO: Use f16 for i8 when possible?
2472   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2473   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2474 
2475   // Legal types should have been checked in the RISCVTargetLowering
2476   // constructor.
2477   // TODO: Splitting may make sense in some cases.
2478   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2479          "Expected legal float type!");
2480 
2481   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2482   // The trailing zero count is equal to log2 of this single bit value.
2483   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2484     SDValue Neg =
2485         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2486     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2487   }
2488 
2489   // We have a legal FP type, convert to it.
2490   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2491   // Bitcast to integer and shift the exponent to the LSB.
2492   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2493   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2494   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2495   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2496                               DAG.getConstant(ShiftAmt, DL, IntVT));
2497   // Truncate back to original type to allow vnsrl.
2498   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2499   // The exponent contains log2 of the value in biased form.
2500   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2501 
2502   // For trailing zeros, we just need to subtract the bias.
2503   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2504     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2505                        DAG.getConstant(ExponentBias, DL, VT));
2506 
2507   // For leading zeros, we need to remove the bias and convert from log2 to
2508   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2509   unsigned Adjust = ExponentBias + (EltSize - 1);
2510   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2511 }
2512 
2513 // While RVV has alignment restrictions, we should always be able to load as a
2514 // legal equivalently-sized byte-typed vector instead. This method is
2515 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2516 // the load is already correctly-aligned, it returns SDValue().
2517 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2518                                                     SelectionDAG &DAG) const {
2519   auto *Load = cast<LoadSDNode>(Op);
2520   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2521 
2522   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2523                                      Load->getMemoryVT(),
2524                                      *Load->getMemOperand()))
2525     return SDValue();
2526 
2527   SDLoc DL(Op);
2528   MVT VT = Op.getSimpleValueType();
2529   unsigned EltSizeBits = VT.getScalarSizeInBits();
2530   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2531          "Unexpected unaligned RVV load type");
2532   MVT NewVT =
2533       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2534   assert(NewVT.isValid() &&
2535          "Expecting equally-sized RVV vector types to be legal");
2536   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2537                           Load->getPointerInfo(), Load->getOriginalAlign(),
2538                           Load->getMemOperand()->getFlags());
2539   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2540 }
2541 
2542 // While RVV has alignment restrictions, we should always be able to store as a
2543 // legal equivalently-sized byte-typed vector instead. This method is
2544 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2545 // returns SDValue() if the store is already correctly aligned.
2546 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2547                                                      SelectionDAG &DAG) const {
2548   auto *Store = cast<StoreSDNode>(Op);
2549   assert(Store && Store->getValue().getValueType().isVector() &&
2550          "Expected vector store");
2551 
2552   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2553                                      Store->getMemoryVT(),
2554                                      *Store->getMemOperand()))
2555     return SDValue();
2556 
2557   SDLoc DL(Op);
2558   SDValue StoredVal = Store->getValue();
2559   MVT VT = StoredVal.getSimpleValueType();
2560   unsigned EltSizeBits = VT.getScalarSizeInBits();
2561   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2562          "Unexpected unaligned RVV store type");
2563   MVT NewVT =
2564       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2565   assert(NewVT.isValid() &&
2566          "Expecting equally-sized RVV vector types to be legal");
2567   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2568   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2569                       Store->getPointerInfo(), Store->getOriginalAlign(),
2570                       Store->getMemOperand()->getFlags());
2571 }
2572 
2573 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2574                                             SelectionDAG &DAG) const {
2575   switch (Op.getOpcode()) {
2576   default:
2577     report_fatal_error("unimplemented operand");
2578   case ISD::GlobalAddress:
2579     return lowerGlobalAddress(Op, DAG);
2580   case ISD::BlockAddress:
2581     return lowerBlockAddress(Op, DAG);
2582   case ISD::ConstantPool:
2583     return lowerConstantPool(Op, DAG);
2584   case ISD::JumpTable:
2585     return lowerJumpTable(Op, DAG);
2586   case ISD::GlobalTLSAddress:
2587     return lowerGlobalTLSAddress(Op, DAG);
2588   case ISD::SELECT:
2589     return lowerSELECT(Op, DAG);
2590   case ISD::BRCOND:
2591     return lowerBRCOND(Op, DAG);
2592   case ISD::VASTART:
2593     return lowerVASTART(Op, DAG);
2594   case ISD::FRAMEADDR:
2595     return lowerFRAMEADDR(Op, DAG);
2596   case ISD::RETURNADDR:
2597     return lowerRETURNADDR(Op, DAG);
2598   case ISD::SHL_PARTS:
2599     return lowerShiftLeftParts(Op, DAG);
2600   case ISD::SRA_PARTS:
2601     return lowerShiftRightParts(Op, DAG, true);
2602   case ISD::SRL_PARTS:
2603     return lowerShiftRightParts(Op, DAG, false);
2604   case ISD::BITCAST: {
2605     SDLoc DL(Op);
2606     EVT VT = Op.getValueType();
2607     SDValue Op0 = Op.getOperand(0);
2608     EVT Op0VT = Op0.getValueType();
2609     MVT XLenVT = Subtarget.getXLenVT();
2610     if (VT.isFixedLengthVector()) {
2611       // We can handle fixed length vector bitcasts with a simple replacement
2612       // in isel.
2613       if (Op0VT.isFixedLengthVector())
2614         return Op;
2615       // When bitcasting from scalar to fixed-length vector, insert the scalar
2616       // into a one-element vector of the result type, and perform a vector
2617       // bitcast.
2618       if (!Op0VT.isVector()) {
2619         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2620         if (!isTypeLegal(BVT))
2621           return SDValue();
2622         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2623                                               DAG.getUNDEF(BVT), Op0,
2624                                               DAG.getConstant(0, DL, XLenVT)));
2625       }
2626       return SDValue();
2627     }
2628     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2629     // thus: bitcast the vector to a one-element vector type whose element type
2630     // is the same as the result type, and extract the first element.
2631     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2632       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2633       if (!isTypeLegal(BVT))
2634         return SDValue();
2635       SDValue BVec = DAG.getBitcast(BVT, Op0);
2636       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2637                          DAG.getConstant(0, DL, XLenVT));
2638     }
2639     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2640       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2641       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2642       return FPConv;
2643     }
2644     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2645         Subtarget.hasStdExtF()) {
2646       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2647       SDValue FPConv =
2648           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2649       return FPConv;
2650     }
2651     return SDValue();
2652   }
2653   case ISD::INTRINSIC_WO_CHAIN:
2654     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2655   case ISD::INTRINSIC_W_CHAIN:
2656     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2657   case ISD::INTRINSIC_VOID:
2658     return LowerINTRINSIC_VOID(Op, DAG);
2659   case ISD::BSWAP:
2660   case ISD::BITREVERSE: {
2661     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2662     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2663     MVT VT = Op.getSimpleValueType();
2664     SDLoc DL(Op);
2665     // Start with the maximum immediate value which is the bitwidth - 1.
2666     unsigned Imm = VT.getSizeInBits() - 1;
2667     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2668     if (Op.getOpcode() == ISD::BSWAP)
2669       Imm &= ~0x7U;
2670     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2671                        DAG.getConstant(Imm, DL, VT));
2672   }
2673   case ISD::FSHL:
2674   case ISD::FSHR: {
2675     MVT VT = Op.getSimpleValueType();
2676     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2677     SDLoc DL(Op);
2678     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2679       return Op;
2680     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2681     // use log(XLen) bits. Mask the shift amount accordingly.
2682     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2683     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2684                                 DAG.getConstant(ShAmtWidth, DL, VT));
2685     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2686     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2687   }
2688   case ISD::TRUNCATE: {
2689     SDLoc DL(Op);
2690     MVT VT = Op.getSimpleValueType();
2691     // Only custom-lower vector truncates
2692     if (!VT.isVector())
2693       return Op;
2694 
2695     // Truncates to mask types are handled differently
2696     if (VT.getVectorElementType() == MVT::i1)
2697       return lowerVectorMaskTrunc(Op, DAG);
2698 
2699     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2700     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2701     // truncate by one power of two at a time.
2702     MVT DstEltVT = VT.getVectorElementType();
2703 
2704     SDValue Src = Op.getOperand(0);
2705     MVT SrcVT = Src.getSimpleValueType();
2706     MVT SrcEltVT = SrcVT.getVectorElementType();
2707 
2708     assert(DstEltVT.bitsLT(SrcEltVT) &&
2709            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2710            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2711            "Unexpected vector truncate lowering");
2712 
2713     MVT ContainerVT = SrcVT;
2714     if (SrcVT.isFixedLengthVector()) {
2715       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2716       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2717     }
2718 
2719     SDValue Result = Src;
2720     SDValue Mask, VL;
2721     std::tie(Mask, VL) =
2722         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2723     LLVMContext &Context = *DAG.getContext();
2724     const ElementCount Count = ContainerVT.getVectorElementCount();
2725     do {
2726       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2727       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2728       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2729                            Mask, VL);
2730     } while (SrcEltVT != DstEltVT);
2731 
2732     if (SrcVT.isFixedLengthVector())
2733       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2734 
2735     return Result;
2736   }
2737   case ISD::ANY_EXTEND:
2738   case ISD::ZERO_EXTEND:
2739     if (Op.getOperand(0).getValueType().isVector() &&
2740         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2741       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2742     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2743   case ISD::SIGN_EXTEND:
2744     if (Op.getOperand(0).getValueType().isVector() &&
2745         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2746       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2747     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2748   case ISD::SPLAT_VECTOR_PARTS:
2749     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2750   case ISD::INSERT_VECTOR_ELT:
2751     return lowerINSERT_VECTOR_ELT(Op, DAG);
2752   case ISD::EXTRACT_VECTOR_ELT:
2753     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2754   case ISD::VSCALE: {
2755     MVT VT = Op.getSimpleValueType();
2756     SDLoc DL(Op);
2757     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2758     // We define our scalable vector types for lmul=1 to use a 64 bit known
2759     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2760     // vscale as VLENB / 8.
2761     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2762     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2763       // We assume VLENB is a multiple of 8. We manually choose the best shift
2764       // here because SimplifyDemandedBits isn't always able to simplify it.
2765       uint64_t Val = Op.getConstantOperandVal(0);
2766       if (isPowerOf2_64(Val)) {
2767         uint64_t Log2 = Log2_64(Val);
2768         if (Log2 < 3)
2769           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2770                              DAG.getConstant(3 - Log2, DL, VT));
2771         if (Log2 > 3)
2772           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2773                              DAG.getConstant(Log2 - 3, DL, VT));
2774         return VLENB;
2775       }
2776       // If the multiplier is a multiple of 8, scale it down to avoid needing
2777       // to shift the VLENB value.
2778       if ((Val % 8) == 0)
2779         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2780                            DAG.getConstant(Val / 8, DL, VT));
2781     }
2782 
2783     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2784                                  DAG.getConstant(3, DL, VT));
2785     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2786   }
2787   case ISD::FPOWI: {
2788     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
2789     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
2790     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
2791         Op.getOperand(1).getValueType() == MVT::i32) {
2792       SDLoc DL(Op);
2793       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
2794       SDValue Powi =
2795           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
2796       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
2797                          DAG.getIntPtrConstant(0, DL));
2798     }
2799     return SDValue();
2800   }
2801   case ISD::FP_EXTEND: {
2802     // RVV can only do fp_extend to types double the size as the source. We
2803     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2804     // via f32.
2805     SDLoc DL(Op);
2806     MVT VT = Op.getSimpleValueType();
2807     SDValue Src = Op.getOperand(0);
2808     MVT SrcVT = Src.getSimpleValueType();
2809 
2810     // Prepare any fixed-length vector operands.
2811     MVT ContainerVT = VT;
2812     if (SrcVT.isFixedLengthVector()) {
2813       ContainerVT = getContainerForFixedLengthVector(VT);
2814       MVT SrcContainerVT =
2815           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2816       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2817     }
2818 
2819     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2820         SrcVT.getVectorElementType() != MVT::f16) {
2821       // For scalable vectors, we only need to close the gap between
2822       // vXf16->vXf64.
2823       if (!VT.isFixedLengthVector())
2824         return Op;
2825       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2826       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2827       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2828     }
2829 
2830     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2831     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2832     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2833         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2834 
2835     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2836                                            DL, DAG, Subtarget);
2837     if (VT.isFixedLengthVector())
2838       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2839     return Extend;
2840   }
2841   case ISD::FP_ROUND: {
2842     // RVV can only do fp_round to types half the size as the source. We
2843     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2844     // conversion instruction.
2845     SDLoc DL(Op);
2846     MVT VT = Op.getSimpleValueType();
2847     SDValue Src = Op.getOperand(0);
2848     MVT SrcVT = Src.getSimpleValueType();
2849 
2850     // Prepare any fixed-length vector operands.
2851     MVT ContainerVT = VT;
2852     if (VT.isFixedLengthVector()) {
2853       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2854       ContainerVT =
2855           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2856       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2857     }
2858 
2859     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2860         SrcVT.getVectorElementType() != MVT::f64) {
2861       // For scalable vectors, we only need to close the gap between
2862       // vXf64<->vXf16.
2863       if (!VT.isFixedLengthVector())
2864         return Op;
2865       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2866       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2867       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2868     }
2869 
2870     SDValue Mask, VL;
2871     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2872 
2873     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2874     SDValue IntermediateRound =
2875         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2876     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2877                                           DL, DAG, Subtarget);
2878 
2879     if (VT.isFixedLengthVector())
2880       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2881     return Round;
2882   }
2883   case ISD::FP_TO_SINT:
2884   case ISD::FP_TO_UINT:
2885   case ISD::SINT_TO_FP:
2886   case ISD::UINT_TO_FP: {
2887     // RVV can only do fp<->int conversions to types half/double the size as
2888     // the source. We custom-lower any conversions that do two hops into
2889     // sequences.
2890     MVT VT = Op.getSimpleValueType();
2891     if (!VT.isVector())
2892       return Op;
2893     SDLoc DL(Op);
2894     SDValue Src = Op.getOperand(0);
2895     MVT EltVT = VT.getVectorElementType();
2896     MVT SrcVT = Src.getSimpleValueType();
2897     MVT SrcEltVT = SrcVT.getVectorElementType();
2898     unsigned EltSize = EltVT.getSizeInBits();
2899     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2900     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2901            "Unexpected vector element types");
2902 
2903     bool IsInt2FP = SrcEltVT.isInteger();
2904     // Widening conversions
2905     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2906       if (IsInt2FP) {
2907         // Do a regular integer sign/zero extension then convert to float.
2908         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2909                                       VT.getVectorElementCount());
2910         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2911                                  ? ISD::ZERO_EXTEND
2912                                  : ISD::SIGN_EXTEND;
2913         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2914         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2915       }
2916       // FP2Int
2917       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2918       // Do one doubling fp_extend then complete the operation by converting
2919       // to int.
2920       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2921       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2922       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2923     }
2924 
2925     // Narrowing conversions
2926     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2927       if (IsInt2FP) {
2928         // One narrowing int_to_fp, then an fp_round.
2929         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2930         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2931         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2932         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2933       }
2934       // FP2Int
2935       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2936       // representable by the integer, the result is poison.
2937       MVT IVecVT =
2938           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2939                            VT.getVectorElementCount());
2940       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2941       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2942     }
2943 
2944     // Scalable vectors can exit here. Patterns will handle equally-sized
2945     // conversions halving/doubling ones.
2946     if (!VT.isFixedLengthVector())
2947       return Op;
2948 
2949     // For fixed-length vectors we lower to a custom "VL" node.
2950     unsigned RVVOpc = 0;
2951     switch (Op.getOpcode()) {
2952     default:
2953       llvm_unreachable("Impossible opcode");
2954     case ISD::FP_TO_SINT:
2955       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2956       break;
2957     case ISD::FP_TO_UINT:
2958       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2959       break;
2960     case ISD::SINT_TO_FP:
2961       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2962       break;
2963     case ISD::UINT_TO_FP:
2964       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2965       break;
2966     }
2967 
2968     MVT ContainerVT, SrcContainerVT;
2969     // Derive the reference container type from the larger vector type.
2970     if (SrcEltSize > EltSize) {
2971       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2972       ContainerVT =
2973           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2974     } else {
2975       ContainerVT = getContainerForFixedLengthVector(VT);
2976       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2977     }
2978 
2979     SDValue Mask, VL;
2980     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2981 
2982     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2983     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2984     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2985   }
2986   case ISD::FP_TO_SINT_SAT:
2987   case ISD::FP_TO_UINT_SAT:
2988     return lowerFP_TO_INT_SAT(Op, DAG);
2989   case ISD::FTRUNC:
2990   case ISD::FCEIL:
2991   case ISD::FFLOOR:
2992     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
2993   case ISD::VECREDUCE_ADD:
2994   case ISD::VECREDUCE_UMAX:
2995   case ISD::VECREDUCE_SMAX:
2996   case ISD::VECREDUCE_UMIN:
2997   case ISD::VECREDUCE_SMIN:
2998     return lowerVECREDUCE(Op, DAG);
2999   case ISD::VECREDUCE_AND:
3000   case ISD::VECREDUCE_OR:
3001   case ISD::VECREDUCE_XOR:
3002     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3003       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3004     return lowerVECREDUCE(Op, DAG);
3005   case ISD::VECREDUCE_FADD:
3006   case ISD::VECREDUCE_SEQ_FADD:
3007   case ISD::VECREDUCE_FMIN:
3008   case ISD::VECREDUCE_FMAX:
3009     return lowerFPVECREDUCE(Op, DAG);
3010   case ISD::VP_REDUCE_ADD:
3011   case ISD::VP_REDUCE_UMAX:
3012   case ISD::VP_REDUCE_SMAX:
3013   case ISD::VP_REDUCE_UMIN:
3014   case ISD::VP_REDUCE_SMIN:
3015   case ISD::VP_REDUCE_FADD:
3016   case ISD::VP_REDUCE_SEQ_FADD:
3017   case ISD::VP_REDUCE_FMIN:
3018   case ISD::VP_REDUCE_FMAX:
3019     return lowerVPREDUCE(Op, DAG);
3020   case ISD::VP_REDUCE_AND:
3021   case ISD::VP_REDUCE_OR:
3022   case ISD::VP_REDUCE_XOR:
3023     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3024       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3025     return lowerVPREDUCE(Op, DAG);
3026   case ISD::INSERT_SUBVECTOR:
3027     return lowerINSERT_SUBVECTOR(Op, DAG);
3028   case ISD::EXTRACT_SUBVECTOR:
3029     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3030   case ISD::STEP_VECTOR:
3031     return lowerSTEP_VECTOR(Op, DAG);
3032   case ISD::VECTOR_REVERSE:
3033     return lowerVECTOR_REVERSE(Op, DAG);
3034   case ISD::BUILD_VECTOR:
3035     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3036   case ISD::SPLAT_VECTOR:
3037     if (Op.getValueType().getVectorElementType() == MVT::i1)
3038       return lowerVectorMaskSplat(Op, DAG);
3039     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3040   case ISD::VECTOR_SHUFFLE:
3041     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3042   case ISD::CONCAT_VECTORS: {
3043     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3044     // better than going through the stack, as the default expansion does.
3045     SDLoc DL(Op);
3046     MVT VT = Op.getSimpleValueType();
3047     unsigned NumOpElts =
3048         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3049     SDValue Vec = DAG.getUNDEF(VT);
3050     for (const auto &OpIdx : enumerate(Op->ops()))
3051       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
3052                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3053     return Vec;
3054   }
3055   case ISD::LOAD:
3056     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3057       return V;
3058     if (Op.getValueType().isFixedLengthVector())
3059       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3060     return Op;
3061   case ISD::STORE:
3062     if (auto V = expandUnalignedRVVStore(Op, DAG))
3063       return V;
3064     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3065       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3066     return Op;
3067   case ISD::MLOAD:
3068   case ISD::VP_LOAD:
3069     return lowerMaskedLoad(Op, DAG);
3070   case ISD::MSTORE:
3071   case ISD::VP_STORE:
3072     return lowerMaskedStore(Op, DAG);
3073   case ISD::SETCC:
3074     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3075   case ISD::ADD:
3076     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3077   case ISD::SUB:
3078     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3079   case ISD::MUL:
3080     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3081   case ISD::MULHS:
3082     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3083   case ISD::MULHU:
3084     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3085   case ISD::AND:
3086     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3087                                               RISCVISD::AND_VL);
3088   case ISD::OR:
3089     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3090                                               RISCVISD::OR_VL);
3091   case ISD::XOR:
3092     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3093                                               RISCVISD::XOR_VL);
3094   case ISD::SDIV:
3095     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3096   case ISD::SREM:
3097     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3098   case ISD::UDIV:
3099     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3100   case ISD::UREM:
3101     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3102   case ISD::SHL:
3103   case ISD::SRA:
3104   case ISD::SRL:
3105     if (Op.getSimpleValueType().isFixedLengthVector())
3106       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3107     // This can be called for an i32 shift amount that needs to be promoted.
3108     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3109            "Unexpected custom legalisation");
3110     return SDValue();
3111   case ISD::SADDSAT:
3112     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3113   case ISD::UADDSAT:
3114     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3115   case ISD::SSUBSAT:
3116     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3117   case ISD::USUBSAT:
3118     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3119   case ISD::FADD:
3120     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3121   case ISD::FSUB:
3122     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3123   case ISD::FMUL:
3124     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3125   case ISD::FDIV:
3126     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3127   case ISD::FNEG:
3128     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3129   case ISD::FABS:
3130     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3131   case ISD::FSQRT:
3132     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3133   case ISD::FMA:
3134     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3135   case ISD::SMIN:
3136     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3137   case ISD::SMAX:
3138     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3139   case ISD::UMIN:
3140     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3141   case ISD::UMAX:
3142     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3143   case ISD::FMINNUM:
3144     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3145   case ISD::FMAXNUM:
3146     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3147   case ISD::ABS:
3148     return lowerABS(Op, DAG);
3149   case ISD::CTLZ_ZERO_UNDEF:
3150   case ISD::CTTZ_ZERO_UNDEF:
3151     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3152   case ISD::VSELECT:
3153     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3154   case ISD::FCOPYSIGN:
3155     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3156   case ISD::MGATHER:
3157   case ISD::VP_GATHER:
3158     return lowerMaskedGather(Op, DAG);
3159   case ISD::MSCATTER:
3160   case ISD::VP_SCATTER:
3161     return lowerMaskedScatter(Op, DAG);
3162   case ISD::FLT_ROUNDS_:
3163     return lowerGET_ROUNDING(Op, DAG);
3164   case ISD::SET_ROUNDING:
3165     return lowerSET_ROUNDING(Op, DAG);
3166   case ISD::VP_SELECT:
3167     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3168   case ISD::VP_ADD:
3169     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3170   case ISD::VP_SUB:
3171     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3172   case ISD::VP_MUL:
3173     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3174   case ISD::VP_SDIV:
3175     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3176   case ISD::VP_UDIV:
3177     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3178   case ISD::VP_SREM:
3179     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3180   case ISD::VP_UREM:
3181     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3182   case ISD::VP_AND:
3183     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
3184   case ISD::VP_OR:
3185     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
3186   case ISD::VP_XOR:
3187     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
3188   case ISD::VP_ASHR:
3189     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3190   case ISD::VP_LSHR:
3191     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3192   case ISD::VP_SHL:
3193     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3194   case ISD::VP_FADD:
3195     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3196   case ISD::VP_FSUB:
3197     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3198   case ISD::VP_FMUL:
3199     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3200   case ISD::VP_FDIV:
3201     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3202   }
3203 }
3204 
3205 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3206                              SelectionDAG &DAG, unsigned Flags) {
3207   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3208 }
3209 
3210 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3211                              SelectionDAG &DAG, unsigned Flags) {
3212   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3213                                    Flags);
3214 }
3215 
3216 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3217                              SelectionDAG &DAG, unsigned Flags) {
3218   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3219                                    N->getOffset(), Flags);
3220 }
3221 
3222 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3223                              SelectionDAG &DAG, unsigned Flags) {
3224   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3225 }
3226 
3227 template <class NodeTy>
3228 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3229                                      bool IsLocal) const {
3230   SDLoc DL(N);
3231   EVT Ty = getPointerTy(DAG.getDataLayout());
3232 
3233   if (isPositionIndependent()) {
3234     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3235     if (IsLocal)
3236       // Use PC-relative addressing to access the symbol. This generates the
3237       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3238       // %pcrel_lo(auipc)).
3239       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3240 
3241     // Use PC-relative addressing to access the GOT for this symbol, then load
3242     // the address from the GOT. This generates the pattern (PseudoLA sym),
3243     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3244     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3245   }
3246 
3247   switch (getTargetMachine().getCodeModel()) {
3248   default:
3249     report_fatal_error("Unsupported code model for lowering");
3250   case CodeModel::Small: {
3251     // Generate a sequence for accessing addresses within the first 2 GiB of
3252     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3253     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3254     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3255     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3256     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3257   }
3258   case CodeModel::Medium: {
3259     // Generate a sequence for accessing addresses within any 2GiB range within
3260     // the address space. This generates the pattern (PseudoLLA sym), which
3261     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3262     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3263     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3264   }
3265   }
3266 }
3267 
3268 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3269                                                 SelectionDAG &DAG) const {
3270   SDLoc DL(Op);
3271   EVT Ty = Op.getValueType();
3272   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3273   int64_t Offset = N->getOffset();
3274   MVT XLenVT = Subtarget.getXLenVT();
3275 
3276   const GlobalValue *GV = N->getGlobal();
3277   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3278   SDValue Addr = getAddr(N, DAG, IsLocal);
3279 
3280   // In order to maximise the opportunity for common subexpression elimination,
3281   // emit a separate ADD node for the global address offset instead of folding
3282   // it in the global address node. Later peephole optimisations may choose to
3283   // fold it back in when profitable.
3284   if (Offset != 0)
3285     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3286                        DAG.getConstant(Offset, DL, XLenVT));
3287   return Addr;
3288 }
3289 
3290 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3291                                                SelectionDAG &DAG) const {
3292   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3293 
3294   return getAddr(N, DAG);
3295 }
3296 
3297 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3298                                                SelectionDAG &DAG) const {
3299   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3300 
3301   return getAddr(N, DAG);
3302 }
3303 
3304 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3305                                             SelectionDAG &DAG) const {
3306   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3307 
3308   return getAddr(N, DAG);
3309 }
3310 
3311 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3312                                               SelectionDAG &DAG,
3313                                               bool UseGOT) const {
3314   SDLoc DL(N);
3315   EVT Ty = getPointerTy(DAG.getDataLayout());
3316   const GlobalValue *GV = N->getGlobal();
3317   MVT XLenVT = Subtarget.getXLenVT();
3318 
3319   if (UseGOT) {
3320     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3321     // load the address from the GOT and add the thread pointer. This generates
3322     // the pattern (PseudoLA_TLS_IE sym), which expands to
3323     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3324     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3325     SDValue Load =
3326         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3327 
3328     // Add the thread pointer.
3329     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3330     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3331   }
3332 
3333   // Generate a sequence for accessing the address relative to the thread
3334   // pointer, with the appropriate adjustment for the thread pointer offset.
3335   // This generates the pattern
3336   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3337   SDValue AddrHi =
3338       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3339   SDValue AddrAdd =
3340       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3341   SDValue AddrLo =
3342       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3343 
3344   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3345   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3346   SDValue MNAdd = SDValue(
3347       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3348       0);
3349   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3350 }
3351 
3352 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3353                                                SelectionDAG &DAG) const {
3354   SDLoc DL(N);
3355   EVT Ty = getPointerTy(DAG.getDataLayout());
3356   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3357   const GlobalValue *GV = N->getGlobal();
3358 
3359   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3360   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3361   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3362   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3363   SDValue Load =
3364       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3365 
3366   // Prepare argument list to generate call.
3367   ArgListTy Args;
3368   ArgListEntry Entry;
3369   Entry.Node = Load;
3370   Entry.Ty = CallTy;
3371   Args.push_back(Entry);
3372 
3373   // Setup call to __tls_get_addr.
3374   TargetLowering::CallLoweringInfo CLI(DAG);
3375   CLI.setDebugLoc(DL)
3376       .setChain(DAG.getEntryNode())
3377       .setLibCallee(CallingConv::C, CallTy,
3378                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3379                     std::move(Args));
3380 
3381   return LowerCallTo(CLI).first;
3382 }
3383 
3384 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3385                                                    SelectionDAG &DAG) const {
3386   SDLoc DL(Op);
3387   EVT Ty = Op.getValueType();
3388   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3389   int64_t Offset = N->getOffset();
3390   MVT XLenVT = Subtarget.getXLenVT();
3391 
3392   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3393 
3394   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3395       CallingConv::GHC)
3396     report_fatal_error("In GHC calling convention TLS is not supported");
3397 
3398   SDValue Addr;
3399   switch (Model) {
3400   case TLSModel::LocalExec:
3401     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3402     break;
3403   case TLSModel::InitialExec:
3404     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3405     break;
3406   case TLSModel::LocalDynamic:
3407   case TLSModel::GeneralDynamic:
3408     Addr = getDynamicTLSAddr(N, DAG);
3409     break;
3410   }
3411 
3412   // In order to maximise the opportunity for common subexpression elimination,
3413   // emit a separate ADD node for the global address offset instead of folding
3414   // it in the global address node. Later peephole optimisations may choose to
3415   // fold it back in when profitable.
3416   if (Offset != 0)
3417     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3418                        DAG.getConstant(Offset, DL, XLenVT));
3419   return Addr;
3420 }
3421 
3422 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3423   SDValue CondV = Op.getOperand(0);
3424   SDValue TrueV = Op.getOperand(1);
3425   SDValue FalseV = Op.getOperand(2);
3426   SDLoc DL(Op);
3427   MVT VT = Op.getSimpleValueType();
3428   MVT XLenVT = Subtarget.getXLenVT();
3429 
3430   // Lower vector SELECTs to VSELECTs by splatting the condition.
3431   if (VT.isVector()) {
3432     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3433     SDValue CondSplat = VT.isScalableVector()
3434                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3435                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3436     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3437   }
3438 
3439   // If the result type is XLenVT and CondV is the output of a SETCC node
3440   // which also operated on XLenVT inputs, then merge the SETCC node into the
3441   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3442   // compare+branch instructions. i.e.:
3443   // (select (setcc lhs, rhs, cc), truev, falsev)
3444   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3445   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3446       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3447     SDValue LHS = CondV.getOperand(0);
3448     SDValue RHS = CondV.getOperand(1);
3449     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3450     ISD::CondCode CCVal = CC->get();
3451 
3452     // Special case for a select of 2 constants that have a diffence of 1.
3453     // Normally this is done by DAGCombine, but if the select is introduced by
3454     // type legalization or op legalization, we miss it. Restricting to SETLT
3455     // case for now because that is what signed saturating add/sub need.
3456     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3457     // but we would probably want to swap the true/false values if the condition
3458     // is SETGE/SETLE to avoid an XORI.
3459     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3460         CCVal == ISD::SETLT) {
3461       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3462       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3463       if (TrueVal - 1 == FalseVal)
3464         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3465       if (TrueVal + 1 == FalseVal)
3466         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3467     }
3468 
3469     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3470 
3471     SDValue TargetCC = DAG.getCondCode(CCVal);
3472     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3473     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3474   }
3475 
3476   // Otherwise:
3477   // (select condv, truev, falsev)
3478   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3479   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3480   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3481 
3482   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3483 
3484   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3485 }
3486 
3487 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3488   SDValue CondV = Op.getOperand(1);
3489   SDLoc DL(Op);
3490   MVT XLenVT = Subtarget.getXLenVT();
3491 
3492   if (CondV.getOpcode() == ISD::SETCC &&
3493       CondV.getOperand(0).getValueType() == XLenVT) {
3494     SDValue LHS = CondV.getOperand(0);
3495     SDValue RHS = CondV.getOperand(1);
3496     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3497 
3498     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3499 
3500     SDValue TargetCC = DAG.getCondCode(CCVal);
3501     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3502                        LHS, RHS, TargetCC, Op.getOperand(2));
3503   }
3504 
3505   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3506                      CondV, DAG.getConstant(0, DL, XLenVT),
3507                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3508 }
3509 
3510 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3511   MachineFunction &MF = DAG.getMachineFunction();
3512   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3513 
3514   SDLoc DL(Op);
3515   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3516                                  getPointerTy(MF.getDataLayout()));
3517 
3518   // vastart just stores the address of the VarArgsFrameIndex slot into the
3519   // memory location argument.
3520   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3521   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3522                       MachinePointerInfo(SV));
3523 }
3524 
3525 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3526                                             SelectionDAG &DAG) const {
3527   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3528   MachineFunction &MF = DAG.getMachineFunction();
3529   MachineFrameInfo &MFI = MF.getFrameInfo();
3530   MFI.setFrameAddressIsTaken(true);
3531   Register FrameReg = RI.getFrameRegister(MF);
3532   int XLenInBytes = Subtarget.getXLen() / 8;
3533 
3534   EVT VT = Op.getValueType();
3535   SDLoc DL(Op);
3536   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3537   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3538   while (Depth--) {
3539     int Offset = -(XLenInBytes * 2);
3540     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3541                               DAG.getIntPtrConstant(Offset, DL));
3542     FrameAddr =
3543         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3544   }
3545   return FrameAddr;
3546 }
3547 
3548 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3549                                              SelectionDAG &DAG) const {
3550   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3551   MachineFunction &MF = DAG.getMachineFunction();
3552   MachineFrameInfo &MFI = MF.getFrameInfo();
3553   MFI.setReturnAddressIsTaken(true);
3554   MVT XLenVT = Subtarget.getXLenVT();
3555   int XLenInBytes = Subtarget.getXLen() / 8;
3556 
3557   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3558     return SDValue();
3559 
3560   EVT VT = Op.getValueType();
3561   SDLoc DL(Op);
3562   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3563   if (Depth) {
3564     int Off = -XLenInBytes;
3565     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3566     SDValue Offset = DAG.getConstant(Off, DL, VT);
3567     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3568                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3569                        MachinePointerInfo());
3570   }
3571 
3572   // Return the value of the return address register, marking it an implicit
3573   // live-in.
3574   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3575   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3576 }
3577 
3578 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3579                                                  SelectionDAG &DAG) const {
3580   SDLoc DL(Op);
3581   SDValue Lo = Op.getOperand(0);
3582   SDValue Hi = Op.getOperand(1);
3583   SDValue Shamt = Op.getOperand(2);
3584   EVT VT = Lo.getValueType();
3585 
3586   // if Shamt-XLEN < 0: // Shamt < XLEN
3587   //   Lo = Lo << Shamt
3588   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3589   // else:
3590   //   Lo = 0
3591   //   Hi = Lo << (Shamt-XLEN)
3592 
3593   SDValue Zero = DAG.getConstant(0, DL, VT);
3594   SDValue One = DAG.getConstant(1, DL, VT);
3595   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3596   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3597   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3598   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3599 
3600   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3601   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3602   SDValue ShiftRightLo =
3603       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3604   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3605   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3606   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3607 
3608   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3609 
3610   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3611   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3612 
3613   SDValue Parts[2] = {Lo, Hi};
3614   return DAG.getMergeValues(Parts, DL);
3615 }
3616 
3617 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3618                                                   bool IsSRA) const {
3619   SDLoc DL(Op);
3620   SDValue Lo = Op.getOperand(0);
3621   SDValue Hi = Op.getOperand(1);
3622   SDValue Shamt = Op.getOperand(2);
3623   EVT VT = Lo.getValueType();
3624 
3625   // SRA expansion:
3626   //   if Shamt-XLEN < 0: // Shamt < XLEN
3627   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3628   //     Hi = Hi >>s Shamt
3629   //   else:
3630   //     Lo = Hi >>s (Shamt-XLEN);
3631   //     Hi = Hi >>s (XLEN-1)
3632   //
3633   // SRL expansion:
3634   //   if Shamt-XLEN < 0: // Shamt < XLEN
3635   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3636   //     Hi = Hi >>u Shamt
3637   //   else:
3638   //     Lo = Hi >>u (Shamt-XLEN);
3639   //     Hi = 0;
3640 
3641   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3642 
3643   SDValue Zero = DAG.getConstant(0, DL, VT);
3644   SDValue One = DAG.getConstant(1, DL, VT);
3645   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3646   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3647   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3648   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3649 
3650   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3651   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3652   SDValue ShiftLeftHi =
3653       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3654   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3655   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3656   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3657   SDValue HiFalse =
3658       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3659 
3660   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3661 
3662   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3663   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3664 
3665   SDValue Parts[2] = {Lo, Hi};
3666   return DAG.getMergeValues(Parts, DL);
3667 }
3668 
3669 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3670 // legal equivalently-sized i8 type, so we can use that as a go-between.
3671 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3672                                                   SelectionDAG &DAG) const {
3673   SDLoc DL(Op);
3674   MVT VT = Op.getSimpleValueType();
3675   SDValue SplatVal = Op.getOperand(0);
3676   // All-zeros or all-ones splats are handled specially.
3677   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3678     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3679     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3680   }
3681   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3682     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3683     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3684   }
3685   MVT XLenVT = Subtarget.getXLenVT();
3686   assert(SplatVal.getValueType() == XLenVT &&
3687          "Unexpected type for i1 splat value");
3688   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3689   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3690                          DAG.getConstant(1, DL, XLenVT));
3691   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3692   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3693   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3694 }
3695 
3696 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3697 // illegal (currently only vXi64 RV32).
3698 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3699 // them to SPLAT_VECTOR_I64
3700 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3701                                                      SelectionDAG &DAG) const {
3702   SDLoc DL(Op);
3703   MVT VecVT = Op.getSimpleValueType();
3704   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3705          "Unexpected SPLAT_VECTOR_PARTS lowering");
3706 
3707   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3708   SDValue Lo = Op.getOperand(0);
3709   SDValue Hi = Op.getOperand(1);
3710 
3711   if (VecVT.isFixedLengthVector()) {
3712     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3713     SDLoc DL(Op);
3714     SDValue Mask, VL;
3715     std::tie(Mask, VL) =
3716         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3717 
3718     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3719     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3720   }
3721 
3722   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3723     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3724     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3725     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3726     // node in order to try and match RVV vector/scalar instructions.
3727     if ((LoC >> 31) == HiC)
3728       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3729   }
3730 
3731   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3732   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3733       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3734       Hi.getConstantOperandVal(1) == 31)
3735     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3736 
3737   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3738   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3739                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3740 }
3741 
3742 // Custom-lower extensions from mask vectors by using a vselect either with 1
3743 // for zero/any-extension or -1 for sign-extension:
3744 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3745 // Note that any-extension is lowered identically to zero-extension.
3746 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3747                                                 int64_t ExtTrueVal) const {
3748   SDLoc DL(Op);
3749   MVT VecVT = Op.getSimpleValueType();
3750   SDValue Src = Op.getOperand(0);
3751   // Only custom-lower extensions from mask types
3752   assert(Src.getValueType().isVector() &&
3753          Src.getValueType().getVectorElementType() == MVT::i1);
3754 
3755   MVT XLenVT = Subtarget.getXLenVT();
3756   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3757   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3758 
3759   if (VecVT.isScalableVector()) {
3760     // Be careful not to introduce illegal scalar types at this stage, and be
3761     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3762     // illegal and must be expanded. Since we know that the constants are
3763     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3764     bool IsRV32E64 =
3765         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3766 
3767     if (!IsRV32E64) {
3768       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3769       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3770     } else {
3771       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3772       SplatTrueVal =
3773           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3774     }
3775 
3776     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3777   }
3778 
3779   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3780   MVT I1ContainerVT =
3781       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3782 
3783   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3784 
3785   SDValue Mask, VL;
3786   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3787 
3788   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3789   SplatTrueVal =
3790       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3791   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3792                                SplatTrueVal, SplatZero, VL);
3793 
3794   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3795 }
3796 
3797 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3798     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3799   MVT ExtVT = Op.getSimpleValueType();
3800   // Only custom-lower extensions from fixed-length vector types.
3801   if (!ExtVT.isFixedLengthVector())
3802     return Op;
3803   MVT VT = Op.getOperand(0).getSimpleValueType();
3804   // Grab the canonical container type for the extended type. Infer the smaller
3805   // type from that to ensure the same number of vector elements, as we know
3806   // the LMUL will be sufficient to hold the smaller type.
3807   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3808   // Get the extended container type manually to ensure the same number of
3809   // vector elements between source and dest.
3810   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3811                                      ContainerExtVT.getVectorElementCount());
3812 
3813   SDValue Op1 =
3814       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3815 
3816   SDLoc DL(Op);
3817   SDValue Mask, VL;
3818   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3819 
3820   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3821 
3822   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3823 }
3824 
3825 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3826 // setcc operation:
3827 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3828 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3829                                                   SelectionDAG &DAG) const {
3830   SDLoc DL(Op);
3831   EVT MaskVT = Op.getValueType();
3832   // Only expect to custom-lower truncations to mask types
3833   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3834          "Unexpected type for vector mask lowering");
3835   SDValue Src = Op.getOperand(0);
3836   MVT VecVT = Src.getSimpleValueType();
3837 
3838   // If this is a fixed vector, we need to convert it to a scalable vector.
3839   MVT ContainerVT = VecVT;
3840   if (VecVT.isFixedLengthVector()) {
3841     ContainerVT = getContainerForFixedLengthVector(VecVT);
3842     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3843   }
3844 
3845   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3846   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3847 
3848   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3849   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3850 
3851   if (VecVT.isScalableVector()) {
3852     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3853     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3854   }
3855 
3856   SDValue Mask, VL;
3857   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3858 
3859   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3860   SDValue Trunc =
3861       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3862   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3863                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3864   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3865 }
3866 
3867 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3868 // first position of a vector, and that vector is slid up to the insert index.
3869 // By limiting the active vector length to index+1 and merging with the
3870 // original vector (with an undisturbed tail policy for elements >= VL), we
3871 // achieve the desired result of leaving all elements untouched except the one
3872 // at VL-1, which is replaced with the desired value.
3873 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3874                                                     SelectionDAG &DAG) const {
3875   SDLoc DL(Op);
3876   MVT VecVT = Op.getSimpleValueType();
3877   SDValue Vec = Op.getOperand(0);
3878   SDValue Val = Op.getOperand(1);
3879   SDValue Idx = Op.getOperand(2);
3880 
3881   if (VecVT.getVectorElementType() == MVT::i1) {
3882     // FIXME: For now we just promote to an i8 vector and insert into that,
3883     // but this is probably not optimal.
3884     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3885     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3886     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3887     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3888   }
3889 
3890   MVT ContainerVT = VecVT;
3891   // If the operand is a fixed-length vector, convert to a scalable one.
3892   if (VecVT.isFixedLengthVector()) {
3893     ContainerVT = getContainerForFixedLengthVector(VecVT);
3894     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3895   }
3896 
3897   MVT XLenVT = Subtarget.getXLenVT();
3898 
3899   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3900   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3901   // Even i64-element vectors on RV32 can be lowered without scalar
3902   // legalization if the most-significant 32 bits of the value are not affected
3903   // by the sign-extension of the lower 32 bits.
3904   // TODO: We could also catch sign extensions of a 32-bit value.
3905   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3906     const auto *CVal = cast<ConstantSDNode>(Val);
3907     if (isInt<32>(CVal->getSExtValue())) {
3908       IsLegalInsert = true;
3909       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3910     }
3911   }
3912 
3913   SDValue Mask, VL;
3914   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3915 
3916   SDValue ValInVec;
3917 
3918   if (IsLegalInsert) {
3919     unsigned Opc =
3920         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3921     if (isNullConstant(Idx)) {
3922       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3923       if (!VecVT.isFixedLengthVector())
3924         return Vec;
3925       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3926     }
3927     ValInVec =
3928         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3929   } else {
3930     // On RV32, i64-element vectors must be specially handled to place the
3931     // value at element 0, by using two vslide1up instructions in sequence on
3932     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3933     // this.
3934     SDValue One = DAG.getConstant(1, DL, XLenVT);
3935     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3936     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3937     MVT I32ContainerVT =
3938         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3939     SDValue I32Mask =
3940         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3941     // Limit the active VL to two.
3942     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3943     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3944     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3945     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3946                            InsertI64VL);
3947     // First slide in the hi value, then the lo in underneath it.
3948     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3949                            ValHi, I32Mask, InsertI64VL);
3950     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3951                            ValLo, I32Mask, InsertI64VL);
3952     // Bitcast back to the right container type.
3953     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3954   }
3955 
3956   // Now that the value is in a vector, slide it into position.
3957   SDValue InsertVL =
3958       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3959   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3960                                 ValInVec, Idx, Mask, InsertVL);
3961   if (!VecVT.isFixedLengthVector())
3962     return Slideup;
3963   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3964 }
3965 
3966 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3967 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3968 // types this is done using VMV_X_S to allow us to glean information about the
3969 // sign bits of the result.
3970 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3971                                                      SelectionDAG &DAG) const {
3972   SDLoc DL(Op);
3973   SDValue Idx = Op.getOperand(1);
3974   SDValue Vec = Op.getOperand(0);
3975   EVT EltVT = Op.getValueType();
3976   MVT VecVT = Vec.getSimpleValueType();
3977   MVT XLenVT = Subtarget.getXLenVT();
3978 
3979   if (VecVT.getVectorElementType() == MVT::i1) {
3980     // FIXME: For now we just promote to an i8 vector and extract from that,
3981     // but this is probably not optimal.
3982     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3983     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3984     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3985   }
3986 
3987   // If this is a fixed vector, we need to convert it to a scalable vector.
3988   MVT ContainerVT = VecVT;
3989   if (VecVT.isFixedLengthVector()) {
3990     ContainerVT = getContainerForFixedLengthVector(VecVT);
3991     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3992   }
3993 
3994   // If the index is 0, the vector is already in the right position.
3995   if (!isNullConstant(Idx)) {
3996     // Use a VL of 1 to avoid processing more elements than we need.
3997     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3998     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3999     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4000     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4001                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4002   }
4003 
4004   if (!EltVT.isInteger()) {
4005     // Floating-point extracts are handled in TableGen.
4006     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4007                        DAG.getConstant(0, DL, XLenVT));
4008   }
4009 
4010   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4011   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4012 }
4013 
4014 // Some RVV intrinsics may claim that they want an integer operand to be
4015 // promoted or expanded.
4016 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4017                                           const RISCVSubtarget &Subtarget) {
4018   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4019           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4020          "Unexpected opcode");
4021 
4022   if (!Subtarget.hasVInstructions())
4023     return SDValue();
4024 
4025   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4026   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4027   SDLoc DL(Op);
4028 
4029   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4030       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4031   if (!II || !II->SplatOperand)
4032     return SDValue();
4033 
4034   unsigned SplatOp = II->SplatOperand + HasChain;
4035   assert(SplatOp < Op.getNumOperands());
4036 
4037   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4038   SDValue &ScalarOp = Operands[SplatOp];
4039   MVT OpVT = ScalarOp.getSimpleValueType();
4040   MVT XLenVT = Subtarget.getXLenVT();
4041 
4042   // If this isn't a scalar, or its type is XLenVT we're done.
4043   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4044     return SDValue();
4045 
4046   // Simplest case is that the operand needs to be promoted to XLenVT.
4047   if (OpVT.bitsLT(XLenVT)) {
4048     // If the operand is a constant, sign extend to increase our chances
4049     // of being able to use a .vi instruction. ANY_EXTEND would become a
4050     // a zero extend and the simm5 check in isel would fail.
4051     // FIXME: Should we ignore the upper bits in isel instead?
4052     unsigned ExtOpc =
4053         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4054     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4055     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4056   }
4057 
4058   // Use the previous operand to get the vXi64 VT. The result might be a mask
4059   // VT for compares. Using the previous operand assumes that the previous
4060   // operand will never have a smaller element size than a scalar operand and
4061   // that a widening operation never uses SEW=64.
4062   // NOTE: If this fails the below assert, we can probably just find the
4063   // element count from any operand or result and use it to construct the VT.
4064   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
4065   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4066 
4067   // The more complex case is when the scalar is larger than XLenVT.
4068   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4069          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4070 
4071   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4072   // on the instruction to sign-extend since SEW>XLEN.
4073   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4074     if (isInt<32>(CVal->getSExtValue())) {
4075       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4076       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4077     }
4078   }
4079 
4080   // We need to convert the scalar to a splat vector.
4081   // FIXME: Can we implicitly truncate the scalar if it is known to
4082   // be sign extended?
4083   // VL should be the last operand.
4084   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
4085   assert(VL.getValueType() == XLenVT);
4086   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4087   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4088 }
4089 
4090 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4091                                                      SelectionDAG &DAG) const {
4092   unsigned IntNo = Op.getConstantOperandVal(0);
4093   SDLoc DL(Op);
4094   MVT XLenVT = Subtarget.getXLenVT();
4095 
4096   switch (IntNo) {
4097   default:
4098     break; // Don't custom lower most intrinsics.
4099   case Intrinsic::thread_pointer: {
4100     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4101     return DAG.getRegister(RISCV::X4, PtrVT);
4102   }
4103   case Intrinsic::riscv_orc_b:
4104     // Lower to the GORCI encoding for orc.b.
4105     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4106                        DAG.getConstant(7, DL, XLenVT));
4107   case Intrinsic::riscv_grev:
4108   case Intrinsic::riscv_gorc: {
4109     unsigned Opc =
4110         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4111     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4112   }
4113   case Intrinsic::riscv_shfl:
4114   case Intrinsic::riscv_unshfl: {
4115     unsigned Opc =
4116         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4117     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4118   }
4119   case Intrinsic::riscv_bcompress:
4120   case Intrinsic::riscv_bdecompress: {
4121     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4122                                                        : RISCVISD::BDECOMPRESS;
4123     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4124   }
4125   case Intrinsic::riscv_vmv_x_s:
4126     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4127     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4128                        Op.getOperand(1));
4129   case Intrinsic::riscv_vmv_v_x:
4130     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4131                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4132   case Intrinsic::riscv_vfmv_v_f:
4133     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4134                        Op.getOperand(1), Op.getOperand(2));
4135   case Intrinsic::riscv_vmv_s_x: {
4136     SDValue Scalar = Op.getOperand(2);
4137 
4138     if (Scalar.getValueType().bitsLE(XLenVT)) {
4139       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4140       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4141                          Op.getOperand(1), Scalar, Op.getOperand(3));
4142     }
4143 
4144     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4145 
4146     // This is an i64 value that lives in two scalar registers. We have to
4147     // insert this in a convoluted way. First we build vXi64 splat containing
4148     // the/ two values that we assemble using some bit math. Next we'll use
4149     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4150     // to merge element 0 from our splat into the source vector.
4151     // FIXME: This is probably not the best way to do this, but it is
4152     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4153     // point.
4154     //   sw lo, (a0)
4155     //   sw hi, 4(a0)
4156     //   vlse vX, (a0)
4157     //
4158     //   vid.v      vVid
4159     //   vmseq.vx   mMask, vVid, 0
4160     //   vmerge.vvm vDest, vSrc, vVal, mMask
4161     MVT VT = Op.getSimpleValueType();
4162     SDValue Vec = Op.getOperand(1);
4163     SDValue VL = Op.getOperand(3);
4164 
4165     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4166     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4167                                       DAG.getConstant(0, DL, MVT::i32), VL);
4168 
4169     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4170     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4171     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4172     SDValue SelectCond =
4173         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4174                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4175     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4176                        Vec, VL);
4177   }
4178   case Intrinsic::riscv_vslide1up:
4179   case Intrinsic::riscv_vslide1down:
4180   case Intrinsic::riscv_vslide1up_mask:
4181   case Intrinsic::riscv_vslide1down_mask: {
4182     // We need to special case these when the scalar is larger than XLen.
4183     unsigned NumOps = Op.getNumOperands();
4184     bool IsMasked = NumOps == 7;
4185     unsigned OpOffset = IsMasked ? 1 : 0;
4186     SDValue Scalar = Op.getOperand(2 + OpOffset);
4187     if (Scalar.getValueType().bitsLE(XLenVT))
4188       break;
4189 
4190     // Splatting a sign extended constant is fine.
4191     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4192       if (isInt<32>(CVal->getSExtValue()))
4193         break;
4194 
4195     MVT VT = Op.getSimpleValueType();
4196     assert(VT.getVectorElementType() == MVT::i64 &&
4197            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4198 
4199     // Convert the vector source to the equivalent nxvXi32 vector.
4200     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4201     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4202 
4203     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4204                                    DAG.getConstant(0, DL, XLenVT));
4205     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4206                                    DAG.getConstant(1, DL, XLenVT));
4207 
4208     // Double the VL since we halved SEW.
4209     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4210     SDValue I32VL =
4211         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4212 
4213     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4214     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4215 
4216     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4217     // instructions.
4218     if (IntNo == Intrinsic::riscv_vslide1up ||
4219         IntNo == Intrinsic::riscv_vslide1up_mask) {
4220       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4221                         I32Mask, I32VL);
4222       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4223                         I32Mask, I32VL);
4224     } else {
4225       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4226                         I32Mask, I32VL);
4227       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4228                         I32Mask, I32VL);
4229     }
4230 
4231     // Convert back to nxvXi64.
4232     Vec = DAG.getBitcast(VT, Vec);
4233 
4234     if (!IsMasked)
4235       return Vec;
4236 
4237     // Apply mask after the operation.
4238     SDValue Mask = Op.getOperand(NumOps - 3);
4239     SDValue MaskedOff = Op.getOperand(1);
4240     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4241   }
4242   }
4243 
4244   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4245 }
4246 
4247 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4248                                                     SelectionDAG &DAG) const {
4249   unsigned IntNo = Op.getConstantOperandVal(1);
4250   switch (IntNo) {
4251   default:
4252     break;
4253   case Intrinsic::riscv_masked_strided_load: {
4254     SDLoc DL(Op);
4255     MVT XLenVT = Subtarget.getXLenVT();
4256 
4257     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4258     // the selection of the masked intrinsics doesn't do this for us.
4259     SDValue Mask = Op.getOperand(5);
4260     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4261 
4262     MVT VT = Op->getSimpleValueType(0);
4263     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4264 
4265     SDValue PassThru = Op.getOperand(2);
4266     if (!IsUnmasked) {
4267       MVT MaskVT =
4268           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4269       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4270       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4271     }
4272 
4273     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4274 
4275     SDValue IntID = DAG.getTargetConstant(
4276         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4277         XLenVT);
4278 
4279     auto *Load = cast<MemIntrinsicSDNode>(Op);
4280     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4281     if (!IsUnmasked)
4282       Ops.push_back(PassThru);
4283     Ops.push_back(Op.getOperand(3)); // Ptr
4284     Ops.push_back(Op.getOperand(4)); // Stride
4285     if (!IsUnmasked)
4286       Ops.push_back(Mask);
4287     Ops.push_back(VL);
4288     if (!IsUnmasked) {
4289       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4290       Ops.push_back(Policy);
4291     }
4292 
4293     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4294     SDValue Result =
4295         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4296                                 Load->getMemoryVT(), Load->getMemOperand());
4297     SDValue Chain = Result.getValue(1);
4298     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4299     return DAG.getMergeValues({Result, Chain}, DL);
4300   }
4301   }
4302 
4303   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4304 }
4305 
4306 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4307                                                  SelectionDAG &DAG) const {
4308   unsigned IntNo = Op.getConstantOperandVal(1);
4309   switch (IntNo) {
4310   default:
4311     break;
4312   case Intrinsic::riscv_masked_strided_store: {
4313     SDLoc DL(Op);
4314     MVT XLenVT = Subtarget.getXLenVT();
4315 
4316     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4317     // the selection of the masked intrinsics doesn't do this for us.
4318     SDValue Mask = Op.getOperand(5);
4319     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4320 
4321     SDValue Val = Op.getOperand(2);
4322     MVT VT = Val.getSimpleValueType();
4323     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4324 
4325     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4326     if (!IsUnmasked) {
4327       MVT MaskVT =
4328           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4329       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4330     }
4331 
4332     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4333 
4334     SDValue IntID = DAG.getTargetConstant(
4335         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4336         XLenVT);
4337 
4338     auto *Store = cast<MemIntrinsicSDNode>(Op);
4339     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4340     Ops.push_back(Val);
4341     Ops.push_back(Op.getOperand(3)); // Ptr
4342     Ops.push_back(Op.getOperand(4)); // Stride
4343     if (!IsUnmasked)
4344       Ops.push_back(Mask);
4345     Ops.push_back(VL);
4346 
4347     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4348                                    Ops, Store->getMemoryVT(),
4349                                    Store->getMemOperand());
4350   }
4351   }
4352 
4353   return SDValue();
4354 }
4355 
4356 static MVT getLMUL1VT(MVT VT) {
4357   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4358          "Unexpected vector MVT");
4359   return MVT::getScalableVectorVT(
4360       VT.getVectorElementType(),
4361       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4362 }
4363 
4364 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4365   switch (ISDOpcode) {
4366   default:
4367     llvm_unreachable("Unhandled reduction");
4368   case ISD::VECREDUCE_ADD:
4369     return RISCVISD::VECREDUCE_ADD_VL;
4370   case ISD::VECREDUCE_UMAX:
4371     return RISCVISD::VECREDUCE_UMAX_VL;
4372   case ISD::VECREDUCE_SMAX:
4373     return RISCVISD::VECREDUCE_SMAX_VL;
4374   case ISD::VECREDUCE_UMIN:
4375     return RISCVISD::VECREDUCE_UMIN_VL;
4376   case ISD::VECREDUCE_SMIN:
4377     return RISCVISD::VECREDUCE_SMIN_VL;
4378   case ISD::VECREDUCE_AND:
4379     return RISCVISD::VECREDUCE_AND_VL;
4380   case ISD::VECREDUCE_OR:
4381     return RISCVISD::VECREDUCE_OR_VL;
4382   case ISD::VECREDUCE_XOR:
4383     return RISCVISD::VECREDUCE_XOR_VL;
4384   }
4385 }
4386 
4387 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4388                                                          SelectionDAG &DAG,
4389                                                          bool IsVP) const {
4390   SDLoc DL(Op);
4391   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4392   MVT VecVT = Vec.getSimpleValueType();
4393   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4394           Op.getOpcode() == ISD::VECREDUCE_OR ||
4395           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4396           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4397           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4398           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4399          "Unexpected reduction lowering");
4400 
4401   MVT XLenVT = Subtarget.getXLenVT();
4402   assert(Op.getValueType() == XLenVT &&
4403          "Expected reduction output to be legalized to XLenVT");
4404 
4405   MVT ContainerVT = VecVT;
4406   if (VecVT.isFixedLengthVector()) {
4407     ContainerVT = getContainerForFixedLengthVector(VecVT);
4408     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4409   }
4410 
4411   SDValue Mask, VL;
4412   if (IsVP) {
4413     Mask = Op.getOperand(2);
4414     VL = Op.getOperand(3);
4415   } else {
4416     std::tie(Mask, VL) =
4417         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4418   }
4419 
4420   unsigned BaseOpc;
4421   ISD::CondCode CC;
4422   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4423 
4424   switch (Op.getOpcode()) {
4425   default:
4426     llvm_unreachable("Unhandled reduction");
4427   case ISD::VECREDUCE_AND:
4428   case ISD::VP_REDUCE_AND: {
4429     // vcpop ~x == 0
4430     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4431     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4432     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4433     CC = ISD::SETEQ;
4434     BaseOpc = ISD::AND;
4435     break;
4436   }
4437   case ISD::VECREDUCE_OR:
4438   case ISD::VP_REDUCE_OR:
4439     // vcpop x != 0
4440     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4441     CC = ISD::SETNE;
4442     BaseOpc = ISD::OR;
4443     break;
4444   case ISD::VECREDUCE_XOR:
4445   case ISD::VP_REDUCE_XOR: {
4446     // ((vcpop x) & 1) != 0
4447     SDValue One = DAG.getConstant(1, DL, XLenVT);
4448     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4449     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4450     CC = ISD::SETNE;
4451     BaseOpc = ISD::XOR;
4452     break;
4453   }
4454   }
4455 
4456   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4457 
4458   if (!IsVP)
4459     return SetCC;
4460 
4461   // Now include the start value in the operation.
4462   // Note that we must return the start value when no elements are operated
4463   // upon. The vcpop instructions we've emitted in each case above will return
4464   // 0 for an inactive vector, and so we've already received the neutral value:
4465   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4466   // can simply include the start value.
4467   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4468 }
4469 
4470 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4471                                             SelectionDAG &DAG) const {
4472   SDLoc DL(Op);
4473   SDValue Vec = Op.getOperand(0);
4474   EVT VecEVT = Vec.getValueType();
4475 
4476   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4477 
4478   // Due to ordering in legalize types we may have a vector type that needs to
4479   // be split. Do that manually so we can get down to a legal type.
4480   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4481          TargetLowering::TypeSplitVector) {
4482     SDValue Lo, Hi;
4483     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4484     VecEVT = Lo.getValueType();
4485     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4486   }
4487 
4488   // TODO: The type may need to be widened rather than split. Or widened before
4489   // it can be split.
4490   if (!isTypeLegal(VecEVT))
4491     return SDValue();
4492 
4493   MVT VecVT = VecEVT.getSimpleVT();
4494   MVT VecEltVT = VecVT.getVectorElementType();
4495   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4496 
4497   MVT ContainerVT = VecVT;
4498   if (VecVT.isFixedLengthVector()) {
4499     ContainerVT = getContainerForFixedLengthVector(VecVT);
4500     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4501   }
4502 
4503   MVT M1VT = getLMUL1VT(ContainerVT);
4504   MVT XLenVT = Subtarget.getXLenVT();
4505 
4506   SDValue Mask, VL;
4507   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4508 
4509   SDValue NeutralElem =
4510       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4511   SDValue IdentitySplat = lowerScalarSplat(
4512       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4513   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4514                                   IdentitySplat, Mask, VL);
4515   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4516                              DAG.getConstant(0, DL, XLenVT));
4517   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4518 }
4519 
4520 // Given a reduction op, this function returns the matching reduction opcode,
4521 // the vector SDValue and the scalar SDValue required to lower this to a
4522 // RISCVISD node.
4523 static std::tuple<unsigned, SDValue, SDValue>
4524 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4525   SDLoc DL(Op);
4526   auto Flags = Op->getFlags();
4527   unsigned Opcode = Op.getOpcode();
4528   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4529   switch (Opcode) {
4530   default:
4531     llvm_unreachable("Unhandled reduction");
4532   case ISD::VECREDUCE_FADD:
4533     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4534                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4535   case ISD::VECREDUCE_SEQ_FADD:
4536     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4537                            Op.getOperand(0));
4538   case ISD::VECREDUCE_FMIN:
4539     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4540                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4541   case ISD::VECREDUCE_FMAX:
4542     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4543                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4544   }
4545 }
4546 
4547 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4548                                               SelectionDAG &DAG) const {
4549   SDLoc DL(Op);
4550   MVT VecEltVT = Op.getSimpleValueType();
4551 
4552   unsigned RVVOpcode;
4553   SDValue VectorVal, ScalarVal;
4554   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4555       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4556   MVT VecVT = VectorVal.getSimpleValueType();
4557 
4558   MVT ContainerVT = VecVT;
4559   if (VecVT.isFixedLengthVector()) {
4560     ContainerVT = getContainerForFixedLengthVector(VecVT);
4561     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4562   }
4563 
4564   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4565   MVT XLenVT = Subtarget.getXLenVT();
4566 
4567   SDValue Mask, VL;
4568   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4569 
4570   SDValue ScalarSplat = lowerScalarSplat(
4571       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4572   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4573                                   VectorVal, ScalarSplat, Mask, VL);
4574   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4575                      DAG.getConstant(0, DL, XLenVT));
4576 }
4577 
4578 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4579   switch (ISDOpcode) {
4580   default:
4581     llvm_unreachable("Unhandled reduction");
4582   case ISD::VP_REDUCE_ADD:
4583     return RISCVISD::VECREDUCE_ADD_VL;
4584   case ISD::VP_REDUCE_UMAX:
4585     return RISCVISD::VECREDUCE_UMAX_VL;
4586   case ISD::VP_REDUCE_SMAX:
4587     return RISCVISD::VECREDUCE_SMAX_VL;
4588   case ISD::VP_REDUCE_UMIN:
4589     return RISCVISD::VECREDUCE_UMIN_VL;
4590   case ISD::VP_REDUCE_SMIN:
4591     return RISCVISD::VECREDUCE_SMIN_VL;
4592   case ISD::VP_REDUCE_AND:
4593     return RISCVISD::VECREDUCE_AND_VL;
4594   case ISD::VP_REDUCE_OR:
4595     return RISCVISD::VECREDUCE_OR_VL;
4596   case ISD::VP_REDUCE_XOR:
4597     return RISCVISD::VECREDUCE_XOR_VL;
4598   case ISD::VP_REDUCE_FADD:
4599     return RISCVISD::VECREDUCE_FADD_VL;
4600   case ISD::VP_REDUCE_SEQ_FADD:
4601     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4602   case ISD::VP_REDUCE_FMAX:
4603     return RISCVISD::VECREDUCE_FMAX_VL;
4604   case ISD::VP_REDUCE_FMIN:
4605     return RISCVISD::VECREDUCE_FMIN_VL;
4606   }
4607 }
4608 
4609 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4610                                            SelectionDAG &DAG) const {
4611   SDLoc DL(Op);
4612   SDValue Vec = Op.getOperand(1);
4613   EVT VecEVT = Vec.getValueType();
4614 
4615   // TODO: The type may need to be widened rather than split. Or widened before
4616   // it can be split.
4617   if (!isTypeLegal(VecEVT))
4618     return SDValue();
4619 
4620   MVT VecVT = VecEVT.getSimpleVT();
4621   MVT VecEltVT = VecVT.getVectorElementType();
4622   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4623 
4624   MVT ContainerVT = VecVT;
4625   if (VecVT.isFixedLengthVector()) {
4626     ContainerVT = getContainerForFixedLengthVector(VecVT);
4627     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4628   }
4629 
4630   SDValue VL = Op.getOperand(3);
4631   SDValue Mask = Op.getOperand(2);
4632 
4633   MVT M1VT = getLMUL1VT(ContainerVT);
4634   MVT XLenVT = Subtarget.getXLenVT();
4635   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4636 
4637   SDValue StartSplat =
4638       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4639                        DL, DAG, Subtarget);
4640   SDValue Reduction =
4641       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4642   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4643                              DAG.getConstant(0, DL, XLenVT));
4644   if (!VecVT.isInteger())
4645     return Elt0;
4646   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4647 }
4648 
4649 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4650                                                    SelectionDAG &DAG) const {
4651   SDValue Vec = Op.getOperand(0);
4652   SDValue SubVec = Op.getOperand(1);
4653   MVT VecVT = Vec.getSimpleValueType();
4654   MVT SubVecVT = SubVec.getSimpleValueType();
4655 
4656   SDLoc DL(Op);
4657   MVT XLenVT = Subtarget.getXLenVT();
4658   unsigned OrigIdx = Op.getConstantOperandVal(2);
4659   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4660 
4661   // We don't have the ability to slide mask vectors up indexed by their i1
4662   // elements; the smallest we can do is i8. Often we are able to bitcast to
4663   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4664   // into a scalable one, we might not necessarily have enough scalable
4665   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4666   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4667       (OrigIdx != 0 || !Vec.isUndef())) {
4668     if (VecVT.getVectorMinNumElements() >= 8 &&
4669         SubVecVT.getVectorMinNumElements() >= 8) {
4670       assert(OrigIdx % 8 == 0 && "Invalid index");
4671       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4672              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4673              "Unexpected mask vector lowering");
4674       OrigIdx /= 8;
4675       SubVecVT =
4676           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4677                            SubVecVT.isScalableVector());
4678       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4679                                VecVT.isScalableVector());
4680       Vec = DAG.getBitcast(VecVT, Vec);
4681       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4682     } else {
4683       // We can't slide this mask vector up indexed by its i1 elements.
4684       // This poses a problem when we wish to insert a scalable vector which
4685       // can't be re-expressed as a larger type. Just choose the slow path and
4686       // extend to a larger type, then truncate back down.
4687       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4688       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4689       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4690       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4691       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4692                         Op.getOperand(2));
4693       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4694       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4695     }
4696   }
4697 
4698   // If the subvector vector is a fixed-length type, we cannot use subregister
4699   // manipulation to simplify the codegen; we don't know which register of a
4700   // LMUL group contains the specific subvector as we only know the minimum
4701   // register size. Therefore we must slide the vector group up the full
4702   // amount.
4703   if (SubVecVT.isFixedLengthVector()) {
4704     if (OrigIdx == 0 && Vec.isUndef())
4705       return Op;
4706     MVT ContainerVT = VecVT;
4707     if (VecVT.isFixedLengthVector()) {
4708       ContainerVT = getContainerForFixedLengthVector(VecVT);
4709       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4710     }
4711     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4712                          DAG.getUNDEF(ContainerVT), SubVec,
4713                          DAG.getConstant(0, DL, XLenVT));
4714     SDValue Mask =
4715         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4716     // Set the vector length to only the number of elements we care about. Note
4717     // that for slideup this includes the offset.
4718     SDValue VL =
4719         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4720     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4721     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4722                                   SubVec, SlideupAmt, Mask, VL);
4723     if (VecVT.isFixedLengthVector())
4724       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4725     return DAG.getBitcast(Op.getValueType(), Slideup);
4726   }
4727 
4728   unsigned SubRegIdx, RemIdx;
4729   std::tie(SubRegIdx, RemIdx) =
4730       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4731           VecVT, SubVecVT, OrigIdx, TRI);
4732 
4733   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4734   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4735                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4736                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4737 
4738   // 1. If the Idx has been completely eliminated and this subvector's size is
4739   // a vector register or a multiple thereof, or the surrounding elements are
4740   // undef, then this is a subvector insert which naturally aligns to a vector
4741   // register. These can easily be handled using subregister manipulation.
4742   // 2. If the subvector is smaller than a vector register, then the insertion
4743   // must preserve the undisturbed elements of the register. We do this by
4744   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4745   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4746   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4747   // LMUL=1 type back into the larger vector (resolving to another subregister
4748   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4749   // to avoid allocating a large register group to hold our subvector.
4750   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4751     return Op;
4752 
4753   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4754   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4755   // (in our case undisturbed). This means we can set up a subvector insertion
4756   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4757   // size of the subvector.
4758   MVT InterSubVT = VecVT;
4759   SDValue AlignedExtract = Vec;
4760   unsigned AlignedIdx = OrigIdx - RemIdx;
4761   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4762     InterSubVT = getLMUL1VT(VecVT);
4763     // Extract a subvector equal to the nearest full vector register type. This
4764     // should resolve to a EXTRACT_SUBREG instruction.
4765     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4766                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4767   }
4768 
4769   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4770   // For scalable vectors this must be further multiplied by vscale.
4771   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4772 
4773   SDValue Mask, VL;
4774   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4775 
4776   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4777   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4778   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4779   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4780 
4781   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4782                        DAG.getUNDEF(InterSubVT), SubVec,
4783                        DAG.getConstant(0, DL, XLenVT));
4784 
4785   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4786                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4787 
4788   // If required, insert this subvector back into the correct vector register.
4789   // This should resolve to an INSERT_SUBREG instruction.
4790   if (VecVT.bitsGT(InterSubVT))
4791     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4792                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4793 
4794   // We might have bitcast from a mask type: cast back to the original type if
4795   // required.
4796   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4797 }
4798 
4799 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4800                                                     SelectionDAG &DAG) const {
4801   SDValue Vec = Op.getOperand(0);
4802   MVT SubVecVT = Op.getSimpleValueType();
4803   MVT VecVT = Vec.getSimpleValueType();
4804 
4805   SDLoc DL(Op);
4806   MVT XLenVT = Subtarget.getXLenVT();
4807   unsigned OrigIdx = Op.getConstantOperandVal(1);
4808   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4809 
4810   // We don't have the ability to slide mask vectors down indexed by their i1
4811   // elements; the smallest we can do is i8. Often we are able to bitcast to
4812   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4813   // from a scalable one, we might not necessarily have enough scalable
4814   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4815   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4816     if (VecVT.getVectorMinNumElements() >= 8 &&
4817         SubVecVT.getVectorMinNumElements() >= 8) {
4818       assert(OrigIdx % 8 == 0 && "Invalid index");
4819       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4820              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4821              "Unexpected mask vector lowering");
4822       OrigIdx /= 8;
4823       SubVecVT =
4824           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4825                            SubVecVT.isScalableVector());
4826       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4827                                VecVT.isScalableVector());
4828       Vec = DAG.getBitcast(VecVT, Vec);
4829     } else {
4830       // We can't slide this mask vector down, indexed by its i1 elements.
4831       // This poses a problem when we wish to extract a scalable vector which
4832       // can't be re-expressed as a larger type. Just choose the slow path and
4833       // extend to a larger type, then truncate back down.
4834       // TODO: We could probably improve this when extracting certain fixed
4835       // from fixed, where we can extract as i8 and shift the correct element
4836       // right to reach the desired subvector?
4837       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4838       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4839       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4840       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4841                         Op.getOperand(1));
4842       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4843       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4844     }
4845   }
4846 
4847   // If the subvector vector is a fixed-length type, we cannot use subregister
4848   // manipulation to simplify the codegen; we don't know which register of a
4849   // LMUL group contains the specific subvector as we only know the minimum
4850   // register size. Therefore we must slide the vector group down the full
4851   // amount.
4852   if (SubVecVT.isFixedLengthVector()) {
4853     // With an index of 0 this is a cast-like subvector, which can be performed
4854     // with subregister operations.
4855     if (OrigIdx == 0)
4856       return Op;
4857     MVT ContainerVT = VecVT;
4858     if (VecVT.isFixedLengthVector()) {
4859       ContainerVT = getContainerForFixedLengthVector(VecVT);
4860       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4861     }
4862     SDValue Mask =
4863         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4864     // Set the vector length to only the number of elements we care about. This
4865     // avoids sliding down elements we're going to discard straight away.
4866     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4867     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4868     SDValue Slidedown =
4869         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4870                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4871     // Now we can use a cast-like subvector extract to get the result.
4872     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4873                             DAG.getConstant(0, DL, XLenVT));
4874     return DAG.getBitcast(Op.getValueType(), Slidedown);
4875   }
4876 
4877   unsigned SubRegIdx, RemIdx;
4878   std::tie(SubRegIdx, RemIdx) =
4879       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4880           VecVT, SubVecVT, OrigIdx, TRI);
4881 
4882   // If the Idx has been completely eliminated then this is a subvector extract
4883   // which naturally aligns to a vector register. These can easily be handled
4884   // using subregister manipulation.
4885   if (RemIdx == 0)
4886     return Op;
4887 
4888   // Else we must shift our vector register directly to extract the subvector.
4889   // Do this using VSLIDEDOWN.
4890 
4891   // If the vector type is an LMUL-group type, extract a subvector equal to the
4892   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4893   // instruction.
4894   MVT InterSubVT = VecVT;
4895   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4896     InterSubVT = getLMUL1VT(VecVT);
4897     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4898                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4899   }
4900 
4901   // Slide this vector register down by the desired number of elements in order
4902   // to place the desired subvector starting at element 0.
4903   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4904   // For scalable vectors this must be further multiplied by vscale.
4905   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4906 
4907   SDValue Mask, VL;
4908   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4909   SDValue Slidedown =
4910       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4911                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4912 
4913   // Now the vector is in the right position, extract our final subvector. This
4914   // should resolve to a COPY.
4915   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4916                           DAG.getConstant(0, DL, XLenVT));
4917 
4918   // We might have bitcast from a mask type: cast back to the original type if
4919   // required.
4920   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4921 }
4922 
4923 // Lower step_vector to the vid instruction. Any non-identity step value must
4924 // be accounted for my manual expansion.
4925 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4926                                               SelectionDAG &DAG) const {
4927   SDLoc DL(Op);
4928   MVT VT = Op.getSimpleValueType();
4929   MVT XLenVT = Subtarget.getXLenVT();
4930   SDValue Mask, VL;
4931   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4932   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4933   uint64_t StepValImm = Op.getConstantOperandVal(0);
4934   if (StepValImm != 1) {
4935     if (isPowerOf2_64(StepValImm)) {
4936       SDValue StepVal =
4937           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4938                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4939       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4940     } else {
4941       SDValue StepVal = lowerScalarSplat(
4942           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4943           DL, DAG, Subtarget);
4944       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4945     }
4946   }
4947   return StepVec;
4948 }
4949 
4950 // Implement vector_reverse using vrgather.vv with indices determined by
4951 // subtracting the id of each element from (VLMAX-1). This will convert
4952 // the indices like so:
4953 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4954 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4955 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4956                                                  SelectionDAG &DAG) const {
4957   SDLoc DL(Op);
4958   MVT VecVT = Op.getSimpleValueType();
4959   unsigned EltSize = VecVT.getScalarSizeInBits();
4960   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4961 
4962   unsigned MaxVLMAX = 0;
4963   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4964   if (VectorBitsMax != 0)
4965     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4966 
4967   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4968   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4969 
4970   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4971   // to use vrgatherei16.vv.
4972   // TODO: It's also possible to use vrgatherei16.vv for other types to
4973   // decrease register width for the index calculation.
4974   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4975     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4976     // Reverse each half, then reassemble them in reverse order.
4977     // NOTE: It's also possible that after splitting that VLMAX no longer
4978     // requires vrgatherei16.vv.
4979     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4980       SDValue Lo, Hi;
4981       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4982       EVT LoVT, HiVT;
4983       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4984       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4985       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4986       // Reassemble the low and high pieces reversed.
4987       // FIXME: This is a CONCAT_VECTORS.
4988       SDValue Res =
4989           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4990                       DAG.getIntPtrConstant(0, DL));
4991       return DAG.getNode(
4992           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4993           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4994     }
4995 
4996     // Just promote the int type to i16 which will double the LMUL.
4997     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4998     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4999   }
5000 
5001   MVT XLenVT = Subtarget.getXLenVT();
5002   SDValue Mask, VL;
5003   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5004 
5005   // Calculate VLMAX-1 for the desired SEW.
5006   unsigned MinElts = VecVT.getVectorMinNumElements();
5007   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5008                               DAG.getConstant(MinElts, DL, XLenVT));
5009   SDValue VLMinus1 =
5010       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5011 
5012   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5013   bool IsRV32E64 =
5014       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5015   SDValue SplatVL;
5016   if (!IsRV32E64)
5017     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5018   else
5019     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5020 
5021   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5022   SDValue Indices =
5023       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5024 
5025   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5026 }
5027 
5028 SDValue
5029 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5030                                                      SelectionDAG &DAG) const {
5031   SDLoc DL(Op);
5032   auto *Load = cast<LoadSDNode>(Op);
5033 
5034   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5035                                         Load->getMemoryVT(),
5036                                         *Load->getMemOperand()) &&
5037          "Expecting a correctly-aligned load");
5038 
5039   MVT VT = Op.getSimpleValueType();
5040   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5041 
5042   SDValue VL =
5043       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5044 
5045   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5046   SDValue NewLoad = DAG.getMemIntrinsicNode(
5047       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5048       Load->getMemoryVT(), Load->getMemOperand());
5049 
5050   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5051   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5052 }
5053 
5054 SDValue
5055 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5056                                                       SelectionDAG &DAG) const {
5057   SDLoc DL(Op);
5058   auto *Store = cast<StoreSDNode>(Op);
5059 
5060   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5061                                         Store->getMemoryVT(),
5062                                         *Store->getMemOperand()) &&
5063          "Expecting a correctly-aligned store");
5064 
5065   SDValue StoreVal = Store->getValue();
5066   MVT VT = StoreVal.getSimpleValueType();
5067 
5068   // If the size less than a byte, we need to pad with zeros to make a byte.
5069   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5070     VT = MVT::v8i1;
5071     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5072                            DAG.getConstant(0, DL, VT), StoreVal,
5073                            DAG.getIntPtrConstant(0, DL));
5074   }
5075 
5076   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5077 
5078   SDValue VL =
5079       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5080 
5081   SDValue NewValue =
5082       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5083   return DAG.getMemIntrinsicNode(
5084       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5085       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5086       Store->getMemoryVT(), Store->getMemOperand());
5087 }
5088 
5089 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5090                                              SelectionDAG &DAG) const {
5091   SDLoc DL(Op);
5092   MVT VT = Op.getSimpleValueType();
5093 
5094   const auto *MemSD = cast<MemSDNode>(Op);
5095   EVT MemVT = MemSD->getMemoryVT();
5096   MachineMemOperand *MMO = MemSD->getMemOperand();
5097   SDValue Chain = MemSD->getChain();
5098   SDValue BasePtr = MemSD->getBasePtr();
5099 
5100   SDValue Mask, PassThru, VL;
5101   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5102     Mask = VPLoad->getMask();
5103     PassThru = DAG.getUNDEF(VT);
5104     VL = VPLoad->getVectorLength();
5105   } else {
5106     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5107     Mask = MLoad->getMask();
5108     PassThru = MLoad->getPassThru();
5109   }
5110 
5111   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5112 
5113   MVT XLenVT = Subtarget.getXLenVT();
5114 
5115   MVT ContainerVT = VT;
5116   if (VT.isFixedLengthVector()) {
5117     ContainerVT = getContainerForFixedLengthVector(VT);
5118     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5119     if (!IsUnmasked) {
5120       MVT MaskVT =
5121           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5122       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5123     }
5124   }
5125 
5126   if (!VL)
5127     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5128 
5129   unsigned IntID =
5130       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5131   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5132   if (!IsUnmasked)
5133     Ops.push_back(PassThru);
5134   Ops.push_back(BasePtr);
5135   if (!IsUnmasked)
5136     Ops.push_back(Mask);
5137   Ops.push_back(VL);
5138   if (!IsUnmasked)
5139     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5140 
5141   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5142 
5143   SDValue Result =
5144       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5145   Chain = Result.getValue(1);
5146 
5147   if (VT.isFixedLengthVector())
5148     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5149 
5150   return DAG.getMergeValues({Result, Chain}, DL);
5151 }
5152 
5153 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5154                                               SelectionDAG &DAG) const {
5155   SDLoc DL(Op);
5156 
5157   const auto *MemSD = cast<MemSDNode>(Op);
5158   EVT MemVT = MemSD->getMemoryVT();
5159   MachineMemOperand *MMO = MemSD->getMemOperand();
5160   SDValue Chain = MemSD->getChain();
5161   SDValue BasePtr = MemSD->getBasePtr();
5162   SDValue Val, Mask, VL;
5163 
5164   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5165     Val = VPStore->getValue();
5166     Mask = VPStore->getMask();
5167     VL = VPStore->getVectorLength();
5168   } else {
5169     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5170     Val = MStore->getValue();
5171     Mask = MStore->getMask();
5172   }
5173 
5174   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5175 
5176   MVT VT = Val.getSimpleValueType();
5177   MVT XLenVT = Subtarget.getXLenVT();
5178 
5179   MVT ContainerVT = VT;
5180   if (VT.isFixedLengthVector()) {
5181     ContainerVT = getContainerForFixedLengthVector(VT);
5182 
5183     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5184     if (!IsUnmasked) {
5185       MVT MaskVT =
5186           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5187       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5188     }
5189   }
5190 
5191   if (!VL)
5192     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5193 
5194   unsigned IntID =
5195       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5196   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5197   Ops.push_back(Val);
5198   Ops.push_back(BasePtr);
5199   if (!IsUnmasked)
5200     Ops.push_back(Mask);
5201   Ops.push_back(VL);
5202 
5203   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5204                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5205 }
5206 
5207 SDValue
5208 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5209                                                       SelectionDAG &DAG) const {
5210   MVT InVT = Op.getOperand(0).getSimpleValueType();
5211   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5212 
5213   MVT VT = Op.getSimpleValueType();
5214 
5215   SDValue Op1 =
5216       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5217   SDValue Op2 =
5218       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5219 
5220   SDLoc DL(Op);
5221   SDValue VL =
5222       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5223 
5224   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5225   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5226 
5227   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5228                             Op.getOperand(2), Mask, VL);
5229 
5230   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5231 }
5232 
5233 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5234     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5235   MVT VT = Op.getSimpleValueType();
5236 
5237   if (VT.getVectorElementType() == MVT::i1)
5238     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5239 
5240   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5241 }
5242 
5243 SDValue
5244 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5245                                                       SelectionDAG &DAG) const {
5246   unsigned Opc;
5247   switch (Op.getOpcode()) {
5248   default: llvm_unreachable("Unexpected opcode!");
5249   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5250   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5251   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5252   }
5253 
5254   return lowerToScalableOp(Op, DAG, Opc);
5255 }
5256 
5257 // Lower vector ABS to smax(X, sub(0, X)).
5258 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5259   SDLoc DL(Op);
5260   MVT VT = Op.getSimpleValueType();
5261   SDValue X = Op.getOperand(0);
5262 
5263   assert(VT.isFixedLengthVector() && "Unexpected type");
5264 
5265   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5266   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5267 
5268   SDValue Mask, VL;
5269   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5270 
5271   SDValue SplatZero =
5272       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5273                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5274   SDValue NegX =
5275       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5276   SDValue Max =
5277       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5278 
5279   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5280 }
5281 
5282 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5283     SDValue Op, SelectionDAG &DAG) const {
5284   SDLoc DL(Op);
5285   MVT VT = Op.getSimpleValueType();
5286   SDValue Mag = Op.getOperand(0);
5287   SDValue Sign = Op.getOperand(1);
5288   assert(Mag.getValueType() == Sign.getValueType() &&
5289          "Can only handle COPYSIGN with matching types.");
5290 
5291   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5292   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5293   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5294 
5295   SDValue Mask, VL;
5296   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5297 
5298   SDValue CopySign =
5299       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5300 
5301   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5302 }
5303 
5304 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5305     SDValue Op, SelectionDAG &DAG) const {
5306   MVT VT = Op.getSimpleValueType();
5307   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5308 
5309   MVT I1ContainerVT =
5310       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5311 
5312   SDValue CC =
5313       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5314   SDValue Op1 =
5315       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5316   SDValue Op2 =
5317       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5318 
5319   SDLoc DL(Op);
5320   SDValue Mask, VL;
5321   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5322 
5323   SDValue Select =
5324       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5325 
5326   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5327 }
5328 
5329 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5330                                                unsigned NewOpc,
5331                                                bool HasMask) const {
5332   MVT VT = Op.getSimpleValueType();
5333   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5334 
5335   // Create list of operands by converting existing ones to scalable types.
5336   SmallVector<SDValue, 6> Ops;
5337   for (const SDValue &V : Op->op_values()) {
5338     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5339 
5340     // Pass through non-vector operands.
5341     if (!V.getValueType().isVector()) {
5342       Ops.push_back(V);
5343       continue;
5344     }
5345 
5346     // "cast" fixed length vector to a scalable vector.
5347     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5348            "Only fixed length vectors are supported!");
5349     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5350   }
5351 
5352   SDLoc DL(Op);
5353   SDValue Mask, VL;
5354   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5355   if (HasMask)
5356     Ops.push_back(Mask);
5357   Ops.push_back(VL);
5358 
5359   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5360   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5361 }
5362 
5363 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5364 // * Operands of each node are assumed to be in the same order.
5365 // * The EVL operand is promoted from i32 to i64 on RV64.
5366 // * Fixed-length vectors are converted to their scalable-vector container
5367 //   types.
5368 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5369                                        unsigned RISCVISDOpc) const {
5370   SDLoc DL(Op);
5371   MVT VT = Op.getSimpleValueType();
5372   SmallVector<SDValue, 4> Ops;
5373 
5374   for (const auto &OpIdx : enumerate(Op->ops())) {
5375     SDValue V = OpIdx.value();
5376     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5377     // Pass through operands which aren't fixed-length vectors.
5378     if (!V.getValueType().isFixedLengthVector()) {
5379       Ops.push_back(V);
5380       continue;
5381     }
5382     // "cast" fixed length vector to a scalable vector.
5383     MVT OpVT = V.getSimpleValueType();
5384     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5385     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5386            "Only fixed length vectors are supported!");
5387     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5388   }
5389 
5390   if (!VT.isFixedLengthVector())
5391     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5392 
5393   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5394 
5395   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5396 
5397   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5398 }
5399 
5400 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5401 // matched to a RVV indexed load. The RVV indexed load instructions only
5402 // support the "unsigned unscaled" addressing mode; indices are implicitly
5403 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5404 // signed or scaled indexing is extended to the XLEN value type and scaled
5405 // accordingly.
5406 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5407                                                SelectionDAG &DAG) const {
5408   SDLoc DL(Op);
5409   MVT VT = Op.getSimpleValueType();
5410 
5411   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5412   EVT MemVT = MemSD->getMemoryVT();
5413   MachineMemOperand *MMO = MemSD->getMemOperand();
5414   SDValue Chain = MemSD->getChain();
5415   SDValue BasePtr = MemSD->getBasePtr();
5416 
5417   ISD::LoadExtType LoadExtType;
5418   SDValue Index, Mask, PassThru, VL;
5419 
5420   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5421     Index = VPGN->getIndex();
5422     Mask = VPGN->getMask();
5423     PassThru = DAG.getUNDEF(VT);
5424     VL = VPGN->getVectorLength();
5425     // VP doesn't support extending loads.
5426     LoadExtType = ISD::NON_EXTLOAD;
5427   } else {
5428     // Else it must be a MGATHER.
5429     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5430     Index = MGN->getIndex();
5431     Mask = MGN->getMask();
5432     PassThru = MGN->getPassThru();
5433     LoadExtType = MGN->getExtensionType();
5434   }
5435 
5436   MVT IndexVT = Index.getSimpleValueType();
5437   MVT XLenVT = Subtarget.getXLenVT();
5438 
5439   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5440          "Unexpected VTs!");
5441   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5442   // Targets have to explicitly opt-in for extending vector loads.
5443   assert(LoadExtType == ISD::NON_EXTLOAD &&
5444          "Unexpected extending MGATHER/VP_GATHER");
5445   (void)LoadExtType;
5446 
5447   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5448   // the selection of the masked intrinsics doesn't do this for us.
5449   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5450 
5451   MVT ContainerVT = VT;
5452   if (VT.isFixedLengthVector()) {
5453     // We need to use the larger of the result and index type to determine the
5454     // scalable type to use so we don't increase LMUL for any operand/result.
5455     if (VT.bitsGE(IndexVT)) {
5456       ContainerVT = getContainerForFixedLengthVector(VT);
5457       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5458                                  ContainerVT.getVectorElementCount());
5459     } else {
5460       IndexVT = getContainerForFixedLengthVector(IndexVT);
5461       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5462                                      IndexVT.getVectorElementCount());
5463     }
5464 
5465     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5466 
5467     if (!IsUnmasked) {
5468       MVT MaskVT =
5469           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5470       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5471       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5472     }
5473   }
5474 
5475   if (!VL)
5476     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5477 
5478   unsigned IntID =
5479       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5480   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5481   if (!IsUnmasked)
5482     Ops.push_back(PassThru);
5483   Ops.push_back(BasePtr);
5484   Ops.push_back(Index);
5485   if (!IsUnmasked)
5486     Ops.push_back(Mask);
5487   Ops.push_back(VL);
5488   if (!IsUnmasked)
5489     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5490 
5491   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5492   SDValue Result =
5493       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5494   Chain = Result.getValue(1);
5495 
5496   if (VT.isFixedLengthVector())
5497     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5498 
5499   return DAG.getMergeValues({Result, Chain}, DL);
5500 }
5501 
5502 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5503 // matched to a RVV indexed store. The RVV indexed store instructions only
5504 // support the "unsigned unscaled" addressing mode; indices are implicitly
5505 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5506 // signed or scaled indexing is extended to the XLEN value type and scaled
5507 // accordingly.
5508 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5509                                                 SelectionDAG &DAG) const {
5510   SDLoc DL(Op);
5511   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5512   EVT MemVT = MemSD->getMemoryVT();
5513   MachineMemOperand *MMO = MemSD->getMemOperand();
5514   SDValue Chain = MemSD->getChain();
5515   SDValue BasePtr = MemSD->getBasePtr();
5516 
5517   bool IsTruncatingStore = false;
5518   SDValue Index, Mask, Val, VL;
5519 
5520   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5521     Index = VPSN->getIndex();
5522     Mask = VPSN->getMask();
5523     Val = VPSN->getValue();
5524     VL = VPSN->getVectorLength();
5525     // VP doesn't support truncating stores.
5526     IsTruncatingStore = false;
5527   } else {
5528     // Else it must be a MSCATTER.
5529     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5530     Index = MSN->getIndex();
5531     Mask = MSN->getMask();
5532     Val = MSN->getValue();
5533     IsTruncatingStore = MSN->isTruncatingStore();
5534   }
5535 
5536   MVT VT = Val.getSimpleValueType();
5537   MVT IndexVT = Index.getSimpleValueType();
5538   MVT XLenVT = Subtarget.getXLenVT();
5539 
5540   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5541          "Unexpected VTs!");
5542   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5543   // Targets have to explicitly opt-in for extending vector loads and
5544   // truncating vector stores.
5545   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5546   (void)IsTruncatingStore;
5547 
5548   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5549   // the selection of the masked intrinsics doesn't do this for us.
5550   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5551 
5552   MVT ContainerVT = VT;
5553   if (VT.isFixedLengthVector()) {
5554     // We need to use the larger of the value and index type to determine the
5555     // scalable type to use so we don't increase LMUL for any operand/result.
5556     if (VT.bitsGE(IndexVT)) {
5557       ContainerVT = getContainerForFixedLengthVector(VT);
5558       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5559                                  ContainerVT.getVectorElementCount());
5560     } else {
5561       IndexVT = getContainerForFixedLengthVector(IndexVT);
5562       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5563                                      IndexVT.getVectorElementCount());
5564     }
5565 
5566     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5567     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5568 
5569     if (!IsUnmasked) {
5570       MVT MaskVT =
5571           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5572       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5573     }
5574   }
5575 
5576   if (!VL)
5577     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5578 
5579   unsigned IntID =
5580       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5581   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5582   Ops.push_back(Val);
5583   Ops.push_back(BasePtr);
5584   Ops.push_back(Index);
5585   if (!IsUnmasked)
5586     Ops.push_back(Mask);
5587   Ops.push_back(VL);
5588 
5589   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5590                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5591 }
5592 
5593 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5594                                                SelectionDAG &DAG) const {
5595   const MVT XLenVT = Subtarget.getXLenVT();
5596   SDLoc DL(Op);
5597   SDValue Chain = Op->getOperand(0);
5598   SDValue SysRegNo = DAG.getTargetConstant(
5599       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5600   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5601   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5602 
5603   // Encoding used for rounding mode in RISCV differs from that used in
5604   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5605   // table, which consists of a sequence of 4-bit fields, each representing
5606   // corresponding FLT_ROUNDS mode.
5607   static const int Table =
5608       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5609       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5610       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5611       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5612       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5613 
5614   SDValue Shift =
5615       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5616   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5617                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5618   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5619                                DAG.getConstant(7, DL, XLenVT));
5620 
5621   return DAG.getMergeValues({Masked, Chain}, DL);
5622 }
5623 
5624 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5625                                                SelectionDAG &DAG) const {
5626   const MVT XLenVT = Subtarget.getXLenVT();
5627   SDLoc DL(Op);
5628   SDValue Chain = Op->getOperand(0);
5629   SDValue RMValue = Op->getOperand(1);
5630   SDValue SysRegNo = DAG.getTargetConstant(
5631       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5632 
5633   // Encoding used for rounding mode in RISCV differs from that used in
5634   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5635   // a table, which consists of a sequence of 4-bit fields, each representing
5636   // corresponding RISCV mode.
5637   static const unsigned Table =
5638       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5639       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5640       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5641       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5642       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5643 
5644   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5645                               DAG.getConstant(2, DL, XLenVT));
5646   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5647                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5648   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5649                         DAG.getConstant(0x7, DL, XLenVT));
5650   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5651                      RMValue);
5652 }
5653 
5654 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5655 // form of the given Opcode.
5656 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5657   switch (Opcode) {
5658   default:
5659     llvm_unreachable("Unexpected opcode");
5660   case ISD::SHL:
5661     return RISCVISD::SLLW;
5662   case ISD::SRA:
5663     return RISCVISD::SRAW;
5664   case ISD::SRL:
5665     return RISCVISD::SRLW;
5666   case ISD::SDIV:
5667     return RISCVISD::DIVW;
5668   case ISD::UDIV:
5669     return RISCVISD::DIVUW;
5670   case ISD::UREM:
5671     return RISCVISD::REMUW;
5672   case ISD::ROTL:
5673     return RISCVISD::ROLW;
5674   case ISD::ROTR:
5675     return RISCVISD::RORW;
5676   case RISCVISD::GREV:
5677     return RISCVISD::GREVW;
5678   case RISCVISD::GORC:
5679     return RISCVISD::GORCW;
5680   }
5681 }
5682 
5683 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5684 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5685 // otherwise be promoted to i64, making it difficult to select the
5686 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5687 // type i8/i16/i32 is lost.
5688 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5689                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5690   SDLoc DL(N);
5691   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5692   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5693   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5694   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5695   // ReplaceNodeResults requires we maintain the same type for the return value.
5696   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5697 }
5698 
5699 // Converts the given 32-bit operation to a i64 operation with signed extension
5700 // semantic to reduce the signed extension instructions.
5701 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5702   SDLoc DL(N);
5703   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5704   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5705   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5706   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5707                                DAG.getValueType(MVT::i32));
5708   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5709 }
5710 
5711 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5712                                              SmallVectorImpl<SDValue> &Results,
5713                                              SelectionDAG &DAG) const {
5714   SDLoc DL(N);
5715   switch (N->getOpcode()) {
5716   default:
5717     llvm_unreachable("Don't know how to custom type legalize this operation!");
5718   case ISD::STRICT_FP_TO_SINT:
5719   case ISD::STRICT_FP_TO_UINT:
5720   case ISD::FP_TO_SINT:
5721   case ISD::FP_TO_UINT: {
5722     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5723            "Unexpected custom legalisation");
5724     bool IsStrict = N->isStrictFPOpcode();
5725     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5726                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5727     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5728     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5729         TargetLowering::TypeSoftenFloat) {
5730       // FIXME: Support strict FP.
5731       if (IsStrict)
5732         return;
5733       if (!isTypeLegal(Op0.getValueType()))
5734         return;
5735       unsigned Opc =
5736           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5737       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5738       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5739       return;
5740     }
5741     // If the FP type needs to be softened, emit a library call using the 'si'
5742     // version. If we left it to default legalization we'd end up with 'di'. If
5743     // the FP type doesn't need to be softened just let generic type
5744     // legalization promote the result type.
5745     RTLIB::Libcall LC;
5746     if (IsSigned)
5747       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5748     else
5749       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5750     MakeLibCallOptions CallOptions;
5751     EVT OpVT = Op0.getValueType();
5752     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5753     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5754     SDValue Result;
5755     std::tie(Result, Chain) =
5756         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5757     Results.push_back(Result);
5758     if (IsStrict)
5759       Results.push_back(Chain);
5760     break;
5761   }
5762   case ISD::READCYCLECOUNTER: {
5763     assert(!Subtarget.is64Bit() &&
5764            "READCYCLECOUNTER only has custom type legalization on riscv32");
5765 
5766     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5767     SDValue RCW =
5768         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5769 
5770     Results.push_back(
5771         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5772     Results.push_back(RCW.getValue(2));
5773     break;
5774   }
5775   case ISD::MUL: {
5776     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5777     unsigned XLen = Subtarget.getXLen();
5778     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5779     if (Size > XLen) {
5780       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5781       SDValue LHS = N->getOperand(0);
5782       SDValue RHS = N->getOperand(1);
5783       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5784 
5785       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5786       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5787       // We need exactly one side to be unsigned.
5788       if (LHSIsU == RHSIsU)
5789         return;
5790 
5791       auto MakeMULPair = [&](SDValue S, SDValue U) {
5792         MVT XLenVT = Subtarget.getXLenVT();
5793         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5794         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5795         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5796         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5797         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5798       };
5799 
5800       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5801       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5802 
5803       // The other operand should be signed, but still prefer MULH when
5804       // possible.
5805       if (RHSIsU && LHSIsS && !RHSIsS)
5806         Results.push_back(MakeMULPair(LHS, RHS));
5807       else if (LHSIsU && RHSIsS && !LHSIsS)
5808         Results.push_back(MakeMULPair(RHS, LHS));
5809 
5810       return;
5811     }
5812     LLVM_FALLTHROUGH;
5813   }
5814   case ISD::ADD:
5815   case ISD::SUB:
5816     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5817            "Unexpected custom legalisation");
5818     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5819     break;
5820   case ISD::SHL:
5821   case ISD::SRA:
5822   case ISD::SRL:
5823     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5824            "Unexpected custom legalisation");
5825     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5826       Results.push_back(customLegalizeToWOp(N, DAG));
5827       break;
5828     }
5829 
5830     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5831     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5832     // shift amount.
5833     if (N->getOpcode() == ISD::SHL) {
5834       SDLoc DL(N);
5835       SDValue NewOp0 =
5836           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5837       SDValue NewOp1 =
5838           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5839       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5840       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5841                                    DAG.getValueType(MVT::i32));
5842       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5843     }
5844 
5845     break;
5846   case ISD::ROTL:
5847   case ISD::ROTR:
5848     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5849            "Unexpected custom legalisation");
5850     Results.push_back(customLegalizeToWOp(N, DAG));
5851     break;
5852   case ISD::CTTZ:
5853   case ISD::CTTZ_ZERO_UNDEF:
5854   case ISD::CTLZ:
5855   case ISD::CTLZ_ZERO_UNDEF: {
5856     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5857            "Unexpected custom legalisation");
5858 
5859     SDValue NewOp0 =
5860         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5861     bool IsCTZ =
5862         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5863     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5864     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5865     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5866     return;
5867   }
5868   case ISD::SDIV:
5869   case ISD::UDIV:
5870   case ISD::UREM: {
5871     MVT VT = N->getSimpleValueType(0);
5872     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5873            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5874            "Unexpected custom legalisation");
5875     // Don't promote division/remainder by constant since we should expand those
5876     // to multiply by magic constant.
5877     // FIXME: What if the expansion is disabled for minsize.
5878     if (N->getOperand(1).getOpcode() == ISD::Constant)
5879       return;
5880 
5881     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5882     // the upper 32 bits. For other types we need to sign or zero extend
5883     // based on the opcode.
5884     unsigned ExtOpc = ISD::ANY_EXTEND;
5885     if (VT != MVT::i32)
5886       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5887                                            : ISD::ZERO_EXTEND;
5888 
5889     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5890     break;
5891   }
5892   case ISD::UADDO:
5893   case ISD::USUBO: {
5894     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5895            "Unexpected custom legalisation");
5896     bool IsAdd = N->getOpcode() == ISD::UADDO;
5897     // Create an ADDW or SUBW.
5898     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5899     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5900     SDValue Res =
5901         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5902     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5903                       DAG.getValueType(MVT::i32));
5904 
5905     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5906     // Since the inputs are sign extended from i32, this is equivalent to
5907     // comparing the lower 32 bits.
5908     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5909     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5910                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5911 
5912     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5913     Results.push_back(Overflow);
5914     return;
5915   }
5916   case ISD::UADDSAT:
5917   case ISD::USUBSAT: {
5918     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5919            "Unexpected custom legalisation");
5920     if (Subtarget.hasStdExtZbb()) {
5921       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5922       // sign extend allows overflow of the lower 32 bits to be detected on
5923       // the promoted size.
5924       SDValue LHS =
5925           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5926       SDValue RHS =
5927           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5928       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5929       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5930       return;
5931     }
5932 
5933     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5934     // promotion for UADDO/USUBO.
5935     Results.push_back(expandAddSubSat(N, DAG));
5936     return;
5937   }
5938   case ISD::BITCAST: {
5939     EVT VT = N->getValueType(0);
5940     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5941     SDValue Op0 = N->getOperand(0);
5942     EVT Op0VT = Op0.getValueType();
5943     MVT XLenVT = Subtarget.getXLenVT();
5944     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5945       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5946       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5947     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5948                Subtarget.hasStdExtF()) {
5949       SDValue FPConv =
5950           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5951       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5952     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5953                isTypeLegal(Op0VT)) {
5954       // Custom-legalize bitcasts from fixed-length vector types to illegal
5955       // scalar types in order to improve codegen. Bitcast the vector to a
5956       // one-element vector type whose element type is the same as the result
5957       // type, and extract the first element.
5958       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
5959       if (isTypeLegal(BVT)) {
5960         SDValue BVec = DAG.getBitcast(BVT, Op0);
5961         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5962                                       DAG.getConstant(0, DL, XLenVT)));
5963       }
5964     }
5965     break;
5966   }
5967   case RISCVISD::GREV:
5968   case RISCVISD::GORC: {
5969     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5970            "Unexpected custom legalisation");
5971     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5972     // This is similar to customLegalizeToWOp, except that we pass the second
5973     // operand (a TargetConstant) straight through: it is already of type
5974     // XLenVT.
5975     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5976     SDValue NewOp0 =
5977         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5978     SDValue NewOp1 =
5979         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5980     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5981     // ReplaceNodeResults requires we maintain the same type for the return
5982     // value.
5983     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5984     break;
5985   }
5986   case RISCVISD::SHFL: {
5987     // There is no SHFLIW instruction, but we can just promote the operation.
5988     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5989            "Unexpected custom legalisation");
5990     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5991     SDValue NewOp0 =
5992         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5993     SDValue NewOp1 =
5994         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5995     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5996     // ReplaceNodeResults requires we maintain the same type for the return
5997     // value.
5998     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5999     break;
6000   }
6001   case ISD::BSWAP:
6002   case ISD::BITREVERSE: {
6003     MVT VT = N->getSimpleValueType(0);
6004     MVT XLenVT = Subtarget.getXLenVT();
6005     assert((VT == MVT::i8 || VT == MVT::i16 ||
6006             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6007            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6008     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6009     unsigned Imm = VT.getSizeInBits() - 1;
6010     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6011     if (N->getOpcode() == ISD::BSWAP)
6012       Imm &= ~0x7U;
6013     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6014     SDValue GREVI =
6015         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6016     // ReplaceNodeResults requires we maintain the same type for the return
6017     // value.
6018     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6019     break;
6020   }
6021   case ISD::FSHL:
6022   case ISD::FSHR: {
6023     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6024            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6025     SDValue NewOp0 =
6026         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6027     SDValue NewOp1 =
6028         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6029     SDValue NewOp2 =
6030         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6031     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6032     // Mask the shift amount to 5 bits.
6033     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6034                          DAG.getConstant(0x1f, DL, MVT::i64));
6035     unsigned Opc =
6036         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
6037     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
6038     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6039     break;
6040   }
6041   case ISD::EXTRACT_VECTOR_ELT: {
6042     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6043     // type is illegal (currently only vXi64 RV32).
6044     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6045     // transferred to the destination register. We issue two of these from the
6046     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6047     // first element.
6048     SDValue Vec = N->getOperand(0);
6049     SDValue Idx = N->getOperand(1);
6050 
6051     // The vector type hasn't been legalized yet so we can't issue target
6052     // specific nodes if it needs legalization.
6053     // FIXME: We would manually legalize if it's important.
6054     if (!isTypeLegal(Vec.getValueType()))
6055       return;
6056 
6057     MVT VecVT = Vec.getSimpleValueType();
6058 
6059     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6060            VecVT.getVectorElementType() == MVT::i64 &&
6061            "Unexpected EXTRACT_VECTOR_ELT legalization");
6062 
6063     // If this is a fixed vector, we need to convert it to a scalable vector.
6064     MVT ContainerVT = VecVT;
6065     if (VecVT.isFixedLengthVector()) {
6066       ContainerVT = getContainerForFixedLengthVector(VecVT);
6067       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6068     }
6069 
6070     MVT XLenVT = Subtarget.getXLenVT();
6071 
6072     // Use a VL of 1 to avoid processing more elements than we need.
6073     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6074     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6075     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6076 
6077     // Unless the index is known to be 0, we must slide the vector down to get
6078     // the desired element into index 0.
6079     if (!isNullConstant(Idx)) {
6080       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6081                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6082     }
6083 
6084     // Extract the lower XLEN bits of the correct vector element.
6085     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6086 
6087     // To extract the upper XLEN bits of the vector element, shift the first
6088     // element right by 32 bits and re-extract the lower XLEN bits.
6089     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6090                                      DAG.getConstant(32, DL, XLenVT), VL);
6091     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6092                                  ThirtyTwoV, Mask, VL);
6093 
6094     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6095 
6096     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6097     break;
6098   }
6099   case ISD::INTRINSIC_WO_CHAIN: {
6100     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6101     switch (IntNo) {
6102     default:
6103       llvm_unreachable(
6104           "Don't know how to custom type legalize this intrinsic!");
6105     case Intrinsic::riscv_orc_b: {
6106       // Lower to the GORCI encoding for orc.b with the operand extended.
6107       SDValue NewOp =
6108           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6109       // If Zbp is enabled, use GORCIW which will sign extend the result.
6110       unsigned Opc =
6111           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6112       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6113                                 DAG.getConstant(7, DL, MVT::i64));
6114       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6115       return;
6116     }
6117     case Intrinsic::riscv_grev:
6118     case Intrinsic::riscv_gorc: {
6119       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6120              "Unexpected custom legalisation");
6121       SDValue NewOp1 =
6122           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6123       SDValue NewOp2 =
6124           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6125       unsigned Opc =
6126           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
6127       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6128       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6129       break;
6130     }
6131     case Intrinsic::riscv_shfl:
6132     case Intrinsic::riscv_unshfl: {
6133       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6134              "Unexpected custom legalisation");
6135       SDValue NewOp1 =
6136           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6137       SDValue NewOp2 =
6138           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6139       unsigned Opc =
6140           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6141       if (isa<ConstantSDNode>(N->getOperand(2))) {
6142         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6143                              DAG.getConstant(0xf, DL, MVT::i64));
6144         Opc =
6145             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6146       }
6147       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6148       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6149       break;
6150     }
6151     case Intrinsic::riscv_bcompress:
6152     case Intrinsic::riscv_bdecompress: {
6153       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6154              "Unexpected custom legalisation");
6155       SDValue NewOp1 =
6156           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6157       SDValue NewOp2 =
6158           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6159       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
6160                          ? RISCVISD::BCOMPRESSW
6161                          : RISCVISD::BDECOMPRESSW;
6162       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6163       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6164       break;
6165     }
6166     case Intrinsic::riscv_vmv_x_s: {
6167       EVT VT = N->getValueType(0);
6168       MVT XLenVT = Subtarget.getXLenVT();
6169       if (VT.bitsLT(XLenVT)) {
6170         // Simple case just extract using vmv.x.s and truncate.
6171         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6172                                       Subtarget.getXLenVT(), N->getOperand(1));
6173         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6174         return;
6175       }
6176 
6177       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6178              "Unexpected custom legalization");
6179 
6180       // We need to do the move in two steps.
6181       SDValue Vec = N->getOperand(1);
6182       MVT VecVT = Vec.getSimpleValueType();
6183 
6184       // First extract the lower XLEN bits of the element.
6185       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6186 
6187       // To extract the upper XLEN bits of the vector element, shift the first
6188       // element right by 32 bits and re-extract the lower XLEN bits.
6189       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6190       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6191       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6192       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6193                                        DAG.getConstant(32, DL, XLenVT), VL);
6194       SDValue LShr32 =
6195           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6196       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6197 
6198       Results.push_back(
6199           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6200       break;
6201     }
6202     }
6203     break;
6204   }
6205   case ISD::VECREDUCE_ADD:
6206   case ISD::VECREDUCE_AND:
6207   case ISD::VECREDUCE_OR:
6208   case ISD::VECREDUCE_XOR:
6209   case ISD::VECREDUCE_SMAX:
6210   case ISD::VECREDUCE_UMAX:
6211   case ISD::VECREDUCE_SMIN:
6212   case ISD::VECREDUCE_UMIN:
6213     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6214       Results.push_back(V);
6215     break;
6216   case ISD::VP_REDUCE_ADD:
6217   case ISD::VP_REDUCE_AND:
6218   case ISD::VP_REDUCE_OR:
6219   case ISD::VP_REDUCE_XOR:
6220   case ISD::VP_REDUCE_SMAX:
6221   case ISD::VP_REDUCE_UMAX:
6222   case ISD::VP_REDUCE_SMIN:
6223   case ISD::VP_REDUCE_UMIN:
6224     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6225       Results.push_back(V);
6226     break;
6227   case ISD::FLT_ROUNDS_: {
6228     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6229     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6230     Results.push_back(Res.getValue(0));
6231     Results.push_back(Res.getValue(1));
6232     break;
6233   }
6234   }
6235 }
6236 
6237 // A structure to hold one of the bit-manipulation patterns below. Together, a
6238 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6239 //   (or (and (shl x, 1), 0xAAAAAAAA),
6240 //       (and (srl x, 1), 0x55555555))
6241 struct RISCVBitmanipPat {
6242   SDValue Op;
6243   unsigned ShAmt;
6244   bool IsSHL;
6245 
6246   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6247     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6248   }
6249 };
6250 
6251 // Matches patterns of the form
6252 //   (and (shl x, C2), (C1 << C2))
6253 //   (and (srl x, C2), C1)
6254 //   (shl (and x, C1), C2)
6255 //   (srl (and x, (C1 << C2)), C2)
6256 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6257 // The expected masks for each shift amount are specified in BitmanipMasks where
6258 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6259 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6260 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6261 // XLen is 64.
6262 static Optional<RISCVBitmanipPat>
6263 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6264   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6265          "Unexpected number of masks");
6266   Optional<uint64_t> Mask;
6267   // Optionally consume a mask around the shift operation.
6268   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6269     Mask = Op.getConstantOperandVal(1);
6270     Op = Op.getOperand(0);
6271   }
6272   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6273     return None;
6274   bool IsSHL = Op.getOpcode() == ISD::SHL;
6275 
6276   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6277     return None;
6278   uint64_t ShAmt = Op.getConstantOperandVal(1);
6279 
6280   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6281   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6282     return None;
6283   // If we don't have enough masks for 64 bit, then we must be trying to
6284   // match SHFL so we're only allowed to shift 1/4 of the width.
6285   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6286     return None;
6287 
6288   SDValue Src = Op.getOperand(0);
6289 
6290   // The expected mask is shifted left when the AND is found around SHL
6291   // patterns.
6292   //   ((x >> 1) & 0x55555555)
6293   //   ((x << 1) & 0xAAAAAAAA)
6294   bool SHLExpMask = IsSHL;
6295 
6296   if (!Mask) {
6297     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6298     // the mask is all ones: consume that now.
6299     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6300       Mask = Src.getConstantOperandVal(1);
6301       Src = Src.getOperand(0);
6302       // The expected mask is now in fact shifted left for SRL, so reverse the
6303       // decision.
6304       //   ((x & 0xAAAAAAAA) >> 1)
6305       //   ((x & 0x55555555) << 1)
6306       SHLExpMask = !SHLExpMask;
6307     } else {
6308       // Use a default shifted mask of all-ones if there's no AND, truncated
6309       // down to the expected width. This simplifies the logic later on.
6310       Mask = maskTrailingOnes<uint64_t>(Width);
6311       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6312     }
6313   }
6314 
6315   unsigned MaskIdx = Log2_32(ShAmt);
6316   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6317 
6318   if (SHLExpMask)
6319     ExpMask <<= ShAmt;
6320 
6321   if (Mask != ExpMask)
6322     return None;
6323 
6324   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6325 }
6326 
6327 // Matches any of the following bit-manipulation patterns:
6328 //   (and (shl x, 1), (0x55555555 << 1))
6329 //   (and (srl x, 1), 0x55555555)
6330 //   (shl (and x, 0x55555555), 1)
6331 //   (srl (and x, (0x55555555 << 1)), 1)
6332 // where the shift amount and mask may vary thus:
6333 //   [1]  = 0x55555555 / 0xAAAAAAAA
6334 //   [2]  = 0x33333333 / 0xCCCCCCCC
6335 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6336 //   [8]  = 0x00FF00FF / 0xFF00FF00
6337 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6338 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6339 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6340   // These are the unshifted masks which we use to match bit-manipulation
6341   // patterns. They may be shifted left in certain circumstances.
6342   static const uint64_t BitmanipMasks[] = {
6343       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6344       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6345 
6346   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6347 }
6348 
6349 // Match the following pattern as a GREVI(W) operation
6350 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6351 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6352                                const RISCVSubtarget &Subtarget) {
6353   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6354   EVT VT = Op.getValueType();
6355 
6356   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6357     auto LHS = matchGREVIPat(Op.getOperand(0));
6358     auto RHS = matchGREVIPat(Op.getOperand(1));
6359     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6360       SDLoc DL(Op);
6361       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6362                          DAG.getConstant(LHS->ShAmt, DL, VT));
6363     }
6364   }
6365   return SDValue();
6366 }
6367 
6368 // Matches any the following pattern as a GORCI(W) operation
6369 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6370 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6371 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6372 // Note that with the variant of 3.,
6373 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6374 // the inner pattern will first be matched as GREVI and then the outer
6375 // pattern will be matched to GORC via the first rule above.
6376 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6377 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6378                                const RISCVSubtarget &Subtarget) {
6379   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6380   EVT VT = Op.getValueType();
6381 
6382   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6383     SDLoc DL(Op);
6384     SDValue Op0 = Op.getOperand(0);
6385     SDValue Op1 = Op.getOperand(1);
6386 
6387     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6388       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6389           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6390           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6391         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6392       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6393       if ((Reverse.getOpcode() == ISD::ROTL ||
6394            Reverse.getOpcode() == ISD::ROTR) &&
6395           Reverse.getOperand(0) == X &&
6396           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6397         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6398         if (RotAmt == (VT.getSizeInBits() / 2))
6399           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6400                              DAG.getConstant(RotAmt, DL, VT));
6401       }
6402       return SDValue();
6403     };
6404 
6405     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6406     if (SDValue V = MatchOROfReverse(Op0, Op1))
6407       return V;
6408     if (SDValue V = MatchOROfReverse(Op1, Op0))
6409       return V;
6410 
6411     // OR is commutable so canonicalize its OR operand to the left
6412     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6413       std::swap(Op0, Op1);
6414     if (Op0.getOpcode() != ISD::OR)
6415       return SDValue();
6416     SDValue OrOp0 = Op0.getOperand(0);
6417     SDValue OrOp1 = Op0.getOperand(1);
6418     auto LHS = matchGREVIPat(OrOp0);
6419     // OR is commutable so swap the operands and try again: x might have been
6420     // on the left
6421     if (!LHS) {
6422       std::swap(OrOp0, OrOp1);
6423       LHS = matchGREVIPat(OrOp0);
6424     }
6425     auto RHS = matchGREVIPat(Op1);
6426     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6427       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6428                          DAG.getConstant(LHS->ShAmt, DL, VT));
6429     }
6430   }
6431   return SDValue();
6432 }
6433 
6434 // Matches any of the following bit-manipulation patterns:
6435 //   (and (shl x, 1), (0x22222222 << 1))
6436 //   (and (srl x, 1), 0x22222222)
6437 //   (shl (and x, 0x22222222), 1)
6438 //   (srl (and x, (0x22222222 << 1)), 1)
6439 // where the shift amount and mask may vary thus:
6440 //   [1]  = 0x22222222 / 0x44444444
6441 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6442 //   [4]  = 0x00F000F0 / 0x0F000F00
6443 //   [8]  = 0x0000FF00 / 0x00FF0000
6444 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6445 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6446   // These are the unshifted masks which we use to match bit-manipulation
6447   // patterns. They may be shifted left in certain circumstances.
6448   static const uint64_t BitmanipMasks[] = {
6449       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6450       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6451 
6452   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6453 }
6454 
6455 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6456 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6457                                const RISCVSubtarget &Subtarget) {
6458   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6459   EVT VT = Op.getValueType();
6460 
6461   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6462     return SDValue();
6463 
6464   SDValue Op0 = Op.getOperand(0);
6465   SDValue Op1 = Op.getOperand(1);
6466 
6467   // Or is commutable so canonicalize the second OR to the LHS.
6468   if (Op0.getOpcode() != ISD::OR)
6469     std::swap(Op0, Op1);
6470   if (Op0.getOpcode() != ISD::OR)
6471     return SDValue();
6472 
6473   // We found an inner OR, so our operands are the operands of the inner OR
6474   // and the other operand of the outer OR.
6475   SDValue A = Op0.getOperand(0);
6476   SDValue B = Op0.getOperand(1);
6477   SDValue C = Op1;
6478 
6479   auto Match1 = matchSHFLPat(A);
6480   auto Match2 = matchSHFLPat(B);
6481 
6482   // If neither matched, we failed.
6483   if (!Match1 && !Match2)
6484     return SDValue();
6485 
6486   // We had at least one match. if one failed, try the remaining C operand.
6487   if (!Match1) {
6488     std::swap(A, C);
6489     Match1 = matchSHFLPat(A);
6490     if (!Match1)
6491       return SDValue();
6492   } else if (!Match2) {
6493     std::swap(B, C);
6494     Match2 = matchSHFLPat(B);
6495     if (!Match2)
6496       return SDValue();
6497   }
6498   assert(Match1 && Match2);
6499 
6500   // Make sure our matches pair up.
6501   if (!Match1->formsPairWith(*Match2))
6502     return SDValue();
6503 
6504   // All the remains is to make sure C is an AND with the same input, that masks
6505   // out the bits that are being shuffled.
6506   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6507       C.getOperand(0) != Match1->Op)
6508     return SDValue();
6509 
6510   uint64_t Mask = C.getConstantOperandVal(1);
6511 
6512   static const uint64_t BitmanipMasks[] = {
6513       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6514       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6515   };
6516 
6517   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6518   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6519   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6520 
6521   if (Mask != ExpMask)
6522     return SDValue();
6523 
6524   SDLoc DL(Op);
6525   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6526                      DAG.getConstant(Match1->ShAmt, DL, VT));
6527 }
6528 
6529 // Optimize (add (shl x, c0), (shl y, c1)) ->
6530 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6531 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6532                                   const RISCVSubtarget &Subtarget) {
6533   // Perform this optimization only in the zba extension.
6534   if (!Subtarget.hasStdExtZba())
6535     return SDValue();
6536 
6537   // Skip for vector types and larger types.
6538   EVT VT = N->getValueType(0);
6539   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6540     return SDValue();
6541 
6542   // The two operand nodes must be SHL and have no other use.
6543   SDValue N0 = N->getOperand(0);
6544   SDValue N1 = N->getOperand(1);
6545   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6546       !N0->hasOneUse() || !N1->hasOneUse())
6547     return SDValue();
6548 
6549   // Check c0 and c1.
6550   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6551   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6552   if (!N0C || !N1C)
6553     return SDValue();
6554   int64_t C0 = N0C->getSExtValue();
6555   int64_t C1 = N1C->getSExtValue();
6556   if (C0 <= 0 || C1 <= 0)
6557     return SDValue();
6558 
6559   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6560   int64_t Bits = std::min(C0, C1);
6561   int64_t Diff = std::abs(C0 - C1);
6562   if (Diff != 1 && Diff != 2 && Diff != 3)
6563     return SDValue();
6564 
6565   // Build nodes.
6566   SDLoc DL(N);
6567   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6568   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6569   SDValue NA0 =
6570       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6571   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6572   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6573 }
6574 
6575 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6576 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6577 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6578 // not undo itself, but they are redundant.
6579 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6580   SDValue Src = N->getOperand(0);
6581 
6582   if (Src.getOpcode() != N->getOpcode())
6583     return SDValue();
6584 
6585   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6586       !isa<ConstantSDNode>(Src.getOperand(1)))
6587     return SDValue();
6588 
6589   unsigned ShAmt1 = N->getConstantOperandVal(1);
6590   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6591   Src = Src.getOperand(0);
6592 
6593   unsigned CombinedShAmt;
6594   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6595     CombinedShAmt = ShAmt1 | ShAmt2;
6596   else
6597     CombinedShAmt = ShAmt1 ^ ShAmt2;
6598 
6599   if (CombinedShAmt == 0)
6600     return Src;
6601 
6602   SDLoc DL(N);
6603   return DAG.getNode(
6604       N->getOpcode(), DL, N->getValueType(0), Src,
6605       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6606 }
6607 
6608 // Combine a constant select operand into its use:
6609 //
6610 // (and (select cond, -1, c), x)
6611 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6612 // (or  (select cond, 0, c), x)
6613 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6614 // (xor (select cond, 0, c), x)
6615 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6616 // (add (select cond, 0, c), x)
6617 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6618 // (sub x, (select cond, 0, c))
6619 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6620 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6621                                    SelectionDAG &DAG, bool AllOnes) {
6622   EVT VT = N->getValueType(0);
6623 
6624   // Skip vectors.
6625   if (VT.isVector())
6626     return SDValue();
6627 
6628   if ((Slct.getOpcode() != ISD::SELECT &&
6629        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6630       !Slct.hasOneUse())
6631     return SDValue();
6632 
6633   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6634     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6635   };
6636 
6637   bool SwapSelectOps;
6638   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6639   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6640   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6641   SDValue NonConstantVal;
6642   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6643     SwapSelectOps = false;
6644     NonConstantVal = FalseVal;
6645   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6646     SwapSelectOps = true;
6647     NonConstantVal = TrueVal;
6648   } else
6649     return SDValue();
6650 
6651   // Slct is now know to be the desired identity constant when CC is true.
6652   TrueVal = OtherOp;
6653   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6654   // Unless SwapSelectOps says the condition should be false.
6655   if (SwapSelectOps)
6656     std::swap(TrueVal, FalseVal);
6657 
6658   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6659     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6660                        {Slct.getOperand(0), Slct.getOperand(1),
6661                         Slct.getOperand(2), TrueVal, FalseVal});
6662 
6663   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6664                      {Slct.getOperand(0), TrueVal, FalseVal});
6665 }
6666 
6667 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6668 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6669                                               bool AllOnes) {
6670   SDValue N0 = N->getOperand(0);
6671   SDValue N1 = N->getOperand(1);
6672   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6673     return Result;
6674   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6675     return Result;
6676   return SDValue();
6677 }
6678 
6679 // Transform (add (mul x, c0), c1) ->
6680 //           (add (mul (add x, c1/c0), c0), c1%c0).
6681 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6682 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6683 // to an infinite loop in DAGCombine if transformed.
6684 // Or transform (add (mul x, c0), c1) ->
6685 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6686 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6687 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6688 // lead to an infinite loop in DAGCombine if transformed.
6689 // Or transform (add (mul x, c0), c1) ->
6690 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6691 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6692 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6693 // lead to an infinite loop in DAGCombine if transformed.
6694 // Or transform (add (mul x, c0), c1) ->
6695 //              (mul (add x, c1/c0), c0).
6696 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6697 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6698                                      const RISCVSubtarget &Subtarget) {
6699   // Skip for vector types and larger types.
6700   EVT VT = N->getValueType(0);
6701   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6702     return SDValue();
6703   // The first operand node must be a MUL and has no other use.
6704   SDValue N0 = N->getOperand(0);
6705   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6706     return SDValue();
6707   // Check if c0 and c1 match above conditions.
6708   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6709   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6710   if (!N0C || !N1C)
6711     return SDValue();
6712   int64_t C0 = N0C->getSExtValue();
6713   int64_t C1 = N1C->getSExtValue();
6714   int64_t CA, CB;
6715   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6716     return SDValue();
6717   // Search for proper CA (non-zero) and CB that both are simm12.
6718   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6719       !isInt<12>(C0 * (C1 / C0))) {
6720     CA = C1 / C0;
6721     CB = C1 % C0;
6722   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6723              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6724     CA = C1 / C0 + 1;
6725     CB = C1 % C0 - C0;
6726   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6727              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6728     CA = C1 / C0 - 1;
6729     CB = C1 % C0 + C0;
6730   } else
6731     return SDValue();
6732   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6733   SDLoc DL(N);
6734   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6735                              DAG.getConstant(CA, DL, VT));
6736   SDValue New1 =
6737       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6738   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6739 }
6740 
6741 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6742                                  const RISCVSubtarget &Subtarget) {
6743   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6744     return V;
6745   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6746     return V;
6747   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6748   //      (select lhs, rhs, cc, x, (add x, y))
6749   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6750 }
6751 
6752 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6753   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6754   //      (select lhs, rhs, cc, x, (sub x, y))
6755   SDValue N0 = N->getOperand(0);
6756   SDValue N1 = N->getOperand(1);
6757   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6758 }
6759 
6760 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6761   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6762   //      (select lhs, rhs, cc, x, (and x, y))
6763   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6764 }
6765 
6766 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6767                                 const RISCVSubtarget &Subtarget) {
6768   if (Subtarget.hasStdExtZbp()) {
6769     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6770       return GREV;
6771     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6772       return GORC;
6773     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6774       return SHFL;
6775   }
6776 
6777   // fold (or (select cond, 0, y), x) ->
6778   //      (select cond, x, (or x, y))
6779   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6780 }
6781 
6782 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6783   // fold (xor (select cond, 0, y), x) ->
6784   //      (select cond, x, (xor x, y))
6785   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6786 }
6787 
6788 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6789 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6790 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6791 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6792 // ADDW/SUBW/MULW.
6793 static SDValue performANY_EXTENDCombine(SDNode *N,
6794                                         TargetLowering::DAGCombinerInfo &DCI,
6795                                         const RISCVSubtarget &Subtarget) {
6796   if (!Subtarget.is64Bit())
6797     return SDValue();
6798 
6799   SelectionDAG &DAG = DCI.DAG;
6800 
6801   SDValue Src = N->getOperand(0);
6802   EVT VT = N->getValueType(0);
6803   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6804     return SDValue();
6805 
6806   // The opcode must be one that can implicitly sign_extend.
6807   // FIXME: Additional opcodes.
6808   switch (Src.getOpcode()) {
6809   default:
6810     return SDValue();
6811   case ISD::MUL:
6812     if (!Subtarget.hasStdExtM())
6813       return SDValue();
6814     LLVM_FALLTHROUGH;
6815   case ISD::ADD:
6816   case ISD::SUB:
6817     break;
6818   }
6819 
6820   // Only handle cases where the result is used by a CopyToReg. That likely
6821   // means the value is a liveout of the basic block. This helps prevent
6822   // infinite combine loops like PR51206.
6823   if (none_of(N->uses(),
6824               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6825     return SDValue();
6826 
6827   SmallVector<SDNode *, 4> SetCCs;
6828   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6829                             UE = Src.getNode()->use_end();
6830        UI != UE; ++UI) {
6831     SDNode *User = *UI;
6832     if (User == N)
6833       continue;
6834     if (UI.getUse().getResNo() != Src.getResNo())
6835       continue;
6836     // All i32 setccs are legalized by sign extending operands.
6837     if (User->getOpcode() == ISD::SETCC) {
6838       SetCCs.push_back(User);
6839       continue;
6840     }
6841     // We don't know if we can extend this user.
6842     break;
6843   }
6844 
6845   // If we don't have any SetCCs, this isn't worthwhile.
6846   if (SetCCs.empty())
6847     return SDValue();
6848 
6849   SDLoc DL(N);
6850   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6851   DCI.CombineTo(N, SExt);
6852 
6853   // Promote all the setccs.
6854   for (SDNode *SetCC : SetCCs) {
6855     SmallVector<SDValue, 4> Ops;
6856 
6857     for (unsigned j = 0; j != 2; ++j) {
6858       SDValue SOp = SetCC->getOperand(j);
6859       if (SOp == Src)
6860         Ops.push_back(SExt);
6861       else
6862         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6863     }
6864 
6865     Ops.push_back(SetCC->getOperand(2));
6866     DCI.CombineTo(SetCC,
6867                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6868   }
6869   return SDValue(N, 0);
6870 }
6871 
6872 // Try to form VWMUL or VWMULU.
6873 // FIXME: Support VWMULSU.
6874 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6875                                     SelectionDAG &DAG) {
6876   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6877   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6878   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6879   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6880     return SDValue();
6881 
6882   SDValue Mask = N->getOperand(2);
6883   SDValue VL = N->getOperand(3);
6884 
6885   // Make sure the mask and VL match.
6886   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6887     return SDValue();
6888 
6889   MVT VT = N->getSimpleValueType(0);
6890 
6891   // Determine the narrow size for a widening multiply.
6892   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6893   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6894                                   VT.getVectorElementCount());
6895 
6896   SDLoc DL(N);
6897 
6898   // See if the other operand is the same opcode.
6899   if (Op0.getOpcode() == Op1.getOpcode()) {
6900     if (!Op1.hasOneUse())
6901       return SDValue();
6902 
6903     // Make sure the mask and VL match.
6904     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6905       return SDValue();
6906 
6907     Op1 = Op1.getOperand(0);
6908   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6909     // The operand is a splat of a scalar.
6910 
6911     // The VL must be the same.
6912     if (Op1.getOperand(1) != VL)
6913       return SDValue();
6914 
6915     // Get the scalar value.
6916     Op1 = Op1.getOperand(0);
6917 
6918     // See if have enough sign bits or zero bits in the scalar to use a
6919     // widening multiply by splatting to smaller element size.
6920     unsigned EltBits = VT.getScalarSizeInBits();
6921     unsigned ScalarBits = Op1.getValueSizeInBits();
6922     // Make sure we're getting all element bits from the scalar register.
6923     // FIXME: Support implicit sign extension of vmv.v.x?
6924     if (ScalarBits < EltBits)
6925       return SDValue();
6926 
6927     if (IsSignExt) {
6928       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6929         return SDValue();
6930     } else {
6931       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
6932       if (!DAG.MaskedValueIsZero(Op1, Mask))
6933         return SDValue();
6934     }
6935 
6936     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
6937   } else
6938     return SDValue();
6939 
6940   Op0 = Op0.getOperand(0);
6941 
6942   // Re-introduce narrower extends if needed.
6943   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6944   if (Op0.getValueType() != NarrowVT)
6945     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6946   if (Op1.getValueType() != NarrowVT)
6947     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6948 
6949   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6950   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6951 }
6952 
6953 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6954                                                DAGCombinerInfo &DCI) const {
6955   SelectionDAG &DAG = DCI.DAG;
6956 
6957   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6958   // bits are demanded. N will be added to the Worklist if it was not deleted.
6959   // Caller should return SDValue(N, 0) if this returns true.
6960   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6961     SDValue Op = N->getOperand(OpNo);
6962     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6963     if (!SimplifyDemandedBits(Op, Mask, DCI))
6964       return false;
6965 
6966     if (N->getOpcode() != ISD::DELETED_NODE)
6967       DCI.AddToWorklist(N);
6968     return true;
6969   };
6970 
6971   switch (N->getOpcode()) {
6972   default:
6973     break;
6974   case RISCVISD::SplitF64: {
6975     SDValue Op0 = N->getOperand(0);
6976     // If the input to SplitF64 is just BuildPairF64 then the operation is
6977     // redundant. Instead, use BuildPairF64's operands directly.
6978     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6979       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6980 
6981     SDLoc DL(N);
6982 
6983     // It's cheaper to materialise two 32-bit integers than to load a double
6984     // from the constant pool and transfer it to integer registers through the
6985     // stack.
6986     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6987       APInt V = C->getValueAPF().bitcastToAPInt();
6988       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6989       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6990       return DCI.CombineTo(N, Lo, Hi);
6991     }
6992 
6993     // This is a target-specific version of a DAGCombine performed in
6994     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6995     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6996     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6997     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6998         !Op0.getNode()->hasOneUse())
6999       break;
7000     SDValue NewSplitF64 =
7001         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7002                     Op0.getOperand(0));
7003     SDValue Lo = NewSplitF64.getValue(0);
7004     SDValue Hi = NewSplitF64.getValue(1);
7005     APInt SignBit = APInt::getSignMask(32);
7006     if (Op0.getOpcode() == ISD::FNEG) {
7007       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7008                                   DAG.getConstant(SignBit, DL, MVT::i32));
7009       return DCI.CombineTo(N, Lo, NewHi);
7010     }
7011     assert(Op0.getOpcode() == ISD::FABS);
7012     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7013                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7014     return DCI.CombineTo(N, Lo, NewHi);
7015   }
7016   case RISCVISD::SLLW:
7017   case RISCVISD::SRAW:
7018   case RISCVISD::SRLW:
7019   case RISCVISD::ROLW:
7020   case RISCVISD::RORW: {
7021     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7022     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7023         SimplifyDemandedLowBitsHelper(1, 5))
7024       return SDValue(N, 0);
7025     break;
7026   }
7027   case RISCVISD::CLZW:
7028   case RISCVISD::CTZW: {
7029     // Only the lower 32 bits of the first operand are read
7030     if (SimplifyDemandedLowBitsHelper(0, 32))
7031       return SDValue(N, 0);
7032     break;
7033   }
7034   case RISCVISD::FSL:
7035   case RISCVISD::FSR: {
7036     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
7037     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
7038     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7039     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
7040       return SDValue(N, 0);
7041     break;
7042   }
7043   case RISCVISD::FSLW:
7044   case RISCVISD::FSRW: {
7045     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
7046     // read.
7047     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7048         SimplifyDemandedLowBitsHelper(1, 32) ||
7049         SimplifyDemandedLowBitsHelper(2, 6))
7050       return SDValue(N, 0);
7051     break;
7052   }
7053   case RISCVISD::GREV:
7054   case RISCVISD::GORC: {
7055     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7056     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7057     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7058     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7059       return SDValue(N, 0);
7060 
7061     return combineGREVI_GORCI(N, DCI.DAG);
7062   }
7063   case RISCVISD::GREVW:
7064   case RISCVISD::GORCW: {
7065     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7066     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7067         SimplifyDemandedLowBitsHelper(1, 5))
7068       return SDValue(N, 0);
7069 
7070     return combineGREVI_GORCI(N, DCI.DAG);
7071   }
7072   case RISCVISD::SHFL:
7073   case RISCVISD::UNSHFL: {
7074     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7075     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7076     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7077     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7078       return SDValue(N, 0);
7079 
7080     break;
7081   }
7082   case RISCVISD::SHFLW:
7083   case RISCVISD::UNSHFLW: {
7084     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7085     SDValue LHS = N->getOperand(0);
7086     SDValue RHS = N->getOperand(1);
7087     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7088     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7089     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7090         SimplifyDemandedLowBitsHelper(1, 4))
7091       return SDValue(N, 0);
7092 
7093     break;
7094   }
7095   case RISCVISD::BCOMPRESSW:
7096   case RISCVISD::BDECOMPRESSW: {
7097     // Only the lower 32 bits of LHS and RHS are read.
7098     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7099         SimplifyDemandedLowBitsHelper(1, 32))
7100       return SDValue(N, 0);
7101 
7102     break;
7103   }
7104   case RISCVISD::FMV_X_ANYEXTH:
7105   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7106     SDLoc DL(N);
7107     SDValue Op0 = N->getOperand(0);
7108     MVT VT = N->getSimpleValueType(0);
7109     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7110     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7111     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7112     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7113          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7114         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7115          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7116       assert(Op0.getOperand(0).getValueType() == VT &&
7117              "Unexpected value type!");
7118       return Op0.getOperand(0);
7119     }
7120 
7121     // This is a target-specific version of a DAGCombine performed in
7122     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7123     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7124     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7125     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7126         !Op0.getNode()->hasOneUse())
7127       break;
7128     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7129     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7130     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7131     if (Op0.getOpcode() == ISD::FNEG)
7132       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7133                          DAG.getConstant(SignBit, DL, VT));
7134 
7135     assert(Op0.getOpcode() == ISD::FABS);
7136     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7137                        DAG.getConstant(~SignBit, DL, VT));
7138   }
7139   case ISD::ADD:
7140     return performADDCombine(N, DAG, Subtarget);
7141   case ISD::SUB:
7142     return performSUBCombine(N, DAG);
7143   case ISD::AND:
7144     return performANDCombine(N, DAG);
7145   case ISD::OR:
7146     return performORCombine(N, DAG, Subtarget);
7147   case ISD::XOR:
7148     return performXORCombine(N, DAG);
7149   case ISD::ANY_EXTEND:
7150     return performANY_EXTENDCombine(N, DCI, Subtarget);
7151   case ISD::ZERO_EXTEND:
7152     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7153     // type legalization. This is safe because fp_to_uint produces poison if
7154     // it overflows.
7155     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
7156         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
7157         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
7158       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7159                          N->getOperand(0).getOperand(0));
7160     return SDValue();
7161   case RISCVISD::SELECT_CC: {
7162     // Transform
7163     SDValue LHS = N->getOperand(0);
7164     SDValue RHS = N->getOperand(1);
7165     SDValue TrueV = N->getOperand(3);
7166     SDValue FalseV = N->getOperand(4);
7167 
7168     // If the True and False values are the same, we don't need a select_cc.
7169     if (TrueV == FalseV)
7170       return TrueV;
7171 
7172     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7173     if (!ISD::isIntEqualitySetCC(CCVal))
7174       break;
7175 
7176     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7177     //      (select_cc X, Y, lt, trueV, falseV)
7178     // Sometimes the setcc is introduced after select_cc has been formed.
7179     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7180         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7181       // If we're looking for eq 0 instead of ne 0, we need to invert the
7182       // condition.
7183       bool Invert = CCVal == ISD::SETEQ;
7184       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7185       if (Invert)
7186         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7187 
7188       SDLoc DL(N);
7189       RHS = LHS.getOperand(1);
7190       LHS = LHS.getOperand(0);
7191       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7192 
7193       SDValue TargetCC = DAG.getCondCode(CCVal);
7194       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7195                          {LHS, RHS, TargetCC, TrueV, FalseV});
7196     }
7197 
7198     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7199     //      (select_cc X, Y, eq/ne, trueV, falseV)
7200     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7201       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7202                          {LHS.getOperand(0), LHS.getOperand(1),
7203                           N->getOperand(2), TrueV, FalseV});
7204     // (select_cc X, 1, setne, trueV, falseV) ->
7205     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7206     // This can occur when legalizing some floating point comparisons.
7207     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7208     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7209       SDLoc DL(N);
7210       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7211       SDValue TargetCC = DAG.getCondCode(CCVal);
7212       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7213       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7214                          {LHS, RHS, TargetCC, TrueV, FalseV});
7215     }
7216 
7217     break;
7218   }
7219   case RISCVISD::BR_CC: {
7220     SDValue LHS = N->getOperand(1);
7221     SDValue RHS = N->getOperand(2);
7222     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7223     if (!ISD::isIntEqualitySetCC(CCVal))
7224       break;
7225 
7226     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7227     //      (br_cc X, Y, lt, dest)
7228     // Sometimes the setcc is introduced after br_cc has been formed.
7229     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7230         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7231       // If we're looking for eq 0 instead of ne 0, we need to invert the
7232       // condition.
7233       bool Invert = CCVal == ISD::SETEQ;
7234       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7235       if (Invert)
7236         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7237 
7238       SDLoc DL(N);
7239       RHS = LHS.getOperand(1);
7240       LHS = LHS.getOperand(0);
7241       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7242 
7243       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7244                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7245                          N->getOperand(4));
7246     }
7247 
7248     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7249     //      (br_cc X, Y, eq/ne, trueV, falseV)
7250     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7251       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7252                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7253                          N->getOperand(3), N->getOperand(4));
7254 
7255     // (br_cc X, 1, setne, br_cc) ->
7256     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7257     // This can occur when legalizing some floating point comparisons.
7258     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7259     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7260       SDLoc DL(N);
7261       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7262       SDValue TargetCC = DAG.getCondCode(CCVal);
7263       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7264       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7265                          N->getOperand(0), LHS, RHS, TargetCC,
7266                          N->getOperand(4));
7267     }
7268     break;
7269   }
7270   case ISD::FCOPYSIGN: {
7271     EVT VT = N->getValueType(0);
7272     if (!VT.isVector())
7273       break;
7274     // There is a form of VFSGNJ which injects the negated sign of its second
7275     // operand. Try and bubble any FNEG up after the extend/round to produce
7276     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7277     // TRUNC=1.
7278     SDValue In2 = N->getOperand(1);
7279     // Avoid cases where the extend/round has multiple uses, as duplicating
7280     // those is typically more expensive than removing a fneg.
7281     if (!In2.hasOneUse())
7282       break;
7283     if (In2.getOpcode() != ISD::FP_EXTEND &&
7284         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7285       break;
7286     In2 = In2.getOperand(0);
7287     if (In2.getOpcode() != ISD::FNEG)
7288       break;
7289     SDLoc DL(N);
7290     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7291     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7292                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7293   }
7294   case ISD::MGATHER:
7295   case ISD::MSCATTER:
7296   case ISD::VP_GATHER:
7297   case ISD::VP_SCATTER: {
7298     if (!DCI.isBeforeLegalize())
7299       break;
7300     SDValue Index, ScaleOp;
7301     bool IsIndexScaled = false;
7302     bool IsIndexSigned = false;
7303     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7304       Index = VPGSN->getIndex();
7305       ScaleOp = VPGSN->getScale();
7306       IsIndexScaled = VPGSN->isIndexScaled();
7307       IsIndexSigned = VPGSN->isIndexSigned();
7308     } else {
7309       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7310       Index = MGSN->getIndex();
7311       ScaleOp = MGSN->getScale();
7312       IsIndexScaled = MGSN->isIndexScaled();
7313       IsIndexSigned = MGSN->isIndexSigned();
7314     }
7315     EVT IndexVT = Index.getValueType();
7316     MVT XLenVT = Subtarget.getXLenVT();
7317     // RISCV indexed loads only support the "unsigned unscaled" addressing
7318     // mode, so anything else must be manually legalized.
7319     bool NeedsIdxLegalization =
7320         IsIndexScaled ||
7321         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7322     if (!NeedsIdxLegalization)
7323       break;
7324 
7325     SDLoc DL(N);
7326 
7327     // Any index legalization should first promote to XLenVT, so we don't lose
7328     // bits when scaling. This may create an illegal index type so we let
7329     // LLVM's legalization take care of the splitting.
7330     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7331     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7332       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7333       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7334                           DL, IndexVT, Index);
7335     }
7336 
7337     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7338     if (IsIndexScaled && Scale != 1) {
7339       // Manually scale the indices by the element size.
7340       // TODO: Sanitize the scale operand here?
7341       // TODO: For VP nodes, should we use VP_SHL here?
7342       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7343       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7344       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7345     }
7346 
7347     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7348     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7349       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7350                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7351                               VPGN->getScale(), VPGN->getMask(),
7352                               VPGN->getVectorLength()},
7353                              VPGN->getMemOperand(), NewIndexTy);
7354     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7355       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7356                               {VPSN->getChain(), VPSN->getValue(),
7357                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7358                                VPSN->getMask(), VPSN->getVectorLength()},
7359                               VPSN->getMemOperand(), NewIndexTy);
7360     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7361       return DAG.getMaskedGather(
7362           N->getVTList(), MGN->getMemoryVT(), DL,
7363           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7364            MGN->getBasePtr(), Index, MGN->getScale()},
7365           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7366     const auto *MSN = cast<MaskedScatterSDNode>(N);
7367     return DAG.getMaskedScatter(
7368         N->getVTList(), MSN->getMemoryVT(), DL,
7369         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7370          Index, MSN->getScale()},
7371         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7372   }
7373   case RISCVISD::SRA_VL:
7374   case RISCVISD::SRL_VL:
7375   case RISCVISD::SHL_VL: {
7376     SDValue ShAmt = N->getOperand(1);
7377     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7378       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7379       SDLoc DL(N);
7380       SDValue VL = N->getOperand(3);
7381       EVT VT = N->getValueType(0);
7382       ShAmt =
7383           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7384       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7385                          N->getOperand(2), N->getOperand(3));
7386     }
7387     break;
7388   }
7389   case ISD::SRA:
7390   case ISD::SRL:
7391   case ISD::SHL: {
7392     SDValue ShAmt = N->getOperand(1);
7393     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7394       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7395       SDLoc DL(N);
7396       EVT VT = N->getValueType(0);
7397       ShAmt =
7398           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7399       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7400     }
7401     break;
7402   }
7403   case RISCVISD::MUL_VL: {
7404     SDValue Op0 = N->getOperand(0);
7405     SDValue Op1 = N->getOperand(1);
7406     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7407       return V;
7408     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7409       return V;
7410     return SDValue();
7411   }
7412   case ISD::STORE: {
7413     auto *Store = cast<StoreSDNode>(N);
7414     SDValue Val = Store->getValue();
7415     // Combine store of vmv.x.s to vse with VL of 1.
7416     // FIXME: Support FP.
7417     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7418       SDValue Src = Val.getOperand(0);
7419       EVT VecVT = Src.getValueType();
7420       EVT MemVT = Store->getMemoryVT();
7421       // The memory VT and the element type must match.
7422       if (VecVT.getVectorElementType() == MemVT) {
7423         SDLoc DL(N);
7424         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7425         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7426                               DAG.getConstant(1, DL, MaskVT),
7427                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7428                               Store->getPointerInfo(),
7429                               Store->getOriginalAlign(),
7430                               Store->getMemOperand()->getFlags());
7431       }
7432     }
7433 
7434     break;
7435   }
7436   }
7437 
7438   return SDValue();
7439 }
7440 
7441 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7442     const SDNode *N, CombineLevel Level) const {
7443   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7444   // materialised in fewer instructions than `(OP _, c1)`:
7445   //
7446   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7447   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7448   SDValue N0 = N->getOperand(0);
7449   EVT Ty = N0.getValueType();
7450   if (Ty.isScalarInteger() &&
7451       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7452     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7453     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7454     if (C1 && C2) {
7455       const APInt &C1Int = C1->getAPIntValue();
7456       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7457 
7458       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7459       // and the combine should happen, to potentially allow further combines
7460       // later.
7461       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7462           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7463         return true;
7464 
7465       // We can materialise `c1` in an add immediate, so it's "free", and the
7466       // combine should be prevented.
7467       if (C1Int.getMinSignedBits() <= 64 &&
7468           isLegalAddImmediate(C1Int.getSExtValue()))
7469         return false;
7470 
7471       // Neither constant will fit into an immediate, so find materialisation
7472       // costs.
7473       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7474                                               Subtarget.getFeatureBits(),
7475                                               /*CompressionCost*/true);
7476       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7477           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7478           /*CompressionCost*/true);
7479 
7480       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7481       // combine should be prevented.
7482       if (C1Cost < ShiftedC1Cost)
7483         return false;
7484     }
7485   }
7486   return true;
7487 }
7488 
7489 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7490     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7491     TargetLoweringOpt &TLO) const {
7492   // Delay this optimization as late as possible.
7493   if (!TLO.LegalOps)
7494     return false;
7495 
7496   EVT VT = Op.getValueType();
7497   if (VT.isVector())
7498     return false;
7499 
7500   // Only handle AND for now.
7501   if (Op.getOpcode() != ISD::AND)
7502     return false;
7503 
7504   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7505   if (!C)
7506     return false;
7507 
7508   const APInt &Mask = C->getAPIntValue();
7509 
7510   // Clear all non-demanded bits initially.
7511   APInt ShrunkMask = Mask & DemandedBits;
7512 
7513   // Try to make a smaller immediate by setting undemanded bits.
7514 
7515   APInt ExpandedMask = Mask | ~DemandedBits;
7516 
7517   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7518     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7519   };
7520   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7521     if (NewMask == Mask)
7522       return true;
7523     SDLoc DL(Op);
7524     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7525     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7526     return TLO.CombineTo(Op, NewOp);
7527   };
7528 
7529   // If the shrunk mask fits in sign extended 12 bits, let the target
7530   // independent code apply it.
7531   if (ShrunkMask.isSignedIntN(12))
7532     return false;
7533 
7534   // Preserve (and X, 0xffff) when zext.h is supported.
7535   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7536     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7537     if (IsLegalMask(NewMask))
7538       return UseMask(NewMask);
7539   }
7540 
7541   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7542   if (VT == MVT::i64) {
7543     APInt NewMask = APInt(64, 0xffffffff);
7544     if (IsLegalMask(NewMask))
7545       return UseMask(NewMask);
7546   }
7547 
7548   // For the remaining optimizations, we need to be able to make a negative
7549   // number through a combination of mask and undemanded bits.
7550   if (!ExpandedMask.isNegative())
7551     return false;
7552 
7553   // What is the fewest number of bits we need to represent the negative number.
7554   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7555 
7556   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7557   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7558   APInt NewMask = ShrunkMask;
7559   if (MinSignedBits <= 12)
7560     NewMask.setBitsFrom(11);
7561   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7562     NewMask.setBitsFrom(31);
7563   else
7564     return false;
7565 
7566   // Check that our new mask is a subset of the demanded mask.
7567   assert(IsLegalMask(NewMask));
7568   return UseMask(NewMask);
7569 }
7570 
7571 static void computeGREV(APInt &Src, unsigned ShAmt) {
7572   ShAmt &= Src.getBitWidth() - 1;
7573   uint64_t x = Src.getZExtValue();
7574   if (ShAmt & 1)
7575     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7576   if (ShAmt & 2)
7577     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7578   if (ShAmt & 4)
7579     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7580   if (ShAmt & 8)
7581     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7582   if (ShAmt & 16)
7583     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7584   if (ShAmt & 32)
7585     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7586   Src = x;
7587 }
7588 
7589 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7590                                                         KnownBits &Known,
7591                                                         const APInt &DemandedElts,
7592                                                         const SelectionDAG &DAG,
7593                                                         unsigned Depth) const {
7594   unsigned BitWidth = Known.getBitWidth();
7595   unsigned Opc = Op.getOpcode();
7596   assert((Opc >= ISD::BUILTIN_OP_END ||
7597           Opc == ISD::INTRINSIC_WO_CHAIN ||
7598           Opc == ISD::INTRINSIC_W_CHAIN ||
7599           Opc == ISD::INTRINSIC_VOID) &&
7600          "Should use MaskedValueIsZero if you don't know whether Op"
7601          " is a target node!");
7602 
7603   Known.resetAll();
7604   switch (Opc) {
7605   default: break;
7606   case RISCVISD::SELECT_CC: {
7607     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7608     // If we don't know any bits, early out.
7609     if (Known.isUnknown())
7610       break;
7611     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7612 
7613     // Only known if known in both the LHS and RHS.
7614     Known = KnownBits::commonBits(Known, Known2);
7615     break;
7616   }
7617   case RISCVISD::REMUW: {
7618     KnownBits Known2;
7619     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7620     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7621     // We only care about the lower 32 bits.
7622     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7623     // Restore the original width by sign extending.
7624     Known = Known.sext(BitWidth);
7625     break;
7626   }
7627   case RISCVISD::DIVUW: {
7628     KnownBits Known2;
7629     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7630     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7631     // We only care about the lower 32 bits.
7632     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7633     // Restore the original width by sign extending.
7634     Known = Known.sext(BitWidth);
7635     break;
7636   }
7637   case RISCVISD::CTZW: {
7638     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7639     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7640     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7641     Known.Zero.setBitsFrom(LowBits);
7642     break;
7643   }
7644   case RISCVISD::CLZW: {
7645     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7646     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7647     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7648     Known.Zero.setBitsFrom(LowBits);
7649     break;
7650   }
7651   case RISCVISD::GREV:
7652   case RISCVISD::GREVW: {
7653     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7654       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7655       if (Opc == RISCVISD::GREVW)
7656         Known = Known.trunc(32);
7657       unsigned ShAmt = C->getZExtValue();
7658       computeGREV(Known.Zero, ShAmt);
7659       computeGREV(Known.One, ShAmt);
7660       if (Opc == RISCVISD::GREVW)
7661         Known = Known.sext(BitWidth);
7662     }
7663     break;
7664   }
7665   case RISCVISD::READ_VLENB:
7666     // We assume VLENB is at least 16 bytes.
7667     Known.Zero.setLowBits(4);
7668     // We assume VLENB is no more than 65536 / 8 bytes.
7669     Known.Zero.setBitsFrom(14);
7670     break;
7671   case ISD::INTRINSIC_W_CHAIN: {
7672     unsigned IntNo = Op.getConstantOperandVal(1);
7673     switch (IntNo) {
7674     default:
7675       // We can't do anything for most intrinsics.
7676       break;
7677     case Intrinsic::riscv_vsetvli:
7678     case Intrinsic::riscv_vsetvlimax:
7679       // Assume that VL output is positive and would fit in an int32_t.
7680       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7681       if (BitWidth >= 32)
7682         Known.Zero.setBitsFrom(31);
7683       break;
7684     }
7685     break;
7686   }
7687   }
7688 }
7689 
7690 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7691     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7692     unsigned Depth) const {
7693   switch (Op.getOpcode()) {
7694   default:
7695     break;
7696   case RISCVISD::SELECT_CC: {
7697     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7698     if (Tmp == 1) return 1;  // Early out.
7699     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7700     return std::min(Tmp, Tmp2);
7701   }
7702   case RISCVISD::SLLW:
7703   case RISCVISD::SRAW:
7704   case RISCVISD::SRLW:
7705   case RISCVISD::DIVW:
7706   case RISCVISD::DIVUW:
7707   case RISCVISD::REMUW:
7708   case RISCVISD::ROLW:
7709   case RISCVISD::RORW:
7710   case RISCVISD::GREVW:
7711   case RISCVISD::GORCW:
7712   case RISCVISD::FSLW:
7713   case RISCVISD::FSRW:
7714   case RISCVISD::SHFLW:
7715   case RISCVISD::UNSHFLW:
7716   case RISCVISD::BCOMPRESSW:
7717   case RISCVISD::BDECOMPRESSW:
7718   case RISCVISD::FCVT_W_RTZ_RV64:
7719   case RISCVISD::FCVT_WU_RTZ_RV64:
7720     // TODO: As the result is sign-extended, this is conservatively correct. A
7721     // more precise answer could be calculated for SRAW depending on known
7722     // bits in the shift amount.
7723     return 33;
7724   case RISCVISD::SHFL:
7725   case RISCVISD::UNSHFL: {
7726     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7727     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7728     // will stay within the upper 32 bits. If there were more than 32 sign bits
7729     // before there will be at least 33 sign bits after.
7730     if (Op.getValueType() == MVT::i64 &&
7731         isa<ConstantSDNode>(Op.getOperand(1)) &&
7732         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7733       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7734       if (Tmp > 32)
7735         return 33;
7736     }
7737     break;
7738   }
7739   case RISCVISD::VMV_X_S:
7740     // The number of sign bits of the scalar result is computed by obtaining the
7741     // element type of the input vector operand, subtracting its width from the
7742     // XLEN, and then adding one (sign bit within the element type). If the
7743     // element type is wider than XLen, the least-significant XLEN bits are
7744     // taken.
7745     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7746       return 1;
7747     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7748   }
7749 
7750   return 1;
7751 }
7752 
7753 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7754                                                   MachineBasicBlock *BB) {
7755   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7756 
7757   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7758   // Should the count have wrapped while it was being read, we need to try
7759   // again.
7760   // ...
7761   // read:
7762   // rdcycleh x3 # load high word of cycle
7763   // rdcycle  x2 # load low word of cycle
7764   // rdcycleh x4 # load high word of cycle
7765   // bne x3, x4, read # check if high word reads match, otherwise try again
7766   // ...
7767 
7768   MachineFunction &MF = *BB->getParent();
7769   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7770   MachineFunction::iterator It = ++BB->getIterator();
7771 
7772   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7773   MF.insert(It, LoopMBB);
7774 
7775   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7776   MF.insert(It, DoneMBB);
7777 
7778   // Transfer the remainder of BB and its successor edges to DoneMBB.
7779   DoneMBB->splice(DoneMBB->begin(), BB,
7780                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7781   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7782 
7783   BB->addSuccessor(LoopMBB);
7784 
7785   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7786   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7787   Register LoReg = MI.getOperand(0).getReg();
7788   Register HiReg = MI.getOperand(1).getReg();
7789   DebugLoc DL = MI.getDebugLoc();
7790 
7791   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7792   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7793       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7794       .addReg(RISCV::X0);
7795   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7796       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7797       .addReg(RISCV::X0);
7798   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7799       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7800       .addReg(RISCV::X0);
7801 
7802   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7803       .addReg(HiReg)
7804       .addReg(ReadAgainReg)
7805       .addMBB(LoopMBB);
7806 
7807   LoopMBB->addSuccessor(LoopMBB);
7808   LoopMBB->addSuccessor(DoneMBB);
7809 
7810   MI.eraseFromParent();
7811 
7812   return DoneMBB;
7813 }
7814 
7815 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7816                                              MachineBasicBlock *BB) {
7817   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7818 
7819   MachineFunction &MF = *BB->getParent();
7820   DebugLoc DL = MI.getDebugLoc();
7821   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7822   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7823   Register LoReg = MI.getOperand(0).getReg();
7824   Register HiReg = MI.getOperand(1).getReg();
7825   Register SrcReg = MI.getOperand(2).getReg();
7826   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7827   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7828 
7829   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7830                           RI);
7831   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7832   MachineMemOperand *MMOLo =
7833       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7834   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7835       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7836   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7837       .addFrameIndex(FI)
7838       .addImm(0)
7839       .addMemOperand(MMOLo);
7840   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7841       .addFrameIndex(FI)
7842       .addImm(4)
7843       .addMemOperand(MMOHi);
7844   MI.eraseFromParent(); // The pseudo instruction is gone now.
7845   return BB;
7846 }
7847 
7848 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7849                                                  MachineBasicBlock *BB) {
7850   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7851          "Unexpected instruction");
7852 
7853   MachineFunction &MF = *BB->getParent();
7854   DebugLoc DL = MI.getDebugLoc();
7855   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7856   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7857   Register DstReg = MI.getOperand(0).getReg();
7858   Register LoReg = MI.getOperand(1).getReg();
7859   Register HiReg = MI.getOperand(2).getReg();
7860   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7861   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7862 
7863   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7864   MachineMemOperand *MMOLo =
7865       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7866   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7867       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7868   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7869       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7870       .addFrameIndex(FI)
7871       .addImm(0)
7872       .addMemOperand(MMOLo);
7873   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7874       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7875       .addFrameIndex(FI)
7876       .addImm(4)
7877       .addMemOperand(MMOHi);
7878   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7879   MI.eraseFromParent(); // The pseudo instruction is gone now.
7880   return BB;
7881 }
7882 
7883 static bool isSelectPseudo(MachineInstr &MI) {
7884   switch (MI.getOpcode()) {
7885   default:
7886     return false;
7887   case RISCV::Select_GPR_Using_CC_GPR:
7888   case RISCV::Select_FPR16_Using_CC_GPR:
7889   case RISCV::Select_FPR32_Using_CC_GPR:
7890   case RISCV::Select_FPR64_Using_CC_GPR:
7891     return true;
7892   }
7893 }
7894 
7895 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7896                                            MachineBasicBlock *BB,
7897                                            const RISCVSubtarget &Subtarget) {
7898   // To "insert" Select_* instructions, we actually have to insert the triangle
7899   // control-flow pattern.  The incoming instructions know the destination vreg
7900   // to set, the condition code register to branch on, the true/false values to
7901   // select between, and the condcode to use to select the appropriate branch.
7902   //
7903   // We produce the following control flow:
7904   //     HeadMBB
7905   //     |  \
7906   //     |  IfFalseMBB
7907   //     | /
7908   //    TailMBB
7909   //
7910   // When we find a sequence of selects we attempt to optimize their emission
7911   // by sharing the control flow. Currently we only handle cases where we have
7912   // multiple selects with the exact same condition (same LHS, RHS and CC).
7913   // The selects may be interleaved with other instructions if the other
7914   // instructions meet some requirements we deem safe:
7915   // - They are debug instructions. Otherwise,
7916   // - They do not have side-effects, do not access memory and their inputs do
7917   //   not depend on the results of the select pseudo-instructions.
7918   // The TrueV/FalseV operands of the selects cannot depend on the result of
7919   // previous selects in the sequence.
7920   // These conditions could be further relaxed. See the X86 target for a
7921   // related approach and more information.
7922   Register LHS = MI.getOperand(1).getReg();
7923   Register RHS = MI.getOperand(2).getReg();
7924   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7925 
7926   SmallVector<MachineInstr *, 4> SelectDebugValues;
7927   SmallSet<Register, 4> SelectDests;
7928   SelectDests.insert(MI.getOperand(0).getReg());
7929 
7930   MachineInstr *LastSelectPseudo = &MI;
7931 
7932   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7933        SequenceMBBI != E; ++SequenceMBBI) {
7934     if (SequenceMBBI->isDebugInstr())
7935       continue;
7936     else if (isSelectPseudo(*SequenceMBBI)) {
7937       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7938           SequenceMBBI->getOperand(2).getReg() != RHS ||
7939           SequenceMBBI->getOperand(3).getImm() != CC ||
7940           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7941           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7942         break;
7943       LastSelectPseudo = &*SequenceMBBI;
7944       SequenceMBBI->collectDebugValues(SelectDebugValues);
7945       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7946     } else {
7947       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7948           SequenceMBBI->mayLoadOrStore())
7949         break;
7950       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7951             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7952           }))
7953         break;
7954     }
7955   }
7956 
7957   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7958   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7959   DebugLoc DL = MI.getDebugLoc();
7960   MachineFunction::iterator I = ++BB->getIterator();
7961 
7962   MachineBasicBlock *HeadMBB = BB;
7963   MachineFunction *F = BB->getParent();
7964   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7965   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7966 
7967   F->insert(I, IfFalseMBB);
7968   F->insert(I, TailMBB);
7969 
7970   // Transfer debug instructions associated with the selects to TailMBB.
7971   for (MachineInstr *DebugInstr : SelectDebugValues) {
7972     TailMBB->push_back(DebugInstr->removeFromParent());
7973   }
7974 
7975   // Move all instructions after the sequence to TailMBB.
7976   TailMBB->splice(TailMBB->end(), HeadMBB,
7977                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7978   // Update machine-CFG edges by transferring all successors of the current
7979   // block to the new block which will contain the Phi nodes for the selects.
7980   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7981   // Set the successors for HeadMBB.
7982   HeadMBB->addSuccessor(IfFalseMBB);
7983   HeadMBB->addSuccessor(TailMBB);
7984 
7985   // Insert appropriate branch.
7986   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7987     .addReg(LHS)
7988     .addReg(RHS)
7989     .addMBB(TailMBB);
7990 
7991   // IfFalseMBB just falls through to TailMBB.
7992   IfFalseMBB->addSuccessor(TailMBB);
7993 
7994   // Create PHIs for all of the select pseudo-instructions.
7995   auto SelectMBBI = MI.getIterator();
7996   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7997   auto InsertionPoint = TailMBB->begin();
7998   while (SelectMBBI != SelectEnd) {
7999     auto Next = std::next(SelectMBBI);
8000     if (isSelectPseudo(*SelectMBBI)) {
8001       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8002       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8003               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8004           .addReg(SelectMBBI->getOperand(4).getReg())
8005           .addMBB(HeadMBB)
8006           .addReg(SelectMBBI->getOperand(5).getReg())
8007           .addMBB(IfFalseMBB);
8008       SelectMBBI->eraseFromParent();
8009     }
8010     SelectMBBI = Next;
8011   }
8012 
8013   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8014   return TailMBB;
8015 }
8016 
8017 MachineBasicBlock *
8018 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8019                                                  MachineBasicBlock *BB) const {
8020   switch (MI.getOpcode()) {
8021   default:
8022     llvm_unreachable("Unexpected instr type to insert");
8023   case RISCV::ReadCycleWide:
8024     assert(!Subtarget.is64Bit() &&
8025            "ReadCycleWrite is only to be used on riscv32");
8026     return emitReadCycleWidePseudo(MI, BB);
8027   case RISCV::Select_GPR_Using_CC_GPR:
8028   case RISCV::Select_FPR16_Using_CC_GPR:
8029   case RISCV::Select_FPR32_Using_CC_GPR:
8030   case RISCV::Select_FPR64_Using_CC_GPR:
8031     return emitSelectPseudo(MI, BB, Subtarget);
8032   case RISCV::BuildPairF64Pseudo:
8033     return emitBuildPairF64Pseudo(MI, BB);
8034   case RISCV::SplitF64Pseudo:
8035     return emitSplitF64Pseudo(MI, BB);
8036   }
8037 }
8038 
8039 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8040                                                         SDNode *Node) const {
8041   // Add FRM dependency to any instructions with dynamic rounding mode.
8042   unsigned Opc = MI.getOpcode();
8043   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8044   if (Idx < 0)
8045     return;
8046   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8047     return;
8048   // If the instruction already reads FRM, don't add another read.
8049   if (MI.readsRegister(RISCV::FRM))
8050     return;
8051   MI.addOperand(
8052       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8053 }
8054 
8055 // Calling Convention Implementation.
8056 // The expectations for frontend ABI lowering vary from target to target.
8057 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8058 // details, but this is a longer term goal. For now, we simply try to keep the
8059 // role of the frontend as simple and well-defined as possible. The rules can
8060 // be summarised as:
8061 // * Never split up large scalar arguments. We handle them here.
8062 // * If a hardfloat calling convention is being used, and the struct may be
8063 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8064 // available, then pass as two separate arguments. If either the GPRs or FPRs
8065 // are exhausted, then pass according to the rule below.
8066 // * If a struct could never be passed in registers or directly in a stack
8067 // slot (as it is larger than 2*XLEN and the floating point rules don't
8068 // apply), then pass it using a pointer with the byval attribute.
8069 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8070 // word-sized array or a 2*XLEN scalar (depending on alignment).
8071 // * The frontend can determine whether a struct is returned by reference or
8072 // not based on its size and fields. If it will be returned by reference, the
8073 // frontend must modify the prototype so a pointer with the sret annotation is
8074 // passed as the first argument. This is not necessary for large scalar
8075 // returns.
8076 // * Struct return values and varargs should be coerced to structs containing
8077 // register-size fields in the same situations they would be for fixed
8078 // arguments.
8079 
8080 static const MCPhysReg ArgGPRs[] = {
8081   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8082   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8083 };
8084 static const MCPhysReg ArgFPR16s[] = {
8085   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8086   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8087 };
8088 static const MCPhysReg ArgFPR32s[] = {
8089   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8090   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8091 };
8092 static const MCPhysReg ArgFPR64s[] = {
8093   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8094   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8095 };
8096 // This is an interim calling convention and it may be changed in the future.
8097 static const MCPhysReg ArgVRs[] = {
8098     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8099     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8100     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8101 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8102                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8103                                      RISCV::V20M2, RISCV::V22M2};
8104 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8105                                      RISCV::V20M4};
8106 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8107 
8108 // Pass a 2*XLEN argument that has been split into two XLEN values through
8109 // registers or the stack as necessary.
8110 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8111                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8112                                 MVT ValVT2, MVT LocVT2,
8113                                 ISD::ArgFlagsTy ArgFlags2) {
8114   unsigned XLenInBytes = XLen / 8;
8115   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8116     // At least one half can be passed via register.
8117     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8118                                      VA1.getLocVT(), CCValAssign::Full));
8119   } else {
8120     // Both halves must be passed on the stack, with proper alignment.
8121     Align StackAlign =
8122         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8123     State.addLoc(
8124         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8125                             State.AllocateStack(XLenInBytes, StackAlign),
8126                             VA1.getLocVT(), CCValAssign::Full));
8127     State.addLoc(CCValAssign::getMem(
8128         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8129         LocVT2, CCValAssign::Full));
8130     return false;
8131   }
8132 
8133   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8134     // The second half can also be passed via register.
8135     State.addLoc(
8136         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8137   } else {
8138     // The second half is passed via the stack, without additional alignment.
8139     State.addLoc(CCValAssign::getMem(
8140         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8141         LocVT2, CCValAssign::Full));
8142   }
8143 
8144   return false;
8145 }
8146 
8147 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8148                                Optional<unsigned> FirstMaskArgument,
8149                                CCState &State, const RISCVTargetLowering &TLI) {
8150   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8151   if (RC == &RISCV::VRRegClass) {
8152     // Assign the first mask argument to V0.
8153     // This is an interim calling convention and it may be changed in the
8154     // future.
8155     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8156       return State.AllocateReg(RISCV::V0);
8157     return State.AllocateReg(ArgVRs);
8158   }
8159   if (RC == &RISCV::VRM2RegClass)
8160     return State.AllocateReg(ArgVRM2s);
8161   if (RC == &RISCV::VRM4RegClass)
8162     return State.AllocateReg(ArgVRM4s);
8163   if (RC == &RISCV::VRM8RegClass)
8164     return State.AllocateReg(ArgVRM8s);
8165   llvm_unreachable("Unhandled register class for ValueType");
8166 }
8167 
8168 // Implements the RISC-V calling convention. Returns true upon failure.
8169 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8170                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8171                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8172                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8173                      Optional<unsigned> FirstMaskArgument) {
8174   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8175   assert(XLen == 32 || XLen == 64);
8176   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8177 
8178   // Any return value split in to more than two values can't be returned
8179   // directly. Vectors are returned via the available vector registers.
8180   if (!LocVT.isVector() && IsRet && ValNo > 1)
8181     return true;
8182 
8183   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8184   // variadic argument, or if no F16/F32 argument registers are available.
8185   bool UseGPRForF16_F32 = true;
8186   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8187   // variadic argument, or if no F64 argument registers are available.
8188   bool UseGPRForF64 = true;
8189 
8190   switch (ABI) {
8191   default:
8192     llvm_unreachable("Unexpected ABI");
8193   case RISCVABI::ABI_ILP32:
8194   case RISCVABI::ABI_LP64:
8195     break;
8196   case RISCVABI::ABI_ILP32F:
8197   case RISCVABI::ABI_LP64F:
8198     UseGPRForF16_F32 = !IsFixed;
8199     break;
8200   case RISCVABI::ABI_ILP32D:
8201   case RISCVABI::ABI_LP64D:
8202     UseGPRForF16_F32 = !IsFixed;
8203     UseGPRForF64 = !IsFixed;
8204     break;
8205   }
8206 
8207   // FPR16, FPR32, and FPR64 alias each other.
8208   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8209     UseGPRForF16_F32 = true;
8210     UseGPRForF64 = true;
8211   }
8212 
8213   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8214   // similar local variables rather than directly checking against the target
8215   // ABI.
8216 
8217   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8218     LocVT = XLenVT;
8219     LocInfo = CCValAssign::BCvt;
8220   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8221     LocVT = MVT::i64;
8222     LocInfo = CCValAssign::BCvt;
8223   }
8224 
8225   // If this is a variadic argument, the RISC-V calling convention requires
8226   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8227   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8228   // be used regardless of whether the original argument was split during
8229   // legalisation or not. The argument will not be passed by registers if the
8230   // original type is larger than 2*XLEN, so the register alignment rule does
8231   // not apply.
8232   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8233   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8234       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8235     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8236     // Skip 'odd' register if necessary.
8237     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8238       State.AllocateReg(ArgGPRs);
8239   }
8240 
8241   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8242   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8243       State.getPendingArgFlags();
8244 
8245   assert(PendingLocs.size() == PendingArgFlags.size() &&
8246          "PendingLocs and PendingArgFlags out of sync");
8247 
8248   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8249   // registers are exhausted.
8250   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8251     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8252            "Can't lower f64 if it is split");
8253     // Depending on available argument GPRS, f64 may be passed in a pair of
8254     // GPRs, split between a GPR and the stack, or passed completely on the
8255     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8256     // cases.
8257     Register Reg = State.AllocateReg(ArgGPRs);
8258     LocVT = MVT::i32;
8259     if (!Reg) {
8260       unsigned StackOffset = State.AllocateStack(8, Align(8));
8261       State.addLoc(
8262           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8263       return false;
8264     }
8265     if (!State.AllocateReg(ArgGPRs))
8266       State.AllocateStack(4, Align(4));
8267     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8268     return false;
8269   }
8270 
8271   // Fixed-length vectors are located in the corresponding scalable-vector
8272   // container types.
8273   if (ValVT.isFixedLengthVector())
8274     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8275 
8276   // Split arguments might be passed indirectly, so keep track of the pending
8277   // values. Split vectors are passed via a mix of registers and indirectly, so
8278   // treat them as we would any other argument.
8279   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8280     LocVT = XLenVT;
8281     LocInfo = CCValAssign::Indirect;
8282     PendingLocs.push_back(
8283         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8284     PendingArgFlags.push_back(ArgFlags);
8285     if (!ArgFlags.isSplitEnd()) {
8286       return false;
8287     }
8288   }
8289 
8290   // If the split argument only had two elements, it should be passed directly
8291   // in registers or on the stack.
8292   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8293       PendingLocs.size() <= 2) {
8294     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8295     // Apply the normal calling convention rules to the first half of the
8296     // split argument.
8297     CCValAssign VA = PendingLocs[0];
8298     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8299     PendingLocs.clear();
8300     PendingArgFlags.clear();
8301     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8302                                ArgFlags);
8303   }
8304 
8305   // Allocate to a register if possible, or else a stack slot.
8306   Register Reg;
8307   unsigned StoreSizeBytes = XLen / 8;
8308   Align StackAlign = Align(XLen / 8);
8309 
8310   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8311     Reg = State.AllocateReg(ArgFPR16s);
8312   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8313     Reg = State.AllocateReg(ArgFPR32s);
8314   else if (ValVT == MVT::f64 && !UseGPRForF64)
8315     Reg = State.AllocateReg(ArgFPR64s);
8316   else if (ValVT.isVector()) {
8317     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8318     if (!Reg) {
8319       // For return values, the vector must be passed fully via registers or
8320       // via the stack.
8321       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8322       // but we're using all of them.
8323       if (IsRet)
8324         return true;
8325       // Try using a GPR to pass the address
8326       if ((Reg = State.AllocateReg(ArgGPRs))) {
8327         LocVT = XLenVT;
8328         LocInfo = CCValAssign::Indirect;
8329       } else if (ValVT.isScalableVector()) {
8330         report_fatal_error("Unable to pass scalable vector types on the stack");
8331       } else {
8332         // Pass fixed-length vectors on the stack.
8333         LocVT = ValVT;
8334         StoreSizeBytes = ValVT.getStoreSize();
8335         // Align vectors to their element sizes, being careful for vXi1
8336         // vectors.
8337         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8338       }
8339     }
8340   } else {
8341     Reg = State.AllocateReg(ArgGPRs);
8342   }
8343 
8344   unsigned StackOffset =
8345       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8346 
8347   // If we reach this point and PendingLocs is non-empty, we must be at the
8348   // end of a split argument that must be passed indirectly.
8349   if (!PendingLocs.empty()) {
8350     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8351     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8352 
8353     for (auto &It : PendingLocs) {
8354       if (Reg)
8355         It.convertToReg(Reg);
8356       else
8357         It.convertToMem(StackOffset);
8358       State.addLoc(It);
8359     }
8360     PendingLocs.clear();
8361     PendingArgFlags.clear();
8362     return false;
8363   }
8364 
8365   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8366           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8367          "Expected an XLenVT or vector types at this stage");
8368 
8369   if (Reg) {
8370     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8371     return false;
8372   }
8373 
8374   // When a floating-point value is passed on the stack, no bit-conversion is
8375   // needed.
8376   if (ValVT.isFloatingPoint()) {
8377     LocVT = ValVT;
8378     LocInfo = CCValAssign::Full;
8379   }
8380   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8381   return false;
8382 }
8383 
8384 template <typename ArgTy>
8385 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8386   for (const auto &ArgIdx : enumerate(Args)) {
8387     MVT ArgVT = ArgIdx.value().VT;
8388     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8389       return ArgIdx.index();
8390   }
8391   return None;
8392 }
8393 
8394 void RISCVTargetLowering::analyzeInputArgs(
8395     MachineFunction &MF, CCState &CCInfo,
8396     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8397     RISCVCCAssignFn Fn) const {
8398   unsigned NumArgs = Ins.size();
8399   FunctionType *FType = MF.getFunction().getFunctionType();
8400 
8401   Optional<unsigned> FirstMaskArgument;
8402   if (Subtarget.hasVInstructions())
8403     FirstMaskArgument = preAssignMask(Ins);
8404 
8405   for (unsigned i = 0; i != NumArgs; ++i) {
8406     MVT ArgVT = Ins[i].VT;
8407     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8408 
8409     Type *ArgTy = nullptr;
8410     if (IsRet)
8411       ArgTy = FType->getReturnType();
8412     else if (Ins[i].isOrigArg())
8413       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8414 
8415     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8416     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8417            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8418            FirstMaskArgument)) {
8419       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8420                         << EVT(ArgVT).getEVTString() << '\n');
8421       llvm_unreachable(nullptr);
8422     }
8423   }
8424 }
8425 
8426 void RISCVTargetLowering::analyzeOutputArgs(
8427     MachineFunction &MF, CCState &CCInfo,
8428     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8429     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8430   unsigned NumArgs = Outs.size();
8431 
8432   Optional<unsigned> FirstMaskArgument;
8433   if (Subtarget.hasVInstructions())
8434     FirstMaskArgument = preAssignMask(Outs);
8435 
8436   for (unsigned i = 0; i != NumArgs; i++) {
8437     MVT ArgVT = Outs[i].VT;
8438     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8439     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8440 
8441     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8442     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8443            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8444            FirstMaskArgument)) {
8445       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8446                         << EVT(ArgVT).getEVTString() << "\n");
8447       llvm_unreachable(nullptr);
8448     }
8449   }
8450 }
8451 
8452 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8453 // values.
8454 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8455                                    const CCValAssign &VA, const SDLoc &DL,
8456                                    const RISCVSubtarget &Subtarget) {
8457   switch (VA.getLocInfo()) {
8458   default:
8459     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8460   case CCValAssign::Full:
8461     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8462       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8463     break;
8464   case CCValAssign::BCvt:
8465     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8466       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8467     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8468       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8469     else
8470       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8471     break;
8472   }
8473   return Val;
8474 }
8475 
8476 // The caller is responsible for loading the full value if the argument is
8477 // passed with CCValAssign::Indirect.
8478 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8479                                 const CCValAssign &VA, const SDLoc &DL,
8480                                 const RISCVTargetLowering &TLI) {
8481   MachineFunction &MF = DAG.getMachineFunction();
8482   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8483   EVT LocVT = VA.getLocVT();
8484   SDValue Val;
8485   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8486   Register VReg = RegInfo.createVirtualRegister(RC);
8487   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8488   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8489 
8490   if (VA.getLocInfo() == CCValAssign::Indirect)
8491     return Val;
8492 
8493   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8494 }
8495 
8496 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8497                                    const CCValAssign &VA, const SDLoc &DL,
8498                                    const RISCVSubtarget &Subtarget) {
8499   EVT LocVT = VA.getLocVT();
8500 
8501   switch (VA.getLocInfo()) {
8502   default:
8503     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8504   case CCValAssign::Full:
8505     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8506       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8507     break;
8508   case CCValAssign::BCvt:
8509     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8510       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8511     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8512       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8513     else
8514       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8515     break;
8516   }
8517   return Val;
8518 }
8519 
8520 // The caller is responsible for loading the full value if the argument is
8521 // passed with CCValAssign::Indirect.
8522 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8523                                 const CCValAssign &VA, const SDLoc &DL) {
8524   MachineFunction &MF = DAG.getMachineFunction();
8525   MachineFrameInfo &MFI = MF.getFrameInfo();
8526   EVT LocVT = VA.getLocVT();
8527   EVT ValVT = VA.getValVT();
8528   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8529   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8530                                  /*Immutable=*/true);
8531   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8532   SDValue Val;
8533 
8534   ISD::LoadExtType ExtType;
8535   switch (VA.getLocInfo()) {
8536   default:
8537     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8538   case CCValAssign::Full:
8539   case CCValAssign::Indirect:
8540   case CCValAssign::BCvt:
8541     ExtType = ISD::NON_EXTLOAD;
8542     break;
8543   }
8544   Val = DAG.getExtLoad(
8545       ExtType, DL, LocVT, Chain, FIN,
8546       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8547   return Val;
8548 }
8549 
8550 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8551                                        const CCValAssign &VA, const SDLoc &DL) {
8552   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8553          "Unexpected VA");
8554   MachineFunction &MF = DAG.getMachineFunction();
8555   MachineFrameInfo &MFI = MF.getFrameInfo();
8556   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8557 
8558   if (VA.isMemLoc()) {
8559     // f64 is passed on the stack.
8560     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8561     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8562     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8563                        MachinePointerInfo::getFixedStack(MF, FI));
8564   }
8565 
8566   assert(VA.isRegLoc() && "Expected register VA assignment");
8567 
8568   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8569   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8570   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8571   SDValue Hi;
8572   if (VA.getLocReg() == RISCV::X17) {
8573     // Second half of f64 is passed on the stack.
8574     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8575     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8576     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8577                      MachinePointerInfo::getFixedStack(MF, FI));
8578   } else {
8579     // Second half of f64 is passed in another GPR.
8580     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8581     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8582     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8583   }
8584   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8585 }
8586 
8587 // FastCC has less than 1% performance improvement for some particular
8588 // benchmark. But theoretically, it may has benenfit for some cases.
8589 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8590                             unsigned ValNo, MVT ValVT, MVT LocVT,
8591                             CCValAssign::LocInfo LocInfo,
8592                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8593                             bool IsFixed, bool IsRet, Type *OrigTy,
8594                             const RISCVTargetLowering &TLI,
8595                             Optional<unsigned> FirstMaskArgument) {
8596 
8597   // X5 and X6 might be used for save-restore libcall.
8598   static const MCPhysReg GPRList[] = {
8599       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8600       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8601       RISCV::X29, RISCV::X30, RISCV::X31};
8602 
8603   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8604     if (unsigned Reg = State.AllocateReg(GPRList)) {
8605       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8606       return false;
8607     }
8608   }
8609 
8610   if (LocVT == MVT::f16) {
8611     static const MCPhysReg FPR16List[] = {
8612         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8613         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8614         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8615         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8616     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8617       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8618       return false;
8619     }
8620   }
8621 
8622   if (LocVT == MVT::f32) {
8623     static const MCPhysReg FPR32List[] = {
8624         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8625         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8626         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8627         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8628     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8629       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8630       return false;
8631     }
8632   }
8633 
8634   if (LocVT == MVT::f64) {
8635     static const MCPhysReg FPR64List[] = {
8636         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8637         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8638         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8639         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8640     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8641       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8642       return false;
8643     }
8644   }
8645 
8646   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8647     unsigned Offset4 = State.AllocateStack(4, Align(4));
8648     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8649     return false;
8650   }
8651 
8652   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8653     unsigned Offset5 = State.AllocateStack(8, Align(8));
8654     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8655     return false;
8656   }
8657 
8658   if (LocVT.isVector()) {
8659     if (unsigned Reg =
8660             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8661       // Fixed-length vectors are located in the corresponding scalable-vector
8662       // container types.
8663       if (ValVT.isFixedLengthVector())
8664         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8665       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8666     } else {
8667       // Try and pass the address via a "fast" GPR.
8668       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8669         LocInfo = CCValAssign::Indirect;
8670         LocVT = TLI.getSubtarget().getXLenVT();
8671         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8672       } else if (ValVT.isFixedLengthVector()) {
8673         auto StackAlign =
8674             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8675         unsigned StackOffset =
8676             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8677         State.addLoc(
8678             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8679       } else {
8680         // Can't pass scalable vectors on the stack.
8681         return true;
8682       }
8683     }
8684 
8685     return false;
8686   }
8687 
8688   return true; // CC didn't match.
8689 }
8690 
8691 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8692                          CCValAssign::LocInfo LocInfo,
8693                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8694 
8695   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8696     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8697     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8698     static const MCPhysReg GPRList[] = {
8699         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8700         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8701     if (unsigned Reg = State.AllocateReg(GPRList)) {
8702       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8703       return false;
8704     }
8705   }
8706 
8707   if (LocVT == MVT::f32) {
8708     // Pass in STG registers: F1, ..., F6
8709     //                        fs0 ... fs5
8710     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8711                                           RISCV::F18_F, RISCV::F19_F,
8712                                           RISCV::F20_F, RISCV::F21_F};
8713     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8714       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8715       return false;
8716     }
8717   }
8718 
8719   if (LocVT == MVT::f64) {
8720     // Pass in STG registers: D1, ..., D6
8721     //                        fs6 ... fs11
8722     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8723                                           RISCV::F24_D, RISCV::F25_D,
8724                                           RISCV::F26_D, RISCV::F27_D};
8725     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8726       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8727       return false;
8728     }
8729   }
8730 
8731   report_fatal_error("No registers left in GHC calling convention");
8732   return true;
8733 }
8734 
8735 // Transform physical registers into virtual registers.
8736 SDValue RISCVTargetLowering::LowerFormalArguments(
8737     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8738     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8739     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8740 
8741   MachineFunction &MF = DAG.getMachineFunction();
8742 
8743   switch (CallConv) {
8744   default:
8745     report_fatal_error("Unsupported calling convention");
8746   case CallingConv::C:
8747   case CallingConv::Fast:
8748     break;
8749   case CallingConv::GHC:
8750     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8751         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8752       report_fatal_error(
8753         "GHC calling convention requires the F and D instruction set extensions");
8754   }
8755 
8756   const Function &Func = MF.getFunction();
8757   if (Func.hasFnAttribute("interrupt")) {
8758     if (!Func.arg_empty())
8759       report_fatal_error(
8760         "Functions with the interrupt attribute cannot have arguments!");
8761 
8762     StringRef Kind =
8763       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8764 
8765     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8766       report_fatal_error(
8767         "Function interrupt attribute argument not supported!");
8768   }
8769 
8770   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8771   MVT XLenVT = Subtarget.getXLenVT();
8772   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8773   // Used with vargs to acumulate store chains.
8774   std::vector<SDValue> OutChains;
8775 
8776   // Assign locations to all of the incoming arguments.
8777   SmallVector<CCValAssign, 16> ArgLocs;
8778   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8779 
8780   if (CallConv == CallingConv::GHC)
8781     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8782   else
8783     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8784                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8785                                                    : CC_RISCV);
8786 
8787   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8788     CCValAssign &VA = ArgLocs[i];
8789     SDValue ArgValue;
8790     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8791     // case.
8792     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8793       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8794     else if (VA.isRegLoc())
8795       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8796     else
8797       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8798 
8799     if (VA.getLocInfo() == CCValAssign::Indirect) {
8800       // If the original argument was split and passed by reference (e.g. i128
8801       // on RV32), we need to load all parts of it here (using the same
8802       // address). Vectors may be partly split to registers and partly to the
8803       // stack, in which case the base address is partly offset and subsequent
8804       // stores are relative to that.
8805       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8806                                    MachinePointerInfo()));
8807       unsigned ArgIndex = Ins[i].OrigArgIndex;
8808       unsigned ArgPartOffset = Ins[i].PartOffset;
8809       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8810       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8811         CCValAssign &PartVA = ArgLocs[i + 1];
8812         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8813         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8814         if (PartVA.getValVT().isScalableVector())
8815           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8816         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8817         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8818                                      MachinePointerInfo()));
8819         ++i;
8820       }
8821       continue;
8822     }
8823     InVals.push_back(ArgValue);
8824   }
8825 
8826   if (IsVarArg) {
8827     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8828     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8829     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8830     MachineFrameInfo &MFI = MF.getFrameInfo();
8831     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8832     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8833 
8834     // Offset of the first variable argument from stack pointer, and size of
8835     // the vararg save area. For now, the varargs save area is either zero or
8836     // large enough to hold a0-a7.
8837     int VaArgOffset, VarArgsSaveSize;
8838 
8839     // If all registers are allocated, then all varargs must be passed on the
8840     // stack and we don't need to save any argregs.
8841     if (ArgRegs.size() == Idx) {
8842       VaArgOffset = CCInfo.getNextStackOffset();
8843       VarArgsSaveSize = 0;
8844     } else {
8845       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8846       VaArgOffset = -VarArgsSaveSize;
8847     }
8848 
8849     // Record the frame index of the first variable argument
8850     // which is a value necessary to VASTART.
8851     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8852     RVFI->setVarArgsFrameIndex(FI);
8853 
8854     // If saving an odd number of registers then create an extra stack slot to
8855     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8856     // offsets to even-numbered registered remain 2*XLEN-aligned.
8857     if (Idx % 2) {
8858       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8859       VarArgsSaveSize += XLenInBytes;
8860     }
8861 
8862     // Copy the integer registers that may have been used for passing varargs
8863     // to the vararg save area.
8864     for (unsigned I = Idx; I < ArgRegs.size();
8865          ++I, VaArgOffset += XLenInBytes) {
8866       const Register Reg = RegInfo.createVirtualRegister(RC);
8867       RegInfo.addLiveIn(ArgRegs[I], Reg);
8868       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8869       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8870       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8871       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8872                                    MachinePointerInfo::getFixedStack(MF, FI));
8873       cast<StoreSDNode>(Store.getNode())
8874           ->getMemOperand()
8875           ->setValue((Value *)nullptr);
8876       OutChains.push_back(Store);
8877     }
8878     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8879   }
8880 
8881   // All stores are grouped in one node to allow the matching between
8882   // the size of Ins and InVals. This only happens for vararg functions.
8883   if (!OutChains.empty()) {
8884     OutChains.push_back(Chain);
8885     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8886   }
8887 
8888   return Chain;
8889 }
8890 
8891 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8892 /// for tail call optimization.
8893 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8894 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8895     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8896     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8897 
8898   auto &Callee = CLI.Callee;
8899   auto CalleeCC = CLI.CallConv;
8900   auto &Outs = CLI.Outs;
8901   auto &Caller = MF.getFunction();
8902   auto CallerCC = Caller.getCallingConv();
8903 
8904   // Exception-handling functions need a special set of instructions to
8905   // indicate a return to the hardware. Tail-calling another function would
8906   // probably break this.
8907   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8908   // should be expanded as new function attributes are introduced.
8909   if (Caller.hasFnAttribute("interrupt"))
8910     return false;
8911 
8912   // Do not tail call opt if the stack is used to pass parameters.
8913   if (CCInfo.getNextStackOffset() != 0)
8914     return false;
8915 
8916   // Do not tail call opt if any parameters need to be passed indirectly.
8917   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8918   // passed indirectly. So the address of the value will be passed in a
8919   // register, or if not available, then the address is put on the stack. In
8920   // order to pass indirectly, space on the stack often needs to be allocated
8921   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8922   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8923   // are passed CCValAssign::Indirect.
8924   for (auto &VA : ArgLocs)
8925     if (VA.getLocInfo() == CCValAssign::Indirect)
8926       return false;
8927 
8928   // Do not tail call opt if either caller or callee uses struct return
8929   // semantics.
8930   auto IsCallerStructRet = Caller.hasStructRetAttr();
8931   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8932   if (IsCallerStructRet || IsCalleeStructRet)
8933     return false;
8934 
8935   // Externally-defined functions with weak linkage should not be
8936   // tail-called. The behaviour of branch instructions in this situation (as
8937   // used for tail calls) is implementation-defined, so we cannot rely on the
8938   // linker replacing the tail call with a return.
8939   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8940     const GlobalValue *GV = G->getGlobal();
8941     if (GV->hasExternalWeakLinkage())
8942       return false;
8943   }
8944 
8945   // The callee has to preserve all registers the caller needs to preserve.
8946   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8947   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8948   if (CalleeCC != CallerCC) {
8949     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8950     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8951       return false;
8952   }
8953 
8954   // Byval parameters hand the function a pointer directly into the stack area
8955   // we want to reuse during a tail call. Working around this *is* possible
8956   // but less efficient and uglier in LowerCall.
8957   for (auto &Arg : Outs)
8958     if (Arg.Flags.isByVal())
8959       return false;
8960 
8961   return true;
8962 }
8963 
8964 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8965   return DAG.getDataLayout().getPrefTypeAlign(
8966       VT.getTypeForEVT(*DAG.getContext()));
8967 }
8968 
8969 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8970 // and output parameter nodes.
8971 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8972                                        SmallVectorImpl<SDValue> &InVals) const {
8973   SelectionDAG &DAG = CLI.DAG;
8974   SDLoc &DL = CLI.DL;
8975   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8976   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8977   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8978   SDValue Chain = CLI.Chain;
8979   SDValue Callee = CLI.Callee;
8980   bool &IsTailCall = CLI.IsTailCall;
8981   CallingConv::ID CallConv = CLI.CallConv;
8982   bool IsVarArg = CLI.IsVarArg;
8983   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8984   MVT XLenVT = Subtarget.getXLenVT();
8985 
8986   MachineFunction &MF = DAG.getMachineFunction();
8987 
8988   // Analyze the operands of the call, assigning locations to each operand.
8989   SmallVector<CCValAssign, 16> ArgLocs;
8990   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8991 
8992   if (CallConv == CallingConv::GHC)
8993     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8994   else
8995     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8996                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8997                                                     : CC_RISCV);
8998 
8999   // Check if it's really possible to do a tail call.
9000   if (IsTailCall)
9001     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9002 
9003   if (IsTailCall)
9004     ++NumTailCalls;
9005   else if (CLI.CB && CLI.CB->isMustTailCall())
9006     report_fatal_error("failed to perform tail call elimination on a call "
9007                        "site marked musttail");
9008 
9009   // Get a count of how many bytes are to be pushed on the stack.
9010   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9011 
9012   // Create local copies for byval args
9013   SmallVector<SDValue, 8> ByValArgs;
9014   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9015     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9016     if (!Flags.isByVal())
9017       continue;
9018 
9019     SDValue Arg = OutVals[i];
9020     unsigned Size = Flags.getByValSize();
9021     Align Alignment = Flags.getNonZeroByValAlign();
9022 
9023     int FI =
9024         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9025     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9026     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9027 
9028     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9029                           /*IsVolatile=*/false,
9030                           /*AlwaysInline=*/false, IsTailCall,
9031                           MachinePointerInfo(), MachinePointerInfo());
9032     ByValArgs.push_back(FIPtr);
9033   }
9034 
9035   if (!IsTailCall)
9036     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9037 
9038   // Copy argument values to their designated locations.
9039   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9040   SmallVector<SDValue, 8> MemOpChains;
9041   SDValue StackPtr;
9042   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9043     CCValAssign &VA = ArgLocs[i];
9044     SDValue ArgValue = OutVals[i];
9045     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9046 
9047     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9048     bool IsF64OnRV32DSoftABI =
9049         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9050     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9051       SDValue SplitF64 = DAG.getNode(
9052           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9053       SDValue Lo = SplitF64.getValue(0);
9054       SDValue Hi = SplitF64.getValue(1);
9055 
9056       Register RegLo = VA.getLocReg();
9057       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9058 
9059       if (RegLo == RISCV::X17) {
9060         // Second half of f64 is passed on the stack.
9061         // Work out the address of the stack slot.
9062         if (!StackPtr.getNode())
9063           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9064         // Emit the store.
9065         MemOpChains.push_back(
9066             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9067       } else {
9068         // Second half of f64 is passed in another GPR.
9069         assert(RegLo < RISCV::X31 && "Invalid register pair");
9070         Register RegHigh = RegLo + 1;
9071         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9072       }
9073       continue;
9074     }
9075 
9076     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9077     // as any other MemLoc.
9078 
9079     // Promote the value if needed.
9080     // For now, only handle fully promoted and indirect arguments.
9081     if (VA.getLocInfo() == CCValAssign::Indirect) {
9082       // Store the argument in a stack slot and pass its address.
9083       Align StackAlign =
9084           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9085                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9086       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9087       // If the original argument was split (e.g. i128), we need
9088       // to store the required parts of it here (and pass just one address).
9089       // Vectors may be partly split to registers and partly to the stack, in
9090       // which case the base address is partly offset and subsequent stores are
9091       // relative to that.
9092       unsigned ArgIndex = Outs[i].OrigArgIndex;
9093       unsigned ArgPartOffset = Outs[i].PartOffset;
9094       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9095       // Calculate the total size to store. We don't have access to what we're
9096       // actually storing other than performing the loop and collecting the
9097       // info.
9098       SmallVector<std::pair<SDValue, SDValue>> Parts;
9099       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9100         SDValue PartValue = OutVals[i + 1];
9101         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9102         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9103         EVT PartVT = PartValue.getValueType();
9104         if (PartVT.isScalableVector())
9105           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9106         StoredSize += PartVT.getStoreSize();
9107         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9108         Parts.push_back(std::make_pair(PartValue, Offset));
9109         ++i;
9110       }
9111       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9112       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9113       MemOpChains.push_back(
9114           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9115                        MachinePointerInfo::getFixedStack(MF, FI)));
9116       for (const auto &Part : Parts) {
9117         SDValue PartValue = Part.first;
9118         SDValue PartOffset = Part.second;
9119         SDValue Address =
9120             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9121         MemOpChains.push_back(
9122             DAG.getStore(Chain, DL, PartValue, Address,
9123                          MachinePointerInfo::getFixedStack(MF, FI)));
9124       }
9125       ArgValue = SpillSlot;
9126     } else {
9127       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9128     }
9129 
9130     // Use local copy if it is a byval arg.
9131     if (Flags.isByVal())
9132       ArgValue = ByValArgs[j++];
9133 
9134     if (VA.isRegLoc()) {
9135       // Queue up the argument copies and emit them at the end.
9136       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9137     } else {
9138       assert(VA.isMemLoc() && "Argument not register or memory");
9139       assert(!IsTailCall && "Tail call not allowed if stack is used "
9140                             "for passing parameters");
9141 
9142       // Work out the address of the stack slot.
9143       if (!StackPtr.getNode())
9144         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9145       SDValue Address =
9146           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9147                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9148 
9149       // Emit the store.
9150       MemOpChains.push_back(
9151           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9152     }
9153   }
9154 
9155   // Join the stores, which are independent of one another.
9156   if (!MemOpChains.empty())
9157     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9158 
9159   SDValue Glue;
9160 
9161   // Build a sequence of copy-to-reg nodes, chained and glued together.
9162   for (auto &Reg : RegsToPass) {
9163     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9164     Glue = Chain.getValue(1);
9165   }
9166 
9167   // Validate that none of the argument registers have been marked as
9168   // reserved, if so report an error. Do the same for the return address if this
9169   // is not a tailcall.
9170   validateCCReservedRegs(RegsToPass, MF);
9171   if (!IsTailCall &&
9172       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9173     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9174         MF.getFunction(),
9175         "Return address register required, but has been reserved."});
9176 
9177   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9178   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9179   // split it and then direct call can be matched by PseudoCALL.
9180   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9181     const GlobalValue *GV = S->getGlobal();
9182 
9183     unsigned OpFlags = RISCVII::MO_CALL;
9184     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9185       OpFlags = RISCVII::MO_PLT;
9186 
9187     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9188   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9189     unsigned OpFlags = RISCVII::MO_CALL;
9190 
9191     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9192                                                  nullptr))
9193       OpFlags = RISCVII::MO_PLT;
9194 
9195     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9196   }
9197 
9198   // The first call operand is the chain and the second is the target address.
9199   SmallVector<SDValue, 8> Ops;
9200   Ops.push_back(Chain);
9201   Ops.push_back(Callee);
9202 
9203   // Add argument registers to the end of the list so that they are
9204   // known live into the call.
9205   for (auto &Reg : RegsToPass)
9206     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9207 
9208   if (!IsTailCall) {
9209     // Add a register mask operand representing the call-preserved registers.
9210     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9211     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9212     assert(Mask && "Missing call preserved mask for calling convention");
9213     Ops.push_back(DAG.getRegisterMask(Mask));
9214   }
9215 
9216   // Glue the call to the argument copies, if any.
9217   if (Glue.getNode())
9218     Ops.push_back(Glue);
9219 
9220   // Emit the call.
9221   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9222 
9223   if (IsTailCall) {
9224     MF.getFrameInfo().setHasTailCall();
9225     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9226   }
9227 
9228   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9229   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9230   Glue = Chain.getValue(1);
9231 
9232   // Mark the end of the call, which is glued to the call itself.
9233   Chain = DAG.getCALLSEQ_END(Chain,
9234                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9235                              DAG.getConstant(0, DL, PtrVT, true),
9236                              Glue, DL);
9237   Glue = Chain.getValue(1);
9238 
9239   // Assign locations to each value returned by this call.
9240   SmallVector<CCValAssign, 16> RVLocs;
9241   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9242   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9243 
9244   // Copy all of the result registers out of their specified physreg.
9245   for (auto &VA : RVLocs) {
9246     // Copy the value out
9247     SDValue RetValue =
9248         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9249     // Glue the RetValue to the end of the call sequence
9250     Chain = RetValue.getValue(1);
9251     Glue = RetValue.getValue(2);
9252 
9253     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9254       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9255       SDValue RetValue2 =
9256           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9257       Chain = RetValue2.getValue(1);
9258       Glue = RetValue2.getValue(2);
9259       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9260                              RetValue2);
9261     }
9262 
9263     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9264 
9265     InVals.push_back(RetValue);
9266   }
9267 
9268   return Chain;
9269 }
9270 
9271 bool RISCVTargetLowering::CanLowerReturn(
9272     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9273     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9274   SmallVector<CCValAssign, 16> RVLocs;
9275   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9276 
9277   Optional<unsigned> FirstMaskArgument;
9278   if (Subtarget.hasVInstructions())
9279     FirstMaskArgument = preAssignMask(Outs);
9280 
9281   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9282     MVT VT = Outs[i].VT;
9283     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9284     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9285     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9286                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9287                  *this, FirstMaskArgument))
9288       return false;
9289   }
9290   return true;
9291 }
9292 
9293 SDValue
9294 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9295                                  bool IsVarArg,
9296                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9297                                  const SmallVectorImpl<SDValue> &OutVals,
9298                                  const SDLoc &DL, SelectionDAG &DAG) const {
9299   const MachineFunction &MF = DAG.getMachineFunction();
9300   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9301 
9302   // Stores the assignment of the return value to a location.
9303   SmallVector<CCValAssign, 16> RVLocs;
9304 
9305   // Info about the registers and stack slot.
9306   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9307                  *DAG.getContext());
9308 
9309   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9310                     nullptr, CC_RISCV);
9311 
9312   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9313     report_fatal_error("GHC functions return void only");
9314 
9315   SDValue Glue;
9316   SmallVector<SDValue, 4> RetOps(1, Chain);
9317 
9318   // Copy the result values into the output registers.
9319   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9320     SDValue Val = OutVals[i];
9321     CCValAssign &VA = RVLocs[i];
9322     assert(VA.isRegLoc() && "Can only return in registers!");
9323 
9324     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9325       // Handle returning f64 on RV32D with a soft float ABI.
9326       assert(VA.isRegLoc() && "Expected return via registers");
9327       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9328                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9329       SDValue Lo = SplitF64.getValue(0);
9330       SDValue Hi = SplitF64.getValue(1);
9331       Register RegLo = VA.getLocReg();
9332       assert(RegLo < RISCV::X31 && "Invalid register pair");
9333       Register RegHi = RegLo + 1;
9334 
9335       if (STI.isRegisterReservedByUser(RegLo) ||
9336           STI.isRegisterReservedByUser(RegHi))
9337         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9338             MF.getFunction(),
9339             "Return value register required, but has been reserved."});
9340 
9341       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9342       Glue = Chain.getValue(1);
9343       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9344       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9345       Glue = Chain.getValue(1);
9346       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9347     } else {
9348       // Handle a 'normal' return.
9349       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9350       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9351 
9352       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9353         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9354             MF.getFunction(),
9355             "Return value register required, but has been reserved."});
9356 
9357       // Guarantee that all emitted copies are stuck together.
9358       Glue = Chain.getValue(1);
9359       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9360     }
9361   }
9362 
9363   RetOps[0] = Chain; // Update chain.
9364 
9365   // Add the glue node if we have it.
9366   if (Glue.getNode()) {
9367     RetOps.push_back(Glue);
9368   }
9369 
9370   unsigned RetOpc = RISCVISD::RET_FLAG;
9371   // Interrupt service routines use different return instructions.
9372   const Function &Func = DAG.getMachineFunction().getFunction();
9373   if (Func.hasFnAttribute("interrupt")) {
9374     if (!Func.getReturnType()->isVoidTy())
9375       report_fatal_error(
9376           "Functions with the interrupt attribute must have void return type!");
9377 
9378     MachineFunction &MF = DAG.getMachineFunction();
9379     StringRef Kind =
9380       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9381 
9382     if (Kind == "user")
9383       RetOpc = RISCVISD::URET_FLAG;
9384     else if (Kind == "supervisor")
9385       RetOpc = RISCVISD::SRET_FLAG;
9386     else
9387       RetOpc = RISCVISD::MRET_FLAG;
9388   }
9389 
9390   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9391 }
9392 
9393 void RISCVTargetLowering::validateCCReservedRegs(
9394     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9395     MachineFunction &MF) const {
9396   const Function &F = MF.getFunction();
9397   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9398 
9399   if (llvm::any_of(Regs, [&STI](auto Reg) {
9400         return STI.isRegisterReservedByUser(Reg.first);
9401       }))
9402     F.getContext().diagnose(DiagnosticInfoUnsupported{
9403         F, "Argument register required, but has been reserved."});
9404 }
9405 
9406 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9407   return CI->isTailCall();
9408 }
9409 
9410 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9411 #define NODE_NAME_CASE(NODE)                                                   \
9412   case RISCVISD::NODE:                                                         \
9413     return "RISCVISD::" #NODE;
9414   // clang-format off
9415   switch ((RISCVISD::NodeType)Opcode) {
9416   case RISCVISD::FIRST_NUMBER:
9417     break;
9418   NODE_NAME_CASE(RET_FLAG)
9419   NODE_NAME_CASE(URET_FLAG)
9420   NODE_NAME_CASE(SRET_FLAG)
9421   NODE_NAME_CASE(MRET_FLAG)
9422   NODE_NAME_CASE(CALL)
9423   NODE_NAME_CASE(SELECT_CC)
9424   NODE_NAME_CASE(BR_CC)
9425   NODE_NAME_CASE(BuildPairF64)
9426   NODE_NAME_CASE(SplitF64)
9427   NODE_NAME_CASE(TAIL)
9428   NODE_NAME_CASE(MULHSU)
9429   NODE_NAME_CASE(SLLW)
9430   NODE_NAME_CASE(SRAW)
9431   NODE_NAME_CASE(SRLW)
9432   NODE_NAME_CASE(DIVW)
9433   NODE_NAME_CASE(DIVUW)
9434   NODE_NAME_CASE(REMUW)
9435   NODE_NAME_CASE(ROLW)
9436   NODE_NAME_CASE(RORW)
9437   NODE_NAME_CASE(CLZW)
9438   NODE_NAME_CASE(CTZW)
9439   NODE_NAME_CASE(FSLW)
9440   NODE_NAME_CASE(FSRW)
9441   NODE_NAME_CASE(FSL)
9442   NODE_NAME_CASE(FSR)
9443   NODE_NAME_CASE(FMV_H_X)
9444   NODE_NAME_CASE(FMV_X_ANYEXTH)
9445   NODE_NAME_CASE(FMV_W_X_RV64)
9446   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9447   NODE_NAME_CASE(FCVT_X_RTZ)
9448   NODE_NAME_CASE(FCVT_XU_RTZ)
9449   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9450   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9451   NODE_NAME_CASE(READ_CYCLE_WIDE)
9452   NODE_NAME_CASE(GREV)
9453   NODE_NAME_CASE(GREVW)
9454   NODE_NAME_CASE(GORC)
9455   NODE_NAME_CASE(GORCW)
9456   NODE_NAME_CASE(SHFL)
9457   NODE_NAME_CASE(SHFLW)
9458   NODE_NAME_CASE(UNSHFL)
9459   NODE_NAME_CASE(UNSHFLW)
9460   NODE_NAME_CASE(BCOMPRESS)
9461   NODE_NAME_CASE(BCOMPRESSW)
9462   NODE_NAME_CASE(BDECOMPRESS)
9463   NODE_NAME_CASE(BDECOMPRESSW)
9464   NODE_NAME_CASE(VMV_V_X_VL)
9465   NODE_NAME_CASE(VFMV_V_F_VL)
9466   NODE_NAME_CASE(VMV_X_S)
9467   NODE_NAME_CASE(VMV_S_X_VL)
9468   NODE_NAME_CASE(VFMV_S_F_VL)
9469   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9470   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9471   NODE_NAME_CASE(READ_VLENB)
9472   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9473   NODE_NAME_CASE(VSLIDEUP_VL)
9474   NODE_NAME_CASE(VSLIDE1UP_VL)
9475   NODE_NAME_CASE(VSLIDEDOWN_VL)
9476   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9477   NODE_NAME_CASE(VID_VL)
9478   NODE_NAME_CASE(VFNCVT_ROD_VL)
9479   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9480   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9481   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9482   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9483   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9484   NODE_NAME_CASE(VECREDUCE_AND_VL)
9485   NODE_NAME_CASE(VECREDUCE_OR_VL)
9486   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9487   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9488   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9489   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9490   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9491   NODE_NAME_CASE(ADD_VL)
9492   NODE_NAME_CASE(AND_VL)
9493   NODE_NAME_CASE(MUL_VL)
9494   NODE_NAME_CASE(OR_VL)
9495   NODE_NAME_CASE(SDIV_VL)
9496   NODE_NAME_CASE(SHL_VL)
9497   NODE_NAME_CASE(SREM_VL)
9498   NODE_NAME_CASE(SRA_VL)
9499   NODE_NAME_CASE(SRL_VL)
9500   NODE_NAME_CASE(SUB_VL)
9501   NODE_NAME_CASE(UDIV_VL)
9502   NODE_NAME_CASE(UREM_VL)
9503   NODE_NAME_CASE(XOR_VL)
9504   NODE_NAME_CASE(SADDSAT_VL)
9505   NODE_NAME_CASE(UADDSAT_VL)
9506   NODE_NAME_CASE(SSUBSAT_VL)
9507   NODE_NAME_CASE(USUBSAT_VL)
9508   NODE_NAME_CASE(FADD_VL)
9509   NODE_NAME_CASE(FSUB_VL)
9510   NODE_NAME_CASE(FMUL_VL)
9511   NODE_NAME_CASE(FDIV_VL)
9512   NODE_NAME_CASE(FNEG_VL)
9513   NODE_NAME_CASE(FABS_VL)
9514   NODE_NAME_CASE(FSQRT_VL)
9515   NODE_NAME_CASE(FMA_VL)
9516   NODE_NAME_CASE(FCOPYSIGN_VL)
9517   NODE_NAME_CASE(SMIN_VL)
9518   NODE_NAME_CASE(SMAX_VL)
9519   NODE_NAME_CASE(UMIN_VL)
9520   NODE_NAME_CASE(UMAX_VL)
9521   NODE_NAME_CASE(FMINNUM_VL)
9522   NODE_NAME_CASE(FMAXNUM_VL)
9523   NODE_NAME_CASE(MULHS_VL)
9524   NODE_NAME_CASE(MULHU_VL)
9525   NODE_NAME_CASE(FP_TO_SINT_VL)
9526   NODE_NAME_CASE(FP_TO_UINT_VL)
9527   NODE_NAME_CASE(SINT_TO_FP_VL)
9528   NODE_NAME_CASE(UINT_TO_FP_VL)
9529   NODE_NAME_CASE(FP_EXTEND_VL)
9530   NODE_NAME_CASE(FP_ROUND_VL)
9531   NODE_NAME_CASE(VWMUL_VL)
9532   NODE_NAME_CASE(VWMULU_VL)
9533   NODE_NAME_CASE(SETCC_VL)
9534   NODE_NAME_CASE(VSELECT_VL)
9535   NODE_NAME_CASE(VMAND_VL)
9536   NODE_NAME_CASE(VMOR_VL)
9537   NODE_NAME_CASE(VMXOR_VL)
9538   NODE_NAME_CASE(VMCLR_VL)
9539   NODE_NAME_CASE(VMSET_VL)
9540   NODE_NAME_CASE(VRGATHER_VX_VL)
9541   NODE_NAME_CASE(VRGATHER_VV_VL)
9542   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9543   NODE_NAME_CASE(VSEXT_VL)
9544   NODE_NAME_CASE(VZEXT_VL)
9545   NODE_NAME_CASE(VCPOP_VL)
9546   NODE_NAME_CASE(VLE_VL)
9547   NODE_NAME_CASE(VSE_VL)
9548   NODE_NAME_CASE(READ_CSR)
9549   NODE_NAME_CASE(WRITE_CSR)
9550   NODE_NAME_CASE(SWAP_CSR)
9551   }
9552   // clang-format on
9553   return nullptr;
9554 #undef NODE_NAME_CASE
9555 }
9556 
9557 /// getConstraintType - Given a constraint letter, return the type of
9558 /// constraint it is for this target.
9559 RISCVTargetLowering::ConstraintType
9560 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9561   if (Constraint.size() == 1) {
9562     switch (Constraint[0]) {
9563     default:
9564       break;
9565     case 'f':
9566       return C_RegisterClass;
9567     case 'I':
9568     case 'J':
9569     case 'K':
9570       return C_Immediate;
9571     case 'A':
9572       return C_Memory;
9573     case 'S': // A symbolic address
9574       return C_Other;
9575     }
9576   } else {
9577     if (Constraint == "vr" || Constraint == "vm")
9578       return C_RegisterClass;
9579   }
9580   return TargetLowering::getConstraintType(Constraint);
9581 }
9582 
9583 std::pair<unsigned, const TargetRegisterClass *>
9584 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9585                                                   StringRef Constraint,
9586                                                   MVT VT) const {
9587   // First, see if this is a constraint that directly corresponds to a
9588   // RISCV register class.
9589   if (Constraint.size() == 1) {
9590     switch (Constraint[0]) {
9591     case 'r':
9592       return std::make_pair(0U, &RISCV::GPRRegClass);
9593     case 'f':
9594       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9595         return std::make_pair(0U, &RISCV::FPR16RegClass);
9596       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9597         return std::make_pair(0U, &RISCV::FPR32RegClass);
9598       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9599         return std::make_pair(0U, &RISCV::FPR64RegClass);
9600       break;
9601     default:
9602       break;
9603     }
9604   } else {
9605     if (Constraint == "vr") {
9606       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9607                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9608         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9609           return std::make_pair(0U, RC);
9610       }
9611     } else if (Constraint == "vm") {
9612       if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
9613         return std::make_pair(0U, &RISCV::VMV0RegClass);
9614     }
9615   }
9616 
9617   // Clang will correctly decode the usage of register name aliases into their
9618   // official names. However, other frontends like `rustc` do not. This allows
9619   // users of these frontends to use the ABI names for registers in LLVM-style
9620   // register constraints.
9621   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9622                                .Case("{zero}", RISCV::X0)
9623                                .Case("{ra}", RISCV::X1)
9624                                .Case("{sp}", RISCV::X2)
9625                                .Case("{gp}", RISCV::X3)
9626                                .Case("{tp}", RISCV::X4)
9627                                .Case("{t0}", RISCV::X5)
9628                                .Case("{t1}", RISCV::X6)
9629                                .Case("{t2}", RISCV::X7)
9630                                .Cases("{s0}", "{fp}", RISCV::X8)
9631                                .Case("{s1}", RISCV::X9)
9632                                .Case("{a0}", RISCV::X10)
9633                                .Case("{a1}", RISCV::X11)
9634                                .Case("{a2}", RISCV::X12)
9635                                .Case("{a3}", RISCV::X13)
9636                                .Case("{a4}", RISCV::X14)
9637                                .Case("{a5}", RISCV::X15)
9638                                .Case("{a6}", RISCV::X16)
9639                                .Case("{a7}", RISCV::X17)
9640                                .Case("{s2}", RISCV::X18)
9641                                .Case("{s3}", RISCV::X19)
9642                                .Case("{s4}", RISCV::X20)
9643                                .Case("{s5}", RISCV::X21)
9644                                .Case("{s6}", RISCV::X22)
9645                                .Case("{s7}", RISCV::X23)
9646                                .Case("{s8}", RISCV::X24)
9647                                .Case("{s9}", RISCV::X25)
9648                                .Case("{s10}", RISCV::X26)
9649                                .Case("{s11}", RISCV::X27)
9650                                .Case("{t3}", RISCV::X28)
9651                                .Case("{t4}", RISCV::X29)
9652                                .Case("{t5}", RISCV::X30)
9653                                .Case("{t6}", RISCV::X31)
9654                                .Default(RISCV::NoRegister);
9655   if (XRegFromAlias != RISCV::NoRegister)
9656     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9657 
9658   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9659   // TableGen record rather than the AsmName to choose registers for InlineAsm
9660   // constraints, plus we want to match those names to the widest floating point
9661   // register type available, manually select floating point registers here.
9662   //
9663   // The second case is the ABI name of the register, so that frontends can also
9664   // use the ABI names in register constraint lists.
9665   if (Subtarget.hasStdExtF()) {
9666     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9667                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9668                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9669                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9670                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9671                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9672                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9673                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9674                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9675                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9676                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9677                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9678                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9679                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9680                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9681                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9682                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9683                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9684                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9685                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9686                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9687                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9688                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9689                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9690                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9691                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9692                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9693                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9694                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9695                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9696                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9697                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9698                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9699                         .Default(RISCV::NoRegister);
9700     if (FReg != RISCV::NoRegister) {
9701       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9702       if (Subtarget.hasStdExtD()) {
9703         unsigned RegNo = FReg - RISCV::F0_F;
9704         unsigned DReg = RISCV::F0_D + RegNo;
9705         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9706       }
9707       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9708     }
9709   }
9710 
9711   if (Subtarget.hasVInstructions()) {
9712     Register VReg = StringSwitch<Register>(Constraint.lower())
9713                         .Case("{v0}", RISCV::V0)
9714                         .Case("{v1}", RISCV::V1)
9715                         .Case("{v2}", RISCV::V2)
9716                         .Case("{v3}", RISCV::V3)
9717                         .Case("{v4}", RISCV::V4)
9718                         .Case("{v5}", RISCV::V5)
9719                         .Case("{v6}", RISCV::V6)
9720                         .Case("{v7}", RISCV::V7)
9721                         .Case("{v8}", RISCV::V8)
9722                         .Case("{v9}", RISCV::V9)
9723                         .Case("{v10}", RISCV::V10)
9724                         .Case("{v11}", RISCV::V11)
9725                         .Case("{v12}", RISCV::V12)
9726                         .Case("{v13}", RISCV::V13)
9727                         .Case("{v14}", RISCV::V14)
9728                         .Case("{v15}", RISCV::V15)
9729                         .Case("{v16}", RISCV::V16)
9730                         .Case("{v17}", RISCV::V17)
9731                         .Case("{v18}", RISCV::V18)
9732                         .Case("{v19}", RISCV::V19)
9733                         .Case("{v20}", RISCV::V20)
9734                         .Case("{v21}", RISCV::V21)
9735                         .Case("{v22}", RISCV::V22)
9736                         .Case("{v23}", RISCV::V23)
9737                         .Case("{v24}", RISCV::V24)
9738                         .Case("{v25}", RISCV::V25)
9739                         .Case("{v26}", RISCV::V26)
9740                         .Case("{v27}", RISCV::V27)
9741                         .Case("{v28}", RISCV::V28)
9742                         .Case("{v29}", RISCV::V29)
9743                         .Case("{v30}", RISCV::V30)
9744                         .Case("{v31}", RISCV::V31)
9745                         .Default(RISCV::NoRegister);
9746     if (VReg != RISCV::NoRegister) {
9747       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9748         return std::make_pair(VReg, &RISCV::VMRegClass);
9749       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9750         return std::make_pair(VReg, &RISCV::VRRegClass);
9751       for (const auto *RC :
9752            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9753         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9754           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9755           return std::make_pair(VReg, RC);
9756         }
9757       }
9758     }
9759   }
9760 
9761   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9762 }
9763 
9764 unsigned
9765 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9766   // Currently only support length 1 constraints.
9767   if (ConstraintCode.size() == 1) {
9768     switch (ConstraintCode[0]) {
9769     case 'A':
9770       return InlineAsm::Constraint_A;
9771     default:
9772       break;
9773     }
9774   }
9775 
9776   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9777 }
9778 
9779 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9780     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9781     SelectionDAG &DAG) const {
9782   // Currently only support length 1 constraints.
9783   if (Constraint.length() == 1) {
9784     switch (Constraint[0]) {
9785     case 'I':
9786       // Validate & create a 12-bit signed immediate operand.
9787       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9788         uint64_t CVal = C->getSExtValue();
9789         if (isInt<12>(CVal))
9790           Ops.push_back(
9791               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9792       }
9793       return;
9794     case 'J':
9795       // Validate & create an integer zero operand.
9796       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9797         if (C->getZExtValue() == 0)
9798           Ops.push_back(
9799               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9800       return;
9801     case 'K':
9802       // Validate & create a 5-bit unsigned immediate operand.
9803       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9804         uint64_t CVal = C->getZExtValue();
9805         if (isUInt<5>(CVal))
9806           Ops.push_back(
9807               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9808       }
9809       return;
9810     case 'S':
9811       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9812         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9813                                                  GA->getValueType(0)));
9814       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9815         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9816                                                 BA->getValueType(0)));
9817       }
9818       return;
9819     default:
9820       break;
9821     }
9822   }
9823   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9824 }
9825 
9826 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9827                                                    Instruction *Inst,
9828                                                    AtomicOrdering Ord) const {
9829   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9830     return Builder.CreateFence(Ord);
9831   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9832     return Builder.CreateFence(AtomicOrdering::Release);
9833   return nullptr;
9834 }
9835 
9836 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9837                                                     Instruction *Inst,
9838                                                     AtomicOrdering Ord) const {
9839   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9840     return Builder.CreateFence(AtomicOrdering::Acquire);
9841   return nullptr;
9842 }
9843 
9844 TargetLowering::AtomicExpansionKind
9845 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9846   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9847   // point operations can't be used in an lr/sc sequence without breaking the
9848   // forward-progress guarantee.
9849   if (AI->isFloatingPointOperation())
9850     return AtomicExpansionKind::CmpXChg;
9851 
9852   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9853   if (Size == 8 || Size == 16)
9854     return AtomicExpansionKind::MaskedIntrinsic;
9855   return AtomicExpansionKind::None;
9856 }
9857 
9858 static Intrinsic::ID
9859 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9860   if (XLen == 32) {
9861     switch (BinOp) {
9862     default:
9863       llvm_unreachable("Unexpected AtomicRMW BinOp");
9864     case AtomicRMWInst::Xchg:
9865       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9866     case AtomicRMWInst::Add:
9867       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9868     case AtomicRMWInst::Sub:
9869       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9870     case AtomicRMWInst::Nand:
9871       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9872     case AtomicRMWInst::Max:
9873       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9874     case AtomicRMWInst::Min:
9875       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9876     case AtomicRMWInst::UMax:
9877       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9878     case AtomicRMWInst::UMin:
9879       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9880     }
9881   }
9882 
9883   if (XLen == 64) {
9884     switch (BinOp) {
9885     default:
9886       llvm_unreachable("Unexpected AtomicRMW BinOp");
9887     case AtomicRMWInst::Xchg:
9888       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9889     case AtomicRMWInst::Add:
9890       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9891     case AtomicRMWInst::Sub:
9892       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9893     case AtomicRMWInst::Nand:
9894       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9895     case AtomicRMWInst::Max:
9896       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9897     case AtomicRMWInst::Min:
9898       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9899     case AtomicRMWInst::UMax:
9900       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9901     case AtomicRMWInst::UMin:
9902       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9903     }
9904   }
9905 
9906   llvm_unreachable("Unexpected XLen\n");
9907 }
9908 
9909 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9910     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9911     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9912   unsigned XLen = Subtarget.getXLen();
9913   Value *Ordering =
9914       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9915   Type *Tys[] = {AlignedAddr->getType()};
9916   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9917       AI->getModule(),
9918       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9919 
9920   if (XLen == 64) {
9921     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9922     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9923     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9924   }
9925 
9926   Value *Result;
9927 
9928   // Must pass the shift amount needed to sign extend the loaded value prior
9929   // to performing a signed comparison for min/max. ShiftAmt is the number of
9930   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9931   // is the number of bits to left+right shift the value in order to
9932   // sign-extend.
9933   if (AI->getOperation() == AtomicRMWInst::Min ||
9934       AI->getOperation() == AtomicRMWInst::Max) {
9935     const DataLayout &DL = AI->getModule()->getDataLayout();
9936     unsigned ValWidth =
9937         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9938     Value *SextShamt =
9939         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9940     Result = Builder.CreateCall(LrwOpScwLoop,
9941                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9942   } else {
9943     Result =
9944         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9945   }
9946 
9947   if (XLen == 64)
9948     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9949   return Result;
9950 }
9951 
9952 TargetLowering::AtomicExpansionKind
9953 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9954     AtomicCmpXchgInst *CI) const {
9955   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9956   if (Size == 8 || Size == 16)
9957     return AtomicExpansionKind::MaskedIntrinsic;
9958   return AtomicExpansionKind::None;
9959 }
9960 
9961 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9962     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9963     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9964   unsigned XLen = Subtarget.getXLen();
9965   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9966   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9967   if (XLen == 64) {
9968     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9969     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9970     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9971     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9972   }
9973   Type *Tys[] = {AlignedAddr->getType()};
9974   Function *MaskedCmpXchg =
9975       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9976   Value *Result = Builder.CreateCall(
9977       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9978   if (XLen == 64)
9979     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9980   return Result;
9981 }
9982 
9983 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9984   return false;
9985 }
9986 
9987 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
9988                                                EVT VT) const {
9989   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
9990     return false;
9991 
9992   switch (FPVT.getSimpleVT().SimpleTy) {
9993   case MVT::f16:
9994     return Subtarget.hasStdExtZfh();
9995   case MVT::f32:
9996     return Subtarget.hasStdExtF();
9997   case MVT::f64:
9998     return Subtarget.hasStdExtD();
9999   default:
10000     return false;
10001   }
10002 }
10003 
10004 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10005                                                      EVT VT) const {
10006   VT = VT.getScalarType();
10007 
10008   if (!VT.isSimple())
10009     return false;
10010 
10011   switch (VT.getSimpleVT().SimpleTy) {
10012   case MVT::f16:
10013     return Subtarget.hasStdExtZfh();
10014   case MVT::f32:
10015     return Subtarget.hasStdExtF();
10016   case MVT::f64:
10017     return Subtarget.hasStdExtD();
10018   default:
10019     break;
10020   }
10021 
10022   return false;
10023 }
10024 
10025 Register RISCVTargetLowering::getExceptionPointerRegister(
10026     const Constant *PersonalityFn) const {
10027   return RISCV::X10;
10028 }
10029 
10030 Register RISCVTargetLowering::getExceptionSelectorRegister(
10031     const Constant *PersonalityFn) const {
10032   return RISCV::X11;
10033 }
10034 
10035 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10036   // Return false to suppress the unnecessary extensions if the LibCall
10037   // arguments or return value is f32 type for LP64 ABI.
10038   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10039   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10040     return false;
10041 
10042   return true;
10043 }
10044 
10045 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10046   if (Subtarget.is64Bit() && Type == MVT::i32)
10047     return true;
10048 
10049   return IsSigned;
10050 }
10051 
10052 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10053                                                  SDValue C) const {
10054   // Check integral scalar types.
10055   if (VT.isScalarInteger()) {
10056     // Omit the optimization if the sub target has the M extension and the data
10057     // size exceeds XLen.
10058     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10059       return false;
10060     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10061       // Break the MUL to a SLLI and an ADD/SUB.
10062       const APInt &Imm = ConstNode->getAPIntValue();
10063       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10064           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10065         return true;
10066       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10067       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10068           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10069            (Imm - 8).isPowerOf2()))
10070         return true;
10071       // Omit the following optimization if the sub target has the M extension
10072       // and the data size >= XLen.
10073       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10074         return false;
10075       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10076       // a pair of LUI/ADDI.
10077       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10078         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10079         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10080             (1 - ImmS).isPowerOf2())
10081         return true;
10082       }
10083     }
10084   }
10085 
10086   return false;
10087 }
10088 
10089 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10090     const SDValue &AddNode, const SDValue &ConstNode) const {
10091   // Let the DAGCombiner decide for vectors.
10092   EVT VT = AddNode.getValueType();
10093   if (VT.isVector())
10094     return true;
10095 
10096   // Let the DAGCombiner decide for larger types.
10097   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10098     return true;
10099 
10100   // It is worse if c1 is simm12 while c1*c2 is not.
10101   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10102   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10103   const APInt &C1 = C1Node->getAPIntValue();
10104   const APInt &C2 = C2Node->getAPIntValue();
10105   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10106     return false;
10107 
10108   // Default to true and let the DAGCombiner decide.
10109   return true;
10110 }
10111 
10112 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10113     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10114     bool *Fast) const {
10115   if (!VT.isVector())
10116     return false;
10117 
10118   EVT ElemVT = VT.getVectorElementType();
10119   if (Alignment >= ElemVT.getStoreSize()) {
10120     if (Fast)
10121       *Fast = true;
10122     return true;
10123   }
10124 
10125   return false;
10126 }
10127 
10128 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10129     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10130     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10131   bool IsABIRegCopy = CC.hasValue();
10132   EVT ValueVT = Val.getValueType();
10133   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10134     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10135     // and cast to f32.
10136     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10137     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10138     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10139                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10140     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10141     Parts[0] = Val;
10142     return true;
10143   }
10144 
10145   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10146     LLVMContext &Context = *DAG.getContext();
10147     EVT ValueEltVT = ValueVT.getVectorElementType();
10148     EVT PartEltVT = PartVT.getVectorElementType();
10149     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10150     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10151     if (PartVTBitSize % ValueVTBitSize == 0) {
10152       assert(PartVTBitSize >= ValueVTBitSize);
10153       // If the element types are different, bitcast to the same element type of
10154       // PartVT first.
10155       // Give an example here, we want copy a <vscale x 1 x i8> value to
10156       // <vscale x 4 x i16>.
10157       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10158       // subvector, then we can bitcast to <vscale x 4 x i16>.
10159       if (ValueEltVT != PartEltVT) {
10160         if (PartVTBitSize > ValueVTBitSize) {
10161           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10162           assert(Count != 0 && "The number of element should not be zero.");
10163           EVT SameEltTypeVT =
10164               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10165           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10166                             DAG.getUNDEF(SameEltTypeVT), Val,
10167                             DAG.getVectorIdxConstant(0, DL));
10168         }
10169         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10170       } else {
10171         Val =
10172             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10173                         Val, DAG.getVectorIdxConstant(0, DL));
10174       }
10175       Parts[0] = Val;
10176       return true;
10177     }
10178   }
10179   return false;
10180 }
10181 
10182 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10183     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10184     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10185   bool IsABIRegCopy = CC.hasValue();
10186   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10187     SDValue Val = Parts[0];
10188 
10189     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10190     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10191     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10192     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10193     return Val;
10194   }
10195 
10196   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10197     LLVMContext &Context = *DAG.getContext();
10198     SDValue Val = Parts[0];
10199     EVT ValueEltVT = ValueVT.getVectorElementType();
10200     EVT PartEltVT = PartVT.getVectorElementType();
10201     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10202     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10203     if (PartVTBitSize % ValueVTBitSize == 0) {
10204       assert(PartVTBitSize >= ValueVTBitSize);
10205       EVT SameEltTypeVT = ValueVT;
10206       // If the element types are different, convert it to the same element type
10207       // of PartVT.
10208       // Give an example here, we want copy a <vscale x 1 x i8> value from
10209       // <vscale x 4 x i16>.
10210       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10211       // then we can extract <vscale x 1 x i8>.
10212       if (ValueEltVT != PartEltVT) {
10213         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10214         assert(Count != 0 && "The number of element should not be zero.");
10215         SameEltTypeVT =
10216             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10217         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10218       }
10219       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10220                         DAG.getVectorIdxConstant(0, DL));
10221       return Val;
10222     }
10223   }
10224   return SDValue();
10225 }
10226 
10227 #define GET_REGISTER_MATCHER
10228 #include "RISCVGenAsmMatcher.inc"
10229 
10230 Register
10231 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10232                                        const MachineFunction &MF) const {
10233   Register Reg = MatchRegisterAltName(RegName);
10234   if (Reg == RISCV::NoRegister)
10235     Reg = MatchRegisterName(RegName);
10236   if (Reg == RISCV::NoRegister)
10237     report_fatal_error(
10238         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10239   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10240   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10241     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10242                              StringRef(RegName) + "\"."));
10243   return Reg;
10244 }
10245 
10246 namespace llvm {
10247 namespace RISCVVIntrinsicsTable {
10248 
10249 #define GET_RISCVVIntrinsicsTable_IMPL
10250 #include "RISCVGenSearchableTables.inc"
10251 
10252 } // namespace RISCVVIntrinsicsTable
10253 
10254 } // namespace llvm
10255