1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
174     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
185   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction(ISD::VAARG, MVT::Other, Expand);
189   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190   setOperationAction(ISD::VAEND, MVT::Other, Expand);
191 
192   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193   if (!Subtarget.hasStdExtZbb()) {
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
195     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
196   }
197 
198   if (Subtarget.is64Bit()) {
199     setOperationAction(ISD::ADD, MVT::i32, Custom);
200     setOperationAction(ISD::SUB, MVT::i32, Custom);
201     setOperationAction(ISD::SHL, MVT::i32, Custom);
202     setOperationAction(ISD::SRA, MVT::i32, Custom);
203     setOperationAction(ISD::SRL, MVT::i32, Custom);
204 
205     setOperationAction(ISD::UADDO, MVT::i32, Custom);
206     setOperationAction(ISD::USUBO, MVT::i32, Custom);
207     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
208     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
209   } else {
210     setLibcallName(RTLIB::SHL_I128, nullptr);
211     setLibcallName(RTLIB::SRL_I128, nullptr);
212     setLibcallName(RTLIB::SRA_I128, nullptr);
213     setLibcallName(RTLIB::MUL_I128, nullptr);
214     setLibcallName(RTLIB::MULO_I64, nullptr);
215   }
216 
217   if (!Subtarget.hasStdExtM()) {
218     setOperationAction(ISD::MUL, XLenVT, Expand);
219     setOperationAction(ISD::MULHS, XLenVT, Expand);
220     setOperationAction(ISD::MULHU, XLenVT, Expand);
221     setOperationAction(ISD::SDIV, XLenVT, Expand);
222     setOperationAction(ISD::UDIV, XLenVT, Expand);
223     setOperationAction(ISD::SREM, XLenVT, Expand);
224     setOperationAction(ISD::UREM, XLenVT, Expand);
225   } else {
226     if (Subtarget.is64Bit()) {
227       setOperationAction(ISD::MUL, MVT::i32, Custom);
228       setOperationAction(ISD::MUL, MVT::i128, Custom);
229 
230       setOperationAction(ISD::SDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UDIV, MVT::i8, Custom);
232       setOperationAction(ISD::UREM, MVT::i8, Custom);
233       setOperationAction(ISD::SDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UDIV, MVT::i16, Custom);
235       setOperationAction(ISD::UREM, MVT::i16, Custom);
236       setOperationAction(ISD::SDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UDIV, MVT::i32, Custom);
238       setOperationAction(ISD::UREM, MVT::i32, Custom);
239     } else {
240       setOperationAction(ISD::MUL, MVT::i64, Custom);
241     }
242   }
243 
244   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
246   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
247   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
248 
249   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
251   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
252 
253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
254     if (Subtarget.is64Bit()) {
255       setOperationAction(ISD::ROTL, MVT::i32, Custom);
256       setOperationAction(ISD::ROTR, MVT::i32, Custom);
257     }
258   } else {
259     setOperationAction(ISD::ROTL, XLenVT, Expand);
260     setOperationAction(ISD::ROTR, XLenVT, Expand);
261   }
262 
263   if (Subtarget.hasStdExtZbp()) {
264     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
265     // more combining.
266     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
267     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
268     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
269     // BSWAP i8 doesn't exist.
270     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
271     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
272 
273     if (Subtarget.is64Bit()) {
274       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
275       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
276     }
277   } else {
278     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
279     // pattern match it directly in isel.
280     setOperationAction(ISD::BSWAP, XLenVT,
281                        Subtarget.hasStdExtZbb() ? Legal : Expand);
282   }
283 
284   if (Subtarget.hasStdExtZbb()) {
285     setOperationAction(ISD::SMIN, XLenVT, Legal);
286     setOperationAction(ISD::SMAX, XLenVT, Legal);
287     setOperationAction(ISD::UMIN, XLenVT, Legal);
288     setOperationAction(ISD::UMAX, XLenVT, Legal);
289 
290     if (Subtarget.is64Bit()) {
291       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
292       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
293       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
294       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
295     }
296   } else {
297     setOperationAction(ISD::CTTZ, XLenVT, Expand);
298     setOperationAction(ISD::CTLZ, XLenVT, Expand);
299     setOperationAction(ISD::CTPOP, XLenVT, Expand);
300   }
301 
302   if (Subtarget.hasStdExtZbt()) {
303     setOperationAction(ISD::FSHL, XLenVT, Custom);
304     setOperationAction(ISD::FSHR, XLenVT, Custom);
305     setOperationAction(ISD::SELECT, XLenVT, Legal);
306 
307     if (Subtarget.is64Bit()) {
308       setOperationAction(ISD::FSHL, MVT::i32, Custom);
309       setOperationAction(ISD::FSHR, MVT::i32, Custom);
310     }
311   } else {
312     setOperationAction(ISD::SELECT, XLenVT, Custom);
313   }
314 
315   static const ISD::CondCode FPCCToExpand[] = {
316       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
317       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
318       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
319 
320   static const ISD::NodeType FPOpToExpand[] = {
321       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
322       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
323 
324   if (Subtarget.hasStdExtZfh())
325     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
326 
327   if (Subtarget.hasStdExtZfh()) {
328     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
329     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
330     setOperationAction(ISD::LRINT, MVT::f16, Legal);
331     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
332     setOperationAction(ISD::LROUND, MVT::f16, Legal);
333     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
334     setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal);
335     setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal);
336     setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal);
337     setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal);
338     setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal);
339     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
340     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
341     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
342     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
343     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
344     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
345     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
346     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal);
348     for (auto CC : FPCCToExpand)
349       setCondCodeAction(CC, MVT::f16, Expand);
350     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
351     setOperationAction(ISD::SELECT, MVT::f16, Custom);
352     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
353 
354     setOperationAction(ISD::FREM,       MVT::f16, Promote);
355     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
356     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
357     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
358     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
359     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
360     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
361     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
362     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
363     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
364     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
365     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
366     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
367     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
368     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
369     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
370     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
371     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
372 
373     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
374     // complete support for all operations in LegalizeDAG.
375 
376     // We need to custom promote this.
377     if (Subtarget.is64Bit())
378       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
379   }
380 
381   if (Subtarget.hasStdExtF()) {
382     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
383     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
384     setOperationAction(ISD::LRINT, MVT::f32, Legal);
385     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
386     setOperationAction(ISD::LROUND, MVT::f32, Legal);
387     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
388     setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal);
389     setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal);
390     setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal);
391     setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal);
392     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
393     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
394     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
395     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
396     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
397     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
398     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
399     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
400     for (auto CC : FPCCToExpand)
401       setCondCodeAction(CC, MVT::f32, Expand);
402     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
403     setOperationAction(ISD::SELECT, MVT::f32, Custom);
404     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
405     for (auto Op : FPOpToExpand)
406       setOperationAction(Op, MVT::f32, Expand);
407     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
408     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
409   }
410 
411   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
412     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
413 
414   if (Subtarget.hasStdExtD()) {
415     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
416     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
417     setOperationAction(ISD::LRINT, MVT::f64, Legal);
418     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
419     setOperationAction(ISD::LROUND, MVT::f64, Legal);
420     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
421     setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal);
422     setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal);
423     setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal);
424     setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal);
425     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
426     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
427     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
428     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
429     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
430     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
431     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
432     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
433     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
434     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
435     for (auto CC : FPCCToExpand)
436       setCondCodeAction(CC, MVT::f64, Expand);
437     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
438     setOperationAction(ISD::SELECT, MVT::f64, Custom);
439     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
440     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
441     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
442     for (auto Op : FPOpToExpand)
443       setOperationAction(Op, MVT::f64, Expand);
444     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
445     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
446   }
447 
448   if (Subtarget.is64Bit()) {
449     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
450     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
451     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
452     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
453   }
454 
455   if (Subtarget.hasStdExtF()) {
456     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
457     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
458 
459     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
460     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
461     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
462     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
463 
464     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
465     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
466   }
467 
468   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
469   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
470   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
471   setOperationAction(ISD::JumpTable, XLenVT, Custom);
472 
473   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
474 
475   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
476   // Unfortunately this can't be determined just from the ISA naming string.
477   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
478                      Subtarget.is64Bit() ? Legal : Custom);
479 
480   setOperationAction(ISD::TRAP, MVT::Other, Legal);
481   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
482   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
483   if (Subtarget.is64Bit())
484     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
485 
486   if (Subtarget.hasStdExtA()) {
487     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
488     setMinCmpXchgSizeInBits(32);
489   } else {
490     setMaxAtomicSizeInBitsSupported(0);
491   }
492 
493   setBooleanContents(ZeroOrOneBooleanContent);
494 
495   if (Subtarget.hasVInstructions()) {
496     setBooleanVectorContents(ZeroOrOneBooleanContent);
497 
498     setOperationAction(ISD::VSCALE, XLenVT, Custom);
499 
500     // RVV intrinsics may have illegal operands.
501     // We also need to custom legalize vmv.x.s.
502     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
503     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
504     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
505     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
506     if (Subtarget.is64Bit()) {
507       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
508     } else {
509       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
510       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
511     }
512 
513     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
514     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
515 
516     static const unsigned IntegerVPOps[] = {
517         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
518         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
519         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
520         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
521         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
522         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
523         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
524         ISD::VP_MERGE,       ISD::VP_SELECT};
525 
526     static const unsigned FloatingPointVPOps[] = {
527         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
528         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
529         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,
530         ISD::VP_SELECT};
531 
532     if (!Subtarget.is64Bit()) {
533       // We must custom-lower certain vXi64 operations on RV32 due to the vector
534       // element type being illegal.
535       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
536       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
537 
538       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
539       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
540       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
541       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
542       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
543       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
544       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
545       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
546 
547       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
548       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
549       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
550       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
551       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
552       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
553       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
554       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
555     }
556 
557     for (MVT VT : BoolVecVTs) {
558       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
559 
560       // Mask VTs are custom-expanded into a series of standard nodes
561       setOperationAction(ISD::TRUNCATE, VT, Custom);
562       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
563       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
564       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
565 
566       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
567       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
568 
569       setOperationAction(ISD::SELECT, VT, Custom);
570       setOperationAction(ISD::SELECT_CC, VT, Expand);
571       setOperationAction(ISD::VSELECT, VT, Expand);
572       setOperationAction(ISD::VP_SELECT, VT, Expand);
573 
574       setOperationAction(ISD::VP_AND, VT, Custom);
575       setOperationAction(ISD::VP_OR, VT, Custom);
576       setOperationAction(ISD::VP_XOR, VT, Custom);
577 
578       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
579       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
580       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
581 
582       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
583       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
584       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
585 
586       // RVV has native int->float & float->int conversions where the
587       // element type sizes are within one power-of-two of each other. Any
588       // wider distances between type sizes have to be lowered as sequences
589       // which progressively narrow the gap in stages.
590       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
591       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
592       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
593       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
594 
595       // Expand all extending loads to types larger than this, and truncating
596       // stores from types larger than this.
597       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
598         setTruncStoreAction(OtherVT, VT, Expand);
599         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
600         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
601         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
602       }
603     }
604 
605     for (MVT VT : IntVecVTs) {
606       if (VT.getVectorElementType() == MVT::i64 &&
607           !Subtarget.hasVInstructionsI64())
608         continue;
609 
610       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
611       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
612 
613       // Vectors implement MULHS/MULHU.
614       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
615       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
616 
617       setOperationAction(ISD::SMIN, VT, Legal);
618       setOperationAction(ISD::SMAX, VT, Legal);
619       setOperationAction(ISD::UMIN, VT, Legal);
620       setOperationAction(ISD::UMAX, VT, Legal);
621 
622       setOperationAction(ISD::ROTL, VT, Expand);
623       setOperationAction(ISD::ROTR, VT, Expand);
624 
625       setOperationAction(ISD::CTTZ, VT, Expand);
626       setOperationAction(ISD::CTLZ, VT, Expand);
627       setOperationAction(ISD::CTPOP, VT, Expand);
628 
629       setOperationAction(ISD::BSWAP, VT, Expand);
630 
631       // Custom-lower extensions and truncations from/to mask types.
632       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
633       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
634       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
635 
636       // RVV has native int->float & float->int conversions where the
637       // element type sizes are within one power-of-two of each other. Any
638       // wider distances between type sizes have to be lowered as sequences
639       // which progressively narrow the gap in stages.
640       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
641       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
642       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
643       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
644 
645       setOperationAction(ISD::SADDSAT, VT, Legal);
646       setOperationAction(ISD::UADDSAT, VT, Legal);
647       setOperationAction(ISD::SSUBSAT, VT, Legal);
648       setOperationAction(ISD::USUBSAT, VT, Legal);
649 
650       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
651       // nodes which truncate by one power of two at a time.
652       setOperationAction(ISD::TRUNCATE, VT, Custom);
653 
654       // Custom-lower insert/extract operations to simplify patterns.
655       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
656       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
657 
658       // Custom-lower reduction operations to set up the corresponding custom
659       // nodes' operands.
660       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
661       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
662       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
663       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
664       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
665       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
666       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
667       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
668 
669       for (unsigned VPOpc : IntegerVPOps)
670         setOperationAction(VPOpc, VT, Custom);
671 
672       setOperationAction(ISD::LOAD, VT, Custom);
673       setOperationAction(ISD::STORE, VT, Custom);
674 
675       setOperationAction(ISD::MLOAD, VT, Custom);
676       setOperationAction(ISD::MSTORE, VT, Custom);
677       setOperationAction(ISD::MGATHER, VT, Custom);
678       setOperationAction(ISD::MSCATTER, VT, Custom);
679 
680       setOperationAction(ISD::VP_LOAD, VT, Custom);
681       setOperationAction(ISD::VP_STORE, VT, Custom);
682       setOperationAction(ISD::VP_GATHER, VT, Custom);
683       setOperationAction(ISD::VP_SCATTER, VT, Custom);
684 
685       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
686       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
687       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
688 
689       setOperationAction(ISD::SELECT, VT, Custom);
690       setOperationAction(ISD::SELECT_CC, VT, Expand);
691 
692       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
693       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
694 
695       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
696         setTruncStoreAction(VT, OtherVT, Expand);
697         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
698         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
699         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
700       }
701 
702       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
703       // type that can represent the value exactly.
704       if (VT.getVectorElementType() != MVT::i64) {
705         MVT FloatEltVT =
706             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
707         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
708         if (isTypeLegal(FloatVT)) {
709           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
710           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
711         }
712       }
713     }
714 
715     // Expand various CCs to best match the RVV ISA, which natively supports UNE
716     // but no other unordered comparisons, and supports all ordered comparisons
717     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
718     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
719     // and we pattern-match those back to the "original", swapping operands once
720     // more. This way we catch both operations and both "vf" and "fv" forms with
721     // fewer patterns.
722     static const ISD::CondCode VFPCCToExpand[] = {
723         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
724         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
725         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
726     };
727 
728     // Sets common operation actions on RVV floating-point vector types.
729     const auto SetCommonVFPActions = [&](MVT VT) {
730       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
731       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
732       // sizes are within one power-of-two of each other. Therefore conversions
733       // between vXf16 and vXf64 must be lowered as sequences which convert via
734       // vXf32.
735       setOperationAction(ISD::FP_ROUND, VT, Custom);
736       setOperationAction(ISD::FP_EXTEND, VT, Custom);
737       // Custom-lower insert/extract operations to simplify patterns.
738       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
739       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
740       // Expand various condition codes (explained above).
741       for (auto CC : VFPCCToExpand)
742         setCondCodeAction(CC, VT, Expand);
743 
744       setOperationAction(ISD::FMINNUM, VT, Legal);
745       setOperationAction(ISD::FMAXNUM, VT, Legal);
746 
747       setOperationAction(ISD::FTRUNC, VT, Custom);
748       setOperationAction(ISD::FCEIL, VT, Custom);
749       setOperationAction(ISD::FFLOOR, VT, Custom);
750 
751       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
752       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
753       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
754       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
755 
756       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
757 
758       setOperationAction(ISD::LOAD, VT, Custom);
759       setOperationAction(ISD::STORE, VT, Custom);
760 
761       setOperationAction(ISD::MLOAD, VT, Custom);
762       setOperationAction(ISD::MSTORE, VT, Custom);
763       setOperationAction(ISD::MGATHER, VT, Custom);
764       setOperationAction(ISD::MSCATTER, VT, Custom);
765 
766       setOperationAction(ISD::VP_LOAD, VT, Custom);
767       setOperationAction(ISD::VP_STORE, VT, Custom);
768       setOperationAction(ISD::VP_GATHER, VT, Custom);
769       setOperationAction(ISD::VP_SCATTER, VT, Custom);
770 
771       setOperationAction(ISD::SELECT, VT, Custom);
772       setOperationAction(ISD::SELECT_CC, VT, Expand);
773 
774       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
775       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
776       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
777 
778       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
779 
780       for (unsigned VPOpc : FloatingPointVPOps)
781         setOperationAction(VPOpc, VT, Custom);
782     };
783 
784     // Sets common extload/truncstore actions on RVV floating-point vector
785     // types.
786     const auto SetCommonVFPExtLoadTruncStoreActions =
787         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
788           for (auto SmallVT : SmallerVTs) {
789             setTruncStoreAction(VT, SmallVT, Expand);
790             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
791           }
792         };
793 
794     if (Subtarget.hasVInstructionsF16())
795       for (MVT VT : F16VecVTs)
796         SetCommonVFPActions(VT);
797 
798     for (MVT VT : F32VecVTs) {
799       if (Subtarget.hasVInstructionsF32())
800         SetCommonVFPActions(VT);
801       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
802     }
803 
804     for (MVT VT : F64VecVTs) {
805       if (Subtarget.hasVInstructionsF64())
806         SetCommonVFPActions(VT);
807       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
808       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
809     }
810 
811     if (Subtarget.useRVVForFixedLengthVectors()) {
812       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
813         if (!useRVVForFixedLengthVectorVT(VT))
814           continue;
815 
816         // By default everything must be expanded.
817         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
818           setOperationAction(Op, VT, Expand);
819         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
820           setTruncStoreAction(VT, OtherVT, Expand);
821           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
822           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
823           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
824         }
825 
826         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
827         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
828         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
829 
830         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
831         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
832 
833         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
834         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
835 
836         setOperationAction(ISD::LOAD, VT, Custom);
837         setOperationAction(ISD::STORE, VT, Custom);
838 
839         setOperationAction(ISD::SETCC, VT, Custom);
840 
841         setOperationAction(ISD::SELECT, VT, Custom);
842 
843         setOperationAction(ISD::TRUNCATE, VT, Custom);
844 
845         setOperationAction(ISD::BITCAST, VT, Custom);
846 
847         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
848         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
849         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
850 
851         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
852         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
853         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
854 
855         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
856         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
857         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
858         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
859 
860         // Operations below are different for between masks and other vectors.
861         if (VT.getVectorElementType() == MVT::i1) {
862           setOperationAction(ISD::VP_AND, VT, Custom);
863           setOperationAction(ISD::VP_OR, VT, Custom);
864           setOperationAction(ISD::VP_XOR, VT, Custom);
865           setOperationAction(ISD::AND, VT, Custom);
866           setOperationAction(ISD::OR, VT, Custom);
867           setOperationAction(ISD::XOR, VT, Custom);
868           continue;
869         }
870 
871         // Use SPLAT_VECTOR to prevent type legalization from destroying the
872         // splats when type legalizing i64 scalar on RV32.
873         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
874         // improvements first.
875         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
876           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
877           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
878         }
879 
880         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
881         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
882 
883         setOperationAction(ISD::MLOAD, VT, Custom);
884         setOperationAction(ISD::MSTORE, VT, Custom);
885         setOperationAction(ISD::MGATHER, VT, Custom);
886         setOperationAction(ISD::MSCATTER, VT, Custom);
887 
888         setOperationAction(ISD::VP_LOAD, VT, Custom);
889         setOperationAction(ISD::VP_STORE, VT, Custom);
890         setOperationAction(ISD::VP_GATHER, VT, Custom);
891         setOperationAction(ISD::VP_SCATTER, VT, Custom);
892 
893         setOperationAction(ISD::ADD, VT, Custom);
894         setOperationAction(ISD::MUL, VT, Custom);
895         setOperationAction(ISD::SUB, VT, Custom);
896         setOperationAction(ISD::AND, VT, Custom);
897         setOperationAction(ISD::OR, VT, Custom);
898         setOperationAction(ISD::XOR, VT, Custom);
899         setOperationAction(ISD::SDIV, VT, Custom);
900         setOperationAction(ISD::SREM, VT, Custom);
901         setOperationAction(ISD::UDIV, VT, Custom);
902         setOperationAction(ISD::UREM, VT, Custom);
903         setOperationAction(ISD::SHL, VT, Custom);
904         setOperationAction(ISD::SRA, VT, Custom);
905         setOperationAction(ISD::SRL, VT, Custom);
906 
907         setOperationAction(ISD::SMIN, VT, Custom);
908         setOperationAction(ISD::SMAX, VT, Custom);
909         setOperationAction(ISD::UMIN, VT, Custom);
910         setOperationAction(ISD::UMAX, VT, Custom);
911         setOperationAction(ISD::ABS,  VT, Custom);
912 
913         setOperationAction(ISD::MULHS, VT, Custom);
914         setOperationAction(ISD::MULHU, VT, Custom);
915 
916         setOperationAction(ISD::SADDSAT, VT, Custom);
917         setOperationAction(ISD::UADDSAT, VT, Custom);
918         setOperationAction(ISD::SSUBSAT, VT, Custom);
919         setOperationAction(ISD::USUBSAT, VT, Custom);
920 
921         setOperationAction(ISD::VSELECT, VT, Custom);
922         setOperationAction(ISD::SELECT_CC, VT, Expand);
923 
924         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
925         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
926         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
927 
928         // Custom-lower reduction operations to set up the corresponding custom
929         // nodes' operands.
930         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
931         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
932         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
933         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
934         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
935 
936         for (unsigned VPOpc : IntegerVPOps)
937           setOperationAction(VPOpc, VT, Custom);
938 
939         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
940         // type that can represent the value exactly.
941         if (VT.getVectorElementType() != MVT::i64) {
942           MVT FloatEltVT =
943               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
944           EVT FloatVT =
945               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
946           if (isTypeLegal(FloatVT)) {
947             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
948             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
949           }
950         }
951       }
952 
953       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
954         if (!useRVVForFixedLengthVectorVT(VT))
955           continue;
956 
957         // By default everything must be expanded.
958         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
959           setOperationAction(Op, VT, Expand);
960         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
961           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
962           setTruncStoreAction(VT, OtherVT, Expand);
963         }
964 
965         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
966         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
967         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
968 
969         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
970         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
971         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
972         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
973         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
974 
975         setOperationAction(ISD::LOAD, VT, Custom);
976         setOperationAction(ISD::STORE, VT, Custom);
977         setOperationAction(ISD::MLOAD, VT, Custom);
978         setOperationAction(ISD::MSTORE, VT, Custom);
979         setOperationAction(ISD::MGATHER, VT, Custom);
980         setOperationAction(ISD::MSCATTER, VT, Custom);
981 
982         setOperationAction(ISD::VP_LOAD, VT, Custom);
983         setOperationAction(ISD::VP_STORE, VT, Custom);
984         setOperationAction(ISD::VP_GATHER, VT, Custom);
985         setOperationAction(ISD::VP_SCATTER, VT, Custom);
986 
987         setOperationAction(ISD::FADD, VT, Custom);
988         setOperationAction(ISD::FSUB, VT, Custom);
989         setOperationAction(ISD::FMUL, VT, Custom);
990         setOperationAction(ISD::FDIV, VT, Custom);
991         setOperationAction(ISD::FNEG, VT, Custom);
992         setOperationAction(ISD::FABS, VT, Custom);
993         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
994         setOperationAction(ISD::FSQRT, VT, Custom);
995         setOperationAction(ISD::FMA, VT, Custom);
996         setOperationAction(ISD::FMINNUM, VT, Custom);
997         setOperationAction(ISD::FMAXNUM, VT, Custom);
998 
999         setOperationAction(ISD::FP_ROUND, VT, Custom);
1000         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1001 
1002         setOperationAction(ISD::FTRUNC, VT, Custom);
1003         setOperationAction(ISD::FCEIL, VT, Custom);
1004         setOperationAction(ISD::FFLOOR, VT, Custom);
1005 
1006         for (auto CC : VFPCCToExpand)
1007           setCondCodeAction(CC, VT, Expand);
1008 
1009         setOperationAction(ISD::VSELECT, VT, Custom);
1010         setOperationAction(ISD::SELECT, VT, Custom);
1011         setOperationAction(ISD::SELECT_CC, VT, Expand);
1012 
1013         setOperationAction(ISD::BITCAST, VT, Custom);
1014 
1015         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1016         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1017         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1018         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1019 
1020         for (unsigned VPOpc : FloatingPointVPOps)
1021           setOperationAction(VPOpc, VT, Custom);
1022       }
1023 
1024       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1025       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1026       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1027       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1028       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1029       if (Subtarget.hasStdExtZfh())
1030         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1031       if (Subtarget.hasStdExtF())
1032         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1033       if (Subtarget.hasStdExtD())
1034         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1035     }
1036   }
1037 
1038   // Function alignments.
1039   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1040   setMinFunctionAlignment(FunctionAlignment);
1041   setPrefFunctionAlignment(FunctionAlignment);
1042 
1043   setMinimumJumpTableEntries(5);
1044 
1045   // Jumps are expensive, compared to logic
1046   setJumpIsExpensive();
1047 
1048   setTargetDAGCombine(ISD::ADD);
1049   setTargetDAGCombine(ISD::SUB);
1050   setTargetDAGCombine(ISD::AND);
1051   setTargetDAGCombine(ISD::OR);
1052   setTargetDAGCombine(ISD::XOR);
1053   setTargetDAGCombine(ISD::ANY_EXTEND);
1054   if (Subtarget.hasStdExtF()) {
1055     setTargetDAGCombine(ISD::ZERO_EXTEND);
1056     setTargetDAGCombine(ISD::FP_TO_SINT);
1057     setTargetDAGCombine(ISD::FP_TO_UINT);
1058     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1059     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1060   }
1061   if (Subtarget.hasVInstructions()) {
1062     setTargetDAGCombine(ISD::FCOPYSIGN);
1063     setTargetDAGCombine(ISD::MGATHER);
1064     setTargetDAGCombine(ISD::MSCATTER);
1065     setTargetDAGCombine(ISD::VP_GATHER);
1066     setTargetDAGCombine(ISD::VP_SCATTER);
1067     setTargetDAGCombine(ISD::SRA);
1068     setTargetDAGCombine(ISD::SRL);
1069     setTargetDAGCombine(ISD::SHL);
1070     setTargetDAGCombine(ISD::STORE);
1071   }
1072 }
1073 
1074 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1075                                             LLVMContext &Context,
1076                                             EVT VT) const {
1077   if (!VT.isVector())
1078     return getPointerTy(DL);
1079   if (Subtarget.hasVInstructions() &&
1080       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1081     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1082   return VT.changeVectorElementTypeToInteger();
1083 }
1084 
1085 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1086   return Subtarget.getXLenVT();
1087 }
1088 
1089 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1090                                              const CallInst &I,
1091                                              MachineFunction &MF,
1092                                              unsigned Intrinsic) const {
1093   auto &DL = I.getModule()->getDataLayout();
1094   switch (Intrinsic) {
1095   default:
1096     return false;
1097   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1100   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1101   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1102   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1103   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1104   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1105   case Intrinsic::riscv_masked_cmpxchg_i32: {
1106     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1107     Info.opc = ISD::INTRINSIC_W_CHAIN;
1108     Info.memVT = MVT::getVT(PtrTy->getElementType());
1109     Info.ptrVal = I.getArgOperand(0);
1110     Info.offset = 0;
1111     Info.align = Align(4);
1112     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1113                  MachineMemOperand::MOVolatile;
1114     return true;
1115   }
1116   case Intrinsic::riscv_masked_strided_load:
1117     Info.opc = ISD::INTRINSIC_W_CHAIN;
1118     Info.ptrVal = I.getArgOperand(1);
1119     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1120     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1121     Info.size = MemoryLocation::UnknownSize;
1122     Info.flags |= MachineMemOperand::MOLoad;
1123     return true;
1124   case Intrinsic::riscv_masked_strided_store:
1125     Info.opc = ISD::INTRINSIC_VOID;
1126     Info.ptrVal = I.getArgOperand(1);
1127     Info.memVT =
1128         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1129     Info.align = Align(
1130         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1131         8);
1132     Info.size = MemoryLocation::UnknownSize;
1133     Info.flags |= MachineMemOperand::MOStore;
1134     return true;
1135   }
1136 }
1137 
1138 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1139                                                 const AddrMode &AM, Type *Ty,
1140                                                 unsigned AS,
1141                                                 Instruction *I) const {
1142   // No global is ever allowed as a base.
1143   if (AM.BaseGV)
1144     return false;
1145 
1146   // Require a 12-bit signed offset.
1147   if (!isInt<12>(AM.BaseOffs))
1148     return false;
1149 
1150   switch (AM.Scale) {
1151   case 0: // "r+i" or just "i", depending on HasBaseReg.
1152     break;
1153   case 1:
1154     if (!AM.HasBaseReg) // allow "r+i".
1155       break;
1156     return false; // disallow "r+r" or "r+r+i".
1157   default:
1158     return false;
1159   }
1160 
1161   return true;
1162 }
1163 
1164 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1165   return isInt<12>(Imm);
1166 }
1167 
1168 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1169   return isInt<12>(Imm);
1170 }
1171 
1172 // On RV32, 64-bit integers are split into their high and low parts and held
1173 // in two different registers, so the trunc is free since the low register can
1174 // just be used.
1175 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1176   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1177     return false;
1178   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1179   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1180   return (SrcBits == 64 && DestBits == 32);
1181 }
1182 
1183 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1184   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1185       !SrcVT.isInteger() || !DstVT.isInteger())
1186     return false;
1187   unsigned SrcBits = SrcVT.getSizeInBits();
1188   unsigned DestBits = DstVT.getSizeInBits();
1189   return (SrcBits == 64 && DestBits == 32);
1190 }
1191 
1192 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1193   // Zexts are free if they can be combined with a load.
1194   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1195   // poorly with type legalization of compares preferring sext.
1196   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1197     EVT MemVT = LD->getMemoryVT();
1198     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1199         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1200          LD->getExtensionType() == ISD::ZEXTLOAD))
1201       return true;
1202   }
1203 
1204   return TargetLowering::isZExtFree(Val, VT2);
1205 }
1206 
1207 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1208   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1209 }
1210 
1211 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1212   return Subtarget.hasStdExtZbb();
1213 }
1214 
1215 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1216   return Subtarget.hasStdExtZbb();
1217 }
1218 
1219 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1220   EVT VT = Y.getValueType();
1221 
1222   // FIXME: Support vectors once we have tests.
1223   if (VT.isVector())
1224     return false;
1225 
1226   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1227 }
1228 
1229 /// Check if sinking \p I's operands to I's basic block is profitable, because
1230 /// the operands can be folded into a target instruction, e.g.
1231 /// splats of scalars can fold into vector instructions.
1232 bool RISCVTargetLowering::shouldSinkOperands(
1233     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1234   using namespace llvm::PatternMatch;
1235 
1236   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1237     return false;
1238 
1239   auto IsSinker = [&](Instruction *I, int Operand) {
1240     switch (I->getOpcode()) {
1241     case Instruction::Add:
1242     case Instruction::Sub:
1243     case Instruction::Mul:
1244     case Instruction::And:
1245     case Instruction::Or:
1246     case Instruction::Xor:
1247     case Instruction::FAdd:
1248     case Instruction::FSub:
1249     case Instruction::FMul:
1250     case Instruction::FDiv:
1251     case Instruction::ICmp:
1252     case Instruction::FCmp:
1253       return true;
1254     case Instruction::Shl:
1255     case Instruction::LShr:
1256     case Instruction::AShr:
1257     case Instruction::UDiv:
1258     case Instruction::SDiv:
1259     case Instruction::URem:
1260     case Instruction::SRem:
1261       return Operand == 1;
1262     case Instruction::Call:
1263       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1264         switch (II->getIntrinsicID()) {
1265         case Intrinsic::fma:
1266           return Operand == 0 || Operand == 1;
1267         // FIXME: Our patterns can only match vx/vf instructions when the splat
1268         // it on the RHS, because TableGen doesn't recognize our VP operations
1269         // as commutative.
1270         case Intrinsic::vp_add:
1271         case Intrinsic::vp_mul:
1272         case Intrinsic::vp_and:
1273         case Intrinsic::vp_or:
1274         case Intrinsic::vp_xor:
1275         case Intrinsic::vp_fadd:
1276         case Intrinsic::vp_fmul:
1277         case Intrinsic::vp_shl:
1278         case Intrinsic::vp_lshr:
1279         case Intrinsic::vp_ashr:
1280         case Intrinsic::vp_udiv:
1281         case Intrinsic::vp_sdiv:
1282         case Intrinsic::vp_urem:
1283         case Intrinsic::vp_srem:
1284           return Operand == 1;
1285         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1286         // explicit patterns for both LHS and RHS (as 'vr' versions).
1287         case Intrinsic::vp_sub:
1288         case Intrinsic::vp_fsub:
1289         case Intrinsic::vp_fdiv:
1290           return Operand == 0 || Operand == 1;
1291         default:
1292           return false;
1293         }
1294       }
1295       return false;
1296     default:
1297       return false;
1298     }
1299   };
1300 
1301   for (auto OpIdx : enumerate(I->operands())) {
1302     if (!IsSinker(I, OpIdx.index()))
1303       continue;
1304 
1305     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1306     // Make sure we are not already sinking this operand
1307     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1308       continue;
1309 
1310     // We are looking for a splat that can be sunk.
1311     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1312                              m_Undef(), m_ZeroMask())))
1313       continue;
1314 
1315     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1316     // and vector registers
1317     for (Use &U : Op->uses()) {
1318       Instruction *Insn = cast<Instruction>(U.getUser());
1319       if (!IsSinker(Insn, U.getOperandNo()))
1320         return false;
1321     }
1322 
1323     Ops.push_back(&Op->getOperandUse(0));
1324     Ops.push_back(&OpIdx.value());
1325   }
1326   return true;
1327 }
1328 
1329 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1330                                        bool ForCodeSize) const {
1331   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1332   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1333     return false;
1334   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1335     return false;
1336   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1337     return false;
1338   return Imm.isZero();
1339 }
1340 
1341 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1342   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1343          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1344          (VT == MVT::f64 && Subtarget.hasStdExtD());
1345 }
1346 
1347 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1348                                                       CallingConv::ID CC,
1349                                                       EVT VT) const {
1350   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1351   // We might still end up using a GPR but that will be decided based on ABI.
1352   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1353   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1354     return MVT::f32;
1355 
1356   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1357 }
1358 
1359 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1360                                                            CallingConv::ID CC,
1361                                                            EVT VT) const {
1362   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1363   // We might still end up using a GPR but that will be decided based on ABI.
1364   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1365   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1366     return 1;
1367 
1368   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1369 }
1370 
1371 // Changes the condition code and swaps operands if necessary, so the SetCC
1372 // operation matches one of the comparisons supported directly by branches
1373 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1374 // with 1/-1.
1375 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1376                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1377   // Convert X > -1 to X >= 0.
1378   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1379     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1380     CC = ISD::SETGE;
1381     return;
1382   }
1383   // Convert X < 1 to 0 >= X.
1384   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1385     RHS = LHS;
1386     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1387     CC = ISD::SETGE;
1388     return;
1389   }
1390 
1391   switch (CC) {
1392   default:
1393     break;
1394   case ISD::SETGT:
1395   case ISD::SETLE:
1396   case ISD::SETUGT:
1397   case ISD::SETULE:
1398     CC = ISD::getSetCCSwappedOperands(CC);
1399     std::swap(LHS, RHS);
1400     break;
1401   }
1402 }
1403 
1404 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1405   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1406   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1407   if (VT.getVectorElementType() == MVT::i1)
1408     KnownSize *= 8;
1409 
1410   switch (KnownSize) {
1411   default:
1412     llvm_unreachable("Invalid LMUL.");
1413   case 8:
1414     return RISCVII::VLMUL::LMUL_F8;
1415   case 16:
1416     return RISCVII::VLMUL::LMUL_F4;
1417   case 32:
1418     return RISCVII::VLMUL::LMUL_F2;
1419   case 64:
1420     return RISCVII::VLMUL::LMUL_1;
1421   case 128:
1422     return RISCVII::VLMUL::LMUL_2;
1423   case 256:
1424     return RISCVII::VLMUL::LMUL_4;
1425   case 512:
1426     return RISCVII::VLMUL::LMUL_8;
1427   }
1428 }
1429 
1430 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1431   switch (LMul) {
1432   default:
1433     llvm_unreachable("Invalid LMUL.");
1434   case RISCVII::VLMUL::LMUL_F8:
1435   case RISCVII::VLMUL::LMUL_F4:
1436   case RISCVII::VLMUL::LMUL_F2:
1437   case RISCVII::VLMUL::LMUL_1:
1438     return RISCV::VRRegClassID;
1439   case RISCVII::VLMUL::LMUL_2:
1440     return RISCV::VRM2RegClassID;
1441   case RISCVII::VLMUL::LMUL_4:
1442     return RISCV::VRM4RegClassID;
1443   case RISCVII::VLMUL::LMUL_8:
1444     return RISCV::VRM8RegClassID;
1445   }
1446 }
1447 
1448 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1449   RISCVII::VLMUL LMUL = getLMUL(VT);
1450   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1451       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1452       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1453       LMUL == RISCVII::VLMUL::LMUL_1) {
1454     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1455                   "Unexpected subreg numbering");
1456     return RISCV::sub_vrm1_0 + Index;
1457   }
1458   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1459     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1460                   "Unexpected subreg numbering");
1461     return RISCV::sub_vrm2_0 + Index;
1462   }
1463   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1464     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1465                   "Unexpected subreg numbering");
1466     return RISCV::sub_vrm4_0 + Index;
1467   }
1468   llvm_unreachable("Invalid vector type.");
1469 }
1470 
1471 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1472   if (VT.getVectorElementType() == MVT::i1)
1473     return RISCV::VRRegClassID;
1474   return getRegClassIDForLMUL(getLMUL(VT));
1475 }
1476 
1477 // Attempt to decompose a subvector insert/extract between VecVT and
1478 // SubVecVT via subregister indices. Returns the subregister index that
1479 // can perform the subvector insert/extract with the given element index, as
1480 // well as the index corresponding to any leftover subvectors that must be
1481 // further inserted/extracted within the register class for SubVecVT.
1482 std::pair<unsigned, unsigned>
1483 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1484     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1485     const RISCVRegisterInfo *TRI) {
1486   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1487                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1488                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1489                 "Register classes not ordered");
1490   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1491   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1492   // Try to compose a subregister index that takes us from the incoming
1493   // LMUL>1 register class down to the outgoing one. At each step we half
1494   // the LMUL:
1495   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1496   // Note that this is not guaranteed to find a subregister index, such as
1497   // when we are extracting from one VR type to another.
1498   unsigned SubRegIdx = RISCV::NoSubRegister;
1499   for (const unsigned RCID :
1500        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1501     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1502       VecVT = VecVT.getHalfNumVectorElementsVT();
1503       bool IsHi =
1504           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1505       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1506                                             getSubregIndexByMVT(VecVT, IsHi));
1507       if (IsHi)
1508         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1509     }
1510   return {SubRegIdx, InsertExtractIdx};
1511 }
1512 
1513 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1514 // stores for those types.
1515 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1516   return !Subtarget.useRVVForFixedLengthVectors() ||
1517          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1518 }
1519 
1520 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1521   if (ScalarTy->isPointerTy())
1522     return true;
1523 
1524   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1525       ScalarTy->isIntegerTy(32))
1526     return true;
1527 
1528   if (ScalarTy->isIntegerTy(64))
1529     return Subtarget.hasVInstructionsI64();
1530 
1531   if (ScalarTy->isHalfTy())
1532     return Subtarget.hasVInstructionsF16();
1533   if (ScalarTy->isFloatTy())
1534     return Subtarget.hasVInstructionsF32();
1535   if (ScalarTy->isDoubleTy())
1536     return Subtarget.hasVInstructionsF64();
1537 
1538   return false;
1539 }
1540 
1541 static bool useRVVForFixedLengthVectorVT(MVT VT,
1542                                          const RISCVSubtarget &Subtarget) {
1543   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1544   if (!Subtarget.useRVVForFixedLengthVectors())
1545     return false;
1546 
1547   // We only support a set of vector types with a consistent maximum fixed size
1548   // across all supported vector element types to avoid legalization issues.
1549   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1550   // fixed-length vector type we support is 1024 bytes.
1551   if (VT.getFixedSizeInBits() > 1024 * 8)
1552     return false;
1553 
1554   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1555 
1556   MVT EltVT = VT.getVectorElementType();
1557 
1558   // Don't use RVV for vectors we cannot scalarize if required.
1559   switch (EltVT.SimpleTy) {
1560   // i1 is supported but has different rules.
1561   default:
1562     return false;
1563   case MVT::i1:
1564     // Masks can only use a single register.
1565     if (VT.getVectorNumElements() > MinVLen)
1566       return false;
1567     MinVLen /= 8;
1568     break;
1569   case MVT::i8:
1570   case MVT::i16:
1571   case MVT::i32:
1572     break;
1573   case MVT::i64:
1574     if (!Subtarget.hasVInstructionsI64())
1575       return false;
1576     break;
1577   case MVT::f16:
1578     if (!Subtarget.hasVInstructionsF16())
1579       return false;
1580     break;
1581   case MVT::f32:
1582     if (!Subtarget.hasVInstructionsF32())
1583       return false;
1584     break;
1585   case MVT::f64:
1586     if (!Subtarget.hasVInstructionsF64())
1587       return false;
1588     break;
1589   }
1590 
1591   // Reject elements larger than ELEN.
1592   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1593     return false;
1594 
1595   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1596   // Don't use RVV for types that don't fit.
1597   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1598     return false;
1599 
1600   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1601   // the base fixed length RVV support in place.
1602   if (!VT.isPow2VectorType())
1603     return false;
1604 
1605   return true;
1606 }
1607 
1608 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1609   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1610 }
1611 
1612 // Return the largest legal scalable vector type that matches VT's element type.
1613 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1614                                             const RISCVSubtarget &Subtarget) {
1615   // This may be called before legal types are setup.
1616   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1617           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1618          "Expected legal fixed length vector!");
1619 
1620   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1621   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1622 
1623   MVT EltVT = VT.getVectorElementType();
1624   switch (EltVT.SimpleTy) {
1625   default:
1626     llvm_unreachable("unexpected element type for RVV container");
1627   case MVT::i1:
1628   case MVT::i8:
1629   case MVT::i16:
1630   case MVT::i32:
1631   case MVT::i64:
1632   case MVT::f16:
1633   case MVT::f32:
1634   case MVT::f64: {
1635     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1636     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1637     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1638     unsigned NumElts =
1639         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1640     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1641     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1642     return MVT::getScalableVectorVT(EltVT, NumElts);
1643   }
1644   }
1645 }
1646 
1647 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1648                                             const RISCVSubtarget &Subtarget) {
1649   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1650                                           Subtarget);
1651 }
1652 
1653 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1654   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1655 }
1656 
1657 // Grow V to consume an entire RVV register.
1658 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1659                                        const RISCVSubtarget &Subtarget) {
1660   assert(VT.isScalableVector() &&
1661          "Expected to convert into a scalable vector!");
1662   assert(V.getValueType().isFixedLengthVector() &&
1663          "Expected a fixed length vector operand!");
1664   SDLoc DL(V);
1665   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1666   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1667 }
1668 
1669 // Shrink V so it's just big enough to maintain a VT's worth of data.
1670 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1671                                          const RISCVSubtarget &Subtarget) {
1672   assert(VT.isFixedLengthVector() &&
1673          "Expected to convert into a fixed length vector!");
1674   assert(V.getValueType().isScalableVector() &&
1675          "Expected a scalable vector operand!");
1676   SDLoc DL(V);
1677   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1678   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1679 }
1680 
1681 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1682 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1683 // the vector type that it is contained in.
1684 static std::pair<SDValue, SDValue>
1685 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1686                 const RISCVSubtarget &Subtarget) {
1687   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1688   MVT XLenVT = Subtarget.getXLenVT();
1689   SDValue VL = VecVT.isFixedLengthVector()
1690                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1691                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1692   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1693   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1694   return {Mask, VL};
1695 }
1696 
1697 // As above but assuming the given type is a scalable vector type.
1698 static std::pair<SDValue, SDValue>
1699 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1700                         const RISCVSubtarget &Subtarget) {
1701   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1702   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1703 }
1704 
1705 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1706 // of either is (currently) supported. This can get us into an infinite loop
1707 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1708 // as a ..., etc.
1709 // Until either (or both) of these can reliably lower any node, reporting that
1710 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1711 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1712 // which is not desirable.
1713 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1714     EVT VT, unsigned DefinedValues) const {
1715   return false;
1716 }
1717 
1718 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1719   // Only splats are currently supported.
1720   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1721     return true;
1722 
1723   return false;
1724 }
1725 
1726 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1727                                   const RISCVSubtarget &Subtarget) {
1728   // RISCV FP-to-int conversions saturate to the destination register size, but
1729   // don't produce 0 for nan. We can use a conversion instruction and fix the
1730   // nan case with a compare and a select.
1731   SDValue Src = Op.getOperand(0);
1732 
1733   EVT DstVT = Op.getValueType();
1734   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1735 
1736   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1737   unsigned Opc;
1738   if (SatVT == DstVT)
1739     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1740   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1741     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1742   else
1743     return SDValue();
1744   // FIXME: Support other SatVTs by clamping before or after the conversion.
1745 
1746   SDLoc DL(Op);
1747   SDValue FpToInt = DAG.getNode(
1748       Opc, DL, DstVT, Src,
1749       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1750 
1751   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1752   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1753 }
1754 
1755 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1756 // and back. Taking care to avoid converting values that are nan or already
1757 // correct.
1758 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1759 // have FRM dependencies modeled yet.
1760 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1761   MVT VT = Op.getSimpleValueType();
1762   assert(VT.isVector() && "Unexpected type");
1763 
1764   SDLoc DL(Op);
1765 
1766   // Freeze the source since we are increasing the number of uses.
1767   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1768 
1769   // Truncate to integer and convert back to FP.
1770   MVT IntVT = VT.changeVectorElementTypeToInteger();
1771   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1772   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1773 
1774   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1775 
1776   if (Op.getOpcode() == ISD::FCEIL) {
1777     // If the truncated value is the greater than or equal to the original
1778     // value, we've computed the ceil. Otherwise, we went the wrong way and
1779     // need to increase by 1.
1780     // FIXME: This should use a masked operation. Handle here or in isel?
1781     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1782                                  DAG.getConstantFP(1.0, DL, VT));
1783     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1784     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1785   } else if (Op.getOpcode() == ISD::FFLOOR) {
1786     // If the truncated value is the less than or equal to the original value,
1787     // we've computed the floor. Otherwise, we went the wrong way and need to
1788     // decrease by 1.
1789     // FIXME: This should use a masked operation. Handle here or in isel?
1790     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1791                                  DAG.getConstantFP(1.0, DL, VT));
1792     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1793     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1794   }
1795 
1796   // Restore the original sign so that -0.0 is preserved.
1797   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1798 
1799   // Determine the largest integer that can be represented exactly. This and
1800   // values larger than it don't have any fractional bits so don't need to
1801   // be converted.
1802   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1803   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1804   APFloat MaxVal = APFloat(FltSem);
1805   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1806                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1807   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1808 
1809   // If abs(Src) was larger than MaxVal or nan, keep it.
1810   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1811   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1812   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1813 }
1814 
1815 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1816                                  const RISCVSubtarget &Subtarget) {
1817   MVT VT = Op.getSimpleValueType();
1818   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1819 
1820   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1821 
1822   SDLoc DL(Op);
1823   SDValue Mask, VL;
1824   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1825 
1826   unsigned Opc =
1827       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1828   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1829   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1830 }
1831 
1832 struct VIDSequence {
1833   int64_t StepNumerator;
1834   unsigned StepDenominator;
1835   int64_t Addend;
1836 };
1837 
1838 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1839 // to the (non-zero) step S and start value X. This can be then lowered as the
1840 // RVV sequence (VID * S) + X, for example.
1841 // The step S is represented as an integer numerator divided by a positive
1842 // denominator. Note that the implementation currently only identifies
1843 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1844 // cannot detect 2/3, for example.
1845 // Note that this method will also match potentially unappealing index
1846 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1847 // determine whether this is worth generating code for.
1848 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1849   unsigned NumElts = Op.getNumOperands();
1850   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1851   if (!Op.getValueType().isInteger())
1852     return None;
1853 
1854   Optional<unsigned> SeqStepDenom;
1855   Optional<int64_t> SeqStepNum, SeqAddend;
1856   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1857   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1858   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1859     // Assume undef elements match the sequence; we just have to be careful
1860     // when interpolating across them.
1861     if (Op.getOperand(Idx).isUndef())
1862       continue;
1863     // The BUILD_VECTOR must be all constants.
1864     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1865       return None;
1866 
1867     uint64_t Val = Op.getConstantOperandVal(Idx) &
1868                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1869 
1870     if (PrevElt) {
1871       // Calculate the step since the last non-undef element, and ensure
1872       // it's consistent across the entire sequence.
1873       unsigned IdxDiff = Idx - PrevElt->second;
1874       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1875 
1876       // A zero-value value difference means that we're somewhere in the middle
1877       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1878       // step change before evaluating the sequence.
1879       if (ValDiff != 0) {
1880         int64_t Remainder = ValDiff % IdxDiff;
1881         // Normalize the step if it's greater than 1.
1882         if (Remainder != ValDiff) {
1883           // The difference must cleanly divide the element span.
1884           if (Remainder != 0)
1885             return None;
1886           ValDiff /= IdxDiff;
1887           IdxDiff = 1;
1888         }
1889 
1890         if (!SeqStepNum)
1891           SeqStepNum = ValDiff;
1892         else if (ValDiff != SeqStepNum)
1893           return None;
1894 
1895         if (!SeqStepDenom)
1896           SeqStepDenom = IdxDiff;
1897         else if (IdxDiff != *SeqStepDenom)
1898           return None;
1899       }
1900     }
1901 
1902     // Record and/or check any addend.
1903     if (SeqStepNum && SeqStepDenom) {
1904       uint64_t ExpectedVal =
1905           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1906       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1907       if (!SeqAddend)
1908         SeqAddend = Addend;
1909       else if (SeqAddend != Addend)
1910         return None;
1911     }
1912 
1913     // Record this non-undef element for later.
1914     if (!PrevElt || PrevElt->first != Val)
1915       PrevElt = std::make_pair(Val, Idx);
1916   }
1917   // We need to have logged both a step and an addend for this to count as
1918   // a legal index sequence.
1919   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1920     return None;
1921 
1922   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1923 }
1924 
1925 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1926                                  const RISCVSubtarget &Subtarget) {
1927   MVT VT = Op.getSimpleValueType();
1928   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1929 
1930   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1931 
1932   SDLoc DL(Op);
1933   SDValue Mask, VL;
1934   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1935 
1936   MVT XLenVT = Subtarget.getXLenVT();
1937   unsigned NumElts = Op.getNumOperands();
1938 
1939   if (VT.getVectorElementType() == MVT::i1) {
1940     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1941       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1942       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1943     }
1944 
1945     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1946       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1947       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1948     }
1949 
1950     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1951     // scalar integer chunks whose bit-width depends on the number of mask
1952     // bits and XLEN.
1953     // First, determine the most appropriate scalar integer type to use. This
1954     // is at most XLenVT, but may be shrunk to a smaller vector element type
1955     // according to the size of the final vector - use i8 chunks rather than
1956     // XLenVT if we're producing a v8i1. This results in more consistent
1957     // codegen across RV32 and RV64.
1958     unsigned NumViaIntegerBits =
1959         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1960     NumViaIntegerBits = std::min(NumViaIntegerBits,
1961                                  Subtarget.getMaxELENForFixedLengthVectors());
1962     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1963       // If we have to use more than one INSERT_VECTOR_ELT then this
1964       // optimization is likely to increase code size; avoid peforming it in
1965       // such a case. We can use a load from a constant pool in this case.
1966       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1967         return SDValue();
1968       // Now we can create our integer vector type. Note that it may be larger
1969       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1970       MVT IntegerViaVecVT =
1971           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1972                            divideCeil(NumElts, NumViaIntegerBits));
1973 
1974       uint64_t Bits = 0;
1975       unsigned BitPos = 0, IntegerEltIdx = 0;
1976       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1977 
1978       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1979         // Once we accumulate enough bits to fill our scalar type, insert into
1980         // our vector and clear our accumulated data.
1981         if (I != 0 && I % NumViaIntegerBits == 0) {
1982           if (NumViaIntegerBits <= 32)
1983             Bits = SignExtend64(Bits, 32);
1984           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1985           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1986                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1987           Bits = 0;
1988           BitPos = 0;
1989           IntegerEltIdx++;
1990         }
1991         SDValue V = Op.getOperand(I);
1992         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1993         Bits |= ((uint64_t)BitValue << BitPos);
1994       }
1995 
1996       // Insert the (remaining) scalar value into position in our integer
1997       // vector type.
1998       if (NumViaIntegerBits <= 32)
1999         Bits = SignExtend64(Bits, 32);
2000       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2001       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2002                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2003 
2004       if (NumElts < NumViaIntegerBits) {
2005         // If we're producing a smaller vector than our minimum legal integer
2006         // type, bitcast to the equivalent (known-legal) mask type, and extract
2007         // our final mask.
2008         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2009         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2010         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2011                           DAG.getConstant(0, DL, XLenVT));
2012       } else {
2013         // Else we must have produced an integer type with the same size as the
2014         // mask type; bitcast for the final result.
2015         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2016         Vec = DAG.getBitcast(VT, Vec);
2017       }
2018 
2019       return Vec;
2020     }
2021 
2022     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2023     // vector type, we have a legal equivalently-sized i8 type, so we can use
2024     // that.
2025     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2026     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2027 
2028     SDValue WideVec;
2029     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2030       // For a splat, perform a scalar truncate before creating the wider
2031       // vector.
2032       assert(Splat.getValueType() == XLenVT &&
2033              "Unexpected type for i1 splat value");
2034       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2035                           DAG.getConstant(1, DL, XLenVT));
2036       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2037     } else {
2038       SmallVector<SDValue, 8> Ops(Op->op_values());
2039       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2040       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2041       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2042     }
2043 
2044     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2045   }
2046 
2047   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2048     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2049                                         : RISCVISD::VMV_V_X_VL;
2050     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2051     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2052   }
2053 
2054   // Try and match index sequences, which we can lower to the vid instruction
2055   // with optional modifications. An all-undef vector is matched by
2056   // getSplatValue, above.
2057   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2058     int64_t StepNumerator = SimpleVID->StepNumerator;
2059     unsigned StepDenominator = SimpleVID->StepDenominator;
2060     int64_t Addend = SimpleVID->Addend;
2061 
2062     assert(StepNumerator != 0 && "Invalid step");
2063     bool Negate = false;
2064     int64_t SplatStepVal = StepNumerator;
2065     unsigned StepOpcode = ISD::MUL;
2066     if (StepNumerator != 1) {
2067       if (isPowerOf2_64(std::abs(StepNumerator))) {
2068         Negate = StepNumerator < 0;
2069         StepOpcode = ISD::SHL;
2070         SplatStepVal = Log2_64(std::abs(StepNumerator));
2071       }
2072     }
2073 
2074     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2075     // threshold since it's the immediate value many RVV instructions accept.
2076     // There is no vmul.vi instruction so ensure multiply constant can fit in
2077     // a single addi instruction.
2078     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2079          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2080         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2081       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2082       // Convert right out of the scalable type so we can use standard ISD
2083       // nodes for the rest of the computation. If we used scalable types with
2084       // these, we'd lose the fixed-length vector info and generate worse
2085       // vsetvli code.
2086       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2087       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2088           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2089         SDValue SplatStep = DAG.getSplatVector(
2090             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2091         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2092       }
2093       if (StepDenominator != 1) {
2094         SDValue SplatStep = DAG.getSplatVector(
2095             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2096         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2097       }
2098       if (Addend != 0 || Negate) {
2099         SDValue SplatAddend =
2100             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2101         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2102       }
2103       return VID;
2104     }
2105   }
2106 
2107   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2108   // when re-interpreted as a vector with a larger element type. For example,
2109   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2110   // could be instead splat as
2111   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2112   // TODO: This optimization could also work on non-constant splats, but it
2113   // would require bit-manipulation instructions to construct the splat value.
2114   SmallVector<SDValue> Sequence;
2115   unsigned EltBitSize = VT.getScalarSizeInBits();
2116   const auto *BV = cast<BuildVectorSDNode>(Op);
2117   if (VT.isInteger() && EltBitSize < 64 &&
2118       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2119       BV->getRepeatedSequence(Sequence) &&
2120       (Sequence.size() * EltBitSize) <= 64) {
2121     unsigned SeqLen = Sequence.size();
2122     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2123     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2124     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2125             ViaIntVT == MVT::i64) &&
2126            "Unexpected sequence type");
2127 
2128     unsigned EltIdx = 0;
2129     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2130     uint64_t SplatValue = 0;
2131     // Construct the amalgamated value which can be splatted as this larger
2132     // vector type.
2133     for (const auto &SeqV : Sequence) {
2134       if (!SeqV.isUndef())
2135         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2136                        << (EltIdx * EltBitSize));
2137       EltIdx++;
2138     }
2139 
2140     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2141     // achieve better constant materializion.
2142     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2143       SplatValue = SignExtend64(SplatValue, 32);
2144 
2145     // Since we can't introduce illegal i64 types at this stage, we can only
2146     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2147     // way we can use RVV instructions to splat.
2148     assert((ViaIntVT.bitsLE(XLenVT) ||
2149             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2150            "Unexpected bitcast sequence");
2151     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2152       SDValue ViaVL =
2153           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2154       MVT ViaContainerVT =
2155           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2156       SDValue Splat =
2157           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2158                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2159       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2160       return DAG.getBitcast(VT, Splat);
2161     }
2162   }
2163 
2164   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2165   // which constitute a large proportion of the elements. In such cases we can
2166   // splat a vector with the dominant element and make up the shortfall with
2167   // INSERT_VECTOR_ELTs.
2168   // Note that this includes vectors of 2 elements by association. The
2169   // upper-most element is the "dominant" one, allowing us to use a splat to
2170   // "insert" the upper element, and an insert of the lower element at position
2171   // 0, which improves codegen.
2172   SDValue DominantValue;
2173   unsigned MostCommonCount = 0;
2174   DenseMap<SDValue, unsigned> ValueCounts;
2175   unsigned NumUndefElts =
2176       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2177 
2178   // Track the number of scalar loads we know we'd be inserting, estimated as
2179   // any non-zero floating-point constant. Other kinds of element are either
2180   // already in registers or are materialized on demand. The threshold at which
2181   // a vector load is more desirable than several scalar materializion and
2182   // vector-insertion instructions is not known.
2183   unsigned NumScalarLoads = 0;
2184 
2185   for (SDValue V : Op->op_values()) {
2186     if (V.isUndef())
2187       continue;
2188 
2189     ValueCounts.insert(std::make_pair(V, 0));
2190     unsigned &Count = ValueCounts[V];
2191 
2192     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2193       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2194 
2195     // Is this value dominant? In case of a tie, prefer the highest element as
2196     // it's cheaper to insert near the beginning of a vector than it is at the
2197     // end.
2198     if (++Count >= MostCommonCount) {
2199       DominantValue = V;
2200       MostCommonCount = Count;
2201     }
2202   }
2203 
2204   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2205   unsigned NumDefElts = NumElts - NumUndefElts;
2206   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2207 
2208   // Don't perform this optimization when optimizing for size, since
2209   // materializing elements and inserting them tends to cause code bloat.
2210   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2211       ((MostCommonCount > DominantValueCountThreshold) ||
2212        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2213     // Start by splatting the most common element.
2214     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2215 
2216     DenseSet<SDValue> Processed{DominantValue};
2217     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2218     for (const auto &OpIdx : enumerate(Op->ops())) {
2219       const SDValue &V = OpIdx.value();
2220       if (V.isUndef() || !Processed.insert(V).second)
2221         continue;
2222       if (ValueCounts[V] == 1) {
2223         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2224                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2225       } else {
2226         // Blend in all instances of this value using a VSELECT, using a
2227         // mask where each bit signals whether that element is the one
2228         // we're after.
2229         SmallVector<SDValue> Ops;
2230         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2231           return DAG.getConstant(V == V1, DL, XLenVT);
2232         });
2233         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2234                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2235                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2236       }
2237     }
2238 
2239     return Vec;
2240   }
2241 
2242   return SDValue();
2243 }
2244 
2245 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2246                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2247   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2248     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2249     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2250     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2251     // node in order to try and match RVV vector/scalar instructions.
2252     if ((LoC >> 31) == HiC)
2253       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2254 
2255     // If vl is equal to VLMax and Hi constant is equal to Lo, we could use
2256     // vmv.v.x whose EEW = 32 to lower it.
2257     auto *Const = dyn_cast<ConstantSDNode>(VL);
2258     if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) {
2259       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2260       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2261       // access the subtarget here now.
2262       auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL);
2263       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2264     }
2265   }
2266 
2267   // Fall back to a stack store and stride x0 vector load.
2268   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2269 }
2270 
2271 // Called by type legalization to handle splat of i64 on RV32.
2272 // FIXME: We can optimize this when the type has sign or zero bits in one
2273 // of the halves.
2274 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2275                                    SDValue VL, SelectionDAG &DAG) {
2276   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2277   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2278                            DAG.getConstant(0, DL, MVT::i32));
2279   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2280                            DAG.getConstant(1, DL, MVT::i32));
2281   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2282 }
2283 
2284 // This function lowers a splat of a scalar operand Splat with the vector
2285 // length VL. It ensures the final sequence is type legal, which is useful when
2286 // lowering a splat after type legalization.
2287 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2288                                 SelectionDAG &DAG,
2289                                 const RISCVSubtarget &Subtarget) {
2290   if (VT.isFloatingPoint()) {
2291     // If VL is 1, we could use vfmv.s.f.
2292     if (isOneConstant(VL))
2293       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2294                          Scalar, VL);
2295     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2296   }
2297 
2298   MVT XLenVT = Subtarget.getXLenVT();
2299 
2300   // Simplest case is that the operand needs to be promoted to XLenVT.
2301   if (Scalar.getValueType().bitsLE(XLenVT)) {
2302     // If the operand is a constant, sign extend to increase our chances
2303     // of being able to use a .vi instruction. ANY_EXTEND would become a
2304     // a zero extend and the simm5 check in isel would fail.
2305     // FIXME: Should we ignore the upper bits in isel instead?
2306     unsigned ExtOpc =
2307         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2308     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2309     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2310     // If VL is 1 and the scalar value won't benefit from immediate, we could
2311     // use vmv.s.x.
2312     if (isOneConstant(VL) &&
2313         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2314       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2315                          VL);
2316     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2317   }
2318 
2319   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2320          "Unexpected scalar for splat lowering!");
2321 
2322   if (isOneConstant(VL) && isNullConstant(Scalar))
2323     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2324                        DAG.getConstant(0, DL, XLenVT), VL);
2325 
2326   // Otherwise use the more complicated splatting algorithm.
2327   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2328 }
2329 
2330 // Is the mask a slidedown that shifts in undefs.
2331 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2332   int Size = Mask.size();
2333 
2334   // Elements shifted in should be undef.
2335   auto CheckUndefs = [&](int Shift) {
2336     for (int i = Size - Shift; i != Size; ++i)
2337       if (Mask[i] >= 0)
2338         return false;
2339     return true;
2340   };
2341 
2342   // Elements should be shifted or undef.
2343   auto MatchShift = [&](int Shift) {
2344     for (int i = 0; i != Size - Shift; ++i)
2345        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2346          return false;
2347     return true;
2348   };
2349 
2350   // Try all possible shifts.
2351   for (int Shift = 1; Shift != Size; ++Shift)
2352     if (CheckUndefs(Shift) && MatchShift(Shift))
2353       return Shift;
2354 
2355   // No match.
2356   return -1;
2357 }
2358 
2359 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2360                                 const RISCVSubtarget &Subtarget) {
2361   // We need to be able to widen elements to the next larger integer type.
2362   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2363     return false;
2364 
2365   int Size = Mask.size();
2366   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2367 
2368   int Srcs[] = {-1, -1};
2369   for (int i = 0; i != Size; ++i) {
2370     // Ignore undef elements.
2371     if (Mask[i] < 0)
2372       continue;
2373 
2374     // Is this an even or odd element.
2375     int Pol = i % 2;
2376 
2377     // Ensure we consistently use the same source for this element polarity.
2378     int Src = Mask[i] / Size;
2379     if (Srcs[Pol] < 0)
2380       Srcs[Pol] = Src;
2381     if (Srcs[Pol] != Src)
2382       return false;
2383 
2384     // Make sure the element within the source is appropriate for this element
2385     // in the destination.
2386     int Elt = Mask[i] % Size;
2387     if (Elt != i / 2)
2388       return false;
2389   }
2390 
2391   // We need to find a source for each polarity and they can't be the same.
2392   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2393     return false;
2394 
2395   // Swap the sources if the second source was in the even polarity.
2396   SwapSources = Srcs[0] > Srcs[1];
2397 
2398   return true;
2399 }
2400 
2401 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2402                                    const RISCVSubtarget &Subtarget) {
2403   SDValue V1 = Op.getOperand(0);
2404   SDValue V2 = Op.getOperand(1);
2405   SDLoc DL(Op);
2406   MVT XLenVT = Subtarget.getXLenVT();
2407   MVT VT = Op.getSimpleValueType();
2408   unsigned NumElts = VT.getVectorNumElements();
2409   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2410 
2411   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2412 
2413   SDValue TrueMask, VL;
2414   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2415 
2416   if (SVN->isSplat()) {
2417     const int Lane = SVN->getSplatIndex();
2418     if (Lane >= 0) {
2419       MVT SVT = VT.getVectorElementType();
2420 
2421       // Turn splatted vector load into a strided load with an X0 stride.
2422       SDValue V = V1;
2423       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2424       // with undef.
2425       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2426       int Offset = Lane;
2427       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2428         int OpElements =
2429             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2430         V = V.getOperand(Offset / OpElements);
2431         Offset %= OpElements;
2432       }
2433 
2434       // We need to ensure the load isn't atomic or volatile.
2435       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2436         auto *Ld = cast<LoadSDNode>(V);
2437         Offset *= SVT.getStoreSize();
2438         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2439                                                    TypeSize::Fixed(Offset), DL);
2440 
2441         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2442         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2443           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2444           SDValue IntID =
2445               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2446           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2447                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2448           SDValue NewLoad = DAG.getMemIntrinsicNode(
2449               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2450               DAG.getMachineFunction().getMachineMemOperand(
2451                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2452           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2453           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2454         }
2455 
2456         // Otherwise use a scalar load and splat. This will give the best
2457         // opportunity to fold a splat into the operation. ISel can turn it into
2458         // the x0 strided load if we aren't able to fold away the select.
2459         if (SVT.isFloatingPoint())
2460           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2461                           Ld->getPointerInfo().getWithOffset(Offset),
2462                           Ld->getOriginalAlign(),
2463                           Ld->getMemOperand()->getFlags());
2464         else
2465           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2466                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2467                              Ld->getOriginalAlign(),
2468                              Ld->getMemOperand()->getFlags());
2469         DAG.makeEquivalentMemoryOrdering(Ld, V);
2470 
2471         unsigned Opc =
2472             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2473         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2474         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2475       }
2476 
2477       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2478       assert(Lane < (int)NumElts && "Unexpected lane!");
2479       SDValue Gather =
2480           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2481                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2482       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2483     }
2484   }
2485 
2486   ArrayRef<int> Mask = SVN->getMask();
2487 
2488   // Try to match as a slidedown.
2489   int SlideAmt = matchShuffleAsSlideDown(Mask);
2490   if (SlideAmt >= 0) {
2491     // TODO: Should we reduce the VL to account for the upper undef elements?
2492     // Requires additional vsetvlis, but might be faster to execute.
2493     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2494     SDValue SlideDown =
2495         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2496                     DAG.getUNDEF(ContainerVT), V1,
2497                     DAG.getConstant(SlideAmt, DL, XLenVT),
2498                     TrueMask, VL);
2499     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2500   }
2501 
2502   // Detect an interleave shuffle and lower to
2503   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2504   bool SwapSources;
2505   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2506     // Swap sources if needed.
2507     if (SwapSources)
2508       std::swap(V1, V2);
2509 
2510     // Extract the lower half of the vectors.
2511     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2512     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2513                      DAG.getConstant(0, DL, XLenVT));
2514     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2515                      DAG.getConstant(0, DL, XLenVT));
2516 
2517     // Double the element width and halve the number of elements in an int type.
2518     unsigned EltBits = VT.getScalarSizeInBits();
2519     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2520     MVT WideIntVT =
2521         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2522     // Convert this to a scalable vector. We need to base this on the
2523     // destination size to ensure there's always a type with a smaller LMUL.
2524     MVT WideIntContainerVT =
2525         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2526 
2527     // Convert sources to scalable vectors with the same element count as the
2528     // larger type.
2529     MVT HalfContainerVT = MVT::getVectorVT(
2530         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2531     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2532     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2533 
2534     // Cast sources to integer.
2535     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2536     MVT IntHalfVT =
2537         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2538     V1 = DAG.getBitcast(IntHalfVT, V1);
2539     V2 = DAG.getBitcast(IntHalfVT, V2);
2540 
2541     // Freeze V2 since we use it twice and we need to be sure that the add and
2542     // multiply see the same value.
2543     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2544 
2545     // Recreate TrueMask using the widened type's element count.
2546     MVT MaskVT =
2547         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2548     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2549 
2550     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2551     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2552                               V2, TrueMask, VL);
2553     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2554     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2555                                      DAG.getAllOnesConstant(DL, XLenVT));
2556     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2557                                    V2, Multiplier, TrueMask, VL);
2558     // Add the new copies to our previous addition giving us 2^eltbits copies of
2559     // V2. This is equivalent to shifting V2 left by eltbits. This should
2560     // combine with the vwmulu.vv above to form vwmaccu.vv.
2561     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2562                       TrueMask, VL);
2563     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2564     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2565     // vector VT.
2566     ContainerVT =
2567         MVT::getVectorVT(VT.getVectorElementType(),
2568                          WideIntContainerVT.getVectorElementCount() * 2);
2569     Add = DAG.getBitcast(ContainerVT, Add);
2570     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2571   }
2572 
2573   // Detect shuffles which can be re-expressed as vector selects; these are
2574   // shuffles in which each element in the destination is taken from an element
2575   // at the corresponding index in either source vectors.
2576   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2577     int MaskIndex = MaskIdx.value();
2578     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2579   });
2580 
2581   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2582 
2583   SmallVector<SDValue> MaskVals;
2584   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2585   // merged with a second vrgather.
2586   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2587 
2588   // By default we preserve the original operand order, and use a mask to
2589   // select LHS as true and RHS as false. However, since RVV vector selects may
2590   // feature splats but only on the LHS, we may choose to invert our mask and
2591   // instead select between RHS and LHS.
2592   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2593   bool InvertMask = IsSelect == SwapOps;
2594 
2595   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2596   // half.
2597   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2598 
2599   // Now construct the mask that will be used by the vselect or blended
2600   // vrgather operation. For vrgathers, construct the appropriate indices into
2601   // each vector.
2602   for (int MaskIndex : Mask) {
2603     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2604     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2605     if (!IsSelect) {
2606       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2607       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2608                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2609                                      : DAG.getUNDEF(XLenVT));
2610       GatherIndicesRHS.push_back(
2611           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2612                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2613       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2614         ++LHSIndexCounts[MaskIndex];
2615       if (!IsLHSOrUndefIndex)
2616         ++RHSIndexCounts[MaskIndex - NumElts];
2617     }
2618   }
2619 
2620   if (SwapOps) {
2621     std::swap(V1, V2);
2622     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2623   }
2624 
2625   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2626   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2627   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2628 
2629   if (IsSelect)
2630     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2631 
2632   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2633     // On such a large vector we're unable to use i8 as the index type.
2634     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2635     // may involve vector splitting if we're already at LMUL=8, or our
2636     // user-supplied maximum fixed-length LMUL.
2637     return SDValue();
2638   }
2639 
2640   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2641   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2642   MVT IndexVT = VT.changeTypeToInteger();
2643   // Since we can't introduce illegal index types at this stage, use i16 and
2644   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2645   // than XLenVT.
2646   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2647     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2648     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2649   }
2650 
2651   MVT IndexContainerVT =
2652       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2653 
2654   SDValue Gather;
2655   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2656   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2657   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2658     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2659   } else {
2660     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2661     // If only one index is used, we can use a "splat" vrgather.
2662     // TODO: We can splat the most-common index and fix-up any stragglers, if
2663     // that's beneficial.
2664     if (LHSIndexCounts.size() == 1) {
2665       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2666       Gather =
2667           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2668                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2669     } else {
2670       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2671       LHSIndices =
2672           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2673 
2674       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2675                            TrueMask, VL);
2676     }
2677   }
2678 
2679   // If a second vector operand is used by this shuffle, blend it in with an
2680   // additional vrgather.
2681   if (!V2.isUndef()) {
2682     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2683     // If only one index is used, we can use a "splat" vrgather.
2684     // TODO: We can splat the most-common index and fix-up any stragglers, if
2685     // that's beneficial.
2686     if (RHSIndexCounts.size() == 1) {
2687       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2688       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2689                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2690     } else {
2691       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2692       RHSIndices =
2693           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2694       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2695                        VL);
2696     }
2697 
2698     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2699     SelectMask =
2700         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2701 
2702     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2703                          Gather, VL);
2704   }
2705 
2706   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2707 }
2708 
2709 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2710                                      SDLoc DL, SelectionDAG &DAG,
2711                                      const RISCVSubtarget &Subtarget) {
2712   if (VT.isScalableVector())
2713     return DAG.getFPExtendOrRound(Op, DL, VT);
2714   assert(VT.isFixedLengthVector() &&
2715          "Unexpected value type for RVV FP extend/round lowering");
2716   SDValue Mask, VL;
2717   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2718   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2719                         ? RISCVISD::FP_EXTEND_VL
2720                         : RISCVISD::FP_ROUND_VL;
2721   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2722 }
2723 
2724 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2725 // the exponent.
2726 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2727   MVT VT = Op.getSimpleValueType();
2728   unsigned EltSize = VT.getScalarSizeInBits();
2729   SDValue Src = Op.getOperand(0);
2730   SDLoc DL(Op);
2731 
2732   // We need a FP type that can represent the value.
2733   // TODO: Use f16 for i8 when possible?
2734   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2735   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2736 
2737   // Legal types should have been checked in the RISCVTargetLowering
2738   // constructor.
2739   // TODO: Splitting may make sense in some cases.
2740   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2741          "Expected legal float type!");
2742 
2743   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2744   // The trailing zero count is equal to log2 of this single bit value.
2745   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2746     SDValue Neg =
2747         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2748     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2749   }
2750 
2751   // We have a legal FP type, convert to it.
2752   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2753   // Bitcast to integer and shift the exponent to the LSB.
2754   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2755   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2756   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2757   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2758                               DAG.getConstant(ShiftAmt, DL, IntVT));
2759   // Truncate back to original type to allow vnsrl.
2760   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2761   // The exponent contains log2 of the value in biased form.
2762   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2763 
2764   // For trailing zeros, we just need to subtract the bias.
2765   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2766     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2767                        DAG.getConstant(ExponentBias, DL, VT));
2768 
2769   // For leading zeros, we need to remove the bias and convert from log2 to
2770   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2771   unsigned Adjust = ExponentBias + (EltSize - 1);
2772   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2773 }
2774 
2775 // While RVV has alignment restrictions, we should always be able to load as a
2776 // legal equivalently-sized byte-typed vector instead. This method is
2777 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2778 // the load is already correctly-aligned, it returns SDValue().
2779 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2780                                                     SelectionDAG &DAG) const {
2781   auto *Load = cast<LoadSDNode>(Op);
2782   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2783 
2784   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2785                                      Load->getMemoryVT(),
2786                                      *Load->getMemOperand()))
2787     return SDValue();
2788 
2789   SDLoc DL(Op);
2790   MVT VT = Op.getSimpleValueType();
2791   unsigned EltSizeBits = VT.getScalarSizeInBits();
2792   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2793          "Unexpected unaligned RVV load type");
2794   MVT NewVT =
2795       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2796   assert(NewVT.isValid() &&
2797          "Expecting equally-sized RVV vector types to be legal");
2798   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2799                           Load->getPointerInfo(), Load->getOriginalAlign(),
2800                           Load->getMemOperand()->getFlags());
2801   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2802 }
2803 
2804 // While RVV has alignment restrictions, we should always be able to store as a
2805 // legal equivalently-sized byte-typed vector instead. This method is
2806 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2807 // returns SDValue() if the store is already correctly aligned.
2808 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2809                                                      SelectionDAG &DAG) const {
2810   auto *Store = cast<StoreSDNode>(Op);
2811   assert(Store && Store->getValue().getValueType().isVector() &&
2812          "Expected vector store");
2813 
2814   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2815                                      Store->getMemoryVT(),
2816                                      *Store->getMemOperand()))
2817     return SDValue();
2818 
2819   SDLoc DL(Op);
2820   SDValue StoredVal = Store->getValue();
2821   MVT VT = StoredVal.getSimpleValueType();
2822   unsigned EltSizeBits = VT.getScalarSizeInBits();
2823   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2824          "Unexpected unaligned RVV store type");
2825   MVT NewVT =
2826       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2827   assert(NewVT.isValid() &&
2828          "Expecting equally-sized RVV vector types to be legal");
2829   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2830   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2831                       Store->getPointerInfo(), Store->getOriginalAlign(),
2832                       Store->getMemOperand()->getFlags());
2833 }
2834 
2835 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2836                                             SelectionDAG &DAG) const {
2837   switch (Op.getOpcode()) {
2838   default:
2839     report_fatal_error("unimplemented operand");
2840   case ISD::GlobalAddress:
2841     return lowerGlobalAddress(Op, DAG);
2842   case ISD::BlockAddress:
2843     return lowerBlockAddress(Op, DAG);
2844   case ISD::ConstantPool:
2845     return lowerConstantPool(Op, DAG);
2846   case ISD::JumpTable:
2847     return lowerJumpTable(Op, DAG);
2848   case ISD::GlobalTLSAddress:
2849     return lowerGlobalTLSAddress(Op, DAG);
2850   case ISD::SELECT:
2851     return lowerSELECT(Op, DAG);
2852   case ISD::BRCOND:
2853     return lowerBRCOND(Op, DAG);
2854   case ISD::VASTART:
2855     return lowerVASTART(Op, DAG);
2856   case ISD::FRAMEADDR:
2857     return lowerFRAMEADDR(Op, DAG);
2858   case ISD::RETURNADDR:
2859     return lowerRETURNADDR(Op, DAG);
2860   case ISD::SHL_PARTS:
2861     return lowerShiftLeftParts(Op, DAG);
2862   case ISD::SRA_PARTS:
2863     return lowerShiftRightParts(Op, DAG, true);
2864   case ISD::SRL_PARTS:
2865     return lowerShiftRightParts(Op, DAG, false);
2866   case ISD::BITCAST: {
2867     SDLoc DL(Op);
2868     EVT VT = Op.getValueType();
2869     SDValue Op0 = Op.getOperand(0);
2870     EVT Op0VT = Op0.getValueType();
2871     MVT XLenVT = Subtarget.getXLenVT();
2872     if (VT.isFixedLengthVector()) {
2873       // We can handle fixed length vector bitcasts with a simple replacement
2874       // in isel.
2875       if (Op0VT.isFixedLengthVector())
2876         return Op;
2877       // When bitcasting from scalar to fixed-length vector, insert the scalar
2878       // into a one-element vector of the result type, and perform a vector
2879       // bitcast.
2880       if (!Op0VT.isVector()) {
2881         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2882         if (!isTypeLegal(BVT))
2883           return SDValue();
2884         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2885                                               DAG.getUNDEF(BVT), Op0,
2886                                               DAG.getConstant(0, DL, XLenVT)));
2887       }
2888       return SDValue();
2889     }
2890     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2891     // thus: bitcast the vector to a one-element vector type whose element type
2892     // is the same as the result type, and extract the first element.
2893     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2894       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2895       if (!isTypeLegal(BVT))
2896         return SDValue();
2897       SDValue BVec = DAG.getBitcast(BVT, Op0);
2898       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2899                          DAG.getConstant(0, DL, XLenVT));
2900     }
2901     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2902       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2903       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2904       return FPConv;
2905     }
2906     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2907         Subtarget.hasStdExtF()) {
2908       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2909       SDValue FPConv =
2910           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2911       return FPConv;
2912     }
2913     return SDValue();
2914   }
2915   case ISD::INTRINSIC_WO_CHAIN:
2916     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2917   case ISD::INTRINSIC_W_CHAIN:
2918     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2919   case ISD::INTRINSIC_VOID:
2920     return LowerINTRINSIC_VOID(Op, DAG);
2921   case ISD::BSWAP:
2922   case ISD::BITREVERSE: {
2923     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2924     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2925     MVT VT = Op.getSimpleValueType();
2926     SDLoc DL(Op);
2927     // Start with the maximum immediate value which is the bitwidth - 1.
2928     unsigned Imm = VT.getSizeInBits() - 1;
2929     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2930     if (Op.getOpcode() == ISD::BSWAP)
2931       Imm &= ~0x7U;
2932     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2933                        DAG.getConstant(Imm, DL, VT));
2934   }
2935   case ISD::FSHL:
2936   case ISD::FSHR: {
2937     MVT VT = Op.getSimpleValueType();
2938     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2939     SDLoc DL(Op);
2940     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2941     // use log(XLen) bits. Mask the shift amount accordingly to prevent
2942     // accidentally setting the extra bit.
2943     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2944     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2945                                 DAG.getConstant(ShAmtWidth, DL, VT));
2946     // fshl and fshr concatenate their operands in the same order. fsr and fsl
2947     // instruction use different orders. fshl will return its first operand for
2948     // shift of zero, fshr will return its second operand. fsl and fsr both
2949     // return rs1 so the ISD nodes need to have different operand orders.
2950     // Shift amount is in rs2.
2951     SDValue Op0 = Op.getOperand(0);
2952     SDValue Op1 = Op.getOperand(1);
2953     unsigned Opc = RISCVISD::FSL;
2954     if (Op.getOpcode() == ISD::FSHR) {
2955       std::swap(Op0, Op1);
2956       Opc = RISCVISD::FSR;
2957     }
2958     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
2959   }
2960   case ISD::TRUNCATE: {
2961     SDLoc DL(Op);
2962     MVT VT = Op.getSimpleValueType();
2963     // Only custom-lower vector truncates
2964     if (!VT.isVector())
2965       return Op;
2966 
2967     // Truncates to mask types are handled differently
2968     if (VT.getVectorElementType() == MVT::i1)
2969       return lowerVectorMaskTrunc(Op, DAG);
2970 
2971     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2972     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2973     // truncate by one power of two at a time.
2974     MVT DstEltVT = VT.getVectorElementType();
2975 
2976     SDValue Src = Op.getOperand(0);
2977     MVT SrcVT = Src.getSimpleValueType();
2978     MVT SrcEltVT = SrcVT.getVectorElementType();
2979 
2980     assert(DstEltVT.bitsLT(SrcEltVT) &&
2981            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2982            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2983            "Unexpected vector truncate lowering");
2984 
2985     MVT ContainerVT = SrcVT;
2986     if (SrcVT.isFixedLengthVector()) {
2987       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2988       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2989     }
2990 
2991     SDValue Result = Src;
2992     SDValue Mask, VL;
2993     std::tie(Mask, VL) =
2994         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2995     LLVMContext &Context = *DAG.getContext();
2996     const ElementCount Count = ContainerVT.getVectorElementCount();
2997     do {
2998       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2999       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3000       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3001                            Mask, VL);
3002     } while (SrcEltVT != DstEltVT);
3003 
3004     if (SrcVT.isFixedLengthVector())
3005       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3006 
3007     return Result;
3008   }
3009   case ISD::ANY_EXTEND:
3010   case ISD::ZERO_EXTEND:
3011     if (Op.getOperand(0).getValueType().isVector() &&
3012         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3013       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3014     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3015   case ISD::SIGN_EXTEND:
3016     if (Op.getOperand(0).getValueType().isVector() &&
3017         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3018       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3019     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3020   case ISD::SPLAT_VECTOR_PARTS:
3021     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3022   case ISD::INSERT_VECTOR_ELT:
3023     return lowerINSERT_VECTOR_ELT(Op, DAG);
3024   case ISD::EXTRACT_VECTOR_ELT:
3025     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3026   case ISD::VSCALE: {
3027     MVT VT = Op.getSimpleValueType();
3028     SDLoc DL(Op);
3029     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3030     // We define our scalable vector types for lmul=1 to use a 64 bit known
3031     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3032     // vscale as VLENB / 8.
3033     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3034     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3035       // We assume VLENB is a multiple of 8. We manually choose the best shift
3036       // here because SimplifyDemandedBits isn't always able to simplify it.
3037       uint64_t Val = Op.getConstantOperandVal(0);
3038       if (isPowerOf2_64(Val)) {
3039         uint64_t Log2 = Log2_64(Val);
3040         if (Log2 < 3)
3041           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3042                              DAG.getConstant(3 - Log2, DL, VT));
3043         if (Log2 > 3)
3044           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3045                              DAG.getConstant(Log2 - 3, DL, VT));
3046         return VLENB;
3047       }
3048       // If the multiplier is a multiple of 8, scale it down to avoid needing
3049       // to shift the VLENB value.
3050       if ((Val % 8) == 0)
3051         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3052                            DAG.getConstant(Val / 8, DL, VT));
3053     }
3054 
3055     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3056                                  DAG.getConstant(3, DL, VT));
3057     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3058   }
3059   case ISD::FPOWI: {
3060     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3061     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3062     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3063         Op.getOperand(1).getValueType() == MVT::i32) {
3064       SDLoc DL(Op);
3065       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3066       SDValue Powi =
3067           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3068       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3069                          DAG.getIntPtrConstant(0, DL));
3070     }
3071     return SDValue();
3072   }
3073   case ISD::FP_EXTEND: {
3074     // RVV can only do fp_extend to types double the size as the source. We
3075     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3076     // via f32.
3077     SDLoc DL(Op);
3078     MVT VT = Op.getSimpleValueType();
3079     SDValue Src = Op.getOperand(0);
3080     MVT SrcVT = Src.getSimpleValueType();
3081 
3082     // Prepare any fixed-length vector operands.
3083     MVT ContainerVT = VT;
3084     if (SrcVT.isFixedLengthVector()) {
3085       ContainerVT = getContainerForFixedLengthVector(VT);
3086       MVT SrcContainerVT =
3087           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3088       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3089     }
3090 
3091     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3092         SrcVT.getVectorElementType() != MVT::f16) {
3093       // For scalable vectors, we only need to close the gap between
3094       // vXf16->vXf64.
3095       if (!VT.isFixedLengthVector())
3096         return Op;
3097       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3098       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3099       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3100     }
3101 
3102     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3103     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3104     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3105         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3106 
3107     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3108                                            DL, DAG, Subtarget);
3109     if (VT.isFixedLengthVector())
3110       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3111     return Extend;
3112   }
3113   case ISD::FP_ROUND: {
3114     // RVV can only do fp_round to types half the size as the source. We
3115     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3116     // conversion instruction.
3117     SDLoc DL(Op);
3118     MVT VT = Op.getSimpleValueType();
3119     SDValue Src = Op.getOperand(0);
3120     MVT SrcVT = Src.getSimpleValueType();
3121 
3122     // Prepare any fixed-length vector operands.
3123     MVT ContainerVT = VT;
3124     if (VT.isFixedLengthVector()) {
3125       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3126       ContainerVT =
3127           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3128       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3129     }
3130 
3131     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3132         SrcVT.getVectorElementType() != MVT::f64) {
3133       // For scalable vectors, we only need to close the gap between
3134       // vXf64<->vXf16.
3135       if (!VT.isFixedLengthVector())
3136         return Op;
3137       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3138       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3139       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3140     }
3141 
3142     SDValue Mask, VL;
3143     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3144 
3145     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3146     SDValue IntermediateRound =
3147         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3148     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3149                                           DL, DAG, Subtarget);
3150 
3151     if (VT.isFixedLengthVector())
3152       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3153     return Round;
3154   }
3155   case ISD::FP_TO_SINT:
3156   case ISD::FP_TO_UINT:
3157   case ISD::SINT_TO_FP:
3158   case ISD::UINT_TO_FP: {
3159     // RVV can only do fp<->int conversions to types half/double the size as
3160     // the source. We custom-lower any conversions that do two hops into
3161     // sequences.
3162     MVT VT = Op.getSimpleValueType();
3163     if (!VT.isVector())
3164       return Op;
3165     SDLoc DL(Op);
3166     SDValue Src = Op.getOperand(0);
3167     MVT EltVT = VT.getVectorElementType();
3168     MVT SrcVT = Src.getSimpleValueType();
3169     MVT SrcEltVT = SrcVT.getVectorElementType();
3170     unsigned EltSize = EltVT.getSizeInBits();
3171     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3172     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3173            "Unexpected vector element types");
3174 
3175     bool IsInt2FP = SrcEltVT.isInteger();
3176     // Widening conversions
3177     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3178       if (IsInt2FP) {
3179         // Do a regular integer sign/zero extension then convert to float.
3180         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3181                                       VT.getVectorElementCount());
3182         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3183                                  ? ISD::ZERO_EXTEND
3184                                  : ISD::SIGN_EXTEND;
3185         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3186         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3187       }
3188       // FP2Int
3189       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3190       // Do one doubling fp_extend then complete the operation by converting
3191       // to int.
3192       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3193       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3194       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3195     }
3196 
3197     // Narrowing conversions
3198     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3199       if (IsInt2FP) {
3200         // One narrowing int_to_fp, then an fp_round.
3201         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3202         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3203         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3204         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3205       }
3206       // FP2Int
3207       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3208       // representable by the integer, the result is poison.
3209       MVT IVecVT =
3210           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3211                            VT.getVectorElementCount());
3212       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3213       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3214     }
3215 
3216     // Scalable vectors can exit here. Patterns will handle equally-sized
3217     // conversions halving/doubling ones.
3218     if (!VT.isFixedLengthVector())
3219       return Op;
3220 
3221     // For fixed-length vectors we lower to a custom "VL" node.
3222     unsigned RVVOpc = 0;
3223     switch (Op.getOpcode()) {
3224     default:
3225       llvm_unreachable("Impossible opcode");
3226     case ISD::FP_TO_SINT:
3227       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3228       break;
3229     case ISD::FP_TO_UINT:
3230       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3231       break;
3232     case ISD::SINT_TO_FP:
3233       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3234       break;
3235     case ISD::UINT_TO_FP:
3236       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3237       break;
3238     }
3239 
3240     MVT ContainerVT, SrcContainerVT;
3241     // Derive the reference container type from the larger vector type.
3242     if (SrcEltSize > EltSize) {
3243       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3244       ContainerVT =
3245           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3246     } else {
3247       ContainerVT = getContainerForFixedLengthVector(VT);
3248       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3249     }
3250 
3251     SDValue Mask, VL;
3252     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3253 
3254     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3255     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3256     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3257   }
3258   case ISD::FP_TO_SINT_SAT:
3259   case ISD::FP_TO_UINT_SAT:
3260     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3261   case ISD::FTRUNC:
3262   case ISD::FCEIL:
3263   case ISD::FFLOOR:
3264     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3265   case ISD::VECREDUCE_ADD:
3266   case ISD::VECREDUCE_UMAX:
3267   case ISD::VECREDUCE_SMAX:
3268   case ISD::VECREDUCE_UMIN:
3269   case ISD::VECREDUCE_SMIN:
3270     return lowerVECREDUCE(Op, DAG);
3271   case ISD::VECREDUCE_AND:
3272   case ISD::VECREDUCE_OR:
3273   case ISD::VECREDUCE_XOR:
3274     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3275       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3276     return lowerVECREDUCE(Op, DAG);
3277   case ISD::VECREDUCE_FADD:
3278   case ISD::VECREDUCE_SEQ_FADD:
3279   case ISD::VECREDUCE_FMIN:
3280   case ISD::VECREDUCE_FMAX:
3281     return lowerFPVECREDUCE(Op, DAG);
3282   case ISD::VP_REDUCE_ADD:
3283   case ISD::VP_REDUCE_UMAX:
3284   case ISD::VP_REDUCE_SMAX:
3285   case ISD::VP_REDUCE_UMIN:
3286   case ISD::VP_REDUCE_SMIN:
3287   case ISD::VP_REDUCE_FADD:
3288   case ISD::VP_REDUCE_SEQ_FADD:
3289   case ISD::VP_REDUCE_FMIN:
3290   case ISD::VP_REDUCE_FMAX:
3291     return lowerVPREDUCE(Op, DAG);
3292   case ISD::VP_REDUCE_AND:
3293   case ISD::VP_REDUCE_OR:
3294   case ISD::VP_REDUCE_XOR:
3295     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3296       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3297     return lowerVPREDUCE(Op, DAG);
3298   case ISD::INSERT_SUBVECTOR:
3299     return lowerINSERT_SUBVECTOR(Op, DAG);
3300   case ISD::EXTRACT_SUBVECTOR:
3301     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3302   case ISD::STEP_VECTOR:
3303     return lowerSTEP_VECTOR(Op, DAG);
3304   case ISD::VECTOR_REVERSE:
3305     return lowerVECTOR_REVERSE(Op, DAG);
3306   case ISD::BUILD_VECTOR:
3307     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3308   case ISD::SPLAT_VECTOR:
3309     if (Op.getValueType().getVectorElementType() == MVT::i1)
3310       return lowerVectorMaskSplat(Op, DAG);
3311     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3312   case ISD::VECTOR_SHUFFLE:
3313     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3314   case ISD::CONCAT_VECTORS: {
3315     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3316     // better than going through the stack, as the default expansion does.
3317     SDLoc DL(Op);
3318     MVT VT = Op.getSimpleValueType();
3319     unsigned NumOpElts =
3320         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3321     SDValue Vec = DAG.getUNDEF(VT);
3322     for (const auto &OpIdx : enumerate(Op->ops())) {
3323       SDValue SubVec = OpIdx.value();
3324       // Don't insert undef subvectors.
3325       if (SubVec.isUndef())
3326         continue;
3327       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3328                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3329     }
3330     return Vec;
3331   }
3332   case ISD::LOAD:
3333     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3334       return V;
3335     if (Op.getValueType().isFixedLengthVector())
3336       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3337     return Op;
3338   case ISD::STORE:
3339     if (auto V = expandUnalignedRVVStore(Op, DAG))
3340       return V;
3341     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3342       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3343     return Op;
3344   case ISD::MLOAD:
3345   case ISD::VP_LOAD:
3346     return lowerMaskedLoad(Op, DAG);
3347   case ISD::MSTORE:
3348   case ISD::VP_STORE:
3349     return lowerMaskedStore(Op, DAG);
3350   case ISD::SETCC:
3351     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3352   case ISD::ADD:
3353     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3354   case ISD::SUB:
3355     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3356   case ISD::MUL:
3357     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3358   case ISD::MULHS:
3359     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3360   case ISD::MULHU:
3361     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3362   case ISD::AND:
3363     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3364                                               RISCVISD::AND_VL);
3365   case ISD::OR:
3366     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3367                                               RISCVISD::OR_VL);
3368   case ISD::XOR:
3369     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3370                                               RISCVISD::XOR_VL);
3371   case ISD::SDIV:
3372     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3373   case ISD::SREM:
3374     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3375   case ISD::UDIV:
3376     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3377   case ISD::UREM:
3378     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3379   case ISD::SHL:
3380   case ISD::SRA:
3381   case ISD::SRL:
3382     if (Op.getSimpleValueType().isFixedLengthVector())
3383       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3384     // This can be called for an i32 shift amount that needs to be promoted.
3385     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3386            "Unexpected custom legalisation");
3387     return SDValue();
3388   case ISD::SADDSAT:
3389     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3390   case ISD::UADDSAT:
3391     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3392   case ISD::SSUBSAT:
3393     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3394   case ISD::USUBSAT:
3395     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3396   case ISD::FADD:
3397     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3398   case ISD::FSUB:
3399     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3400   case ISD::FMUL:
3401     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3402   case ISD::FDIV:
3403     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3404   case ISD::FNEG:
3405     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3406   case ISD::FABS:
3407     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3408   case ISD::FSQRT:
3409     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3410   case ISD::FMA:
3411     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3412   case ISD::SMIN:
3413     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3414   case ISD::SMAX:
3415     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3416   case ISD::UMIN:
3417     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3418   case ISD::UMAX:
3419     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3420   case ISD::FMINNUM:
3421     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3422   case ISD::FMAXNUM:
3423     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3424   case ISD::ABS:
3425     return lowerABS(Op, DAG);
3426   case ISD::CTLZ_ZERO_UNDEF:
3427   case ISD::CTTZ_ZERO_UNDEF:
3428     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3429   case ISD::VSELECT:
3430     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3431   case ISD::FCOPYSIGN:
3432     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3433   case ISD::MGATHER:
3434   case ISD::VP_GATHER:
3435     return lowerMaskedGather(Op, DAG);
3436   case ISD::MSCATTER:
3437   case ISD::VP_SCATTER:
3438     return lowerMaskedScatter(Op, DAG);
3439   case ISD::FLT_ROUNDS_:
3440     return lowerGET_ROUNDING(Op, DAG);
3441   case ISD::SET_ROUNDING:
3442     return lowerSET_ROUNDING(Op, DAG);
3443   case ISD::VP_SELECT:
3444     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3445   case ISD::VP_MERGE:
3446     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3447   case ISD::VP_ADD:
3448     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3449   case ISD::VP_SUB:
3450     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3451   case ISD::VP_MUL:
3452     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3453   case ISD::VP_SDIV:
3454     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3455   case ISD::VP_UDIV:
3456     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3457   case ISD::VP_SREM:
3458     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3459   case ISD::VP_UREM:
3460     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3461   case ISD::VP_AND:
3462     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3463   case ISD::VP_OR:
3464     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3465   case ISD::VP_XOR:
3466     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3467   case ISD::VP_ASHR:
3468     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3469   case ISD::VP_LSHR:
3470     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3471   case ISD::VP_SHL:
3472     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3473   case ISD::VP_FADD:
3474     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3475   case ISD::VP_FSUB:
3476     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3477   case ISD::VP_FMUL:
3478     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3479   case ISD::VP_FDIV:
3480     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3481   }
3482 }
3483 
3484 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3485                              SelectionDAG &DAG, unsigned Flags) {
3486   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3487 }
3488 
3489 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3490                              SelectionDAG &DAG, unsigned Flags) {
3491   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3492                                    Flags);
3493 }
3494 
3495 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3496                              SelectionDAG &DAG, unsigned Flags) {
3497   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3498                                    N->getOffset(), Flags);
3499 }
3500 
3501 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3502                              SelectionDAG &DAG, unsigned Flags) {
3503   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3504 }
3505 
3506 template <class NodeTy>
3507 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3508                                      bool IsLocal) const {
3509   SDLoc DL(N);
3510   EVT Ty = getPointerTy(DAG.getDataLayout());
3511 
3512   if (isPositionIndependent()) {
3513     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3514     if (IsLocal)
3515       // Use PC-relative addressing to access the symbol. This generates the
3516       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3517       // %pcrel_lo(auipc)).
3518       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3519 
3520     // Use PC-relative addressing to access the GOT for this symbol, then load
3521     // the address from the GOT. This generates the pattern (PseudoLA sym),
3522     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3523     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3524   }
3525 
3526   switch (getTargetMachine().getCodeModel()) {
3527   default:
3528     report_fatal_error("Unsupported code model for lowering");
3529   case CodeModel::Small: {
3530     // Generate a sequence for accessing addresses within the first 2 GiB of
3531     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3532     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3533     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3534     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3535     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3536   }
3537   case CodeModel::Medium: {
3538     // Generate a sequence for accessing addresses within any 2GiB range within
3539     // the address space. This generates the pattern (PseudoLLA sym), which
3540     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3541     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3542     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3543   }
3544   }
3545 }
3546 
3547 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3548                                                 SelectionDAG &DAG) const {
3549   SDLoc DL(Op);
3550   EVT Ty = Op.getValueType();
3551   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3552   int64_t Offset = N->getOffset();
3553   MVT XLenVT = Subtarget.getXLenVT();
3554 
3555   const GlobalValue *GV = N->getGlobal();
3556   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3557   SDValue Addr = getAddr(N, DAG, IsLocal);
3558 
3559   // In order to maximise the opportunity for common subexpression elimination,
3560   // emit a separate ADD node for the global address offset instead of folding
3561   // it in the global address node. Later peephole optimisations may choose to
3562   // fold it back in when profitable.
3563   if (Offset != 0)
3564     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3565                        DAG.getConstant(Offset, DL, XLenVT));
3566   return Addr;
3567 }
3568 
3569 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3570                                                SelectionDAG &DAG) const {
3571   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3572 
3573   return getAddr(N, DAG);
3574 }
3575 
3576 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3577                                                SelectionDAG &DAG) const {
3578   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3579 
3580   return getAddr(N, DAG);
3581 }
3582 
3583 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3584                                             SelectionDAG &DAG) const {
3585   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3586 
3587   return getAddr(N, DAG);
3588 }
3589 
3590 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3591                                               SelectionDAG &DAG,
3592                                               bool UseGOT) const {
3593   SDLoc DL(N);
3594   EVT Ty = getPointerTy(DAG.getDataLayout());
3595   const GlobalValue *GV = N->getGlobal();
3596   MVT XLenVT = Subtarget.getXLenVT();
3597 
3598   if (UseGOT) {
3599     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3600     // load the address from the GOT and add the thread pointer. This generates
3601     // the pattern (PseudoLA_TLS_IE sym), which expands to
3602     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3603     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3604     SDValue Load =
3605         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3606 
3607     // Add the thread pointer.
3608     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3609     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3610   }
3611 
3612   // Generate a sequence for accessing the address relative to the thread
3613   // pointer, with the appropriate adjustment for the thread pointer offset.
3614   // This generates the pattern
3615   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3616   SDValue AddrHi =
3617       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3618   SDValue AddrAdd =
3619       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3620   SDValue AddrLo =
3621       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3622 
3623   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3624   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3625   SDValue MNAdd = SDValue(
3626       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3627       0);
3628   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3629 }
3630 
3631 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3632                                                SelectionDAG &DAG) const {
3633   SDLoc DL(N);
3634   EVT Ty = getPointerTy(DAG.getDataLayout());
3635   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3636   const GlobalValue *GV = N->getGlobal();
3637 
3638   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3639   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3640   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3641   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3642   SDValue Load =
3643       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3644 
3645   // Prepare argument list to generate call.
3646   ArgListTy Args;
3647   ArgListEntry Entry;
3648   Entry.Node = Load;
3649   Entry.Ty = CallTy;
3650   Args.push_back(Entry);
3651 
3652   // Setup call to __tls_get_addr.
3653   TargetLowering::CallLoweringInfo CLI(DAG);
3654   CLI.setDebugLoc(DL)
3655       .setChain(DAG.getEntryNode())
3656       .setLibCallee(CallingConv::C, CallTy,
3657                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3658                     std::move(Args));
3659 
3660   return LowerCallTo(CLI).first;
3661 }
3662 
3663 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3664                                                    SelectionDAG &DAG) const {
3665   SDLoc DL(Op);
3666   EVT Ty = Op.getValueType();
3667   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3668   int64_t Offset = N->getOffset();
3669   MVT XLenVT = Subtarget.getXLenVT();
3670 
3671   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3672 
3673   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3674       CallingConv::GHC)
3675     report_fatal_error("In GHC calling convention TLS is not supported");
3676 
3677   SDValue Addr;
3678   switch (Model) {
3679   case TLSModel::LocalExec:
3680     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3681     break;
3682   case TLSModel::InitialExec:
3683     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3684     break;
3685   case TLSModel::LocalDynamic:
3686   case TLSModel::GeneralDynamic:
3687     Addr = getDynamicTLSAddr(N, DAG);
3688     break;
3689   }
3690 
3691   // In order to maximise the opportunity for common subexpression elimination,
3692   // emit a separate ADD node for the global address offset instead of folding
3693   // it in the global address node. Later peephole optimisations may choose to
3694   // fold it back in when profitable.
3695   if (Offset != 0)
3696     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3697                        DAG.getConstant(Offset, DL, XLenVT));
3698   return Addr;
3699 }
3700 
3701 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3702   SDValue CondV = Op.getOperand(0);
3703   SDValue TrueV = Op.getOperand(1);
3704   SDValue FalseV = Op.getOperand(2);
3705   SDLoc DL(Op);
3706   MVT VT = Op.getSimpleValueType();
3707   MVT XLenVT = Subtarget.getXLenVT();
3708 
3709   // Lower vector SELECTs to VSELECTs by splatting the condition.
3710   if (VT.isVector()) {
3711     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3712     SDValue CondSplat = VT.isScalableVector()
3713                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3714                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3715     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3716   }
3717 
3718   // If the result type is XLenVT and CondV is the output of a SETCC node
3719   // which also operated on XLenVT inputs, then merge the SETCC node into the
3720   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3721   // compare+branch instructions. i.e.:
3722   // (select (setcc lhs, rhs, cc), truev, falsev)
3723   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3724   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3725       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3726     SDValue LHS = CondV.getOperand(0);
3727     SDValue RHS = CondV.getOperand(1);
3728     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3729     ISD::CondCode CCVal = CC->get();
3730 
3731     // Special case for a select of 2 constants that have a diffence of 1.
3732     // Normally this is done by DAGCombine, but if the select is introduced by
3733     // type legalization or op legalization, we miss it. Restricting to SETLT
3734     // case for now because that is what signed saturating add/sub need.
3735     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3736     // but we would probably want to swap the true/false values if the condition
3737     // is SETGE/SETLE to avoid an XORI.
3738     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3739         CCVal == ISD::SETLT) {
3740       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3741       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3742       if (TrueVal - 1 == FalseVal)
3743         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3744       if (TrueVal + 1 == FalseVal)
3745         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3746     }
3747 
3748     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3749 
3750     SDValue TargetCC = DAG.getCondCode(CCVal);
3751     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3752     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3753   }
3754 
3755   // Otherwise:
3756   // (select condv, truev, falsev)
3757   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3758   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3759   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3760 
3761   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3762 
3763   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3764 }
3765 
3766 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3767   SDValue CondV = Op.getOperand(1);
3768   SDLoc DL(Op);
3769   MVT XLenVT = Subtarget.getXLenVT();
3770 
3771   if (CondV.getOpcode() == ISD::SETCC &&
3772       CondV.getOperand(0).getValueType() == XLenVT) {
3773     SDValue LHS = CondV.getOperand(0);
3774     SDValue RHS = CondV.getOperand(1);
3775     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3776 
3777     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3778 
3779     SDValue TargetCC = DAG.getCondCode(CCVal);
3780     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3781                        LHS, RHS, TargetCC, Op.getOperand(2));
3782   }
3783 
3784   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3785                      CondV, DAG.getConstant(0, DL, XLenVT),
3786                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3787 }
3788 
3789 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3790   MachineFunction &MF = DAG.getMachineFunction();
3791   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3792 
3793   SDLoc DL(Op);
3794   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3795                                  getPointerTy(MF.getDataLayout()));
3796 
3797   // vastart just stores the address of the VarArgsFrameIndex slot into the
3798   // memory location argument.
3799   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3800   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3801                       MachinePointerInfo(SV));
3802 }
3803 
3804 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3805                                             SelectionDAG &DAG) const {
3806   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3807   MachineFunction &MF = DAG.getMachineFunction();
3808   MachineFrameInfo &MFI = MF.getFrameInfo();
3809   MFI.setFrameAddressIsTaken(true);
3810   Register FrameReg = RI.getFrameRegister(MF);
3811   int XLenInBytes = Subtarget.getXLen() / 8;
3812 
3813   EVT VT = Op.getValueType();
3814   SDLoc DL(Op);
3815   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3816   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3817   while (Depth--) {
3818     int Offset = -(XLenInBytes * 2);
3819     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3820                               DAG.getIntPtrConstant(Offset, DL));
3821     FrameAddr =
3822         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3823   }
3824   return FrameAddr;
3825 }
3826 
3827 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3828                                              SelectionDAG &DAG) const {
3829   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3830   MachineFunction &MF = DAG.getMachineFunction();
3831   MachineFrameInfo &MFI = MF.getFrameInfo();
3832   MFI.setReturnAddressIsTaken(true);
3833   MVT XLenVT = Subtarget.getXLenVT();
3834   int XLenInBytes = Subtarget.getXLen() / 8;
3835 
3836   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3837     return SDValue();
3838 
3839   EVT VT = Op.getValueType();
3840   SDLoc DL(Op);
3841   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3842   if (Depth) {
3843     int Off = -XLenInBytes;
3844     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3845     SDValue Offset = DAG.getConstant(Off, DL, VT);
3846     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3847                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3848                        MachinePointerInfo());
3849   }
3850 
3851   // Return the value of the return address register, marking it an implicit
3852   // live-in.
3853   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3854   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3855 }
3856 
3857 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3858                                                  SelectionDAG &DAG) const {
3859   SDLoc DL(Op);
3860   SDValue Lo = Op.getOperand(0);
3861   SDValue Hi = Op.getOperand(1);
3862   SDValue Shamt = Op.getOperand(2);
3863   EVT VT = Lo.getValueType();
3864 
3865   // if Shamt-XLEN < 0: // Shamt < XLEN
3866   //   Lo = Lo << Shamt
3867   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3868   // else:
3869   //   Lo = 0
3870   //   Hi = Lo << (Shamt-XLEN)
3871 
3872   SDValue Zero = DAG.getConstant(0, DL, VT);
3873   SDValue One = DAG.getConstant(1, DL, VT);
3874   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3875   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3876   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3877   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3878 
3879   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3880   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3881   SDValue ShiftRightLo =
3882       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3883   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3884   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3885   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3886 
3887   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3888 
3889   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3890   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3891 
3892   SDValue Parts[2] = {Lo, Hi};
3893   return DAG.getMergeValues(Parts, DL);
3894 }
3895 
3896 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3897                                                   bool IsSRA) const {
3898   SDLoc DL(Op);
3899   SDValue Lo = Op.getOperand(0);
3900   SDValue Hi = Op.getOperand(1);
3901   SDValue Shamt = Op.getOperand(2);
3902   EVT VT = Lo.getValueType();
3903 
3904   // SRA expansion:
3905   //   if Shamt-XLEN < 0: // Shamt < XLEN
3906   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3907   //     Hi = Hi >>s Shamt
3908   //   else:
3909   //     Lo = Hi >>s (Shamt-XLEN);
3910   //     Hi = Hi >>s (XLEN-1)
3911   //
3912   // SRL expansion:
3913   //   if Shamt-XLEN < 0: // Shamt < XLEN
3914   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3915   //     Hi = Hi >>u Shamt
3916   //   else:
3917   //     Lo = Hi >>u (Shamt-XLEN);
3918   //     Hi = 0;
3919 
3920   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3921 
3922   SDValue Zero = DAG.getConstant(0, DL, VT);
3923   SDValue One = DAG.getConstant(1, DL, VT);
3924   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3925   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3926   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3927   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3928 
3929   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3930   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3931   SDValue ShiftLeftHi =
3932       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3933   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3934   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3935   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3936   SDValue HiFalse =
3937       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3938 
3939   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3940 
3941   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3942   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3943 
3944   SDValue Parts[2] = {Lo, Hi};
3945   return DAG.getMergeValues(Parts, DL);
3946 }
3947 
3948 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3949 // legal equivalently-sized i8 type, so we can use that as a go-between.
3950 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3951                                                   SelectionDAG &DAG) const {
3952   SDLoc DL(Op);
3953   MVT VT = Op.getSimpleValueType();
3954   SDValue SplatVal = Op.getOperand(0);
3955   // All-zeros or all-ones splats are handled specially.
3956   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3957     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3958     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3959   }
3960   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3961     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3962     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3963   }
3964   MVT XLenVT = Subtarget.getXLenVT();
3965   assert(SplatVal.getValueType() == XLenVT &&
3966          "Unexpected type for i1 splat value");
3967   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3968   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3969                          DAG.getConstant(1, DL, XLenVT));
3970   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3971   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3972   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3973 }
3974 
3975 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3976 // illegal (currently only vXi64 RV32).
3977 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3978 // them to SPLAT_VECTOR_I64
3979 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3980                                                      SelectionDAG &DAG) const {
3981   SDLoc DL(Op);
3982   MVT VecVT = Op.getSimpleValueType();
3983   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3984          "Unexpected SPLAT_VECTOR_PARTS lowering");
3985 
3986   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3987   SDValue Lo = Op.getOperand(0);
3988   SDValue Hi = Op.getOperand(1);
3989 
3990   if (VecVT.isFixedLengthVector()) {
3991     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3992     SDLoc DL(Op);
3993     SDValue Mask, VL;
3994     std::tie(Mask, VL) =
3995         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3996 
3997     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3998     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3999   }
4000 
4001   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4002     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4003     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4004     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4005     // node in order to try and match RVV vector/scalar instructions.
4006     if ((LoC >> 31) == HiC)
4007       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4008   }
4009 
4010   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4011   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4012       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4013       Hi.getConstantOperandVal(1) == 31)
4014     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4015 
4016   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4017   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
4018                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
4019 }
4020 
4021 // Custom-lower extensions from mask vectors by using a vselect either with 1
4022 // for zero/any-extension or -1 for sign-extension:
4023 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4024 // Note that any-extension is lowered identically to zero-extension.
4025 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4026                                                 int64_t ExtTrueVal) const {
4027   SDLoc DL(Op);
4028   MVT VecVT = Op.getSimpleValueType();
4029   SDValue Src = Op.getOperand(0);
4030   // Only custom-lower extensions from mask types
4031   assert(Src.getValueType().isVector() &&
4032          Src.getValueType().getVectorElementType() == MVT::i1);
4033 
4034   MVT XLenVT = Subtarget.getXLenVT();
4035   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4036   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4037 
4038   if (VecVT.isScalableVector()) {
4039     // Be careful not to introduce illegal scalar types at this stage, and be
4040     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4041     // illegal and must be expanded. Since we know that the constants are
4042     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
4043     bool IsRV32E64 =
4044         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4045 
4046     if (!IsRV32E64) {
4047       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4048       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4049     } else {
4050       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
4051       SplatTrueVal =
4052           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
4053     }
4054 
4055     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4056   }
4057 
4058   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4059   MVT I1ContainerVT =
4060       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4061 
4062   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4063 
4064   SDValue Mask, VL;
4065   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4066 
4067   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
4068   SplatTrueVal =
4069       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
4070   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4071                                SplatTrueVal, SplatZero, VL);
4072 
4073   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4074 }
4075 
4076 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4077     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4078   MVT ExtVT = Op.getSimpleValueType();
4079   // Only custom-lower extensions from fixed-length vector types.
4080   if (!ExtVT.isFixedLengthVector())
4081     return Op;
4082   MVT VT = Op.getOperand(0).getSimpleValueType();
4083   // Grab the canonical container type for the extended type. Infer the smaller
4084   // type from that to ensure the same number of vector elements, as we know
4085   // the LMUL will be sufficient to hold the smaller type.
4086   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4087   // Get the extended container type manually to ensure the same number of
4088   // vector elements between source and dest.
4089   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4090                                      ContainerExtVT.getVectorElementCount());
4091 
4092   SDValue Op1 =
4093       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4094 
4095   SDLoc DL(Op);
4096   SDValue Mask, VL;
4097   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4098 
4099   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4100 
4101   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4102 }
4103 
4104 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4105 // setcc operation:
4106 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4107 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4108                                                   SelectionDAG &DAG) const {
4109   SDLoc DL(Op);
4110   EVT MaskVT = Op.getValueType();
4111   // Only expect to custom-lower truncations to mask types
4112   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4113          "Unexpected type for vector mask lowering");
4114   SDValue Src = Op.getOperand(0);
4115   MVT VecVT = Src.getSimpleValueType();
4116 
4117   // If this is a fixed vector, we need to convert it to a scalable vector.
4118   MVT ContainerVT = VecVT;
4119   if (VecVT.isFixedLengthVector()) {
4120     ContainerVT = getContainerForFixedLengthVector(VecVT);
4121     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4122   }
4123 
4124   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4125   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4126 
4127   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
4128   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
4129 
4130   if (VecVT.isScalableVector()) {
4131     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4132     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4133   }
4134 
4135   SDValue Mask, VL;
4136   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4137 
4138   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4139   SDValue Trunc =
4140       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4141   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4142                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4143   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4144 }
4145 
4146 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4147 // first position of a vector, and that vector is slid up to the insert index.
4148 // By limiting the active vector length to index+1 and merging with the
4149 // original vector (with an undisturbed tail policy for elements >= VL), we
4150 // achieve the desired result of leaving all elements untouched except the one
4151 // at VL-1, which is replaced with the desired value.
4152 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4153                                                     SelectionDAG &DAG) const {
4154   SDLoc DL(Op);
4155   MVT VecVT = Op.getSimpleValueType();
4156   SDValue Vec = Op.getOperand(0);
4157   SDValue Val = Op.getOperand(1);
4158   SDValue Idx = Op.getOperand(2);
4159 
4160   if (VecVT.getVectorElementType() == MVT::i1) {
4161     // FIXME: For now we just promote to an i8 vector and insert into that,
4162     // but this is probably not optimal.
4163     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4164     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4165     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4166     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4167   }
4168 
4169   MVT ContainerVT = VecVT;
4170   // If the operand is a fixed-length vector, convert to a scalable one.
4171   if (VecVT.isFixedLengthVector()) {
4172     ContainerVT = getContainerForFixedLengthVector(VecVT);
4173     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4174   }
4175 
4176   MVT XLenVT = Subtarget.getXLenVT();
4177 
4178   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4179   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4180   // Even i64-element vectors on RV32 can be lowered without scalar
4181   // legalization if the most-significant 32 bits of the value are not affected
4182   // by the sign-extension of the lower 32 bits.
4183   // TODO: We could also catch sign extensions of a 32-bit value.
4184   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4185     const auto *CVal = cast<ConstantSDNode>(Val);
4186     if (isInt<32>(CVal->getSExtValue())) {
4187       IsLegalInsert = true;
4188       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4189     }
4190   }
4191 
4192   SDValue Mask, VL;
4193   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4194 
4195   SDValue ValInVec;
4196 
4197   if (IsLegalInsert) {
4198     unsigned Opc =
4199         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4200     if (isNullConstant(Idx)) {
4201       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4202       if (!VecVT.isFixedLengthVector())
4203         return Vec;
4204       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4205     }
4206     ValInVec =
4207         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4208   } else {
4209     // On RV32, i64-element vectors must be specially handled to place the
4210     // value at element 0, by using two vslide1up instructions in sequence on
4211     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4212     // this.
4213     SDValue One = DAG.getConstant(1, DL, XLenVT);
4214     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4215     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4216     MVT I32ContainerVT =
4217         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4218     SDValue I32Mask =
4219         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4220     // Limit the active VL to two.
4221     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4222     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4223     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4224     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4225                            InsertI64VL);
4226     // First slide in the hi value, then the lo in underneath it.
4227     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4228                            ValHi, I32Mask, InsertI64VL);
4229     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4230                            ValLo, I32Mask, InsertI64VL);
4231     // Bitcast back to the right container type.
4232     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4233   }
4234 
4235   // Now that the value is in a vector, slide it into position.
4236   SDValue InsertVL =
4237       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4238   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4239                                 ValInVec, Idx, Mask, InsertVL);
4240   if (!VecVT.isFixedLengthVector())
4241     return Slideup;
4242   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4243 }
4244 
4245 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4246 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4247 // types this is done using VMV_X_S to allow us to glean information about the
4248 // sign bits of the result.
4249 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4250                                                      SelectionDAG &DAG) const {
4251   SDLoc DL(Op);
4252   SDValue Idx = Op.getOperand(1);
4253   SDValue Vec = Op.getOperand(0);
4254   EVT EltVT = Op.getValueType();
4255   MVT VecVT = Vec.getSimpleValueType();
4256   MVT XLenVT = Subtarget.getXLenVT();
4257 
4258   if (VecVT.getVectorElementType() == MVT::i1) {
4259     // FIXME: For now we just promote to an i8 vector and extract from that,
4260     // but this is probably not optimal.
4261     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4262     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4263     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4264   }
4265 
4266   // If this is a fixed vector, we need to convert it to a scalable vector.
4267   MVT ContainerVT = VecVT;
4268   if (VecVT.isFixedLengthVector()) {
4269     ContainerVT = getContainerForFixedLengthVector(VecVT);
4270     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4271   }
4272 
4273   // If the index is 0, the vector is already in the right position.
4274   if (!isNullConstant(Idx)) {
4275     // Use a VL of 1 to avoid processing more elements than we need.
4276     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4277     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4278     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4279     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4280                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4281   }
4282 
4283   if (!EltVT.isInteger()) {
4284     // Floating-point extracts are handled in TableGen.
4285     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4286                        DAG.getConstant(0, DL, XLenVT));
4287   }
4288 
4289   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4290   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4291 }
4292 
4293 // Some RVV intrinsics may claim that they want an integer operand to be
4294 // promoted or expanded.
4295 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4296                                           const RISCVSubtarget &Subtarget) {
4297   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4298           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4299          "Unexpected opcode");
4300 
4301   if (!Subtarget.hasVInstructions())
4302     return SDValue();
4303 
4304   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4305   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4306   SDLoc DL(Op);
4307 
4308   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4309       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4310   if (!II || !II->hasSplatOperand())
4311     return SDValue();
4312 
4313   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4314   assert(SplatOp < Op.getNumOperands());
4315 
4316   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4317   SDValue &ScalarOp = Operands[SplatOp];
4318   MVT OpVT = ScalarOp.getSimpleValueType();
4319   MVT XLenVT = Subtarget.getXLenVT();
4320 
4321   // If this isn't a scalar, or its type is XLenVT we're done.
4322   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4323     return SDValue();
4324 
4325   // Simplest case is that the operand needs to be promoted to XLenVT.
4326   if (OpVT.bitsLT(XLenVT)) {
4327     // If the operand is a constant, sign extend to increase our chances
4328     // of being able to use a .vi instruction. ANY_EXTEND would become a
4329     // a zero extend and the simm5 check in isel would fail.
4330     // FIXME: Should we ignore the upper bits in isel instead?
4331     unsigned ExtOpc =
4332         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4333     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4334     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4335   }
4336 
4337   // Use the previous operand to get the vXi64 VT. The result might be a mask
4338   // VT for compares. Using the previous operand assumes that the previous
4339   // operand will never have a smaller element size than a scalar operand and
4340   // that a widening operation never uses SEW=64.
4341   // NOTE: If this fails the below assert, we can probably just find the
4342   // element count from any operand or result and use it to construct the VT.
4343   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4344   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4345 
4346   // The more complex case is when the scalar is larger than XLenVT.
4347   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4348          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4349 
4350   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4351   // on the instruction to sign-extend since SEW>XLEN.
4352   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4353     if (isInt<32>(CVal->getSExtValue())) {
4354       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4355       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4356     }
4357   }
4358 
4359   // We need to convert the scalar to a splat vector.
4360   // FIXME: Can we implicitly truncate the scalar if it is known to
4361   // be sign extended?
4362   SDValue VL = Op.getOperand(II->VLOperand + 1 + HasChain);
4363   assert(VL.getValueType() == XLenVT);
4364   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4365   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4366 }
4367 
4368 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4369                                                      SelectionDAG &DAG) const {
4370   unsigned IntNo = Op.getConstantOperandVal(0);
4371   SDLoc DL(Op);
4372   MVT XLenVT = Subtarget.getXLenVT();
4373 
4374   switch (IntNo) {
4375   default:
4376     break; // Don't custom lower most intrinsics.
4377   case Intrinsic::thread_pointer: {
4378     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4379     return DAG.getRegister(RISCV::X4, PtrVT);
4380   }
4381   case Intrinsic::riscv_orc_b:
4382     // Lower to the GORCI encoding for orc.b.
4383     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4384                        DAG.getConstant(7, DL, XLenVT));
4385   case Intrinsic::riscv_grev:
4386   case Intrinsic::riscv_gorc: {
4387     unsigned Opc =
4388         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4389     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4390   }
4391   case Intrinsic::riscv_shfl:
4392   case Intrinsic::riscv_unshfl: {
4393     unsigned Opc =
4394         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4395     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4396   }
4397   case Intrinsic::riscv_bcompress:
4398   case Intrinsic::riscv_bdecompress: {
4399     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4400                                                        : RISCVISD::BDECOMPRESS;
4401     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4402   }
4403   case Intrinsic::riscv_bfp:
4404     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4405                        Op.getOperand(2));
4406   case Intrinsic::riscv_fsl:
4407     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4408                        Op.getOperand(2), Op.getOperand(3));
4409   case Intrinsic::riscv_fsr:
4410     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4411                        Op.getOperand(2), Op.getOperand(3));
4412   case Intrinsic::riscv_vmv_x_s:
4413     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4414     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4415                        Op.getOperand(1));
4416   case Intrinsic::riscv_vmv_v_x:
4417     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4418                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4419   case Intrinsic::riscv_vfmv_v_f:
4420     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4421                        Op.getOperand(1), Op.getOperand(2));
4422   case Intrinsic::riscv_vmv_s_x: {
4423     SDValue Scalar = Op.getOperand(2);
4424 
4425     if (Scalar.getValueType().bitsLE(XLenVT)) {
4426       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4427       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4428                          Op.getOperand(1), Scalar, Op.getOperand(3));
4429     }
4430 
4431     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4432 
4433     // This is an i64 value that lives in two scalar registers. We have to
4434     // insert this in a convoluted way. First we build vXi64 splat containing
4435     // the/ two values that we assemble using some bit math. Next we'll use
4436     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4437     // to merge element 0 from our splat into the source vector.
4438     // FIXME: This is probably not the best way to do this, but it is
4439     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4440     // point.
4441     //   sw lo, (a0)
4442     //   sw hi, 4(a0)
4443     //   vlse vX, (a0)
4444     //
4445     //   vid.v      vVid
4446     //   vmseq.vx   mMask, vVid, 0
4447     //   vmerge.vvm vDest, vSrc, vVal, mMask
4448     MVT VT = Op.getSimpleValueType();
4449     SDValue Vec = Op.getOperand(1);
4450     SDValue VL = Op.getOperand(3);
4451 
4452     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4453     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4454                                       DAG.getConstant(0, DL, MVT::i32), VL);
4455 
4456     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4457     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4458     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4459     SDValue SelectCond =
4460         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4461                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4462     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4463                        Vec, VL);
4464   }
4465   case Intrinsic::riscv_vslide1up:
4466   case Intrinsic::riscv_vslide1down:
4467   case Intrinsic::riscv_vslide1up_mask:
4468   case Intrinsic::riscv_vslide1down_mask: {
4469     // We need to special case these when the scalar is larger than XLen.
4470     unsigned NumOps = Op.getNumOperands();
4471     bool IsMasked = NumOps == 7;
4472     unsigned OpOffset = IsMasked ? 1 : 0;
4473     SDValue Scalar = Op.getOperand(2 + OpOffset);
4474     if (Scalar.getValueType().bitsLE(XLenVT))
4475       break;
4476 
4477     // Splatting a sign extended constant is fine.
4478     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4479       if (isInt<32>(CVal->getSExtValue()))
4480         break;
4481 
4482     MVT VT = Op.getSimpleValueType();
4483     assert(VT.getVectorElementType() == MVT::i64 &&
4484            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4485 
4486     // Convert the vector source to the equivalent nxvXi32 vector.
4487     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4488     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4489 
4490     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4491                                    DAG.getConstant(0, DL, XLenVT));
4492     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4493                                    DAG.getConstant(1, DL, XLenVT));
4494 
4495     // Double the VL since we halved SEW.
4496     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4497     SDValue I32VL =
4498         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4499 
4500     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4501     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4502 
4503     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4504     // instructions.
4505     if (IntNo == Intrinsic::riscv_vslide1up ||
4506         IntNo == Intrinsic::riscv_vslide1up_mask) {
4507       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4508                         I32Mask, I32VL);
4509       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4510                         I32Mask, I32VL);
4511     } else {
4512       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4513                         I32Mask, I32VL);
4514       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4515                         I32Mask, I32VL);
4516     }
4517 
4518     // Convert back to nxvXi64.
4519     Vec = DAG.getBitcast(VT, Vec);
4520 
4521     if (!IsMasked)
4522       return Vec;
4523 
4524     // Apply mask after the operation.
4525     SDValue Mask = Op.getOperand(NumOps - 3);
4526     SDValue MaskedOff = Op.getOperand(1);
4527     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4528   }
4529   }
4530 
4531   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4532 }
4533 
4534 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4535                                                     SelectionDAG &DAG) const {
4536   unsigned IntNo = Op.getConstantOperandVal(1);
4537   switch (IntNo) {
4538   default:
4539     break;
4540   case Intrinsic::riscv_masked_strided_load: {
4541     SDLoc DL(Op);
4542     MVT XLenVT = Subtarget.getXLenVT();
4543 
4544     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4545     // the selection of the masked intrinsics doesn't do this for us.
4546     SDValue Mask = Op.getOperand(5);
4547     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4548 
4549     MVT VT = Op->getSimpleValueType(0);
4550     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4551 
4552     SDValue PassThru = Op.getOperand(2);
4553     if (!IsUnmasked) {
4554       MVT MaskVT =
4555           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4556       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4557       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4558     }
4559 
4560     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4561 
4562     SDValue IntID = DAG.getTargetConstant(
4563         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4564         XLenVT);
4565 
4566     auto *Load = cast<MemIntrinsicSDNode>(Op);
4567     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4568     if (!IsUnmasked)
4569       Ops.push_back(PassThru);
4570     Ops.push_back(Op.getOperand(3)); // Ptr
4571     Ops.push_back(Op.getOperand(4)); // Stride
4572     if (!IsUnmasked)
4573       Ops.push_back(Mask);
4574     Ops.push_back(VL);
4575     if (!IsUnmasked) {
4576       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4577       Ops.push_back(Policy);
4578     }
4579 
4580     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4581     SDValue Result =
4582         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4583                                 Load->getMemoryVT(), Load->getMemOperand());
4584     SDValue Chain = Result.getValue(1);
4585     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4586     return DAG.getMergeValues({Result, Chain}, DL);
4587   }
4588   }
4589 
4590   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4591 }
4592 
4593 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4594                                                  SelectionDAG &DAG) const {
4595   unsigned IntNo = Op.getConstantOperandVal(1);
4596   switch (IntNo) {
4597   default:
4598     break;
4599   case Intrinsic::riscv_masked_strided_store: {
4600     SDLoc DL(Op);
4601     MVT XLenVT = Subtarget.getXLenVT();
4602 
4603     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4604     // the selection of the masked intrinsics doesn't do this for us.
4605     SDValue Mask = Op.getOperand(5);
4606     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4607 
4608     SDValue Val = Op.getOperand(2);
4609     MVT VT = Val.getSimpleValueType();
4610     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4611 
4612     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4613     if (!IsUnmasked) {
4614       MVT MaskVT =
4615           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4616       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4617     }
4618 
4619     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4620 
4621     SDValue IntID = DAG.getTargetConstant(
4622         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4623         XLenVT);
4624 
4625     auto *Store = cast<MemIntrinsicSDNode>(Op);
4626     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4627     Ops.push_back(Val);
4628     Ops.push_back(Op.getOperand(3)); // Ptr
4629     Ops.push_back(Op.getOperand(4)); // Stride
4630     if (!IsUnmasked)
4631       Ops.push_back(Mask);
4632     Ops.push_back(VL);
4633 
4634     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4635                                    Ops, Store->getMemoryVT(),
4636                                    Store->getMemOperand());
4637   }
4638   }
4639 
4640   return SDValue();
4641 }
4642 
4643 static MVT getLMUL1VT(MVT VT) {
4644   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4645          "Unexpected vector MVT");
4646   return MVT::getScalableVectorVT(
4647       VT.getVectorElementType(),
4648       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4649 }
4650 
4651 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4652   switch (ISDOpcode) {
4653   default:
4654     llvm_unreachable("Unhandled reduction");
4655   case ISD::VECREDUCE_ADD:
4656     return RISCVISD::VECREDUCE_ADD_VL;
4657   case ISD::VECREDUCE_UMAX:
4658     return RISCVISD::VECREDUCE_UMAX_VL;
4659   case ISD::VECREDUCE_SMAX:
4660     return RISCVISD::VECREDUCE_SMAX_VL;
4661   case ISD::VECREDUCE_UMIN:
4662     return RISCVISD::VECREDUCE_UMIN_VL;
4663   case ISD::VECREDUCE_SMIN:
4664     return RISCVISD::VECREDUCE_SMIN_VL;
4665   case ISD::VECREDUCE_AND:
4666     return RISCVISD::VECREDUCE_AND_VL;
4667   case ISD::VECREDUCE_OR:
4668     return RISCVISD::VECREDUCE_OR_VL;
4669   case ISD::VECREDUCE_XOR:
4670     return RISCVISD::VECREDUCE_XOR_VL;
4671   }
4672 }
4673 
4674 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4675                                                          SelectionDAG &DAG,
4676                                                          bool IsVP) const {
4677   SDLoc DL(Op);
4678   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4679   MVT VecVT = Vec.getSimpleValueType();
4680   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4681           Op.getOpcode() == ISD::VECREDUCE_OR ||
4682           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4683           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4684           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4685           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4686          "Unexpected reduction lowering");
4687 
4688   MVT XLenVT = Subtarget.getXLenVT();
4689   assert(Op.getValueType() == XLenVT &&
4690          "Expected reduction output to be legalized to XLenVT");
4691 
4692   MVT ContainerVT = VecVT;
4693   if (VecVT.isFixedLengthVector()) {
4694     ContainerVT = getContainerForFixedLengthVector(VecVT);
4695     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4696   }
4697 
4698   SDValue Mask, VL;
4699   if (IsVP) {
4700     Mask = Op.getOperand(2);
4701     VL = Op.getOperand(3);
4702   } else {
4703     std::tie(Mask, VL) =
4704         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4705   }
4706 
4707   unsigned BaseOpc;
4708   ISD::CondCode CC;
4709   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4710 
4711   switch (Op.getOpcode()) {
4712   default:
4713     llvm_unreachable("Unhandled reduction");
4714   case ISD::VECREDUCE_AND:
4715   case ISD::VP_REDUCE_AND: {
4716     // vcpop ~x == 0
4717     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4718     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4719     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4720     CC = ISD::SETEQ;
4721     BaseOpc = ISD::AND;
4722     break;
4723   }
4724   case ISD::VECREDUCE_OR:
4725   case ISD::VP_REDUCE_OR:
4726     // vcpop x != 0
4727     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4728     CC = ISD::SETNE;
4729     BaseOpc = ISD::OR;
4730     break;
4731   case ISD::VECREDUCE_XOR:
4732   case ISD::VP_REDUCE_XOR: {
4733     // ((vcpop x) & 1) != 0
4734     SDValue One = DAG.getConstant(1, DL, XLenVT);
4735     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4736     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4737     CC = ISD::SETNE;
4738     BaseOpc = ISD::XOR;
4739     break;
4740   }
4741   }
4742 
4743   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4744 
4745   if (!IsVP)
4746     return SetCC;
4747 
4748   // Now include the start value in the operation.
4749   // Note that we must return the start value when no elements are operated
4750   // upon. The vcpop instructions we've emitted in each case above will return
4751   // 0 for an inactive vector, and so we've already received the neutral value:
4752   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4753   // can simply include the start value.
4754   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4755 }
4756 
4757 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4758                                             SelectionDAG &DAG) const {
4759   SDLoc DL(Op);
4760   SDValue Vec = Op.getOperand(0);
4761   EVT VecEVT = Vec.getValueType();
4762 
4763   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4764 
4765   // Due to ordering in legalize types we may have a vector type that needs to
4766   // be split. Do that manually so we can get down to a legal type.
4767   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4768          TargetLowering::TypeSplitVector) {
4769     SDValue Lo, Hi;
4770     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4771     VecEVT = Lo.getValueType();
4772     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4773   }
4774 
4775   // TODO: The type may need to be widened rather than split. Or widened before
4776   // it can be split.
4777   if (!isTypeLegal(VecEVT))
4778     return SDValue();
4779 
4780   MVT VecVT = VecEVT.getSimpleVT();
4781   MVT VecEltVT = VecVT.getVectorElementType();
4782   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4783 
4784   MVT ContainerVT = VecVT;
4785   if (VecVT.isFixedLengthVector()) {
4786     ContainerVT = getContainerForFixedLengthVector(VecVT);
4787     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4788   }
4789 
4790   MVT M1VT = getLMUL1VT(ContainerVT);
4791   MVT XLenVT = Subtarget.getXLenVT();
4792 
4793   SDValue Mask, VL;
4794   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4795 
4796   SDValue NeutralElem =
4797       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4798   SDValue IdentitySplat = lowerScalarSplat(
4799       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4800   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4801                                   IdentitySplat, Mask, VL);
4802   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4803                              DAG.getConstant(0, DL, XLenVT));
4804   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4805 }
4806 
4807 // Given a reduction op, this function returns the matching reduction opcode,
4808 // the vector SDValue and the scalar SDValue required to lower this to a
4809 // RISCVISD node.
4810 static std::tuple<unsigned, SDValue, SDValue>
4811 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4812   SDLoc DL(Op);
4813   auto Flags = Op->getFlags();
4814   unsigned Opcode = Op.getOpcode();
4815   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4816   switch (Opcode) {
4817   default:
4818     llvm_unreachable("Unhandled reduction");
4819   case ISD::VECREDUCE_FADD: {
4820     // Use positive zero if we can. It is cheaper to materialize.
4821     SDValue Zero =
4822         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4823     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4824   }
4825   case ISD::VECREDUCE_SEQ_FADD:
4826     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4827                            Op.getOperand(0));
4828   case ISD::VECREDUCE_FMIN:
4829     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4830                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4831   case ISD::VECREDUCE_FMAX:
4832     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4833                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4834   }
4835 }
4836 
4837 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4838                                               SelectionDAG &DAG) const {
4839   SDLoc DL(Op);
4840   MVT VecEltVT = Op.getSimpleValueType();
4841 
4842   unsigned RVVOpcode;
4843   SDValue VectorVal, ScalarVal;
4844   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4845       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4846   MVT VecVT = VectorVal.getSimpleValueType();
4847 
4848   MVT ContainerVT = VecVT;
4849   if (VecVT.isFixedLengthVector()) {
4850     ContainerVT = getContainerForFixedLengthVector(VecVT);
4851     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4852   }
4853 
4854   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4855   MVT XLenVT = Subtarget.getXLenVT();
4856 
4857   SDValue Mask, VL;
4858   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4859 
4860   SDValue ScalarSplat = lowerScalarSplat(
4861       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4862   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4863                                   VectorVal, ScalarSplat, Mask, VL);
4864   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4865                      DAG.getConstant(0, DL, XLenVT));
4866 }
4867 
4868 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4869   switch (ISDOpcode) {
4870   default:
4871     llvm_unreachable("Unhandled reduction");
4872   case ISD::VP_REDUCE_ADD:
4873     return RISCVISD::VECREDUCE_ADD_VL;
4874   case ISD::VP_REDUCE_UMAX:
4875     return RISCVISD::VECREDUCE_UMAX_VL;
4876   case ISD::VP_REDUCE_SMAX:
4877     return RISCVISD::VECREDUCE_SMAX_VL;
4878   case ISD::VP_REDUCE_UMIN:
4879     return RISCVISD::VECREDUCE_UMIN_VL;
4880   case ISD::VP_REDUCE_SMIN:
4881     return RISCVISD::VECREDUCE_SMIN_VL;
4882   case ISD::VP_REDUCE_AND:
4883     return RISCVISD::VECREDUCE_AND_VL;
4884   case ISD::VP_REDUCE_OR:
4885     return RISCVISD::VECREDUCE_OR_VL;
4886   case ISD::VP_REDUCE_XOR:
4887     return RISCVISD::VECREDUCE_XOR_VL;
4888   case ISD::VP_REDUCE_FADD:
4889     return RISCVISD::VECREDUCE_FADD_VL;
4890   case ISD::VP_REDUCE_SEQ_FADD:
4891     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4892   case ISD::VP_REDUCE_FMAX:
4893     return RISCVISD::VECREDUCE_FMAX_VL;
4894   case ISD::VP_REDUCE_FMIN:
4895     return RISCVISD::VECREDUCE_FMIN_VL;
4896   }
4897 }
4898 
4899 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4900                                            SelectionDAG &DAG) const {
4901   SDLoc DL(Op);
4902   SDValue Vec = Op.getOperand(1);
4903   EVT VecEVT = Vec.getValueType();
4904 
4905   // TODO: The type may need to be widened rather than split. Or widened before
4906   // it can be split.
4907   if (!isTypeLegal(VecEVT))
4908     return SDValue();
4909 
4910   MVT VecVT = VecEVT.getSimpleVT();
4911   MVT VecEltVT = VecVT.getVectorElementType();
4912   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4913 
4914   MVT ContainerVT = VecVT;
4915   if (VecVT.isFixedLengthVector()) {
4916     ContainerVT = getContainerForFixedLengthVector(VecVT);
4917     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4918   }
4919 
4920   SDValue VL = Op.getOperand(3);
4921   SDValue Mask = Op.getOperand(2);
4922 
4923   MVT M1VT = getLMUL1VT(ContainerVT);
4924   MVT XLenVT = Subtarget.getXLenVT();
4925   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4926 
4927   SDValue StartSplat =
4928       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4929                        DL, DAG, Subtarget);
4930   SDValue Reduction =
4931       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4932   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4933                              DAG.getConstant(0, DL, XLenVT));
4934   if (!VecVT.isInteger())
4935     return Elt0;
4936   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4937 }
4938 
4939 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4940                                                    SelectionDAG &DAG) const {
4941   SDValue Vec = Op.getOperand(0);
4942   SDValue SubVec = Op.getOperand(1);
4943   MVT VecVT = Vec.getSimpleValueType();
4944   MVT SubVecVT = SubVec.getSimpleValueType();
4945 
4946   SDLoc DL(Op);
4947   MVT XLenVT = Subtarget.getXLenVT();
4948   unsigned OrigIdx = Op.getConstantOperandVal(2);
4949   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4950 
4951   // We don't have the ability to slide mask vectors up indexed by their i1
4952   // elements; the smallest we can do is i8. Often we are able to bitcast to
4953   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4954   // into a scalable one, we might not necessarily have enough scalable
4955   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4956   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4957       (OrigIdx != 0 || !Vec.isUndef())) {
4958     if (VecVT.getVectorMinNumElements() >= 8 &&
4959         SubVecVT.getVectorMinNumElements() >= 8) {
4960       assert(OrigIdx % 8 == 0 && "Invalid index");
4961       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4962              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4963              "Unexpected mask vector lowering");
4964       OrigIdx /= 8;
4965       SubVecVT =
4966           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4967                            SubVecVT.isScalableVector());
4968       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4969                                VecVT.isScalableVector());
4970       Vec = DAG.getBitcast(VecVT, Vec);
4971       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4972     } else {
4973       // We can't slide this mask vector up indexed by its i1 elements.
4974       // This poses a problem when we wish to insert a scalable vector which
4975       // can't be re-expressed as a larger type. Just choose the slow path and
4976       // extend to a larger type, then truncate back down.
4977       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4978       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4979       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4980       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4981       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4982                         Op.getOperand(2));
4983       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4984       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4985     }
4986   }
4987 
4988   // If the subvector vector is a fixed-length type, we cannot use subregister
4989   // manipulation to simplify the codegen; we don't know which register of a
4990   // LMUL group contains the specific subvector as we only know the minimum
4991   // register size. Therefore we must slide the vector group up the full
4992   // amount.
4993   if (SubVecVT.isFixedLengthVector()) {
4994     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
4995       return Op;
4996     MVT ContainerVT = VecVT;
4997     if (VecVT.isFixedLengthVector()) {
4998       ContainerVT = getContainerForFixedLengthVector(VecVT);
4999       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5000     }
5001     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5002                          DAG.getUNDEF(ContainerVT), SubVec,
5003                          DAG.getConstant(0, DL, XLenVT));
5004     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5005       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5006       return DAG.getBitcast(Op.getValueType(), SubVec);
5007     }
5008     SDValue Mask =
5009         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5010     // Set the vector length to only the number of elements we care about. Note
5011     // that for slideup this includes the offset.
5012     SDValue VL =
5013         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5014     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5015     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5016                                   SubVec, SlideupAmt, Mask, VL);
5017     if (VecVT.isFixedLengthVector())
5018       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5019     return DAG.getBitcast(Op.getValueType(), Slideup);
5020   }
5021 
5022   unsigned SubRegIdx, RemIdx;
5023   std::tie(SubRegIdx, RemIdx) =
5024       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5025           VecVT, SubVecVT, OrigIdx, TRI);
5026 
5027   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5028   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5029                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5030                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5031 
5032   // 1. If the Idx has been completely eliminated and this subvector's size is
5033   // a vector register or a multiple thereof, or the surrounding elements are
5034   // undef, then this is a subvector insert which naturally aligns to a vector
5035   // register. These can easily be handled using subregister manipulation.
5036   // 2. If the subvector is smaller than a vector register, then the insertion
5037   // must preserve the undisturbed elements of the register. We do this by
5038   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5039   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5040   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5041   // LMUL=1 type back into the larger vector (resolving to another subregister
5042   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5043   // to avoid allocating a large register group to hold our subvector.
5044   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5045     return Op;
5046 
5047   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5048   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5049   // (in our case undisturbed). This means we can set up a subvector insertion
5050   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5051   // size of the subvector.
5052   MVT InterSubVT = VecVT;
5053   SDValue AlignedExtract = Vec;
5054   unsigned AlignedIdx = OrigIdx - RemIdx;
5055   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5056     InterSubVT = getLMUL1VT(VecVT);
5057     // Extract a subvector equal to the nearest full vector register type. This
5058     // should resolve to a EXTRACT_SUBREG instruction.
5059     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5060                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5061   }
5062 
5063   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5064   // For scalable vectors this must be further multiplied by vscale.
5065   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5066 
5067   SDValue Mask, VL;
5068   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5069 
5070   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5071   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5072   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5073   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5074 
5075   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5076                        DAG.getUNDEF(InterSubVT), SubVec,
5077                        DAG.getConstant(0, DL, XLenVT));
5078 
5079   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5080                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5081 
5082   // If required, insert this subvector back into the correct vector register.
5083   // This should resolve to an INSERT_SUBREG instruction.
5084   if (VecVT.bitsGT(InterSubVT))
5085     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5086                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5087 
5088   // We might have bitcast from a mask type: cast back to the original type if
5089   // required.
5090   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5091 }
5092 
5093 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5094                                                     SelectionDAG &DAG) const {
5095   SDValue Vec = Op.getOperand(0);
5096   MVT SubVecVT = Op.getSimpleValueType();
5097   MVT VecVT = Vec.getSimpleValueType();
5098 
5099   SDLoc DL(Op);
5100   MVT XLenVT = Subtarget.getXLenVT();
5101   unsigned OrigIdx = Op.getConstantOperandVal(1);
5102   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5103 
5104   // We don't have the ability to slide mask vectors down indexed by their i1
5105   // elements; the smallest we can do is i8. Often we are able to bitcast to
5106   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5107   // from a scalable one, we might not necessarily have enough scalable
5108   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5109   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5110     if (VecVT.getVectorMinNumElements() >= 8 &&
5111         SubVecVT.getVectorMinNumElements() >= 8) {
5112       assert(OrigIdx % 8 == 0 && "Invalid index");
5113       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5114              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5115              "Unexpected mask vector lowering");
5116       OrigIdx /= 8;
5117       SubVecVT =
5118           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5119                            SubVecVT.isScalableVector());
5120       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5121                                VecVT.isScalableVector());
5122       Vec = DAG.getBitcast(VecVT, Vec);
5123     } else {
5124       // We can't slide this mask vector down, indexed by its i1 elements.
5125       // This poses a problem when we wish to extract a scalable vector which
5126       // can't be re-expressed as a larger type. Just choose the slow path and
5127       // extend to a larger type, then truncate back down.
5128       // TODO: We could probably improve this when extracting certain fixed
5129       // from fixed, where we can extract as i8 and shift the correct element
5130       // right to reach the desired subvector?
5131       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5132       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5133       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5134       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5135                         Op.getOperand(1));
5136       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5137       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5138     }
5139   }
5140 
5141   // If the subvector vector is a fixed-length type, we cannot use subregister
5142   // manipulation to simplify the codegen; we don't know which register of a
5143   // LMUL group contains the specific subvector as we only know the minimum
5144   // register size. Therefore we must slide the vector group down the full
5145   // amount.
5146   if (SubVecVT.isFixedLengthVector()) {
5147     // With an index of 0 this is a cast-like subvector, which can be performed
5148     // with subregister operations.
5149     if (OrigIdx == 0)
5150       return Op;
5151     MVT ContainerVT = VecVT;
5152     if (VecVT.isFixedLengthVector()) {
5153       ContainerVT = getContainerForFixedLengthVector(VecVT);
5154       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5155     }
5156     SDValue Mask =
5157         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5158     // Set the vector length to only the number of elements we care about. This
5159     // avoids sliding down elements we're going to discard straight away.
5160     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5161     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5162     SDValue Slidedown =
5163         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5164                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5165     // Now we can use a cast-like subvector extract to get the result.
5166     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5167                             DAG.getConstant(0, DL, XLenVT));
5168     return DAG.getBitcast(Op.getValueType(), Slidedown);
5169   }
5170 
5171   unsigned SubRegIdx, RemIdx;
5172   std::tie(SubRegIdx, RemIdx) =
5173       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5174           VecVT, SubVecVT, OrigIdx, TRI);
5175 
5176   // If the Idx has been completely eliminated then this is a subvector extract
5177   // which naturally aligns to a vector register. These can easily be handled
5178   // using subregister manipulation.
5179   if (RemIdx == 0)
5180     return Op;
5181 
5182   // Else we must shift our vector register directly to extract the subvector.
5183   // Do this using VSLIDEDOWN.
5184 
5185   // If the vector type is an LMUL-group type, extract a subvector equal to the
5186   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5187   // instruction.
5188   MVT InterSubVT = VecVT;
5189   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5190     InterSubVT = getLMUL1VT(VecVT);
5191     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5192                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5193   }
5194 
5195   // Slide this vector register down by the desired number of elements in order
5196   // to place the desired subvector starting at element 0.
5197   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5198   // For scalable vectors this must be further multiplied by vscale.
5199   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5200 
5201   SDValue Mask, VL;
5202   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5203   SDValue Slidedown =
5204       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5205                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5206 
5207   // Now the vector is in the right position, extract our final subvector. This
5208   // should resolve to a COPY.
5209   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5210                           DAG.getConstant(0, DL, XLenVT));
5211 
5212   // We might have bitcast from a mask type: cast back to the original type if
5213   // required.
5214   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5215 }
5216 
5217 // Lower step_vector to the vid instruction. Any non-identity step value must
5218 // be accounted for my manual expansion.
5219 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5220                                               SelectionDAG &DAG) const {
5221   SDLoc DL(Op);
5222   MVT VT = Op.getSimpleValueType();
5223   MVT XLenVT = Subtarget.getXLenVT();
5224   SDValue Mask, VL;
5225   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5226   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5227   uint64_t StepValImm = Op.getConstantOperandVal(0);
5228   if (StepValImm != 1) {
5229     if (isPowerOf2_64(StepValImm)) {
5230       SDValue StepVal =
5231           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5232                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5233       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5234     } else {
5235       SDValue StepVal = lowerScalarSplat(
5236           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5237           DL, DAG, Subtarget);
5238       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5239     }
5240   }
5241   return StepVec;
5242 }
5243 
5244 // Implement vector_reverse using vrgather.vv with indices determined by
5245 // subtracting the id of each element from (VLMAX-1). This will convert
5246 // the indices like so:
5247 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5248 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5249 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5250                                                  SelectionDAG &DAG) const {
5251   SDLoc DL(Op);
5252   MVT VecVT = Op.getSimpleValueType();
5253   unsigned EltSize = VecVT.getScalarSizeInBits();
5254   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5255 
5256   unsigned MaxVLMAX = 0;
5257   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5258   if (VectorBitsMax != 0)
5259     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5260 
5261   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5262   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5263 
5264   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5265   // to use vrgatherei16.vv.
5266   // TODO: It's also possible to use vrgatherei16.vv for other types to
5267   // decrease register width for the index calculation.
5268   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5269     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5270     // Reverse each half, then reassemble them in reverse order.
5271     // NOTE: It's also possible that after splitting that VLMAX no longer
5272     // requires vrgatherei16.vv.
5273     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5274       SDValue Lo, Hi;
5275       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5276       EVT LoVT, HiVT;
5277       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5278       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5279       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5280       // Reassemble the low and high pieces reversed.
5281       // FIXME: This is a CONCAT_VECTORS.
5282       SDValue Res =
5283           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5284                       DAG.getIntPtrConstant(0, DL));
5285       return DAG.getNode(
5286           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5287           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5288     }
5289 
5290     // Just promote the int type to i16 which will double the LMUL.
5291     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5292     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5293   }
5294 
5295   MVT XLenVT = Subtarget.getXLenVT();
5296   SDValue Mask, VL;
5297   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5298 
5299   // Calculate VLMAX-1 for the desired SEW.
5300   unsigned MinElts = VecVT.getVectorMinNumElements();
5301   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5302                               DAG.getConstant(MinElts, DL, XLenVT));
5303   SDValue VLMinus1 =
5304       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5305 
5306   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5307   bool IsRV32E64 =
5308       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5309   SDValue SplatVL;
5310   if (!IsRV32E64)
5311     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5312   else
5313     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5314 
5315   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5316   SDValue Indices =
5317       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5318 
5319   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5320 }
5321 
5322 SDValue
5323 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5324                                                      SelectionDAG &DAG) const {
5325   SDLoc DL(Op);
5326   auto *Load = cast<LoadSDNode>(Op);
5327 
5328   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5329                                         Load->getMemoryVT(),
5330                                         *Load->getMemOperand()) &&
5331          "Expecting a correctly-aligned load");
5332 
5333   MVT VT = Op.getSimpleValueType();
5334   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5335 
5336   SDValue VL =
5337       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5338 
5339   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5340   SDValue NewLoad = DAG.getMemIntrinsicNode(
5341       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5342       Load->getMemoryVT(), Load->getMemOperand());
5343 
5344   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5345   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5346 }
5347 
5348 SDValue
5349 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5350                                                       SelectionDAG &DAG) const {
5351   SDLoc DL(Op);
5352   auto *Store = cast<StoreSDNode>(Op);
5353 
5354   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5355                                         Store->getMemoryVT(),
5356                                         *Store->getMemOperand()) &&
5357          "Expecting a correctly-aligned store");
5358 
5359   SDValue StoreVal = Store->getValue();
5360   MVT VT = StoreVal.getSimpleValueType();
5361 
5362   // If the size less than a byte, we need to pad with zeros to make a byte.
5363   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5364     VT = MVT::v8i1;
5365     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5366                            DAG.getConstant(0, DL, VT), StoreVal,
5367                            DAG.getIntPtrConstant(0, DL));
5368   }
5369 
5370   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5371 
5372   SDValue VL =
5373       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5374 
5375   SDValue NewValue =
5376       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5377   return DAG.getMemIntrinsicNode(
5378       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5379       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5380       Store->getMemoryVT(), Store->getMemOperand());
5381 }
5382 
5383 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5384                                              SelectionDAG &DAG) const {
5385   SDLoc DL(Op);
5386   MVT VT = Op.getSimpleValueType();
5387 
5388   const auto *MemSD = cast<MemSDNode>(Op);
5389   EVT MemVT = MemSD->getMemoryVT();
5390   MachineMemOperand *MMO = MemSD->getMemOperand();
5391   SDValue Chain = MemSD->getChain();
5392   SDValue BasePtr = MemSD->getBasePtr();
5393 
5394   SDValue Mask, PassThru, VL;
5395   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5396     Mask = VPLoad->getMask();
5397     PassThru = DAG.getUNDEF(VT);
5398     VL = VPLoad->getVectorLength();
5399   } else {
5400     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5401     Mask = MLoad->getMask();
5402     PassThru = MLoad->getPassThru();
5403   }
5404 
5405   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5406 
5407   MVT XLenVT = Subtarget.getXLenVT();
5408 
5409   MVT ContainerVT = VT;
5410   if (VT.isFixedLengthVector()) {
5411     ContainerVT = getContainerForFixedLengthVector(VT);
5412     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5413     if (!IsUnmasked) {
5414       MVT MaskVT =
5415           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5416       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5417     }
5418   }
5419 
5420   if (!VL)
5421     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5422 
5423   unsigned IntID =
5424       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5425   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5426   if (!IsUnmasked)
5427     Ops.push_back(PassThru);
5428   Ops.push_back(BasePtr);
5429   if (!IsUnmasked)
5430     Ops.push_back(Mask);
5431   Ops.push_back(VL);
5432   if (!IsUnmasked)
5433     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5434 
5435   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5436 
5437   SDValue Result =
5438       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5439   Chain = Result.getValue(1);
5440 
5441   if (VT.isFixedLengthVector())
5442     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5443 
5444   return DAG.getMergeValues({Result, Chain}, DL);
5445 }
5446 
5447 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5448                                               SelectionDAG &DAG) const {
5449   SDLoc DL(Op);
5450 
5451   const auto *MemSD = cast<MemSDNode>(Op);
5452   EVT MemVT = MemSD->getMemoryVT();
5453   MachineMemOperand *MMO = MemSD->getMemOperand();
5454   SDValue Chain = MemSD->getChain();
5455   SDValue BasePtr = MemSD->getBasePtr();
5456   SDValue Val, Mask, VL;
5457 
5458   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5459     Val = VPStore->getValue();
5460     Mask = VPStore->getMask();
5461     VL = VPStore->getVectorLength();
5462   } else {
5463     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5464     Val = MStore->getValue();
5465     Mask = MStore->getMask();
5466   }
5467 
5468   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5469 
5470   MVT VT = Val.getSimpleValueType();
5471   MVT XLenVT = Subtarget.getXLenVT();
5472 
5473   MVT ContainerVT = VT;
5474   if (VT.isFixedLengthVector()) {
5475     ContainerVT = getContainerForFixedLengthVector(VT);
5476 
5477     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5478     if (!IsUnmasked) {
5479       MVT MaskVT =
5480           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5481       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5482     }
5483   }
5484 
5485   if (!VL)
5486     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5487 
5488   unsigned IntID =
5489       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5490   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5491   Ops.push_back(Val);
5492   Ops.push_back(BasePtr);
5493   if (!IsUnmasked)
5494     Ops.push_back(Mask);
5495   Ops.push_back(VL);
5496 
5497   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5498                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5499 }
5500 
5501 SDValue
5502 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5503                                                       SelectionDAG &DAG) const {
5504   MVT InVT = Op.getOperand(0).getSimpleValueType();
5505   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5506 
5507   MVT VT = Op.getSimpleValueType();
5508 
5509   SDValue Op1 =
5510       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5511   SDValue Op2 =
5512       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5513 
5514   SDLoc DL(Op);
5515   SDValue VL =
5516       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5517 
5518   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5519   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5520 
5521   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5522                             Op.getOperand(2), Mask, VL);
5523 
5524   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5525 }
5526 
5527 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5528     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5529   MVT VT = Op.getSimpleValueType();
5530 
5531   if (VT.getVectorElementType() == MVT::i1)
5532     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5533 
5534   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5535 }
5536 
5537 SDValue
5538 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5539                                                       SelectionDAG &DAG) const {
5540   unsigned Opc;
5541   switch (Op.getOpcode()) {
5542   default: llvm_unreachable("Unexpected opcode!");
5543   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5544   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5545   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5546   }
5547 
5548   return lowerToScalableOp(Op, DAG, Opc);
5549 }
5550 
5551 // Lower vector ABS to smax(X, sub(0, X)).
5552 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5553   SDLoc DL(Op);
5554   MVT VT = Op.getSimpleValueType();
5555   SDValue X = Op.getOperand(0);
5556 
5557   assert(VT.isFixedLengthVector() && "Unexpected type");
5558 
5559   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5560   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5561 
5562   SDValue Mask, VL;
5563   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5564 
5565   SDValue SplatZero =
5566       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5567                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5568   SDValue NegX =
5569       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5570   SDValue Max =
5571       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5572 
5573   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5574 }
5575 
5576 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5577     SDValue Op, SelectionDAG &DAG) const {
5578   SDLoc DL(Op);
5579   MVT VT = Op.getSimpleValueType();
5580   SDValue Mag = Op.getOperand(0);
5581   SDValue Sign = Op.getOperand(1);
5582   assert(Mag.getValueType() == Sign.getValueType() &&
5583          "Can only handle COPYSIGN with matching types.");
5584 
5585   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5586   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5587   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5588 
5589   SDValue Mask, VL;
5590   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5591 
5592   SDValue CopySign =
5593       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5594 
5595   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5596 }
5597 
5598 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5599     SDValue Op, SelectionDAG &DAG) const {
5600   MVT VT = Op.getSimpleValueType();
5601   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5602 
5603   MVT I1ContainerVT =
5604       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5605 
5606   SDValue CC =
5607       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5608   SDValue Op1 =
5609       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5610   SDValue Op2 =
5611       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5612 
5613   SDLoc DL(Op);
5614   SDValue Mask, VL;
5615   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5616 
5617   SDValue Select =
5618       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5619 
5620   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5621 }
5622 
5623 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5624                                                unsigned NewOpc,
5625                                                bool HasMask) const {
5626   MVT VT = Op.getSimpleValueType();
5627   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5628 
5629   // Create list of operands by converting existing ones to scalable types.
5630   SmallVector<SDValue, 6> Ops;
5631   for (const SDValue &V : Op->op_values()) {
5632     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5633 
5634     // Pass through non-vector operands.
5635     if (!V.getValueType().isVector()) {
5636       Ops.push_back(V);
5637       continue;
5638     }
5639 
5640     // "cast" fixed length vector to a scalable vector.
5641     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5642            "Only fixed length vectors are supported!");
5643     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5644   }
5645 
5646   SDLoc DL(Op);
5647   SDValue Mask, VL;
5648   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5649   if (HasMask)
5650     Ops.push_back(Mask);
5651   Ops.push_back(VL);
5652 
5653   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5654   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5655 }
5656 
5657 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5658 // * Operands of each node are assumed to be in the same order.
5659 // * The EVL operand is promoted from i32 to i64 on RV64.
5660 // * Fixed-length vectors are converted to their scalable-vector container
5661 //   types.
5662 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5663                                        unsigned RISCVISDOpc) const {
5664   SDLoc DL(Op);
5665   MVT VT = Op.getSimpleValueType();
5666   SmallVector<SDValue, 4> Ops;
5667 
5668   for (const auto &OpIdx : enumerate(Op->ops())) {
5669     SDValue V = OpIdx.value();
5670     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5671     // Pass through operands which aren't fixed-length vectors.
5672     if (!V.getValueType().isFixedLengthVector()) {
5673       Ops.push_back(V);
5674       continue;
5675     }
5676     // "cast" fixed length vector to a scalable vector.
5677     MVT OpVT = V.getSimpleValueType();
5678     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5679     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5680            "Only fixed length vectors are supported!");
5681     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5682   }
5683 
5684   if (!VT.isFixedLengthVector())
5685     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5686 
5687   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5688 
5689   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5690 
5691   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5692 }
5693 
5694 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5695                                             unsigned MaskOpc,
5696                                             unsigned VecOpc) const {
5697   MVT VT = Op.getSimpleValueType();
5698   if (VT.getVectorElementType() != MVT::i1)
5699     return lowerVPOp(Op, DAG, VecOpc);
5700 
5701   // It is safe to drop mask parameter as masked-off elements are undef.
5702   SDValue Op1 = Op->getOperand(0);
5703   SDValue Op2 = Op->getOperand(1);
5704   SDValue VL = Op->getOperand(3);
5705 
5706   MVT ContainerVT = VT;
5707   const bool IsFixed = VT.isFixedLengthVector();
5708   if (IsFixed) {
5709     ContainerVT = getContainerForFixedLengthVector(VT);
5710     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5711     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5712   }
5713 
5714   SDLoc DL(Op);
5715   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5716   if (!IsFixed)
5717     return Val;
5718   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5719 }
5720 
5721 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5722 // matched to a RVV indexed load. The RVV indexed load instructions only
5723 // support the "unsigned unscaled" addressing mode; indices are implicitly
5724 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5725 // signed or scaled indexing is extended to the XLEN value type and scaled
5726 // accordingly.
5727 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5728                                                SelectionDAG &DAG) const {
5729   SDLoc DL(Op);
5730   MVT VT = Op.getSimpleValueType();
5731 
5732   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5733   EVT MemVT = MemSD->getMemoryVT();
5734   MachineMemOperand *MMO = MemSD->getMemOperand();
5735   SDValue Chain = MemSD->getChain();
5736   SDValue BasePtr = MemSD->getBasePtr();
5737 
5738   ISD::LoadExtType LoadExtType;
5739   SDValue Index, Mask, PassThru, VL;
5740 
5741   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5742     Index = VPGN->getIndex();
5743     Mask = VPGN->getMask();
5744     PassThru = DAG.getUNDEF(VT);
5745     VL = VPGN->getVectorLength();
5746     // VP doesn't support extending loads.
5747     LoadExtType = ISD::NON_EXTLOAD;
5748   } else {
5749     // Else it must be a MGATHER.
5750     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5751     Index = MGN->getIndex();
5752     Mask = MGN->getMask();
5753     PassThru = MGN->getPassThru();
5754     LoadExtType = MGN->getExtensionType();
5755   }
5756 
5757   MVT IndexVT = Index.getSimpleValueType();
5758   MVT XLenVT = Subtarget.getXLenVT();
5759 
5760   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5761          "Unexpected VTs!");
5762   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5763   // Targets have to explicitly opt-in for extending vector loads.
5764   assert(LoadExtType == ISD::NON_EXTLOAD &&
5765          "Unexpected extending MGATHER/VP_GATHER");
5766   (void)LoadExtType;
5767 
5768   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5769   // the selection of the masked intrinsics doesn't do this for us.
5770   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5771 
5772   MVT ContainerVT = VT;
5773   if (VT.isFixedLengthVector()) {
5774     // We need to use the larger of the result and index type to determine the
5775     // scalable type to use so we don't increase LMUL for any operand/result.
5776     if (VT.bitsGE(IndexVT)) {
5777       ContainerVT = getContainerForFixedLengthVector(VT);
5778       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5779                                  ContainerVT.getVectorElementCount());
5780     } else {
5781       IndexVT = getContainerForFixedLengthVector(IndexVT);
5782       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5783                                      IndexVT.getVectorElementCount());
5784     }
5785 
5786     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5787 
5788     if (!IsUnmasked) {
5789       MVT MaskVT =
5790           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5791       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5792       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5793     }
5794   }
5795 
5796   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5797       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5798       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5799   }
5800 
5801   if (!VL)
5802     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5803 
5804   unsigned IntID =
5805       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5806   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5807   if (!IsUnmasked)
5808     Ops.push_back(PassThru);
5809   Ops.push_back(BasePtr);
5810   Ops.push_back(Index);
5811   if (!IsUnmasked)
5812     Ops.push_back(Mask);
5813   Ops.push_back(VL);
5814   if (!IsUnmasked)
5815     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5816 
5817   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5818   SDValue Result =
5819       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5820   Chain = Result.getValue(1);
5821 
5822   if (VT.isFixedLengthVector())
5823     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5824 
5825   return DAG.getMergeValues({Result, Chain}, DL);
5826 }
5827 
5828 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5829 // matched to a RVV indexed store. The RVV indexed store instructions only
5830 // support the "unsigned unscaled" addressing mode; indices are implicitly
5831 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5832 // signed or scaled indexing is extended to the XLEN value type and scaled
5833 // accordingly.
5834 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5835                                                 SelectionDAG &DAG) const {
5836   SDLoc DL(Op);
5837   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5838   EVT MemVT = MemSD->getMemoryVT();
5839   MachineMemOperand *MMO = MemSD->getMemOperand();
5840   SDValue Chain = MemSD->getChain();
5841   SDValue BasePtr = MemSD->getBasePtr();
5842 
5843   bool IsTruncatingStore = false;
5844   SDValue Index, Mask, Val, VL;
5845 
5846   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5847     Index = VPSN->getIndex();
5848     Mask = VPSN->getMask();
5849     Val = VPSN->getValue();
5850     VL = VPSN->getVectorLength();
5851     // VP doesn't support truncating stores.
5852     IsTruncatingStore = false;
5853   } else {
5854     // Else it must be a MSCATTER.
5855     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5856     Index = MSN->getIndex();
5857     Mask = MSN->getMask();
5858     Val = MSN->getValue();
5859     IsTruncatingStore = MSN->isTruncatingStore();
5860   }
5861 
5862   MVT VT = Val.getSimpleValueType();
5863   MVT IndexVT = Index.getSimpleValueType();
5864   MVT XLenVT = Subtarget.getXLenVT();
5865 
5866   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5867          "Unexpected VTs!");
5868   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5869   // Targets have to explicitly opt-in for extending vector loads and
5870   // truncating vector stores.
5871   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5872   (void)IsTruncatingStore;
5873 
5874   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5875   // the selection of the masked intrinsics doesn't do this for us.
5876   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5877 
5878   MVT ContainerVT = VT;
5879   if (VT.isFixedLengthVector()) {
5880     // We need to use the larger of the value and index type to determine the
5881     // scalable type to use so we don't increase LMUL for any operand/result.
5882     if (VT.bitsGE(IndexVT)) {
5883       ContainerVT = getContainerForFixedLengthVector(VT);
5884       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5885                                  ContainerVT.getVectorElementCount());
5886     } else {
5887       IndexVT = getContainerForFixedLengthVector(IndexVT);
5888       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5889                                      IndexVT.getVectorElementCount());
5890     }
5891 
5892     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5893     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5894 
5895     if (!IsUnmasked) {
5896       MVT MaskVT =
5897           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5898       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5899     }
5900   }
5901 
5902   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5903       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5904       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5905   }
5906 
5907   if (!VL)
5908     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5909 
5910   unsigned IntID =
5911       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5912   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5913   Ops.push_back(Val);
5914   Ops.push_back(BasePtr);
5915   Ops.push_back(Index);
5916   if (!IsUnmasked)
5917     Ops.push_back(Mask);
5918   Ops.push_back(VL);
5919 
5920   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5921                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5922 }
5923 
5924 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5925                                                SelectionDAG &DAG) const {
5926   const MVT XLenVT = Subtarget.getXLenVT();
5927   SDLoc DL(Op);
5928   SDValue Chain = Op->getOperand(0);
5929   SDValue SysRegNo = DAG.getTargetConstant(
5930       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5931   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5932   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5933 
5934   // Encoding used for rounding mode in RISCV differs from that used in
5935   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5936   // table, which consists of a sequence of 4-bit fields, each representing
5937   // corresponding FLT_ROUNDS mode.
5938   static const int Table =
5939       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5940       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5941       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5942       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5943       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5944 
5945   SDValue Shift =
5946       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5947   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5948                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5949   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5950                                DAG.getConstant(7, DL, XLenVT));
5951 
5952   return DAG.getMergeValues({Masked, Chain}, DL);
5953 }
5954 
5955 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5956                                                SelectionDAG &DAG) const {
5957   const MVT XLenVT = Subtarget.getXLenVT();
5958   SDLoc DL(Op);
5959   SDValue Chain = Op->getOperand(0);
5960   SDValue RMValue = Op->getOperand(1);
5961   SDValue SysRegNo = DAG.getTargetConstant(
5962       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5963 
5964   // Encoding used for rounding mode in RISCV differs from that used in
5965   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5966   // a table, which consists of a sequence of 4-bit fields, each representing
5967   // corresponding RISCV mode.
5968   static const unsigned Table =
5969       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5970       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5971       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5972       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5973       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5974 
5975   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5976                               DAG.getConstant(2, DL, XLenVT));
5977   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5978                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5979   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5980                         DAG.getConstant(0x7, DL, XLenVT));
5981   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5982                      RMValue);
5983 }
5984 
5985 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
5986   switch (IntNo) {
5987   default:
5988     llvm_unreachable("Unexpected Intrinsic");
5989   case Intrinsic::riscv_grev:
5990     return RISCVISD::GREVW;
5991   case Intrinsic::riscv_gorc:
5992     return RISCVISD::GORCW;
5993   case Intrinsic::riscv_bcompress:
5994     return RISCVISD::BCOMPRESSW;
5995   case Intrinsic::riscv_bdecompress:
5996     return RISCVISD::BDECOMPRESSW;
5997   case Intrinsic::riscv_bfp:
5998     return RISCVISD::BFPW;
5999   case Intrinsic::riscv_fsl:
6000     return RISCVISD::FSLW;
6001   case Intrinsic::riscv_fsr:
6002     return RISCVISD::FSRW;
6003   }
6004 }
6005 
6006 // Converts the given intrinsic to a i64 operation with any extension.
6007 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6008                                          unsigned IntNo) {
6009   SDLoc DL(N);
6010   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6011   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6012   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6013   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6014   // ReplaceNodeResults requires we maintain the same type for the return value.
6015   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6016 }
6017 
6018 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6019 // form of the given Opcode.
6020 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6021   switch (Opcode) {
6022   default:
6023     llvm_unreachable("Unexpected opcode");
6024   case ISD::SHL:
6025     return RISCVISD::SLLW;
6026   case ISD::SRA:
6027     return RISCVISD::SRAW;
6028   case ISD::SRL:
6029     return RISCVISD::SRLW;
6030   case ISD::SDIV:
6031     return RISCVISD::DIVW;
6032   case ISD::UDIV:
6033     return RISCVISD::DIVUW;
6034   case ISD::UREM:
6035     return RISCVISD::REMUW;
6036   case ISD::ROTL:
6037     return RISCVISD::ROLW;
6038   case ISD::ROTR:
6039     return RISCVISD::RORW;
6040   case RISCVISD::GREV:
6041     return RISCVISD::GREVW;
6042   case RISCVISD::GORC:
6043     return RISCVISD::GORCW;
6044   }
6045 }
6046 
6047 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6048 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6049 // otherwise be promoted to i64, making it difficult to select the
6050 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6051 // type i8/i16/i32 is lost.
6052 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6053                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6054   SDLoc DL(N);
6055   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6056   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6057   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6058   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6059   // ReplaceNodeResults requires we maintain the same type for the return value.
6060   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6061 }
6062 
6063 // Converts the given 32-bit operation to a i64 operation with signed extension
6064 // semantic to reduce the signed extension instructions.
6065 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6066   SDLoc DL(N);
6067   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6068   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6069   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6070   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6071                                DAG.getValueType(MVT::i32));
6072   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6073 }
6074 
6075 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6076                                              SmallVectorImpl<SDValue> &Results,
6077                                              SelectionDAG &DAG) const {
6078   SDLoc DL(N);
6079   switch (N->getOpcode()) {
6080   default:
6081     llvm_unreachable("Don't know how to custom type legalize this operation!");
6082   case ISD::STRICT_FP_TO_SINT:
6083   case ISD::STRICT_FP_TO_UINT:
6084   case ISD::FP_TO_SINT:
6085   case ISD::FP_TO_UINT: {
6086     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6087            "Unexpected custom legalisation");
6088     bool IsStrict = N->isStrictFPOpcode();
6089     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6090                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6091     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6092     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6093         TargetLowering::TypeSoftenFloat) {
6094       if (!isTypeLegal(Op0.getValueType()))
6095         return;
6096       if (IsStrict) {
6097         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6098                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6099         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6100         SDValue Res = DAG.getNode(
6101             Opc, DL, VTs, N->getOperand(0), Op0,
6102             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6103         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6104         Results.push_back(Res.getValue(1));
6105         return;
6106       }
6107       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6108       SDValue Res =
6109           DAG.getNode(Opc, DL, MVT::i64, Op0,
6110                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6111       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6112       return;
6113     }
6114     // If the FP type needs to be softened, emit a library call using the 'si'
6115     // version. If we left it to default legalization we'd end up with 'di'. If
6116     // the FP type doesn't need to be softened just let generic type
6117     // legalization promote the result type.
6118     RTLIB::Libcall LC;
6119     if (IsSigned)
6120       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6121     else
6122       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6123     MakeLibCallOptions CallOptions;
6124     EVT OpVT = Op0.getValueType();
6125     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6126     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6127     SDValue Result;
6128     std::tie(Result, Chain) =
6129         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6130     Results.push_back(Result);
6131     if (IsStrict)
6132       Results.push_back(Chain);
6133     break;
6134   }
6135   case ISD::READCYCLECOUNTER: {
6136     assert(!Subtarget.is64Bit() &&
6137            "READCYCLECOUNTER only has custom type legalization on riscv32");
6138 
6139     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6140     SDValue RCW =
6141         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6142 
6143     Results.push_back(
6144         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6145     Results.push_back(RCW.getValue(2));
6146     break;
6147   }
6148   case ISD::MUL: {
6149     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6150     unsigned XLen = Subtarget.getXLen();
6151     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6152     if (Size > XLen) {
6153       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6154       SDValue LHS = N->getOperand(0);
6155       SDValue RHS = N->getOperand(1);
6156       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6157 
6158       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6159       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6160       // We need exactly one side to be unsigned.
6161       if (LHSIsU == RHSIsU)
6162         return;
6163 
6164       auto MakeMULPair = [&](SDValue S, SDValue U) {
6165         MVT XLenVT = Subtarget.getXLenVT();
6166         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6167         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6168         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6169         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6170         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6171       };
6172 
6173       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6174       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6175 
6176       // The other operand should be signed, but still prefer MULH when
6177       // possible.
6178       if (RHSIsU && LHSIsS && !RHSIsS)
6179         Results.push_back(MakeMULPair(LHS, RHS));
6180       else if (LHSIsU && RHSIsS && !LHSIsS)
6181         Results.push_back(MakeMULPair(RHS, LHS));
6182 
6183       return;
6184     }
6185     LLVM_FALLTHROUGH;
6186   }
6187   case ISD::ADD:
6188   case ISD::SUB:
6189     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6190            "Unexpected custom legalisation");
6191     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6192     break;
6193   case ISD::SHL:
6194   case ISD::SRA:
6195   case ISD::SRL:
6196     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6197            "Unexpected custom legalisation");
6198     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6199       Results.push_back(customLegalizeToWOp(N, DAG));
6200       break;
6201     }
6202 
6203     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6204     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6205     // shift amount.
6206     if (N->getOpcode() == ISD::SHL) {
6207       SDLoc DL(N);
6208       SDValue NewOp0 =
6209           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6210       SDValue NewOp1 =
6211           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6212       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6213       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6214                                    DAG.getValueType(MVT::i32));
6215       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6216     }
6217 
6218     break;
6219   case ISD::ROTL:
6220   case ISD::ROTR:
6221     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6222            "Unexpected custom legalisation");
6223     Results.push_back(customLegalizeToWOp(N, DAG));
6224     break;
6225   case ISD::CTTZ:
6226   case ISD::CTTZ_ZERO_UNDEF:
6227   case ISD::CTLZ:
6228   case ISD::CTLZ_ZERO_UNDEF: {
6229     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6230            "Unexpected custom legalisation");
6231 
6232     SDValue NewOp0 =
6233         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6234     bool IsCTZ =
6235         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6236     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6237     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6238     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6239     return;
6240   }
6241   case ISD::SDIV:
6242   case ISD::UDIV:
6243   case ISD::UREM: {
6244     MVT VT = N->getSimpleValueType(0);
6245     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6246            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6247            "Unexpected custom legalisation");
6248     // Don't promote division/remainder by constant since we should expand those
6249     // to multiply by magic constant.
6250     // FIXME: What if the expansion is disabled for minsize.
6251     if (N->getOperand(1).getOpcode() == ISD::Constant)
6252       return;
6253 
6254     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6255     // the upper 32 bits. For other types we need to sign or zero extend
6256     // based on the opcode.
6257     unsigned ExtOpc = ISD::ANY_EXTEND;
6258     if (VT != MVT::i32)
6259       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6260                                            : ISD::ZERO_EXTEND;
6261 
6262     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6263     break;
6264   }
6265   case ISD::UADDO:
6266   case ISD::USUBO: {
6267     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6268            "Unexpected custom legalisation");
6269     bool IsAdd = N->getOpcode() == ISD::UADDO;
6270     // Create an ADDW or SUBW.
6271     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6272     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6273     SDValue Res =
6274         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6275     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6276                       DAG.getValueType(MVT::i32));
6277 
6278     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6279     // Since the inputs are sign extended from i32, this is equivalent to
6280     // comparing the lower 32 bits.
6281     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6282     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6283                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6284 
6285     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6286     Results.push_back(Overflow);
6287     return;
6288   }
6289   case ISD::UADDSAT:
6290   case ISD::USUBSAT: {
6291     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6292            "Unexpected custom legalisation");
6293     if (Subtarget.hasStdExtZbb()) {
6294       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6295       // sign extend allows overflow of the lower 32 bits to be detected on
6296       // the promoted size.
6297       SDValue LHS =
6298           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6299       SDValue RHS =
6300           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6301       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6302       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6303       return;
6304     }
6305 
6306     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6307     // promotion for UADDO/USUBO.
6308     Results.push_back(expandAddSubSat(N, DAG));
6309     return;
6310   }
6311   case ISD::BITCAST: {
6312     EVT VT = N->getValueType(0);
6313     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6314     SDValue Op0 = N->getOperand(0);
6315     EVT Op0VT = Op0.getValueType();
6316     MVT XLenVT = Subtarget.getXLenVT();
6317     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6318       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6319       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6320     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6321                Subtarget.hasStdExtF()) {
6322       SDValue FPConv =
6323           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6324       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6325     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6326                isTypeLegal(Op0VT)) {
6327       // Custom-legalize bitcasts from fixed-length vector types to illegal
6328       // scalar types in order to improve codegen. Bitcast the vector to a
6329       // one-element vector type whose element type is the same as the result
6330       // type, and extract the first element.
6331       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6332       if (isTypeLegal(BVT)) {
6333         SDValue BVec = DAG.getBitcast(BVT, Op0);
6334         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6335                                       DAG.getConstant(0, DL, XLenVT)));
6336       }
6337     }
6338     break;
6339   }
6340   case RISCVISD::GREV:
6341   case RISCVISD::GORC: {
6342     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6343            "Unexpected custom legalisation");
6344     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6345     // This is similar to customLegalizeToWOp, except that we pass the second
6346     // operand (a TargetConstant) straight through: it is already of type
6347     // XLenVT.
6348     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6349     SDValue NewOp0 =
6350         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6351     SDValue NewOp1 =
6352         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6353     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6354     // ReplaceNodeResults requires we maintain the same type for the return
6355     // value.
6356     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6357     break;
6358   }
6359   case RISCVISD::SHFL: {
6360     // There is no SHFLIW instruction, but we can just promote the operation.
6361     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6362            "Unexpected custom legalisation");
6363     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6364     SDValue NewOp0 =
6365         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6366     SDValue NewOp1 =
6367         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6368     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6369     // ReplaceNodeResults requires we maintain the same type for the return
6370     // value.
6371     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6372     break;
6373   }
6374   case ISD::BSWAP:
6375   case ISD::BITREVERSE: {
6376     MVT VT = N->getSimpleValueType(0);
6377     MVT XLenVT = Subtarget.getXLenVT();
6378     assert((VT == MVT::i8 || VT == MVT::i16 ||
6379             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6380            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6381     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6382     unsigned Imm = VT.getSizeInBits() - 1;
6383     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6384     if (N->getOpcode() == ISD::BSWAP)
6385       Imm &= ~0x7U;
6386     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6387     SDValue GREVI =
6388         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6389     // ReplaceNodeResults requires we maintain the same type for the return
6390     // value.
6391     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6392     break;
6393   }
6394   case ISD::FSHL:
6395   case ISD::FSHR: {
6396     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6397            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6398     SDValue NewOp0 =
6399         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6400     SDValue NewOp1 =
6401         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6402     SDValue NewShAmt =
6403         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6404     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6405     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6406     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6407                            DAG.getConstant(0x1f, DL, MVT::i64));
6408     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6409     // instruction use different orders. fshl will return its first operand for
6410     // shift of zero, fshr will return its second operand. fsl and fsr both
6411     // return rs1 so the ISD nodes need to have different operand orders.
6412     // Shift amount is in rs2.
6413     unsigned Opc = RISCVISD::FSLW;
6414     if (N->getOpcode() == ISD::FSHR) {
6415       std::swap(NewOp0, NewOp1);
6416       Opc = RISCVISD::FSRW;
6417     }
6418     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6419     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6420     break;
6421   }
6422   case ISD::EXTRACT_VECTOR_ELT: {
6423     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6424     // type is illegal (currently only vXi64 RV32).
6425     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6426     // transferred to the destination register. We issue two of these from the
6427     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6428     // first element.
6429     SDValue Vec = N->getOperand(0);
6430     SDValue Idx = N->getOperand(1);
6431 
6432     // The vector type hasn't been legalized yet so we can't issue target
6433     // specific nodes if it needs legalization.
6434     // FIXME: We would manually legalize if it's important.
6435     if (!isTypeLegal(Vec.getValueType()))
6436       return;
6437 
6438     MVT VecVT = Vec.getSimpleValueType();
6439 
6440     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6441            VecVT.getVectorElementType() == MVT::i64 &&
6442            "Unexpected EXTRACT_VECTOR_ELT legalization");
6443 
6444     // If this is a fixed vector, we need to convert it to a scalable vector.
6445     MVT ContainerVT = VecVT;
6446     if (VecVT.isFixedLengthVector()) {
6447       ContainerVT = getContainerForFixedLengthVector(VecVT);
6448       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6449     }
6450 
6451     MVT XLenVT = Subtarget.getXLenVT();
6452 
6453     // Use a VL of 1 to avoid processing more elements than we need.
6454     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6455     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6456     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6457 
6458     // Unless the index is known to be 0, we must slide the vector down to get
6459     // the desired element into index 0.
6460     if (!isNullConstant(Idx)) {
6461       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6462                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6463     }
6464 
6465     // Extract the lower XLEN bits of the correct vector element.
6466     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6467 
6468     // To extract the upper XLEN bits of the vector element, shift the first
6469     // element right by 32 bits and re-extract the lower XLEN bits.
6470     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6471                                      DAG.getConstant(32, DL, XLenVT), VL);
6472     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6473                                  ThirtyTwoV, Mask, VL);
6474 
6475     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6476 
6477     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6478     break;
6479   }
6480   case ISD::INTRINSIC_WO_CHAIN: {
6481     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6482     switch (IntNo) {
6483     default:
6484       llvm_unreachable(
6485           "Don't know how to custom type legalize this intrinsic!");
6486     case Intrinsic::riscv_grev:
6487     case Intrinsic::riscv_gorc:
6488     case Intrinsic::riscv_bcompress:
6489     case Intrinsic::riscv_bdecompress:
6490     case Intrinsic::riscv_bfp: {
6491       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6492              "Unexpected custom legalisation");
6493       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6494       break;
6495     }
6496     case Intrinsic::riscv_fsl:
6497     case Intrinsic::riscv_fsr: {
6498       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6499              "Unexpected custom legalisation");
6500       SDValue NewOp1 =
6501           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6502       SDValue NewOp2 =
6503           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6504       SDValue NewOp3 =
6505           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6506       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6507       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6508       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6509       break;
6510     }
6511     case Intrinsic::riscv_orc_b: {
6512       // Lower to the GORCI encoding for orc.b with the operand extended.
6513       SDValue NewOp =
6514           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6515       // If Zbp is enabled, use GORCIW which will sign extend the result.
6516       unsigned Opc =
6517           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6518       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6519                                 DAG.getConstant(7, DL, MVT::i64));
6520       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6521       return;
6522     }
6523     case Intrinsic::riscv_shfl:
6524     case Intrinsic::riscv_unshfl: {
6525       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6526              "Unexpected custom legalisation");
6527       SDValue NewOp1 =
6528           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6529       SDValue NewOp2 =
6530           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6531       unsigned Opc =
6532           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6533       if (isa<ConstantSDNode>(N->getOperand(2))) {
6534         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6535                              DAG.getConstant(0xf, DL, MVT::i64));
6536         Opc =
6537             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6538       }
6539       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6540       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6541       break;
6542     }
6543     case Intrinsic::riscv_vmv_x_s: {
6544       EVT VT = N->getValueType(0);
6545       MVT XLenVT = Subtarget.getXLenVT();
6546       if (VT.bitsLT(XLenVT)) {
6547         // Simple case just extract using vmv.x.s and truncate.
6548         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6549                                       Subtarget.getXLenVT(), N->getOperand(1));
6550         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6551         return;
6552       }
6553 
6554       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6555              "Unexpected custom legalization");
6556 
6557       // We need to do the move in two steps.
6558       SDValue Vec = N->getOperand(1);
6559       MVT VecVT = Vec.getSimpleValueType();
6560 
6561       // First extract the lower XLEN bits of the element.
6562       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6563 
6564       // To extract the upper XLEN bits of the vector element, shift the first
6565       // element right by 32 bits and re-extract the lower XLEN bits.
6566       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6567       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6568       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6569       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6570                                        DAG.getConstant(32, DL, XLenVT), VL);
6571       SDValue LShr32 =
6572           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6573       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6574 
6575       Results.push_back(
6576           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6577       break;
6578     }
6579     }
6580     break;
6581   }
6582   case ISD::VECREDUCE_ADD:
6583   case ISD::VECREDUCE_AND:
6584   case ISD::VECREDUCE_OR:
6585   case ISD::VECREDUCE_XOR:
6586   case ISD::VECREDUCE_SMAX:
6587   case ISD::VECREDUCE_UMAX:
6588   case ISD::VECREDUCE_SMIN:
6589   case ISD::VECREDUCE_UMIN:
6590     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6591       Results.push_back(V);
6592     break;
6593   case ISD::VP_REDUCE_ADD:
6594   case ISD::VP_REDUCE_AND:
6595   case ISD::VP_REDUCE_OR:
6596   case ISD::VP_REDUCE_XOR:
6597   case ISD::VP_REDUCE_SMAX:
6598   case ISD::VP_REDUCE_UMAX:
6599   case ISD::VP_REDUCE_SMIN:
6600   case ISD::VP_REDUCE_UMIN:
6601     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6602       Results.push_back(V);
6603     break;
6604   case ISD::FLT_ROUNDS_: {
6605     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6606     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6607     Results.push_back(Res.getValue(0));
6608     Results.push_back(Res.getValue(1));
6609     break;
6610   }
6611   }
6612 }
6613 
6614 // A structure to hold one of the bit-manipulation patterns below. Together, a
6615 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6616 //   (or (and (shl x, 1), 0xAAAAAAAA),
6617 //       (and (srl x, 1), 0x55555555))
6618 struct RISCVBitmanipPat {
6619   SDValue Op;
6620   unsigned ShAmt;
6621   bool IsSHL;
6622 
6623   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6624     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6625   }
6626 };
6627 
6628 // Matches patterns of the form
6629 //   (and (shl x, C2), (C1 << C2))
6630 //   (and (srl x, C2), C1)
6631 //   (shl (and x, C1), C2)
6632 //   (srl (and x, (C1 << C2)), C2)
6633 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6634 // The expected masks for each shift amount are specified in BitmanipMasks where
6635 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6636 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6637 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6638 // XLen is 64.
6639 static Optional<RISCVBitmanipPat>
6640 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6641   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6642          "Unexpected number of masks");
6643   Optional<uint64_t> Mask;
6644   // Optionally consume a mask around the shift operation.
6645   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6646     Mask = Op.getConstantOperandVal(1);
6647     Op = Op.getOperand(0);
6648   }
6649   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6650     return None;
6651   bool IsSHL = Op.getOpcode() == ISD::SHL;
6652 
6653   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6654     return None;
6655   uint64_t ShAmt = Op.getConstantOperandVal(1);
6656 
6657   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6658   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6659     return None;
6660   // If we don't have enough masks for 64 bit, then we must be trying to
6661   // match SHFL so we're only allowed to shift 1/4 of the width.
6662   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6663     return None;
6664 
6665   SDValue Src = Op.getOperand(0);
6666 
6667   // The expected mask is shifted left when the AND is found around SHL
6668   // patterns.
6669   //   ((x >> 1) & 0x55555555)
6670   //   ((x << 1) & 0xAAAAAAAA)
6671   bool SHLExpMask = IsSHL;
6672 
6673   if (!Mask) {
6674     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6675     // the mask is all ones: consume that now.
6676     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6677       Mask = Src.getConstantOperandVal(1);
6678       Src = Src.getOperand(0);
6679       // The expected mask is now in fact shifted left for SRL, so reverse the
6680       // decision.
6681       //   ((x & 0xAAAAAAAA) >> 1)
6682       //   ((x & 0x55555555) << 1)
6683       SHLExpMask = !SHLExpMask;
6684     } else {
6685       // Use a default shifted mask of all-ones if there's no AND, truncated
6686       // down to the expected width. This simplifies the logic later on.
6687       Mask = maskTrailingOnes<uint64_t>(Width);
6688       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6689     }
6690   }
6691 
6692   unsigned MaskIdx = Log2_32(ShAmt);
6693   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6694 
6695   if (SHLExpMask)
6696     ExpMask <<= ShAmt;
6697 
6698   if (Mask != ExpMask)
6699     return None;
6700 
6701   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6702 }
6703 
6704 // Matches any of the following bit-manipulation patterns:
6705 //   (and (shl x, 1), (0x55555555 << 1))
6706 //   (and (srl x, 1), 0x55555555)
6707 //   (shl (and x, 0x55555555), 1)
6708 //   (srl (and x, (0x55555555 << 1)), 1)
6709 // where the shift amount and mask may vary thus:
6710 //   [1]  = 0x55555555 / 0xAAAAAAAA
6711 //   [2]  = 0x33333333 / 0xCCCCCCCC
6712 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6713 //   [8]  = 0x00FF00FF / 0xFF00FF00
6714 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6715 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6716 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6717   // These are the unshifted masks which we use to match bit-manipulation
6718   // patterns. They may be shifted left in certain circumstances.
6719   static const uint64_t BitmanipMasks[] = {
6720       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6721       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6722 
6723   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6724 }
6725 
6726 // Match the following pattern as a GREVI(W) operation
6727 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6728 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6729                                const RISCVSubtarget &Subtarget) {
6730   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6731   EVT VT = Op.getValueType();
6732 
6733   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6734     auto LHS = matchGREVIPat(Op.getOperand(0));
6735     auto RHS = matchGREVIPat(Op.getOperand(1));
6736     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6737       SDLoc DL(Op);
6738       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6739                          DAG.getConstant(LHS->ShAmt, DL, VT));
6740     }
6741   }
6742   return SDValue();
6743 }
6744 
6745 // Matches any the following pattern as a GORCI(W) operation
6746 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6747 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6748 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6749 // Note that with the variant of 3.,
6750 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6751 // the inner pattern will first be matched as GREVI and then the outer
6752 // pattern will be matched to GORC via the first rule above.
6753 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6754 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6755                                const RISCVSubtarget &Subtarget) {
6756   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6757   EVT VT = Op.getValueType();
6758 
6759   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6760     SDLoc DL(Op);
6761     SDValue Op0 = Op.getOperand(0);
6762     SDValue Op1 = Op.getOperand(1);
6763 
6764     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6765       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6766           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6767           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6768         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6769       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6770       if ((Reverse.getOpcode() == ISD::ROTL ||
6771            Reverse.getOpcode() == ISD::ROTR) &&
6772           Reverse.getOperand(0) == X &&
6773           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6774         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6775         if (RotAmt == (VT.getSizeInBits() / 2))
6776           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6777                              DAG.getConstant(RotAmt, DL, VT));
6778       }
6779       return SDValue();
6780     };
6781 
6782     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6783     if (SDValue V = MatchOROfReverse(Op0, Op1))
6784       return V;
6785     if (SDValue V = MatchOROfReverse(Op1, Op0))
6786       return V;
6787 
6788     // OR is commutable so canonicalize its OR operand to the left
6789     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6790       std::swap(Op0, Op1);
6791     if (Op0.getOpcode() != ISD::OR)
6792       return SDValue();
6793     SDValue OrOp0 = Op0.getOperand(0);
6794     SDValue OrOp1 = Op0.getOperand(1);
6795     auto LHS = matchGREVIPat(OrOp0);
6796     // OR is commutable so swap the operands and try again: x might have been
6797     // on the left
6798     if (!LHS) {
6799       std::swap(OrOp0, OrOp1);
6800       LHS = matchGREVIPat(OrOp0);
6801     }
6802     auto RHS = matchGREVIPat(Op1);
6803     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6804       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6805                          DAG.getConstant(LHS->ShAmt, DL, VT));
6806     }
6807   }
6808   return SDValue();
6809 }
6810 
6811 // Matches any of the following bit-manipulation patterns:
6812 //   (and (shl x, 1), (0x22222222 << 1))
6813 //   (and (srl x, 1), 0x22222222)
6814 //   (shl (and x, 0x22222222), 1)
6815 //   (srl (and x, (0x22222222 << 1)), 1)
6816 // where the shift amount and mask may vary thus:
6817 //   [1]  = 0x22222222 / 0x44444444
6818 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6819 //   [4]  = 0x00F000F0 / 0x0F000F00
6820 //   [8]  = 0x0000FF00 / 0x00FF0000
6821 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6822 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6823   // These are the unshifted masks which we use to match bit-manipulation
6824   // patterns. They may be shifted left in certain circumstances.
6825   static const uint64_t BitmanipMasks[] = {
6826       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6827       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6828 
6829   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6830 }
6831 
6832 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6833 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6834                                const RISCVSubtarget &Subtarget) {
6835   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6836   EVT VT = Op.getValueType();
6837 
6838   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6839     return SDValue();
6840 
6841   SDValue Op0 = Op.getOperand(0);
6842   SDValue Op1 = Op.getOperand(1);
6843 
6844   // Or is commutable so canonicalize the second OR to the LHS.
6845   if (Op0.getOpcode() != ISD::OR)
6846     std::swap(Op0, Op1);
6847   if (Op0.getOpcode() != ISD::OR)
6848     return SDValue();
6849 
6850   // We found an inner OR, so our operands are the operands of the inner OR
6851   // and the other operand of the outer OR.
6852   SDValue A = Op0.getOperand(0);
6853   SDValue B = Op0.getOperand(1);
6854   SDValue C = Op1;
6855 
6856   auto Match1 = matchSHFLPat(A);
6857   auto Match2 = matchSHFLPat(B);
6858 
6859   // If neither matched, we failed.
6860   if (!Match1 && !Match2)
6861     return SDValue();
6862 
6863   // We had at least one match. if one failed, try the remaining C operand.
6864   if (!Match1) {
6865     std::swap(A, C);
6866     Match1 = matchSHFLPat(A);
6867     if (!Match1)
6868       return SDValue();
6869   } else if (!Match2) {
6870     std::swap(B, C);
6871     Match2 = matchSHFLPat(B);
6872     if (!Match2)
6873       return SDValue();
6874   }
6875   assert(Match1 && Match2);
6876 
6877   // Make sure our matches pair up.
6878   if (!Match1->formsPairWith(*Match2))
6879     return SDValue();
6880 
6881   // All the remains is to make sure C is an AND with the same input, that masks
6882   // out the bits that are being shuffled.
6883   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6884       C.getOperand(0) != Match1->Op)
6885     return SDValue();
6886 
6887   uint64_t Mask = C.getConstantOperandVal(1);
6888 
6889   static const uint64_t BitmanipMasks[] = {
6890       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6891       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6892   };
6893 
6894   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6895   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6896   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6897 
6898   if (Mask != ExpMask)
6899     return SDValue();
6900 
6901   SDLoc DL(Op);
6902   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6903                      DAG.getConstant(Match1->ShAmt, DL, VT));
6904 }
6905 
6906 // Optimize (add (shl x, c0), (shl y, c1)) ->
6907 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6908 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6909                                   const RISCVSubtarget &Subtarget) {
6910   // Perform this optimization only in the zba extension.
6911   if (!Subtarget.hasStdExtZba())
6912     return SDValue();
6913 
6914   // Skip for vector types and larger types.
6915   EVT VT = N->getValueType(0);
6916   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6917     return SDValue();
6918 
6919   // The two operand nodes must be SHL and have no other use.
6920   SDValue N0 = N->getOperand(0);
6921   SDValue N1 = N->getOperand(1);
6922   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6923       !N0->hasOneUse() || !N1->hasOneUse())
6924     return SDValue();
6925 
6926   // Check c0 and c1.
6927   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6928   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6929   if (!N0C || !N1C)
6930     return SDValue();
6931   int64_t C0 = N0C->getSExtValue();
6932   int64_t C1 = N1C->getSExtValue();
6933   if (C0 <= 0 || C1 <= 0)
6934     return SDValue();
6935 
6936   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6937   int64_t Bits = std::min(C0, C1);
6938   int64_t Diff = std::abs(C0 - C1);
6939   if (Diff != 1 && Diff != 2 && Diff != 3)
6940     return SDValue();
6941 
6942   // Build nodes.
6943   SDLoc DL(N);
6944   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6945   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6946   SDValue NA0 =
6947       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6948   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6949   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6950 }
6951 
6952 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6953 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6954 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6955 // not undo itself, but they are redundant.
6956 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6957   SDValue Src = N->getOperand(0);
6958 
6959   if (Src.getOpcode() != N->getOpcode())
6960     return SDValue();
6961 
6962   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6963       !isa<ConstantSDNode>(Src.getOperand(1)))
6964     return SDValue();
6965 
6966   unsigned ShAmt1 = N->getConstantOperandVal(1);
6967   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6968   Src = Src.getOperand(0);
6969 
6970   unsigned CombinedShAmt;
6971   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6972     CombinedShAmt = ShAmt1 | ShAmt2;
6973   else
6974     CombinedShAmt = ShAmt1 ^ ShAmt2;
6975 
6976   if (CombinedShAmt == 0)
6977     return Src;
6978 
6979   SDLoc DL(N);
6980   return DAG.getNode(
6981       N->getOpcode(), DL, N->getValueType(0), Src,
6982       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6983 }
6984 
6985 // Combine a constant select operand into its use:
6986 //
6987 // (and (select cond, -1, c), x)
6988 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6989 // (or  (select cond, 0, c), x)
6990 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6991 // (xor (select cond, 0, c), x)
6992 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6993 // (add (select cond, 0, c), x)
6994 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6995 // (sub x, (select cond, 0, c))
6996 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6997 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6998                                    SelectionDAG &DAG, bool AllOnes) {
6999   EVT VT = N->getValueType(0);
7000 
7001   // Skip vectors.
7002   if (VT.isVector())
7003     return SDValue();
7004 
7005   if ((Slct.getOpcode() != ISD::SELECT &&
7006        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7007       !Slct.hasOneUse())
7008     return SDValue();
7009 
7010   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7011     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7012   };
7013 
7014   bool SwapSelectOps;
7015   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7016   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7017   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7018   SDValue NonConstantVal;
7019   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7020     SwapSelectOps = false;
7021     NonConstantVal = FalseVal;
7022   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7023     SwapSelectOps = true;
7024     NonConstantVal = TrueVal;
7025   } else
7026     return SDValue();
7027 
7028   // Slct is now know to be the desired identity constant when CC is true.
7029   TrueVal = OtherOp;
7030   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7031   // Unless SwapSelectOps says the condition should be false.
7032   if (SwapSelectOps)
7033     std::swap(TrueVal, FalseVal);
7034 
7035   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7036     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7037                        {Slct.getOperand(0), Slct.getOperand(1),
7038                         Slct.getOperand(2), TrueVal, FalseVal});
7039 
7040   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7041                      {Slct.getOperand(0), TrueVal, FalseVal});
7042 }
7043 
7044 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7045 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7046                                               bool AllOnes) {
7047   SDValue N0 = N->getOperand(0);
7048   SDValue N1 = N->getOperand(1);
7049   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7050     return Result;
7051   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7052     return Result;
7053   return SDValue();
7054 }
7055 
7056 // Transform (add (mul x, c0), c1) ->
7057 //           (add (mul (add x, c1/c0), c0), c1%c0).
7058 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7059 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7060 // to an infinite loop in DAGCombine if transformed.
7061 // Or transform (add (mul x, c0), c1) ->
7062 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7063 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7064 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7065 // lead to an infinite loop in DAGCombine if transformed.
7066 // Or transform (add (mul x, c0), c1) ->
7067 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7068 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7069 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7070 // lead to an infinite loop in DAGCombine if transformed.
7071 // Or transform (add (mul x, c0), c1) ->
7072 //              (mul (add x, c1/c0), c0).
7073 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7074 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7075                                      const RISCVSubtarget &Subtarget) {
7076   // Skip for vector types and larger types.
7077   EVT VT = N->getValueType(0);
7078   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7079     return SDValue();
7080   // The first operand node must be a MUL and has no other use.
7081   SDValue N0 = N->getOperand(0);
7082   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7083     return SDValue();
7084   // Check if c0 and c1 match above conditions.
7085   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7086   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7087   if (!N0C || !N1C)
7088     return SDValue();
7089   int64_t C0 = N0C->getSExtValue();
7090   int64_t C1 = N1C->getSExtValue();
7091   int64_t CA, CB;
7092   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7093     return SDValue();
7094   // Search for proper CA (non-zero) and CB that both are simm12.
7095   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7096       !isInt<12>(C0 * (C1 / C0))) {
7097     CA = C1 / C0;
7098     CB = C1 % C0;
7099   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7100              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7101     CA = C1 / C0 + 1;
7102     CB = C1 % C0 - C0;
7103   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7104              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7105     CA = C1 / C0 - 1;
7106     CB = C1 % C0 + C0;
7107   } else
7108     return SDValue();
7109   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7110   SDLoc DL(N);
7111   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7112                              DAG.getConstant(CA, DL, VT));
7113   SDValue New1 =
7114       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7115   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7116 }
7117 
7118 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7119                                  const RISCVSubtarget &Subtarget) {
7120   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7121     return V;
7122   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7123     return V;
7124   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7125   //      (select lhs, rhs, cc, x, (add x, y))
7126   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7127 }
7128 
7129 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7130   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7131   //      (select lhs, rhs, cc, x, (sub x, y))
7132   SDValue N0 = N->getOperand(0);
7133   SDValue N1 = N->getOperand(1);
7134   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7135 }
7136 
7137 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7138   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7139   //      (select lhs, rhs, cc, x, (and x, y))
7140   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7141 }
7142 
7143 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7144                                 const RISCVSubtarget &Subtarget) {
7145   if (Subtarget.hasStdExtZbp()) {
7146     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7147       return GREV;
7148     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7149       return GORC;
7150     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7151       return SHFL;
7152   }
7153 
7154   // fold (or (select cond, 0, y), x) ->
7155   //      (select cond, x, (or x, y))
7156   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7157 }
7158 
7159 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7160   // fold (xor (select cond, 0, y), x) ->
7161   //      (select cond, x, (xor x, y))
7162   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7163 }
7164 
7165 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7166 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7167 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7168 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7169 // ADDW/SUBW/MULW.
7170 static SDValue performANY_EXTENDCombine(SDNode *N,
7171                                         TargetLowering::DAGCombinerInfo &DCI,
7172                                         const RISCVSubtarget &Subtarget) {
7173   if (!Subtarget.is64Bit())
7174     return SDValue();
7175 
7176   SelectionDAG &DAG = DCI.DAG;
7177 
7178   SDValue Src = N->getOperand(0);
7179   EVT VT = N->getValueType(0);
7180   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7181     return SDValue();
7182 
7183   // The opcode must be one that can implicitly sign_extend.
7184   // FIXME: Additional opcodes.
7185   switch (Src.getOpcode()) {
7186   default:
7187     return SDValue();
7188   case ISD::MUL:
7189     if (!Subtarget.hasStdExtM())
7190       return SDValue();
7191     LLVM_FALLTHROUGH;
7192   case ISD::ADD:
7193   case ISD::SUB:
7194     break;
7195   }
7196 
7197   // Only handle cases where the result is used by a CopyToReg. That likely
7198   // means the value is a liveout of the basic block. This helps prevent
7199   // infinite combine loops like PR51206.
7200   if (none_of(N->uses(),
7201               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7202     return SDValue();
7203 
7204   SmallVector<SDNode *, 4> SetCCs;
7205   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7206                             UE = Src.getNode()->use_end();
7207        UI != UE; ++UI) {
7208     SDNode *User = *UI;
7209     if (User == N)
7210       continue;
7211     if (UI.getUse().getResNo() != Src.getResNo())
7212       continue;
7213     // All i32 setccs are legalized by sign extending operands.
7214     if (User->getOpcode() == ISD::SETCC) {
7215       SetCCs.push_back(User);
7216       continue;
7217     }
7218     // We don't know if we can extend this user.
7219     break;
7220   }
7221 
7222   // If we don't have any SetCCs, this isn't worthwhile.
7223   if (SetCCs.empty())
7224     return SDValue();
7225 
7226   SDLoc DL(N);
7227   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7228   DCI.CombineTo(N, SExt);
7229 
7230   // Promote all the setccs.
7231   for (SDNode *SetCC : SetCCs) {
7232     SmallVector<SDValue, 4> Ops;
7233 
7234     for (unsigned j = 0; j != 2; ++j) {
7235       SDValue SOp = SetCC->getOperand(j);
7236       if (SOp == Src)
7237         Ops.push_back(SExt);
7238       else
7239         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7240     }
7241 
7242     Ops.push_back(SetCC->getOperand(2));
7243     DCI.CombineTo(SetCC,
7244                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7245   }
7246   return SDValue(N, 0);
7247 }
7248 
7249 // Try to form VWMUL or VWMULU.
7250 // FIXME: Support VWMULSU.
7251 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7252                                        bool Commute) {
7253   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7254   SDValue Op0 = N->getOperand(0);
7255   SDValue Op1 = N->getOperand(1);
7256   if (Commute)
7257     std::swap(Op0, Op1);
7258 
7259   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7260   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7261   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7262     return SDValue();
7263 
7264   SDValue Mask = N->getOperand(2);
7265   SDValue VL = N->getOperand(3);
7266 
7267   // Make sure the mask and VL match.
7268   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7269     return SDValue();
7270 
7271   MVT VT = N->getSimpleValueType(0);
7272 
7273   // Determine the narrow size for a widening multiply.
7274   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7275   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7276                                   VT.getVectorElementCount());
7277 
7278   SDLoc DL(N);
7279 
7280   // See if the other operand is the same opcode.
7281   if (Op0.getOpcode() == Op1.getOpcode()) {
7282     if (!Op1.hasOneUse())
7283       return SDValue();
7284 
7285     // Make sure the mask and VL match.
7286     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7287       return SDValue();
7288 
7289     Op1 = Op1.getOperand(0);
7290   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7291     // The operand is a splat of a scalar.
7292 
7293     // The VL must be the same.
7294     if (Op1.getOperand(1) != VL)
7295       return SDValue();
7296 
7297     // Get the scalar value.
7298     Op1 = Op1.getOperand(0);
7299 
7300     // See if have enough sign bits or zero bits in the scalar to use a
7301     // widening multiply by splatting to smaller element size.
7302     unsigned EltBits = VT.getScalarSizeInBits();
7303     unsigned ScalarBits = Op1.getValueSizeInBits();
7304     // Make sure we're getting all element bits from the scalar register.
7305     // FIXME: Support implicit sign extension of vmv.v.x?
7306     if (ScalarBits < EltBits)
7307       return SDValue();
7308 
7309     if (IsSignExt) {
7310       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7311         return SDValue();
7312     } else {
7313       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7314       if (!DAG.MaskedValueIsZero(Op1, Mask))
7315         return SDValue();
7316     }
7317 
7318     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7319   } else
7320     return SDValue();
7321 
7322   Op0 = Op0.getOperand(0);
7323 
7324   // Re-introduce narrower extends if needed.
7325   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7326   if (Op0.getValueType() != NarrowVT)
7327     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7328   if (Op1.getValueType() != NarrowVT)
7329     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7330 
7331   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7332   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7333 }
7334 
7335 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7336   switch (Op.getOpcode()) {
7337   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7338   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7339   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7340   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7341   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7342   }
7343 
7344   return RISCVFPRndMode::Invalid;
7345 }
7346 
7347 // Fold
7348 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7349 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7350 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7351 //   (fp_to_int (fceil X))      -> fcvt X, rup
7352 //   (fp_to_int (fround X))     -> fcvt X, rmm
7353 static SDValue performFP_TO_INTCombine(SDNode *N,
7354                                        TargetLowering::DAGCombinerInfo &DCI,
7355                                        const RISCVSubtarget &Subtarget) {
7356   SelectionDAG &DAG = DCI.DAG;
7357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7358   MVT XLenVT = Subtarget.getXLenVT();
7359 
7360   // Only handle XLen or i32 types. Other types narrower than XLen will
7361   // eventually be legalized to XLenVT.
7362   EVT VT = N->getValueType(0);
7363   if (VT != MVT::i32 && VT != XLenVT)
7364     return SDValue();
7365 
7366   SDValue Src = N->getOperand(0);
7367 
7368   // Ensure the FP type is also legal.
7369   if (!TLI.isTypeLegal(Src.getValueType()))
7370     return SDValue();
7371 
7372   // Don't do this for f16 with Zfhmin and not Zfh.
7373   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7374     return SDValue();
7375 
7376   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7377   if (FRM == RISCVFPRndMode::Invalid)
7378     return SDValue();
7379 
7380   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7381 
7382   unsigned Opc;
7383   if (VT == XLenVT)
7384     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7385   else
7386     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7387 
7388   SDLoc DL(N);
7389   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7390                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7391   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7392 }
7393 
7394 // Fold
7395 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7396 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7397 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7398 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7399 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7400 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7401                                        TargetLowering::DAGCombinerInfo &DCI,
7402                                        const RISCVSubtarget &Subtarget) {
7403   SelectionDAG &DAG = DCI.DAG;
7404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7405   MVT XLenVT = Subtarget.getXLenVT();
7406 
7407   // Only handle XLen types. Other types narrower than XLen will eventually be
7408   // legalized to XLenVT.
7409   EVT DstVT = N->getValueType(0);
7410   if (DstVT != XLenVT)
7411     return SDValue();
7412 
7413   SDValue Src = N->getOperand(0);
7414 
7415   // Ensure the FP type is also legal.
7416   if (!TLI.isTypeLegal(Src.getValueType()))
7417     return SDValue();
7418 
7419   // Don't do this for f16 with Zfhmin and not Zfh.
7420   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7421     return SDValue();
7422 
7423   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7424 
7425   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7426   if (FRM == RISCVFPRndMode::Invalid)
7427     return SDValue();
7428 
7429   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7430 
7431   unsigned Opc;
7432   if (SatVT == DstVT)
7433     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7434   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7435     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7436   else
7437     return SDValue();
7438   // FIXME: Support other SatVTs by clamping before or after the conversion.
7439 
7440   Src = Src.getOperand(0);
7441 
7442   SDLoc DL(N);
7443   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7444                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7445 
7446   // RISCV FP-to-int conversions saturate to the destination register size, but
7447   // don't produce 0 for nan.
7448   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7449   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7450 }
7451 
7452 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7453                                                DAGCombinerInfo &DCI) const {
7454   SelectionDAG &DAG = DCI.DAG;
7455 
7456   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7457   // bits are demanded. N will be added to the Worklist if it was not deleted.
7458   // Caller should return SDValue(N, 0) if this returns true.
7459   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7460     SDValue Op = N->getOperand(OpNo);
7461     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7462     if (!SimplifyDemandedBits(Op, Mask, DCI))
7463       return false;
7464 
7465     if (N->getOpcode() != ISD::DELETED_NODE)
7466       DCI.AddToWorklist(N);
7467     return true;
7468   };
7469 
7470   switch (N->getOpcode()) {
7471   default:
7472     break;
7473   case RISCVISD::SplitF64: {
7474     SDValue Op0 = N->getOperand(0);
7475     // If the input to SplitF64 is just BuildPairF64 then the operation is
7476     // redundant. Instead, use BuildPairF64's operands directly.
7477     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7478       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7479 
7480     SDLoc DL(N);
7481 
7482     // It's cheaper to materialise two 32-bit integers than to load a double
7483     // from the constant pool and transfer it to integer registers through the
7484     // stack.
7485     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7486       APInt V = C->getValueAPF().bitcastToAPInt();
7487       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7488       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7489       return DCI.CombineTo(N, Lo, Hi);
7490     }
7491 
7492     // This is a target-specific version of a DAGCombine performed in
7493     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7494     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7495     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7496     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7497         !Op0.getNode()->hasOneUse())
7498       break;
7499     SDValue NewSplitF64 =
7500         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7501                     Op0.getOperand(0));
7502     SDValue Lo = NewSplitF64.getValue(0);
7503     SDValue Hi = NewSplitF64.getValue(1);
7504     APInt SignBit = APInt::getSignMask(32);
7505     if (Op0.getOpcode() == ISD::FNEG) {
7506       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7507                                   DAG.getConstant(SignBit, DL, MVT::i32));
7508       return DCI.CombineTo(N, Lo, NewHi);
7509     }
7510     assert(Op0.getOpcode() == ISD::FABS);
7511     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7512                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7513     return DCI.CombineTo(N, Lo, NewHi);
7514   }
7515   case RISCVISD::SLLW:
7516   case RISCVISD::SRAW:
7517   case RISCVISD::SRLW:
7518   case RISCVISD::ROLW:
7519   case RISCVISD::RORW: {
7520     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7521     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7522         SimplifyDemandedLowBitsHelper(1, 5))
7523       return SDValue(N, 0);
7524     break;
7525   }
7526   case RISCVISD::CLZW:
7527   case RISCVISD::CTZW: {
7528     // Only the lower 32 bits of the first operand are read
7529     if (SimplifyDemandedLowBitsHelper(0, 32))
7530       return SDValue(N, 0);
7531     break;
7532   }
7533   case RISCVISD::GREV:
7534   case RISCVISD::GORC: {
7535     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7536     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7537     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7538     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7539       return SDValue(N, 0);
7540 
7541     return combineGREVI_GORCI(N, DAG);
7542   }
7543   case RISCVISD::GREVW:
7544   case RISCVISD::GORCW: {
7545     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7546     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7547         SimplifyDemandedLowBitsHelper(1, 5))
7548       return SDValue(N, 0);
7549 
7550     return combineGREVI_GORCI(N, DAG);
7551   }
7552   case RISCVISD::SHFL:
7553   case RISCVISD::UNSHFL: {
7554     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7555     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7556     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7557     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7558       return SDValue(N, 0);
7559 
7560     break;
7561   }
7562   case RISCVISD::SHFLW:
7563   case RISCVISD::UNSHFLW: {
7564     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7565     SDValue LHS = N->getOperand(0);
7566     SDValue RHS = N->getOperand(1);
7567     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7568     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7569     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7570         SimplifyDemandedLowBitsHelper(1, 4))
7571       return SDValue(N, 0);
7572 
7573     break;
7574   }
7575   case RISCVISD::BCOMPRESSW:
7576   case RISCVISD::BDECOMPRESSW: {
7577     // Only the lower 32 bits of LHS and RHS are read.
7578     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7579         SimplifyDemandedLowBitsHelper(1, 32))
7580       return SDValue(N, 0);
7581 
7582     break;
7583   }
7584   case RISCVISD::FMV_X_ANYEXTH:
7585   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7586     SDLoc DL(N);
7587     SDValue Op0 = N->getOperand(0);
7588     MVT VT = N->getSimpleValueType(0);
7589     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7590     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7591     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7592     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7593          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7594         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7595          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7596       assert(Op0.getOperand(0).getValueType() == VT &&
7597              "Unexpected value type!");
7598       return Op0.getOperand(0);
7599     }
7600 
7601     // This is a target-specific version of a DAGCombine performed in
7602     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7603     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7604     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7605     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7606         !Op0.getNode()->hasOneUse())
7607       break;
7608     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7609     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7610     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7611     if (Op0.getOpcode() == ISD::FNEG)
7612       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7613                          DAG.getConstant(SignBit, DL, VT));
7614 
7615     assert(Op0.getOpcode() == ISD::FABS);
7616     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7617                        DAG.getConstant(~SignBit, DL, VT));
7618   }
7619   case ISD::ADD:
7620     return performADDCombine(N, DAG, Subtarget);
7621   case ISD::SUB:
7622     return performSUBCombine(N, DAG);
7623   case ISD::AND:
7624     return performANDCombine(N, DAG);
7625   case ISD::OR:
7626     return performORCombine(N, DAG, Subtarget);
7627   case ISD::XOR:
7628     return performXORCombine(N, DAG);
7629   case ISD::ANY_EXTEND:
7630     return performANY_EXTENDCombine(N, DCI, Subtarget);
7631   case ISD::ZERO_EXTEND:
7632     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7633     // type legalization. This is safe because fp_to_uint produces poison if
7634     // it overflows.
7635     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7636       SDValue Src = N->getOperand(0);
7637       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7638           isTypeLegal(Src.getOperand(0).getValueType()))
7639         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7640                            Src.getOperand(0));
7641       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7642           isTypeLegal(Src.getOperand(1).getValueType())) {
7643         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7644         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7645                                   Src.getOperand(0), Src.getOperand(1));
7646         DCI.CombineTo(N, Res);
7647         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7648         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7649         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7650       }
7651     }
7652     return SDValue();
7653   case RISCVISD::SELECT_CC: {
7654     // Transform
7655     SDValue LHS = N->getOperand(0);
7656     SDValue RHS = N->getOperand(1);
7657     SDValue TrueV = N->getOperand(3);
7658     SDValue FalseV = N->getOperand(4);
7659 
7660     // If the True and False values are the same, we don't need a select_cc.
7661     if (TrueV == FalseV)
7662       return TrueV;
7663 
7664     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7665     if (!ISD::isIntEqualitySetCC(CCVal))
7666       break;
7667 
7668     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7669     //      (select_cc X, Y, lt, trueV, falseV)
7670     // Sometimes the setcc is introduced after select_cc has been formed.
7671     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7672         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7673       // If we're looking for eq 0 instead of ne 0, we need to invert the
7674       // condition.
7675       bool Invert = CCVal == ISD::SETEQ;
7676       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7677       if (Invert)
7678         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7679 
7680       SDLoc DL(N);
7681       RHS = LHS.getOperand(1);
7682       LHS = LHS.getOperand(0);
7683       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7684 
7685       SDValue TargetCC = DAG.getCondCode(CCVal);
7686       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7687                          {LHS, RHS, TargetCC, TrueV, FalseV});
7688     }
7689 
7690     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7691     //      (select_cc X, Y, eq/ne, trueV, falseV)
7692     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7693       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7694                          {LHS.getOperand(0), LHS.getOperand(1),
7695                           N->getOperand(2), TrueV, FalseV});
7696     // (select_cc X, 1, setne, trueV, falseV) ->
7697     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7698     // This can occur when legalizing some floating point comparisons.
7699     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7700     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7701       SDLoc DL(N);
7702       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7703       SDValue TargetCC = DAG.getCondCode(CCVal);
7704       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7705       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7706                          {LHS, RHS, TargetCC, TrueV, FalseV});
7707     }
7708 
7709     break;
7710   }
7711   case RISCVISD::BR_CC: {
7712     SDValue LHS = N->getOperand(1);
7713     SDValue RHS = N->getOperand(2);
7714     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7715     if (!ISD::isIntEqualitySetCC(CCVal))
7716       break;
7717 
7718     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7719     //      (br_cc X, Y, lt, dest)
7720     // Sometimes the setcc is introduced after br_cc has been formed.
7721     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7722         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7723       // If we're looking for eq 0 instead of ne 0, we need to invert the
7724       // condition.
7725       bool Invert = CCVal == ISD::SETEQ;
7726       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7727       if (Invert)
7728         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7729 
7730       SDLoc DL(N);
7731       RHS = LHS.getOperand(1);
7732       LHS = LHS.getOperand(0);
7733       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7734 
7735       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7736                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7737                          N->getOperand(4));
7738     }
7739 
7740     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7741     //      (br_cc X, Y, eq/ne, trueV, falseV)
7742     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7743       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7744                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7745                          N->getOperand(3), N->getOperand(4));
7746 
7747     // (br_cc X, 1, setne, br_cc) ->
7748     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7749     // This can occur when legalizing some floating point comparisons.
7750     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7751     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7752       SDLoc DL(N);
7753       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7754       SDValue TargetCC = DAG.getCondCode(CCVal);
7755       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7756       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7757                          N->getOperand(0), LHS, RHS, TargetCC,
7758                          N->getOperand(4));
7759     }
7760     break;
7761   }
7762   case ISD::FP_TO_SINT:
7763   case ISD::FP_TO_UINT:
7764     return performFP_TO_INTCombine(N, DCI, Subtarget);
7765   case ISD::FP_TO_SINT_SAT:
7766   case ISD::FP_TO_UINT_SAT:
7767     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
7768   case ISD::FCOPYSIGN: {
7769     EVT VT = N->getValueType(0);
7770     if (!VT.isVector())
7771       break;
7772     // There is a form of VFSGNJ which injects the negated sign of its second
7773     // operand. Try and bubble any FNEG up after the extend/round to produce
7774     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7775     // TRUNC=1.
7776     SDValue In2 = N->getOperand(1);
7777     // Avoid cases where the extend/round has multiple uses, as duplicating
7778     // those is typically more expensive than removing a fneg.
7779     if (!In2.hasOneUse())
7780       break;
7781     if (In2.getOpcode() != ISD::FP_EXTEND &&
7782         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7783       break;
7784     In2 = In2.getOperand(0);
7785     if (In2.getOpcode() != ISD::FNEG)
7786       break;
7787     SDLoc DL(N);
7788     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7789     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7790                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7791   }
7792   case ISD::MGATHER:
7793   case ISD::MSCATTER:
7794   case ISD::VP_GATHER:
7795   case ISD::VP_SCATTER: {
7796     if (!DCI.isBeforeLegalize())
7797       break;
7798     SDValue Index, ScaleOp;
7799     bool IsIndexScaled = false;
7800     bool IsIndexSigned = false;
7801     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7802       Index = VPGSN->getIndex();
7803       ScaleOp = VPGSN->getScale();
7804       IsIndexScaled = VPGSN->isIndexScaled();
7805       IsIndexSigned = VPGSN->isIndexSigned();
7806     } else {
7807       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7808       Index = MGSN->getIndex();
7809       ScaleOp = MGSN->getScale();
7810       IsIndexScaled = MGSN->isIndexScaled();
7811       IsIndexSigned = MGSN->isIndexSigned();
7812     }
7813     EVT IndexVT = Index.getValueType();
7814     MVT XLenVT = Subtarget.getXLenVT();
7815     // RISCV indexed loads only support the "unsigned unscaled" addressing
7816     // mode, so anything else must be manually legalized.
7817     bool NeedsIdxLegalization =
7818         IsIndexScaled ||
7819         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7820     if (!NeedsIdxLegalization)
7821       break;
7822 
7823     SDLoc DL(N);
7824 
7825     // Any index legalization should first promote to XLenVT, so we don't lose
7826     // bits when scaling. This may create an illegal index type so we let
7827     // LLVM's legalization take care of the splitting.
7828     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7829     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7830       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7831       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7832                           DL, IndexVT, Index);
7833     }
7834 
7835     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7836     if (IsIndexScaled && Scale != 1) {
7837       // Manually scale the indices by the element size.
7838       // TODO: Sanitize the scale operand here?
7839       // TODO: For VP nodes, should we use VP_SHL here?
7840       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7841       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7842       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7843     }
7844 
7845     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7846     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7847       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7848                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7849                               VPGN->getScale(), VPGN->getMask(),
7850                               VPGN->getVectorLength()},
7851                              VPGN->getMemOperand(), NewIndexTy);
7852     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7853       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7854                               {VPSN->getChain(), VPSN->getValue(),
7855                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7856                                VPSN->getMask(), VPSN->getVectorLength()},
7857                               VPSN->getMemOperand(), NewIndexTy);
7858     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7859       return DAG.getMaskedGather(
7860           N->getVTList(), MGN->getMemoryVT(), DL,
7861           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7862            MGN->getBasePtr(), Index, MGN->getScale()},
7863           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7864     const auto *MSN = cast<MaskedScatterSDNode>(N);
7865     return DAG.getMaskedScatter(
7866         N->getVTList(), MSN->getMemoryVT(), DL,
7867         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7868          Index, MSN->getScale()},
7869         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7870   }
7871   case RISCVISD::SRA_VL:
7872   case RISCVISD::SRL_VL:
7873   case RISCVISD::SHL_VL: {
7874     SDValue ShAmt = N->getOperand(1);
7875     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7876       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7877       SDLoc DL(N);
7878       SDValue VL = N->getOperand(3);
7879       EVT VT = N->getValueType(0);
7880       ShAmt =
7881           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7882       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7883                          N->getOperand(2), N->getOperand(3));
7884     }
7885     break;
7886   }
7887   case ISD::SRA:
7888   case ISD::SRL:
7889   case ISD::SHL: {
7890     SDValue ShAmt = N->getOperand(1);
7891     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7892       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7893       SDLoc DL(N);
7894       EVT VT = N->getValueType(0);
7895       ShAmt =
7896           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7897       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7898     }
7899     break;
7900   }
7901   case RISCVISD::MUL_VL:
7902     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
7903       return V;
7904     // Mul is commutative.
7905     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
7906   case ISD::STORE: {
7907     auto *Store = cast<StoreSDNode>(N);
7908     SDValue Val = Store->getValue();
7909     // Combine store of vmv.x.s to vse with VL of 1.
7910     // FIXME: Support FP.
7911     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7912       SDValue Src = Val.getOperand(0);
7913       EVT VecVT = Src.getValueType();
7914       EVT MemVT = Store->getMemoryVT();
7915       // The memory VT and the element type must match.
7916       if (VecVT.getVectorElementType() == MemVT) {
7917         SDLoc DL(N);
7918         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7919         return DAG.getStoreVP(
7920             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
7921             DAG.getConstant(1, DL, MaskVT),
7922             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
7923             Store->getMemOperand(), Store->getAddressingMode(),
7924             Store->isTruncatingStore(), /*IsCompress*/ false);
7925       }
7926     }
7927 
7928     break;
7929   }
7930   }
7931 
7932   return SDValue();
7933 }
7934 
7935 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7936     const SDNode *N, CombineLevel Level) const {
7937   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7938   // materialised in fewer instructions than `(OP _, c1)`:
7939   //
7940   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7941   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7942   SDValue N0 = N->getOperand(0);
7943   EVT Ty = N0.getValueType();
7944   if (Ty.isScalarInteger() &&
7945       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7946     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7947     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7948     if (C1 && C2) {
7949       const APInt &C1Int = C1->getAPIntValue();
7950       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7951 
7952       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7953       // and the combine should happen, to potentially allow further combines
7954       // later.
7955       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7956           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7957         return true;
7958 
7959       // We can materialise `c1` in an add immediate, so it's "free", and the
7960       // combine should be prevented.
7961       if (C1Int.getMinSignedBits() <= 64 &&
7962           isLegalAddImmediate(C1Int.getSExtValue()))
7963         return false;
7964 
7965       // Neither constant will fit into an immediate, so find materialisation
7966       // costs.
7967       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7968                                               Subtarget.getFeatureBits(),
7969                                               /*CompressionCost*/true);
7970       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7971           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7972           /*CompressionCost*/true);
7973 
7974       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7975       // combine should be prevented.
7976       if (C1Cost < ShiftedC1Cost)
7977         return false;
7978     }
7979   }
7980   return true;
7981 }
7982 
7983 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7984     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7985     TargetLoweringOpt &TLO) const {
7986   // Delay this optimization as late as possible.
7987   if (!TLO.LegalOps)
7988     return false;
7989 
7990   EVT VT = Op.getValueType();
7991   if (VT.isVector())
7992     return false;
7993 
7994   // Only handle AND for now.
7995   if (Op.getOpcode() != ISD::AND)
7996     return false;
7997 
7998   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7999   if (!C)
8000     return false;
8001 
8002   const APInt &Mask = C->getAPIntValue();
8003 
8004   // Clear all non-demanded bits initially.
8005   APInt ShrunkMask = Mask & DemandedBits;
8006 
8007   // Try to make a smaller immediate by setting undemanded bits.
8008 
8009   APInt ExpandedMask = Mask | ~DemandedBits;
8010 
8011   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8012     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8013   };
8014   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8015     if (NewMask == Mask)
8016       return true;
8017     SDLoc DL(Op);
8018     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8019     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8020     return TLO.CombineTo(Op, NewOp);
8021   };
8022 
8023   // If the shrunk mask fits in sign extended 12 bits, let the target
8024   // independent code apply it.
8025   if (ShrunkMask.isSignedIntN(12))
8026     return false;
8027 
8028   // Preserve (and X, 0xffff) when zext.h is supported.
8029   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8030     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8031     if (IsLegalMask(NewMask))
8032       return UseMask(NewMask);
8033   }
8034 
8035   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8036   if (VT == MVT::i64) {
8037     APInt NewMask = APInt(64, 0xffffffff);
8038     if (IsLegalMask(NewMask))
8039       return UseMask(NewMask);
8040   }
8041 
8042   // For the remaining optimizations, we need to be able to make a negative
8043   // number through a combination of mask and undemanded bits.
8044   if (!ExpandedMask.isNegative())
8045     return false;
8046 
8047   // What is the fewest number of bits we need to represent the negative number.
8048   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8049 
8050   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8051   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8052   APInt NewMask = ShrunkMask;
8053   if (MinSignedBits <= 12)
8054     NewMask.setBitsFrom(11);
8055   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8056     NewMask.setBitsFrom(31);
8057   else
8058     return false;
8059 
8060   // Check that our new mask is a subset of the demanded mask.
8061   assert(IsLegalMask(NewMask));
8062   return UseMask(NewMask);
8063 }
8064 
8065 static void computeGREV(APInt &Src, unsigned ShAmt) {
8066   ShAmt &= Src.getBitWidth() - 1;
8067   uint64_t x = Src.getZExtValue();
8068   if (ShAmt & 1)
8069     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8070   if (ShAmt & 2)
8071     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8072   if (ShAmt & 4)
8073     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8074   if (ShAmt & 8)
8075     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8076   if (ShAmt & 16)
8077     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8078   if (ShAmt & 32)
8079     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8080   Src = x;
8081 }
8082 
8083 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8084                                                         KnownBits &Known,
8085                                                         const APInt &DemandedElts,
8086                                                         const SelectionDAG &DAG,
8087                                                         unsigned Depth) const {
8088   unsigned BitWidth = Known.getBitWidth();
8089   unsigned Opc = Op.getOpcode();
8090   assert((Opc >= ISD::BUILTIN_OP_END ||
8091           Opc == ISD::INTRINSIC_WO_CHAIN ||
8092           Opc == ISD::INTRINSIC_W_CHAIN ||
8093           Opc == ISD::INTRINSIC_VOID) &&
8094          "Should use MaskedValueIsZero if you don't know whether Op"
8095          " is a target node!");
8096 
8097   Known.resetAll();
8098   switch (Opc) {
8099   default: break;
8100   case RISCVISD::SELECT_CC: {
8101     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8102     // If we don't know any bits, early out.
8103     if (Known.isUnknown())
8104       break;
8105     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8106 
8107     // Only known if known in both the LHS and RHS.
8108     Known = KnownBits::commonBits(Known, Known2);
8109     break;
8110   }
8111   case RISCVISD::REMUW: {
8112     KnownBits Known2;
8113     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8114     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8115     // We only care about the lower 32 bits.
8116     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8117     // Restore the original width by sign extending.
8118     Known = Known.sext(BitWidth);
8119     break;
8120   }
8121   case RISCVISD::DIVUW: {
8122     KnownBits Known2;
8123     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8124     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8125     // We only care about the lower 32 bits.
8126     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8127     // Restore the original width by sign extending.
8128     Known = Known.sext(BitWidth);
8129     break;
8130   }
8131   case RISCVISD::CTZW: {
8132     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8133     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8134     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8135     Known.Zero.setBitsFrom(LowBits);
8136     break;
8137   }
8138   case RISCVISD::CLZW: {
8139     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8140     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8141     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8142     Known.Zero.setBitsFrom(LowBits);
8143     break;
8144   }
8145   case RISCVISD::GREV:
8146   case RISCVISD::GREVW: {
8147     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8148       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8149       if (Opc == RISCVISD::GREVW)
8150         Known = Known.trunc(32);
8151       unsigned ShAmt = C->getZExtValue();
8152       computeGREV(Known.Zero, ShAmt);
8153       computeGREV(Known.One, ShAmt);
8154       if (Opc == RISCVISD::GREVW)
8155         Known = Known.sext(BitWidth);
8156     }
8157     break;
8158   }
8159   case RISCVISD::READ_VLENB:
8160     // We assume VLENB is at least 16 bytes.
8161     Known.Zero.setLowBits(4);
8162     // We assume VLENB is no more than 65536 / 8 bytes.
8163     Known.Zero.setBitsFrom(14);
8164     break;
8165   case ISD::INTRINSIC_W_CHAIN:
8166   case ISD::INTRINSIC_WO_CHAIN: {
8167     unsigned IntNo =
8168         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8169     switch (IntNo) {
8170     default:
8171       // We can't do anything for most intrinsics.
8172       break;
8173     case Intrinsic::riscv_vsetvli:
8174     case Intrinsic::riscv_vsetvlimax:
8175     case Intrinsic::riscv_vsetvli_opt:
8176     case Intrinsic::riscv_vsetvlimax_opt:
8177       // Assume that VL output is positive and would fit in an int32_t.
8178       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8179       if (BitWidth >= 32)
8180         Known.Zero.setBitsFrom(31);
8181       break;
8182     }
8183     break;
8184   }
8185   }
8186 }
8187 
8188 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8189     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8190     unsigned Depth) const {
8191   switch (Op.getOpcode()) {
8192   default:
8193     break;
8194   case RISCVISD::SELECT_CC: {
8195     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8196     if (Tmp == 1) return 1;  // Early out.
8197     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8198     return std::min(Tmp, Tmp2);
8199   }
8200   case RISCVISD::SLLW:
8201   case RISCVISD::SRAW:
8202   case RISCVISD::SRLW:
8203   case RISCVISD::DIVW:
8204   case RISCVISD::DIVUW:
8205   case RISCVISD::REMUW:
8206   case RISCVISD::ROLW:
8207   case RISCVISD::RORW:
8208   case RISCVISD::GREVW:
8209   case RISCVISD::GORCW:
8210   case RISCVISD::FSLW:
8211   case RISCVISD::FSRW:
8212   case RISCVISD::SHFLW:
8213   case RISCVISD::UNSHFLW:
8214   case RISCVISD::BCOMPRESSW:
8215   case RISCVISD::BDECOMPRESSW:
8216   case RISCVISD::BFPW:
8217   case RISCVISD::FCVT_W_RV64:
8218   case RISCVISD::FCVT_WU_RV64:
8219   case RISCVISD::STRICT_FCVT_W_RV64:
8220   case RISCVISD::STRICT_FCVT_WU_RV64:
8221     // TODO: As the result is sign-extended, this is conservatively correct. A
8222     // more precise answer could be calculated for SRAW depending on known
8223     // bits in the shift amount.
8224     return 33;
8225   case RISCVISD::SHFL:
8226   case RISCVISD::UNSHFL: {
8227     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8228     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8229     // will stay within the upper 32 bits. If there were more than 32 sign bits
8230     // before there will be at least 33 sign bits after.
8231     if (Op.getValueType() == MVT::i64 &&
8232         isa<ConstantSDNode>(Op.getOperand(1)) &&
8233         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8234       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8235       if (Tmp > 32)
8236         return 33;
8237     }
8238     break;
8239   }
8240   case RISCVISD::VMV_X_S:
8241     // The number of sign bits of the scalar result is computed by obtaining the
8242     // element type of the input vector operand, subtracting its width from the
8243     // XLEN, and then adding one (sign bit within the element type). If the
8244     // element type is wider than XLen, the least-significant XLEN bits are
8245     // taken.
8246     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
8247       return 1;
8248     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
8249   }
8250 
8251   return 1;
8252 }
8253 
8254 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8255                                                   MachineBasicBlock *BB) {
8256   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8257 
8258   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8259   // Should the count have wrapped while it was being read, we need to try
8260   // again.
8261   // ...
8262   // read:
8263   // rdcycleh x3 # load high word of cycle
8264   // rdcycle  x2 # load low word of cycle
8265   // rdcycleh x4 # load high word of cycle
8266   // bne x3, x4, read # check if high word reads match, otherwise try again
8267   // ...
8268 
8269   MachineFunction &MF = *BB->getParent();
8270   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8271   MachineFunction::iterator It = ++BB->getIterator();
8272 
8273   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8274   MF.insert(It, LoopMBB);
8275 
8276   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8277   MF.insert(It, DoneMBB);
8278 
8279   // Transfer the remainder of BB and its successor edges to DoneMBB.
8280   DoneMBB->splice(DoneMBB->begin(), BB,
8281                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8282   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8283 
8284   BB->addSuccessor(LoopMBB);
8285 
8286   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8287   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8288   Register LoReg = MI.getOperand(0).getReg();
8289   Register HiReg = MI.getOperand(1).getReg();
8290   DebugLoc DL = MI.getDebugLoc();
8291 
8292   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8293   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8294       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8295       .addReg(RISCV::X0);
8296   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8297       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8298       .addReg(RISCV::X0);
8299   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8300       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8301       .addReg(RISCV::X0);
8302 
8303   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8304       .addReg(HiReg)
8305       .addReg(ReadAgainReg)
8306       .addMBB(LoopMBB);
8307 
8308   LoopMBB->addSuccessor(LoopMBB);
8309   LoopMBB->addSuccessor(DoneMBB);
8310 
8311   MI.eraseFromParent();
8312 
8313   return DoneMBB;
8314 }
8315 
8316 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8317                                              MachineBasicBlock *BB) {
8318   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8319 
8320   MachineFunction &MF = *BB->getParent();
8321   DebugLoc DL = MI.getDebugLoc();
8322   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8323   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8324   Register LoReg = MI.getOperand(0).getReg();
8325   Register HiReg = MI.getOperand(1).getReg();
8326   Register SrcReg = MI.getOperand(2).getReg();
8327   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8328   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8329 
8330   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8331                           RI);
8332   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8333   MachineMemOperand *MMOLo =
8334       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8335   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8336       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8337   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8338       .addFrameIndex(FI)
8339       .addImm(0)
8340       .addMemOperand(MMOLo);
8341   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8342       .addFrameIndex(FI)
8343       .addImm(4)
8344       .addMemOperand(MMOHi);
8345   MI.eraseFromParent(); // The pseudo instruction is gone now.
8346   return BB;
8347 }
8348 
8349 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8350                                                  MachineBasicBlock *BB) {
8351   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8352          "Unexpected instruction");
8353 
8354   MachineFunction &MF = *BB->getParent();
8355   DebugLoc DL = MI.getDebugLoc();
8356   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8357   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8358   Register DstReg = MI.getOperand(0).getReg();
8359   Register LoReg = MI.getOperand(1).getReg();
8360   Register HiReg = MI.getOperand(2).getReg();
8361   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8362   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8363 
8364   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8365   MachineMemOperand *MMOLo =
8366       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8367   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8368       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8369   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8370       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8371       .addFrameIndex(FI)
8372       .addImm(0)
8373       .addMemOperand(MMOLo);
8374   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8375       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8376       .addFrameIndex(FI)
8377       .addImm(4)
8378       .addMemOperand(MMOHi);
8379   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8380   MI.eraseFromParent(); // The pseudo instruction is gone now.
8381   return BB;
8382 }
8383 
8384 static bool isSelectPseudo(MachineInstr &MI) {
8385   switch (MI.getOpcode()) {
8386   default:
8387     return false;
8388   case RISCV::Select_GPR_Using_CC_GPR:
8389   case RISCV::Select_FPR16_Using_CC_GPR:
8390   case RISCV::Select_FPR32_Using_CC_GPR:
8391   case RISCV::Select_FPR64_Using_CC_GPR:
8392     return true;
8393   }
8394 }
8395 
8396 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8397                                         unsigned RelOpcode, unsigned EqOpcode,
8398                                         const RISCVSubtarget &Subtarget) {
8399   DebugLoc DL = MI.getDebugLoc();
8400   Register DstReg = MI.getOperand(0).getReg();
8401   Register Src1Reg = MI.getOperand(1).getReg();
8402   Register Src2Reg = MI.getOperand(2).getReg();
8403   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8404   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8405   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8406 
8407   // Save the current FFLAGS.
8408   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8409 
8410   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8411                  .addReg(Src1Reg)
8412                  .addReg(Src2Reg);
8413   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8414     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8415 
8416   // Restore the FFLAGS.
8417   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8418       .addReg(SavedFFlags, RegState::Kill);
8419 
8420   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8421   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8422                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8423                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8424   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8425     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8426 
8427   // Erase the pseudoinstruction.
8428   MI.eraseFromParent();
8429   return BB;
8430 }
8431 
8432 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8433                                            MachineBasicBlock *BB,
8434                                            const RISCVSubtarget &Subtarget) {
8435   // To "insert" Select_* instructions, we actually have to insert the triangle
8436   // control-flow pattern.  The incoming instructions know the destination vreg
8437   // to set, the condition code register to branch on, the true/false values to
8438   // select between, and the condcode to use to select the appropriate branch.
8439   //
8440   // We produce the following control flow:
8441   //     HeadMBB
8442   //     |  \
8443   //     |  IfFalseMBB
8444   //     | /
8445   //    TailMBB
8446   //
8447   // When we find a sequence of selects we attempt to optimize their emission
8448   // by sharing the control flow. Currently we only handle cases where we have
8449   // multiple selects with the exact same condition (same LHS, RHS and CC).
8450   // The selects may be interleaved with other instructions if the other
8451   // instructions meet some requirements we deem safe:
8452   // - They are debug instructions. Otherwise,
8453   // - They do not have side-effects, do not access memory and their inputs do
8454   //   not depend on the results of the select pseudo-instructions.
8455   // The TrueV/FalseV operands of the selects cannot depend on the result of
8456   // previous selects in the sequence.
8457   // These conditions could be further relaxed. See the X86 target for a
8458   // related approach and more information.
8459   Register LHS = MI.getOperand(1).getReg();
8460   Register RHS = MI.getOperand(2).getReg();
8461   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8462 
8463   SmallVector<MachineInstr *, 4> SelectDebugValues;
8464   SmallSet<Register, 4> SelectDests;
8465   SelectDests.insert(MI.getOperand(0).getReg());
8466 
8467   MachineInstr *LastSelectPseudo = &MI;
8468 
8469   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8470        SequenceMBBI != E; ++SequenceMBBI) {
8471     if (SequenceMBBI->isDebugInstr())
8472       continue;
8473     else if (isSelectPseudo(*SequenceMBBI)) {
8474       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8475           SequenceMBBI->getOperand(2).getReg() != RHS ||
8476           SequenceMBBI->getOperand(3).getImm() != CC ||
8477           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8478           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8479         break;
8480       LastSelectPseudo = &*SequenceMBBI;
8481       SequenceMBBI->collectDebugValues(SelectDebugValues);
8482       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8483     } else {
8484       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8485           SequenceMBBI->mayLoadOrStore())
8486         break;
8487       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8488             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8489           }))
8490         break;
8491     }
8492   }
8493 
8494   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8495   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8496   DebugLoc DL = MI.getDebugLoc();
8497   MachineFunction::iterator I = ++BB->getIterator();
8498 
8499   MachineBasicBlock *HeadMBB = BB;
8500   MachineFunction *F = BB->getParent();
8501   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8502   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8503 
8504   F->insert(I, IfFalseMBB);
8505   F->insert(I, TailMBB);
8506 
8507   // Transfer debug instructions associated with the selects to TailMBB.
8508   for (MachineInstr *DebugInstr : SelectDebugValues) {
8509     TailMBB->push_back(DebugInstr->removeFromParent());
8510   }
8511 
8512   // Move all instructions after the sequence to TailMBB.
8513   TailMBB->splice(TailMBB->end(), HeadMBB,
8514                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8515   // Update machine-CFG edges by transferring all successors of the current
8516   // block to the new block which will contain the Phi nodes for the selects.
8517   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8518   // Set the successors for HeadMBB.
8519   HeadMBB->addSuccessor(IfFalseMBB);
8520   HeadMBB->addSuccessor(TailMBB);
8521 
8522   // Insert appropriate branch.
8523   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8524     .addReg(LHS)
8525     .addReg(RHS)
8526     .addMBB(TailMBB);
8527 
8528   // IfFalseMBB just falls through to TailMBB.
8529   IfFalseMBB->addSuccessor(TailMBB);
8530 
8531   // Create PHIs for all of the select pseudo-instructions.
8532   auto SelectMBBI = MI.getIterator();
8533   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8534   auto InsertionPoint = TailMBB->begin();
8535   while (SelectMBBI != SelectEnd) {
8536     auto Next = std::next(SelectMBBI);
8537     if (isSelectPseudo(*SelectMBBI)) {
8538       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8539       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8540               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8541           .addReg(SelectMBBI->getOperand(4).getReg())
8542           .addMBB(HeadMBB)
8543           .addReg(SelectMBBI->getOperand(5).getReg())
8544           .addMBB(IfFalseMBB);
8545       SelectMBBI->eraseFromParent();
8546     }
8547     SelectMBBI = Next;
8548   }
8549 
8550   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8551   return TailMBB;
8552 }
8553 
8554 MachineBasicBlock *
8555 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8556                                                  MachineBasicBlock *BB) const {
8557   switch (MI.getOpcode()) {
8558   default:
8559     llvm_unreachable("Unexpected instr type to insert");
8560   case RISCV::ReadCycleWide:
8561     assert(!Subtarget.is64Bit() &&
8562            "ReadCycleWrite is only to be used on riscv32");
8563     return emitReadCycleWidePseudo(MI, BB);
8564   case RISCV::Select_GPR_Using_CC_GPR:
8565   case RISCV::Select_FPR16_Using_CC_GPR:
8566   case RISCV::Select_FPR32_Using_CC_GPR:
8567   case RISCV::Select_FPR64_Using_CC_GPR:
8568     return emitSelectPseudo(MI, BB, Subtarget);
8569   case RISCV::BuildPairF64Pseudo:
8570     return emitBuildPairF64Pseudo(MI, BB);
8571   case RISCV::SplitF64Pseudo:
8572     return emitSplitF64Pseudo(MI, BB);
8573   case RISCV::PseudoQuietFLE_H:
8574     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
8575   case RISCV::PseudoQuietFLT_H:
8576     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
8577   case RISCV::PseudoQuietFLE_S:
8578     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
8579   case RISCV::PseudoQuietFLT_S:
8580     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
8581   case RISCV::PseudoQuietFLE_D:
8582     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
8583   case RISCV::PseudoQuietFLT_D:
8584     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
8585   }
8586 }
8587 
8588 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8589                                                         SDNode *Node) const {
8590   // Add FRM dependency to any instructions with dynamic rounding mode.
8591   unsigned Opc = MI.getOpcode();
8592   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8593   if (Idx < 0)
8594     return;
8595   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8596     return;
8597   // If the instruction already reads FRM, don't add another read.
8598   if (MI.readsRegister(RISCV::FRM))
8599     return;
8600   MI.addOperand(
8601       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8602 }
8603 
8604 // Calling Convention Implementation.
8605 // The expectations for frontend ABI lowering vary from target to target.
8606 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8607 // details, but this is a longer term goal. For now, we simply try to keep the
8608 // role of the frontend as simple and well-defined as possible. The rules can
8609 // be summarised as:
8610 // * Never split up large scalar arguments. We handle them here.
8611 // * If a hardfloat calling convention is being used, and the struct may be
8612 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8613 // available, then pass as two separate arguments. If either the GPRs or FPRs
8614 // are exhausted, then pass according to the rule below.
8615 // * If a struct could never be passed in registers or directly in a stack
8616 // slot (as it is larger than 2*XLEN and the floating point rules don't
8617 // apply), then pass it using a pointer with the byval attribute.
8618 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8619 // word-sized array or a 2*XLEN scalar (depending on alignment).
8620 // * The frontend can determine whether a struct is returned by reference or
8621 // not based on its size and fields. If it will be returned by reference, the
8622 // frontend must modify the prototype so a pointer with the sret annotation is
8623 // passed as the first argument. This is not necessary for large scalar
8624 // returns.
8625 // * Struct return values and varargs should be coerced to structs containing
8626 // register-size fields in the same situations they would be for fixed
8627 // arguments.
8628 
8629 static const MCPhysReg ArgGPRs[] = {
8630   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8631   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8632 };
8633 static const MCPhysReg ArgFPR16s[] = {
8634   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8635   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8636 };
8637 static const MCPhysReg ArgFPR32s[] = {
8638   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8639   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8640 };
8641 static const MCPhysReg ArgFPR64s[] = {
8642   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8643   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8644 };
8645 // This is an interim calling convention and it may be changed in the future.
8646 static const MCPhysReg ArgVRs[] = {
8647     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8648     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8649     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8650 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8651                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8652                                      RISCV::V20M2, RISCV::V22M2};
8653 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8654                                      RISCV::V20M4};
8655 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8656 
8657 // Pass a 2*XLEN argument that has been split into two XLEN values through
8658 // registers or the stack as necessary.
8659 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8660                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8661                                 MVT ValVT2, MVT LocVT2,
8662                                 ISD::ArgFlagsTy ArgFlags2) {
8663   unsigned XLenInBytes = XLen / 8;
8664   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8665     // At least one half can be passed via register.
8666     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8667                                      VA1.getLocVT(), CCValAssign::Full));
8668   } else {
8669     // Both halves must be passed on the stack, with proper alignment.
8670     Align StackAlign =
8671         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8672     State.addLoc(
8673         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8674                             State.AllocateStack(XLenInBytes, StackAlign),
8675                             VA1.getLocVT(), CCValAssign::Full));
8676     State.addLoc(CCValAssign::getMem(
8677         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8678         LocVT2, CCValAssign::Full));
8679     return false;
8680   }
8681 
8682   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8683     // The second half can also be passed via register.
8684     State.addLoc(
8685         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8686   } else {
8687     // The second half is passed via the stack, without additional alignment.
8688     State.addLoc(CCValAssign::getMem(
8689         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8690         LocVT2, CCValAssign::Full));
8691   }
8692 
8693   return false;
8694 }
8695 
8696 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8697                                Optional<unsigned> FirstMaskArgument,
8698                                CCState &State, const RISCVTargetLowering &TLI) {
8699   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8700   if (RC == &RISCV::VRRegClass) {
8701     // Assign the first mask argument to V0.
8702     // This is an interim calling convention and it may be changed in the
8703     // future.
8704     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8705       return State.AllocateReg(RISCV::V0);
8706     return State.AllocateReg(ArgVRs);
8707   }
8708   if (RC == &RISCV::VRM2RegClass)
8709     return State.AllocateReg(ArgVRM2s);
8710   if (RC == &RISCV::VRM4RegClass)
8711     return State.AllocateReg(ArgVRM4s);
8712   if (RC == &RISCV::VRM8RegClass)
8713     return State.AllocateReg(ArgVRM8s);
8714   llvm_unreachable("Unhandled register class for ValueType");
8715 }
8716 
8717 // Implements the RISC-V calling convention. Returns true upon failure.
8718 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8719                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8720                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8721                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8722                      Optional<unsigned> FirstMaskArgument) {
8723   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8724   assert(XLen == 32 || XLen == 64);
8725   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8726 
8727   // Any return value split in to more than two values can't be returned
8728   // directly. Vectors are returned via the available vector registers.
8729   if (!LocVT.isVector() && IsRet && ValNo > 1)
8730     return true;
8731 
8732   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8733   // variadic argument, or if no F16/F32 argument registers are available.
8734   bool UseGPRForF16_F32 = true;
8735   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8736   // variadic argument, or if no F64 argument registers are available.
8737   bool UseGPRForF64 = true;
8738 
8739   switch (ABI) {
8740   default:
8741     llvm_unreachable("Unexpected ABI");
8742   case RISCVABI::ABI_ILP32:
8743   case RISCVABI::ABI_LP64:
8744     break;
8745   case RISCVABI::ABI_ILP32F:
8746   case RISCVABI::ABI_LP64F:
8747     UseGPRForF16_F32 = !IsFixed;
8748     break;
8749   case RISCVABI::ABI_ILP32D:
8750   case RISCVABI::ABI_LP64D:
8751     UseGPRForF16_F32 = !IsFixed;
8752     UseGPRForF64 = !IsFixed;
8753     break;
8754   }
8755 
8756   // FPR16, FPR32, and FPR64 alias each other.
8757   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8758     UseGPRForF16_F32 = true;
8759     UseGPRForF64 = true;
8760   }
8761 
8762   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8763   // similar local variables rather than directly checking against the target
8764   // ABI.
8765 
8766   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8767     LocVT = XLenVT;
8768     LocInfo = CCValAssign::BCvt;
8769   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8770     LocVT = MVT::i64;
8771     LocInfo = CCValAssign::BCvt;
8772   }
8773 
8774   // If this is a variadic argument, the RISC-V calling convention requires
8775   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8776   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8777   // be used regardless of whether the original argument was split during
8778   // legalisation or not. The argument will not be passed by registers if the
8779   // original type is larger than 2*XLEN, so the register alignment rule does
8780   // not apply.
8781   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8782   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8783       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8784     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8785     // Skip 'odd' register if necessary.
8786     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8787       State.AllocateReg(ArgGPRs);
8788   }
8789 
8790   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8791   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8792       State.getPendingArgFlags();
8793 
8794   assert(PendingLocs.size() == PendingArgFlags.size() &&
8795          "PendingLocs and PendingArgFlags out of sync");
8796 
8797   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8798   // registers are exhausted.
8799   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8800     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8801            "Can't lower f64 if it is split");
8802     // Depending on available argument GPRS, f64 may be passed in a pair of
8803     // GPRs, split between a GPR and the stack, or passed completely on the
8804     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8805     // cases.
8806     Register Reg = State.AllocateReg(ArgGPRs);
8807     LocVT = MVT::i32;
8808     if (!Reg) {
8809       unsigned StackOffset = State.AllocateStack(8, Align(8));
8810       State.addLoc(
8811           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8812       return false;
8813     }
8814     if (!State.AllocateReg(ArgGPRs))
8815       State.AllocateStack(4, Align(4));
8816     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8817     return false;
8818   }
8819 
8820   // Fixed-length vectors are located in the corresponding scalable-vector
8821   // container types.
8822   if (ValVT.isFixedLengthVector())
8823     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8824 
8825   // Split arguments might be passed indirectly, so keep track of the pending
8826   // values. Split vectors are passed via a mix of registers and indirectly, so
8827   // treat them as we would any other argument.
8828   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8829     LocVT = XLenVT;
8830     LocInfo = CCValAssign::Indirect;
8831     PendingLocs.push_back(
8832         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8833     PendingArgFlags.push_back(ArgFlags);
8834     if (!ArgFlags.isSplitEnd()) {
8835       return false;
8836     }
8837   }
8838 
8839   // If the split argument only had two elements, it should be passed directly
8840   // in registers or on the stack.
8841   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8842       PendingLocs.size() <= 2) {
8843     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8844     // Apply the normal calling convention rules to the first half of the
8845     // split argument.
8846     CCValAssign VA = PendingLocs[0];
8847     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8848     PendingLocs.clear();
8849     PendingArgFlags.clear();
8850     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8851                                ArgFlags);
8852   }
8853 
8854   // Allocate to a register if possible, or else a stack slot.
8855   Register Reg;
8856   unsigned StoreSizeBytes = XLen / 8;
8857   Align StackAlign = Align(XLen / 8);
8858 
8859   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8860     Reg = State.AllocateReg(ArgFPR16s);
8861   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8862     Reg = State.AllocateReg(ArgFPR32s);
8863   else if (ValVT == MVT::f64 && !UseGPRForF64)
8864     Reg = State.AllocateReg(ArgFPR64s);
8865   else if (ValVT.isVector()) {
8866     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8867     if (!Reg) {
8868       // For return values, the vector must be passed fully via registers or
8869       // via the stack.
8870       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8871       // but we're using all of them.
8872       if (IsRet)
8873         return true;
8874       // Try using a GPR to pass the address
8875       if ((Reg = State.AllocateReg(ArgGPRs))) {
8876         LocVT = XLenVT;
8877         LocInfo = CCValAssign::Indirect;
8878       } else if (ValVT.isScalableVector()) {
8879         LocVT = XLenVT;
8880         LocInfo = CCValAssign::Indirect;
8881       } else {
8882         // Pass fixed-length vectors on the stack.
8883         LocVT = ValVT;
8884         StoreSizeBytes = ValVT.getStoreSize();
8885         // Align vectors to their element sizes, being careful for vXi1
8886         // vectors.
8887         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8888       }
8889     }
8890   } else {
8891     Reg = State.AllocateReg(ArgGPRs);
8892   }
8893 
8894   unsigned StackOffset =
8895       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8896 
8897   // If we reach this point and PendingLocs is non-empty, we must be at the
8898   // end of a split argument that must be passed indirectly.
8899   if (!PendingLocs.empty()) {
8900     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8901     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8902 
8903     for (auto &It : PendingLocs) {
8904       if (Reg)
8905         It.convertToReg(Reg);
8906       else
8907         It.convertToMem(StackOffset);
8908       State.addLoc(It);
8909     }
8910     PendingLocs.clear();
8911     PendingArgFlags.clear();
8912     return false;
8913   }
8914 
8915   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8916           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8917          "Expected an XLenVT or vector types at this stage");
8918 
8919   if (Reg) {
8920     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8921     return false;
8922   }
8923 
8924   // When a floating-point value is passed on the stack, no bit-conversion is
8925   // needed.
8926   if (ValVT.isFloatingPoint()) {
8927     LocVT = ValVT;
8928     LocInfo = CCValAssign::Full;
8929   }
8930   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8931   return false;
8932 }
8933 
8934 template <typename ArgTy>
8935 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8936   for (const auto &ArgIdx : enumerate(Args)) {
8937     MVT ArgVT = ArgIdx.value().VT;
8938     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8939       return ArgIdx.index();
8940   }
8941   return None;
8942 }
8943 
8944 void RISCVTargetLowering::analyzeInputArgs(
8945     MachineFunction &MF, CCState &CCInfo,
8946     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8947     RISCVCCAssignFn Fn) const {
8948   unsigned NumArgs = Ins.size();
8949   FunctionType *FType = MF.getFunction().getFunctionType();
8950 
8951   Optional<unsigned> FirstMaskArgument;
8952   if (Subtarget.hasVInstructions())
8953     FirstMaskArgument = preAssignMask(Ins);
8954 
8955   for (unsigned i = 0; i != NumArgs; ++i) {
8956     MVT ArgVT = Ins[i].VT;
8957     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8958 
8959     Type *ArgTy = nullptr;
8960     if (IsRet)
8961       ArgTy = FType->getReturnType();
8962     else if (Ins[i].isOrigArg())
8963       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8964 
8965     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8966     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8967            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8968            FirstMaskArgument)) {
8969       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8970                         << EVT(ArgVT).getEVTString() << '\n');
8971       llvm_unreachable(nullptr);
8972     }
8973   }
8974 }
8975 
8976 void RISCVTargetLowering::analyzeOutputArgs(
8977     MachineFunction &MF, CCState &CCInfo,
8978     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8979     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8980   unsigned NumArgs = Outs.size();
8981 
8982   Optional<unsigned> FirstMaskArgument;
8983   if (Subtarget.hasVInstructions())
8984     FirstMaskArgument = preAssignMask(Outs);
8985 
8986   for (unsigned i = 0; i != NumArgs; i++) {
8987     MVT ArgVT = Outs[i].VT;
8988     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8989     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8990 
8991     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8992     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8993            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8994            FirstMaskArgument)) {
8995       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8996                         << EVT(ArgVT).getEVTString() << "\n");
8997       llvm_unreachable(nullptr);
8998     }
8999   }
9000 }
9001 
9002 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9003 // values.
9004 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9005                                    const CCValAssign &VA, const SDLoc &DL,
9006                                    const RISCVSubtarget &Subtarget) {
9007   switch (VA.getLocInfo()) {
9008   default:
9009     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9010   case CCValAssign::Full:
9011     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9012       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9013     break;
9014   case CCValAssign::BCvt:
9015     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9016       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9017     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9018       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9019     else
9020       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9021     break;
9022   }
9023   return Val;
9024 }
9025 
9026 // The caller is responsible for loading the full value if the argument is
9027 // passed with CCValAssign::Indirect.
9028 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9029                                 const CCValAssign &VA, const SDLoc &DL,
9030                                 const RISCVTargetLowering &TLI) {
9031   MachineFunction &MF = DAG.getMachineFunction();
9032   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9033   EVT LocVT = VA.getLocVT();
9034   SDValue Val;
9035   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9036   Register VReg = RegInfo.createVirtualRegister(RC);
9037   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9038   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9039 
9040   if (VA.getLocInfo() == CCValAssign::Indirect)
9041     return Val;
9042 
9043   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9044 }
9045 
9046 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9047                                    const CCValAssign &VA, const SDLoc &DL,
9048                                    const RISCVSubtarget &Subtarget) {
9049   EVT LocVT = VA.getLocVT();
9050 
9051   switch (VA.getLocInfo()) {
9052   default:
9053     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9054   case CCValAssign::Full:
9055     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9056       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9057     break;
9058   case CCValAssign::BCvt:
9059     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9060       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9061     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9062       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9063     else
9064       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9065     break;
9066   }
9067   return Val;
9068 }
9069 
9070 // The caller is responsible for loading the full value if the argument is
9071 // passed with CCValAssign::Indirect.
9072 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9073                                 const CCValAssign &VA, const SDLoc &DL) {
9074   MachineFunction &MF = DAG.getMachineFunction();
9075   MachineFrameInfo &MFI = MF.getFrameInfo();
9076   EVT LocVT = VA.getLocVT();
9077   EVT ValVT = VA.getValVT();
9078   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9079   if (ValVT.isScalableVector()) {
9080     // When the value is a scalable vector, we save the pointer which points to
9081     // the scalable vector value in the stack. The ValVT will be the pointer
9082     // type, instead of the scalable vector type.
9083     ValVT = LocVT;
9084   }
9085   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9086                                  /*IsImmutable=*/true);
9087   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9088   SDValue Val;
9089 
9090   ISD::LoadExtType ExtType;
9091   switch (VA.getLocInfo()) {
9092   default:
9093     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9094   case CCValAssign::Full:
9095   case CCValAssign::Indirect:
9096   case CCValAssign::BCvt:
9097     ExtType = ISD::NON_EXTLOAD;
9098     break;
9099   }
9100   Val = DAG.getExtLoad(
9101       ExtType, DL, LocVT, Chain, FIN,
9102       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9103   return Val;
9104 }
9105 
9106 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9107                                        const CCValAssign &VA, const SDLoc &DL) {
9108   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9109          "Unexpected VA");
9110   MachineFunction &MF = DAG.getMachineFunction();
9111   MachineFrameInfo &MFI = MF.getFrameInfo();
9112   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9113 
9114   if (VA.isMemLoc()) {
9115     // f64 is passed on the stack.
9116     int FI =
9117         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9118     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9119     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9120                        MachinePointerInfo::getFixedStack(MF, FI));
9121   }
9122 
9123   assert(VA.isRegLoc() && "Expected register VA assignment");
9124 
9125   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9126   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9127   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9128   SDValue Hi;
9129   if (VA.getLocReg() == RISCV::X17) {
9130     // Second half of f64 is passed on the stack.
9131     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9132     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9133     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9134                      MachinePointerInfo::getFixedStack(MF, FI));
9135   } else {
9136     // Second half of f64 is passed in another GPR.
9137     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9138     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9139     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9140   }
9141   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9142 }
9143 
9144 // FastCC has less than 1% performance improvement for some particular
9145 // benchmark. But theoretically, it may has benenfit for some cases.
9146 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9147                             unsigned ValNo, MVT ValVT, MVT LocVT,
9148                             CCValAssign::LocInfo LocInfo,
9149                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9150                             bool IsFixed, bool IsRet, Type *OrigTy,
9151                             const RISCVTargetLowering &TLI,
9152                             Optional<unsigned> FirstMaskArgument) {
9153 
9154   // X5 and X6 might be used for save-restore libcall.
9155   static const MCPhysReg GPRList[] = {
9156       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9157       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9158       RISCV::X29, RISCV::X30, RISCV::X31};
9159 
9160   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9161     if (unsigned Reg = State.AllocateReg(GPRList)) {
9162       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9163       return false;
9164     }
9165   }
9166 
9167   if (LocVT == MVT::f16) {
9168     static const MCPhysReg FPR16List[] = {
9169         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9170         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9171         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9172         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9173     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9174       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9175       return false;
9176     }
9177   }
9178 
9179   if (LocVT == MVT::f32) {
9180     static const MCPhysReg FPR32List[] = {
9181         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9182         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9183         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9184         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9185     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9186       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9187       return false;
9188     }
9189   }
9190 
9191   if (LocVT == MVT::f64) {
9192     static const MCPhysReg FPR64List[] = {
9193         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9194         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9195         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9196         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9197     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9198       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9199       return false;
9200     }
9201   }
9202 
9203   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9204     unsigned Offset4 = State.AllocateStack(4, Align(4));
9205     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9206     return false;
9207   }
9208 
9209   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9210     unsigned Offset5 = State.AllocateStack(8, Align(8));
9211     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9212     return false;
9213   }
9214 
9215   if (LocVT.isVector()) {
9216     if (unsigned Reg =
9217             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9218       // Fixed-length vectors are located in the corresponding scalable-vector
9219       // container types.
9220       if (ValVT.isFixedLengthVector())
9221         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9222       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9223     } else {
9224       // Try and pass the address via a "fast" GPR.
9225       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9226         LocInfo = CCValAssign::Indirect;
9227         LocVT = TLI.getSubtarget().getXLenVT();
9228         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9229       } else if (ValVT.isFixedLengthVector()) {
9230         auto StackAlign =
9231             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9232         unsigned StackOffset =
9233             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9234         State.addLoc(
9235             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9236       } else {
9237         // Can't pass scalable vectors on the stack.
9238         return true;
9239       }
9240     }
9241 
9242     return false;
9243   }
9244 
9245   return true; // CC didn't match.
9246 }
9247 
9248 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9249                          CCValAssign::LocInfo LocInfo,
9250                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9251 
9252   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9253     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9254     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9255     static const MCPhysReg GPRList[] = {
9256         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9257         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9258     if (unsigned Reg = State.AllocateReg(GPRList)) {
9259       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9260       return false;
9261     }
9262   }
9263 
9264   if (LocVT == MVT::f32) {
9265     // Pass in STG registers: F1, ..., F6
9266     //                        fs0 ... fs5
9267     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9268                                           RISCV::F18_F, RISCV::F19_F,
9269                                           RISCV::F20_F, RISCV::F21_F};
9270     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9271       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9272       return false;
9273     }
9274   }
9275 
9276   if (LocVT == MVT::f64) {
9277     // Pass in STG registers: D1, ..., D6
9278     //                        fs6 ... fs11
9279     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9280                                           RISCV::F24_D, RISCV::F25_D,
9281                                           RISCV::F26_D, RISCV::F27_D};
9282     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9283       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9284       return false;
9285     }
9286   }
9287 
9288   report_fatal_error("No registers left in GHC calling convention");
9289   return true;
9290 }
9291 
9292 // Transform physical registers into virtual registers.
9293 SDValue RISCVTargetLowering::LowerFormalArguments(
9294     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9295     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9296     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9297 
9298   MachineFunction &MF = DAG.getMachineFunction();
9299 
9300   switch (CallConv) {
9301   default:
9302     report_fatal_error("Unsupported calling convention");
9303   case CallingConv::C:
9304   case CallingConv::Fast:
9305     break;
9306   case CallingConv::GHC:
9307     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9308         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9309       report_fatal_error(
9310         "GHC calling convention requires the F and D instruction set extensions");
9311   }
9312 
9313   const Function &Func = MF.getFunction();
9314   if (Func.hasFnAttribute("interrupt")) {
9315     if (!Func.arg_empty())
9316       report_fatal_error(
9317         "Functions with the interrupt attribute cannot have arguments!");
9318 
9319     StringRef Kind =
9320       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9321 
9322     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9323       report_fatal_error(
9324         "Function interrupt attribute argument not supported!");
9325   }
9326 
9327   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9328   MVT XLenVT = Subtarget.getXLenVT();
9329   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9330   // Used with vargs to acumulate store chains.
9331   std::vector<SDValue> OutChains;
9332 
9333   // Assign locations to all of the incoming arguments.
9334   SmallVector<CCValAssign, 16> ArgLocs;
9335   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9336 
9337   if (CallConv == CallingConv::GHC)
9338     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9339   else
9340     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9341                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9342                                                    : CC_RISCV);
9343 
9344   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9345     CCValAssign &VA = ArgLocs[i];
9346     SDValue ArgValue;
9347     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9348     // case.
9349     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9350       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9351     else if (VA.isRegLoc())
9352       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9353     else
9354       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9355 
9356     if (VA.getLocInfo() == CCValAssign::Indirect) {
9357       // If the original argument was split and passed by reference (e.g. i128
9358       // on RV32), we need to load all parts of it here (using the same
9359       // address). Vectors may be partly split to registers and partly to the
9360       // stack, in which case the base address is partly offset and subsequent
9361       // stores are relative to that.
9362       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9363                                    MachinePointerInfo()));
9364       unsigned ArgIndex = Ins[i].OrigArgIndex;
9365       unsigned ArgPartOffset = Ins[i].PartOffset;
9366       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9367       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9368         CCValAssign &PartVA = ArgLocs[i + 1];
9369         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9370         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9371         if (PartVA.getValVT().isScalableVector())
9372           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9373         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9374         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9375                                      MachinePointerInfo()));
9376         ++i;
9377       }
9378       continue;
9379     }
9380     InVals.push_back(ArgValue);
9381   }
9382 
9383   if (IsVarArg) {
9384     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9385     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9386     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9387     MachineFrameInfo &MFI = MF.getFrameInfo();
9388     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9389     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9390 
9391     // Offset of the first variable argument from stack pointer, and size of
9392     // the vararg save area. For now, the varargs save area is either zero or
9393     // large enough to hold a0-a7.
9394     int VaArgOffset, VarArgsSaveSize;
9395 
9396     // If all registers are allocated, then all varargs must be passed on the
9397     // stack and we don't need to save any argregs.
9398     if (ArgRegs.size() == Idx) {
9399       VaArgOffset = CCInfo.getNextStackOffset();
9400       VarArgsSaveSize = 0;
9401     } else {
9402       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9403       VaArgOffset = -VarArgsSaveSize;
9404     }
9405 
9406     // Record the frame index of the first variable argument
9407     // which is a value necessary to VASTART.
9408     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9409     RVFI->setVarArgsFrameIndex(FI);
9410 
9411     // If saving an odd number of registers then create an extra stack slot to
9412     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9413     // offsets to even-numbered registered remain 2*XLEN-aligned.
9414     if (Idx % 2) {
9415       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9416       VarArgsSaveSize += XLenInBytes;
9417     }
9418 
9419     // Copy the integer registers that may have been used for passing varargs
9420     // to the vararg save area.
9421     for (unsigned I = Idx; I < ArgRegs.size();
9422          ++I, VaArgOffset += XLenInBytes) {
9423       const Register Reg = RegInfo.createVirtualRegister(RC);
9424       RegInfo.addLiveIn(ArgRegs[I], Reg);
9425       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9426       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9427       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9428       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9429                                    MachinePointerInfo::getFixedStack(MF, FI));
9430       cast<StoreSDNode>(Store.getNode())
9431           ->getMemOperand()
9432           ->setValue((Value *)nullptr);
9433       OutChains.push_back(Store);
9434     }
9435     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9436   }
9437 
9438   // All stores are grouped in one node to allow the matching between
9439   // the size of Ins and InVals. This only happens for vararg functions.
9440   if (!OutChains.empty()) {
9441     OutChains.push_back(Chain);
9442     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9443   }
9444 
9445   return Chain;
9446 }
9447 
9448 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9449 /// for tail call optimization.
9450 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9451 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9452     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9453     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9454 
9455   auto &Callee = CLI.Callee;
9456   auto CalleeCC = CLI.CallConv;
9457   auto &Outs = CLI.Outs;
9458   auto &Caller = MF.getFunction();
9459   auto CallerCC = Caller.getCallingConv();
9460 
9461   // Exception-handling functions need a special set of instructions to
9462   // indicate a return to the hardware. Tail-calling another function would
9463   // probably break this.
9464   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9465   // should be expanded as new function attributes are introduced.
9466   if (Caller.hasFnAttribute("interrupt"))
9467     return false;
9468 
9469   // Do not tail call opt if the stack is used to pass parameters.
9470   if (CCInfo.getNextStackOffset() != 0)
9471     return false;
9472 
9473   // Do not tail call opt if any parameters need to be passed indirectly.
9474   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9475   // passed indirectly. So the address of the value will be passed in a
9476   // register, or if not available, then the address is put on the stack. In
9477   // order to pass indirectly, space on the stack often needs to be allocated
9478   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9479   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9480   // are passed CCValAssign::Indirect.
9481   for (auto &VA : ArgLocs)
9482     if (VA.getLocInfo() == CCValAssign::Indirect)
9483       return false;
9484 
9485   // Do not tail call opt if either caller or callee uses struct return
9486   // semantics.
9487   auto IsCallerStructRet = Caller.hasStructRetAttr();
9488   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9489   if (IsCallerStructRet || IsCalleeStructRet)
9490     return false;
9491 
9492   // Externally-defined functions with weak linkage should not be
9493   // tail-called. The behaviour of branch instructions in this situation (as
9494   // used for tail calls) is implementation-defined, so we cannot rely on the
9495   // linker replacing the tail call with a return.
9496   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9497     const GlobalValue *GV = G->getGlobal();
9498     if (GV->hasExternalWeakLinkage())
9499       return false;
9500   }
9501 
9502   // The callee has to preserve all registers the caller needs to preserve.
9503   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9504   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9505   if (CalleeCC != CallerCC) {
9506     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9507     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9508       return false;
9509   }
9510 
9511   // Byval parameters hand the function a pointer directly into the stack area
9512   // we want to reuse during a tail call. Working around this *is* possible
9513   // but less efficient and uglier in LowerCall.
9514   for (auto &Arg : Outs)
9515     if (Arg.Flags.isByVal())
9516       return false;
9517 
9518   return true;
9519 }
9520 
9521 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9522   return DAG.getDataLayout().getPrefTypeAlign(
9523       VT.getTypeForEVT(*DAG.getContext()));
9524 }
9525 
9526 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9527 // and output parameter nodes.
9528 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9529                                        SmallVectorImpl<SDValue> &InVals) const {
9530   SelectionDAG &DAG = CLI.DAG;
9531   SDLoc &DL = CLI.DL;
9532   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9533   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9534   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9535   SDValue Chain = CLI.Chain;
9536   SDValue Callee = CLI.Callee;
9537   bool &IsTailCall = CLI.IsTailCall;
9538   CallingConv::ID CallConv = CLI.CallConv;
9539   bool IsVarArg = CLI.IsVarArg;
9540   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9541   MVT XLenVT = Subtarget.getXLenVT();
9542 
9543   MachineFunction &MF = DAG.getMachineFunction();
9544 
9545   // Analyze the operands of the call, assigning locations to each operand.
9546   SmallVector<CCValAssign, 16> ArgLocs;
9547   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9548 
9549   if (CallConv == CallingConv::GHC)
9550     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9551   else
9552     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9553                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9554                                                     : CC_RISCV);
9555 
9556   // Check if it's really possible to do a tail call.
9557   if (IsTailCall)
9558     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9559 
9560   if (IsTailCall)
9561     ++NumTailCalls;
9562   else if (CLI.CB && CLI.CB->isMustTailCall())
9563     report_fatal_error("failed to perform tail call elimination on a call "
9564                        "site marked musttail");
9565 
9566   // Get a count of how many bytes are to be pushed on the stack.
9567   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9568 
9569   // Create local copies for byval args
9570   SmallVector<SDValue, 8> ByValArgs;
9571   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9572     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9573     if (!Flags.isByVal())
9574       continue;
9575 
9576     SDValue Arg = OutVals[i];
9577     unsigned Size = Flags.getByValSize();
9578     Align Alignment = Flags.getNonZeroByValAlign();
9579 
9580     int FI =
9581         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9582     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9583     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9584 
9585     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9586                           /*IsVolatile=*/false,
9587                           /*AlwaysInline=*/false, IsTailCall,
9588                           MachinePointerInfo(), MachinePointerInfo());
9589     ByValArgs.push_back(FIPtr);
9590   }
9591 
9592   if (!IsTailCall)
9593     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9594 
9595   // Copy argument values to their designated locations.
9596   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9597   SmallVector<SDValue, 8> MemOpChains;
9598   SDValue StackPtr;
9599   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9600     CCValAssign &VA = ArgLocs[i];
9601     SDValue ArgValue = OutVals[i];
9602     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9603 
9604     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9605     bool IsF64OnRV32DSoftABI =
9606         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9607     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9608       SDValue SplitF64 = DAG.getNode(
9609           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9610       SDValue Lo = SplitF64.getValue(0);
9611       SDValue Hi = SplitF64.getValue(1);
9612 
9613       Register RegLo = VA.getLocReg();
9614       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9615 
9616       if (RegLo == RISCV::X17) {
9617         // Second half of f64 is passed on the stack.
9618         // Work out the address of the stack slot.
9619         if (!StackPtr.getNode())
9620           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9621         // Emit the store.
9622         MemOpChains.push_back(
9623             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9624       } else {
9625         // Second half of f64 is passed in another GPR.
9626         assert(RegLo < RISCV::X31 && "Invalid register pair");
9627         Register RegHigh = RegLo + 1;
9628         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9629       }
9630       continue;
9631     }
9632 
9633     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9634     // as any other MemLoc.
9635 
9636     // Promote the value if needed.
9637     // For now, only handle fully promoted and indirect arguments.
9638     if (VA.getLocInfo() == CCValAssign::Indirect) {
9639       // Store the argument in a stack slot and pass its address.
9640       Align StackAlign =
9641           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9642                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9643       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9644       // If the original argument was split (e.g. i128), we need
9645       // to store the required parts of it here (and pass just one address).
9646       // Vectors may be partly split to registers and partly to the stack, in
9647       // which case the base address is partly offset and subsequent stores are
9648       // relative to that.
9649       unsigned ArgIndex = Outs[i].OrigArgIndex;
9650       unsigned ArgPartOffset = Outs[i].PartOffset;
9651       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9652       // Calculate the total size to store. We don't have access to what we're
9653       // actually storing other than performing the loop and collecting the
9654       // info.
9655       SmallVector<std::pair<SDValue, SDValue>> Parts;
9656       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9657         SDValue PartValue = OutVals[i + 1];
9658         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9659         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9660         EVT PartVT = PartValue.getValueType();
9661         if (PartVT.isScalableVector())
9662           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9663         StoredSize += PartVT.getStoreSize();
9664         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9665         Parts.push_back(std::make_pair(PartValue, Offset));
9666         ++i;
9667       }
9668       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9669       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9670       MemOpChains.push_back(
9671           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9672                        MachinePointerInfo::getFixedStack(MF, FI)));
9673       for (const auto &Part : Parts) {
9674         SDValue PartValue = Part.first;
9675         SDValue PartOffset = Part.second;
9676         SDValue Address =
9677             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9678         MemOpChains.push_back(
9679             DAG.getStore(Chain, DL, PartValue, Address,
9680                          MachinePointerInfo::getFixedStack(MF, FI)));
9681       }
9682       ArgValue = SpillSlot;
9683     } else {
9684       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9685     }
9686 
9687     // Use local copy if it is a byval arg.
9688     if (Flags.isByVal())
9689       ArgValue = ByValArgs[j++];
9690 
9691     if (VA.isRegLoc()) {
9692       // Queue up the argument copies and emit them at the end.
9693       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9694     } else {
9695       assert(VA.isMemLoc() && "Argument not register or memory");
9696       assert(!IsTailCall && "Tail call not allowed if stack is used "
9697                             "for passing parameters");
9698 
9699       // Work out the address of the stack slot.
9700       if (!StackPtr.getNode())
9701         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9702       SDValue Address =
9703           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9704                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9705 
9706       // Emit the store.
9707       MemOpChains.push_back(
9708           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9709     }
9710   }
9711 
9712   // Join the stores, which are independent of one another.
9713   if (!MemOpChains.empty())
9714     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9715 
9716   SDValue Glue;
9717 
9718   // Build a sequence of copy-to-reg nodes, chained and glued together.
9719   for (auto &Reg : RegsToPass) {
9720     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9721     Glue = Chain.getValue(1);
9722   }
9723 
9724   // Validate that none of the argument registers have been marked as
9725   // reserved, if so report an error. Do the same for the return address if this
9726   // is not a tailcall.
9727   validateCCReservedRegs(RegsToPass, MF);
9728   if (!IsTailCall &&
9729       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9730     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9731         MF.getFunction(),
9732         "Return address register required, but has been reserved."});
9733 
9734   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9735   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9736   // split it and then direct call can be matched by PseudoCALL.
9737   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9738     const GlobalValue *GV = S->getGlobal();
9739 
9740     unsigned OpFlags = RISCVII::MO_CALL;
9741     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9742       OpFlags = RISCVII::MO_PLT;
9743 
9744     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9745   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9746     unsigned OpFlags = RISCVII::MO_CALL;
9747 
9748     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9749                                                  nullptr))
9750       OpFlags = RISCVII::MO_PLT;
9751 
9752     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9753   }
9754 
9755   // The first call operand is the chain and the second is the target address.
9756   SmallVector<SDValue, 8> Ops;
9757   Ops.push_back(Chain);
9758   Ops.push_back(Callee);
9759 
9760   // Add argument registers to the end of the list so that they are
9761   // known live into the call.
9762   for (auto &Reg : RegsToPass)
9763     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9764 
9765   if (!IsTailCall) {
9766     // Add a register mask operand representing the call-preserved registers.
9767     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9768     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9769     assert(Mask && "Missing call preserved mask for calling convention");
9770     Ops.push_back(DAG.getRegisterMask(Mask));
9771   }
9772 
9773   // Glue the call to the argument copies, if any.
9774   if (Glue.getNode())
9775     Ops.push_back(Glue);
9776 
9777   // Emit the call.
9778   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9779 
9780   if (IsTailCall) {
9781     MF.getFrameInfo().setHasTailCall();
9782     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9783   }
9784 
9785   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9786   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9787   Glue = Chain.getValue(1);
9788 
9789   // Mark the end of the call, which is glued to the call itself.
9790   Chain = DAG.getCALLSEQ_END(Chain,
9791                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9792                              DAG.getConstant(0, DL, PtrVT, true),
9793                              Glue, DL);
9794   Glue = Chain.getValue(1);
9795 
9796   // Assign locations to each value returned by this call.
9797   SmallVector<CCValAssign, 16> RVLocs;
9798   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9799   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9800 
9801   // Copy all of the result registers out of their specified physreg.
9802   for (auto &VA : RVLocs) {
9803     // Copy the value out
9804     SDValue RetValue =
9805         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9806     // Glue the RetValue to the end of the call sequence
9807     Chain = RetValue.getValue(1);
9808     Glue = RetValue.getValue(2);
9809 
9810     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9811       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9812       SDValue RetValue2 =
9813           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9814       Chain = RetValue2.getValue(1);
9815       Glue = RetValue2.getValue(2);
9816       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9817                              RetValue2);
9818     }
9819 
9820     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9821 
9822     InVals.push_back(RetValue);
9823   }
9824 
9825   return Chain;
9826 }
9827 
9828 bool RISCVTargetLowering::CanLowerReturn(
9829     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9830     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9831   SmallVector<CCValAssign, 16> RVLocs;
9832   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9833 
9834   Optional<unsigned> FirstMaskArgument;
9835   if (Subtarget.hasVInstructions())
9836     FirstMaskArgument = preAssignMask(Outs);
9837 
9838   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9839     MVT VT = Outs[i].VT;
9840     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9841     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9842     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9843                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9844                  *this, FirstMaskArgument))
9845       return false;
9846   }
9847   return true;
9848 }
9849 
9850 SDValue
9851 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9852                                  bool IsVarArg,
9853                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9854                                  const SmallVectorImpl<SDValue> &OutVals,
9855                                  const SDLoc &DL, SelectionDAG &DAG) const {
9856   const MachineFunction &MF = DAG.getMachineFunction();
9857   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9858 
9859   // Stores the assignment of the return value to a location.
9860   SmallVector<CCValAssign, 16> RVLocs;
9861 
9862   // Info about the registers and stack slot.
9863   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9864                  *DAG.getContext());
9865 
9866   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9867                     nullptr, CC_RISCV);
9868 
9869   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9870     report_fatal_error("GHC functions return void only");
9871 
9872   SDValue Glue;
9873   SmallVector<SDValue, 4> RetOps(1, Chain);
9874 
9875   // Copy the result values into the output registers.
9876   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9877     SDValue Val = OutVals[i];
9878     CCValAssign &VA = RVLocs[i];
9879     assert(VA.isRegLoc() && "Can only return in registers!");
9880 
9881     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9882       // Handle returning f64 on RV32D with a soft float ABI.
9883       assert(VA.isRegLoc() && "Expected return via registers");
9884       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9885                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9886       SDValue Lo = SplitF64.getValue(0);
9887       SDValue Hi = SplitF64.getValue(1);
9888       Register RegLo = VA.getLocReg();
9889       assert(RegLo < RISCV::X31 && "Invalid register pair");
9890       Register RegHi = RegLo + 1;
9891 
9892       if (STI.isRegisterReservedByUser(RegLo) ||
9893           STI.isRegisterReservedByUser(RegHi))
9894         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9895             MF.getFunction(),
9896             "Return value register required, but has been reserved."});
9897 
9898       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9899       Glue = Chain.getValue(1);
9900       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9901       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9902       Glue = Chain.getValue(1);
9903       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9904     } else {
9905       // Handle a 'normal' return.
9906       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9907       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9908 
9909       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9910         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9911             MF.getFunction(),
9912             "Return value register required, but has been reserved."});
9913 
9914       // Guarantee that all emitted copies are stuck together.
9915       Glue = Chain.getValue(1);
9916       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9917     }
9918   }
9919 
9920   RetOps[0] = Chain; // Update chain.
9921 
9922   // Add the glue node if we have it.
9923   if (Glue.getNode()) {
9924     RetOps.push_back(Glue);
9925   }
9926 
9927   unsigned RetOpc = RISCVISD::RET_FLAG;
9928   // Interrupt service routines use different return instructions.
9929   const Function &Func = DAG.getMachineFunction().getFunction();
9930   if (Func.hasFnAttribute("interrupt")) {
9931     if (!Func.getReturnType()->isVoidTy())
9932       report_fatal_error(
9933           "Functions with the interrupt attribute must have void return type!");
9934 
9935     MachineFunction &MF = DAG.getMachineFunction();
9936     StringRef Kind =
9937       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9938 
9939     if (Kind == "user")
9940       RetOpc = RISCVISD::URET_FLAG;
9941     else if (Kind == "supervisor")
9942       RetOpc = RISCVISD::SRET_FLAG;
9943     else
9944       RetOpc = RISCVISD::MRET_FLAG;
9945   }
9946 
9947   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9948 }
9949 
9950 void RISCVTargetLowering::validateCCReservedRegs(
9951     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9952     MachineFunction &MF) const {
9953   const Function &F = MF.getFunction();
9954   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9955 
9956   if (llvm::any_of(Regs, [&STI](auto Reg) {
9957         return STI.isRegisterReservedByUser(Reg.first);
9958       }))
9959     F.getContext().diagnose(DiagnosticInfoUnsupported{
9960         F, "Argument register required, but has been reserved."});
9961 }
9962 
9963 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9964   return CI->isTailCall();
9965 }
9966 
9967 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9968 #define NODE_NAME_CASE(NODE)                                                   \
9969   case RISCVISD::NODE:                                                         \
9970     return "RISCVISD::" #NODE;
9971   // clang-format off
9972   switch ((RISCVISD::NodeType)Opcode) {
9973   case RISCVISD::FIRST_NUMBER:
9974     break;
9975   NODE_NAME_CASE(RET_FLAG)
9976   NODE_NAME_CASE(URET_FLAG)
9977   NODE_NAME_CASE(SRET_FLAG)
9978   NODE_NAME_CASE(MRET_FLAG)
9979   NODE_NAME_CASE(CALL)
9980   NODE_NAME_CASE(SELECT_CC)
9981   NODE_NAME_CASE(BR_CC)
9982   NODE_NAME_CASE(BuildPairF64)
9983   NODE_NAME_CASE(SplitF64)
9984   NODE_NAME_CASE(TAIL)
9985   NODE_NAME_CASE(MULHSU)
9986   NODE_NAME_CASE(SLLW)
9987   NODE_NAME_CASE(SRAW)
9988   NODE_NAME_CASE(SRLW)
9989   NODE_NAME_CASE(DIVW)
9990   NODE_NAME_CASE(DIVUW)
9991   NODE_NAME_CASE(REMUW)
9992   NODE_NAME_CASE(ROLW)
9993   NODE_NAME_CASE(RORW)
9994   NODE_NAME_CASE(CLZW)
9995   NODE_NAME_CASE(CTZW)
9996   NODE_NAME_CASE(FSLW)
9997   NODE_NAME_CASE(FSRW)
9998   NODE_NAME_CASE(FSL)
9999   NODE_NAME_CASE(FSR)
10000   NODE_NAME_CASE(FMV_H_X)
10001   NODE_NAME_CASE(FMV_X_ANYEXTH)
10002   NODE_NAME_CASE(FMV_W_X_RV64)
10003   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10004   NODE_NAME_CASE(FCVT_X)
10005   NODE_NAME_CASE(FCVT_XU)
10006   NODE_NAME_CASE(FCVT_W_RV64)
10007   NODE_NAME_CASE(FCVT_WU_RV64)
10008   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10009   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10010   NODE_NAME_CASE(READ_CYCLE_WIDE)
10011   NODE_NAME_CASE(GREV)
10012   NODE_NAME_CASE(GREVW)
10013   NODE_NAME_CASE(GORC)
10014   NODE_NAME_CASE(GORCW)
10015   NODE_NAME_CASE(SHFL)
10016   NODE_NAME_CASE(SHFLW)
10017   NODE_NAME_CASE(UNSHFL)
10018   NODE_NAME_CASE(UNSHFLW)
10019   NODE_NAME_CASE(BFP)
10020   NODE_NAME_CASE(BFPW)
10021   NODE_NAME_CASE(BCOMPRESS)
10022   NODE_NAME_CASE(BCOMPRESSW)
10023   NODE_NAME_CASE(BDECOMPRESS)
10024   NODE_NAME_CASE(BDECOMPRESSW)
10025   NODE_NAME_CASE(VMV_V_X_VL)
10026   NODE_NAME_CASE(VFMV_V_F_VL)
10027   NODE_NAME_CASE(VMV_X_S)
10028   NODE_NAME_CASE(VMV_S_X_VL)
10029   NODE_NAME_CASE(VFMV_S_F_VL)
10030   NODE_NAME_CASE(SPLAT_VECTOR_I64)
10031   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10032   NODE_NAME_CASE(READ_VLENB)
10033   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10034   NODE_NAME_CASE(VSLIDEUP_VL)
10035   NODE_NAME_CASE(VSLIDE1UP_VL)
10036   NODE_NAME_CASE(VSLIDEDOWN_VL)
10037   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10038   NODE_NAME_CASE(VID_VL)
10039   NODE_NAME_CASE(VFNCVT_ROD_VL)
10040   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10041   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10042   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10043   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10044   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10045   NODE_NAME_CASE(VECREDUCE_AND_VL)
10046   NODE_NAME_CASE(VECREDUCE_OR_VL)
10047   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10048   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10049   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10050   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10051   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10052   NODE_NAME_CASE(ADD_VL)
10053   NODE_NAME_CASE(AND_VL)
10054   NODE_NAME_CASE(MUL_VL)
10055   NODE_NAME_CASE(OR_VL)
10056   NODE_NAME_CASE(SDIV_VL)
10057   NODE_NAME_CASE(SHL_VL)
10058   NODE_NAME_CASE(SREM_VL)
10059   NODE_NAME_CASE(SRA_VL)
10060   NODE_NAME_CASE(SRL_VL)
10061   NODE_NAME_CASE(SUB_VL)
10062   NODE_NAME_CASE(UDIV_VL)
10063   NODE_NAME_CASE(UREM_VL)
10064   NODE_NAME_CASE(XOR_VL)
10065   NODE_NAME_CASE(SADDSAT_VL)
10066   NODE_NAME_CASE(UADDSAT_VL)
10067   NODE_NAME_CASE(SSUBSAT_VL)
10068   NODE_NAME_CASE(USUBSAT_VL)
10069   NODE_NAME_CASE(FADD_VL)
10070   NODE_NAME_CASE(FSUB_VL)
10071   NODE_NAME_CASE(FMUL_VL)
10072   NODE_NAME_CASE(FDIV_VL)
10073   NODE_NAME_CASE(FNEG_VL)
10074   NODE_NAME_CASE(FABS_VL)
10075   NODE_NAME_CASE(FSQRT_VL)
10076   NODE_NAME_CASE(FMA_VL)
10077   NODE_NAME_CASE(FCOPYSIGN_VL)
10078   NODE_NAME_CASE(SMIN_VL)
10079   NODE_NAME_CASE(SMAX_VL)
10080   NODE_NAME_CASE(UMIN_VL)
10081   NODE_NAME_CASE(UMAX_VL)
10082   NODE_NAME_CASE(FMINNUM_VL)
10083   NODE_NAME_CASE(FMAXNUM_VL)
10084   NODE_NAME_CASE(MULHS_VL)
10085   NODE_NAME_CASE(MULHU_VL)
10086   NODE_NAME_CASE(FP_TO_SINT_VL)
10087   NODE_NAME_CASE(FP_TO_UINT_VL)
10088   NODE_NAME_CASE(SINT_TO_FP_VL)
10089   NODE_NAME_CASE(UINT_TO_FP_VL)
10090   NODE_NAME_CASE(FP_EXTEND_VL)
10091   NODE_NAME_CASE(FP_ROUND_VL)
10092   NODE_NAME_CASE(VWMUL_VL)
10093   NODE_NAME_CASE(VWMULU_VL)
10094   NODE_NAME_CASE(VWADDU_VL)
10095   NODE_NAME_CASE(SETCC_VL)
10096   NODE_NAME_CASE(VSELECT_VL)
10097   NODE_NAME_CASE(VP_MERGE_VL)
10098   NODE_NAME_CASE(VMAND_VL)
10099   NODE_NAME_CASE(VMOR_VL)
10100   NODE_NAME_CASE(VMXOR_VL)
10101   NODE_NAME_CASE(VMCLR_VL)
10102   NODE_NAME_CASE(VMSET_VL)
10103   NODE_NAME_CASE(VRGATHER_VX_VL)
10104   NODE_NAME_CASE(VRGATHER_VV_VL)
10105   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10106   NODE_NAME_CASE(VSEXT_VL)
10107   NODE_NAME_CASE(VZEXT_VL)
10108   NODE_NAME_CASE(VCPOP_VL)
10109   NODE_NAME_CASE(VLE_VL)
10110   NODE_NAME_CASE(VSE_VL)
10111   NODE_NAME_CASE(READ_CSR)
10112   NODE_NAME_CASE(WRITE_CSR)
10113   NODE_NAME_CASE(SWAP_CSR)
10114   }
10115   // clang-format on
10116   return nullptr;
10117 #undef NODE_NAME_CASE
10118 }
10119 
10120 /// getConstraintType - Given a constraint letter, return the type of
10121 /// constraint it is for this target.
10122 RISCVTargetLowering::ConstraintType
10123 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10124   if (Constraint.size() == 1) {
10125     switch (Constraint[0]) {
10126     default:
10127       break;
10128     case 'f':
10129       return C_RegisterClass;
10130     case 'I':
10131     case 'J':
10132     case 'K':
10133       return C_Immediate;
10134     case 'A':
10135       return C_Memory;
10136     case 'S': // A symbolic address
10137       return C_Other;
10138     }
10139   } else {
10140     if (Constraint == "vr" || Constraint == "vm")
10141       return C_RegisterClass;
10142   }
10143   return TargetLowering::getConstraintType(Constraint);
10144 }
10145 
10146 std::pair<unsigned, const TargetRegisterClass *>
10147 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10148                                                   StringRef Constraint,
10149                                                   MVT VT) const {
10150   // First, see if this is a constraint that directly corresponds to a
10151   // RISCV register class.
10152   if (Constraint.size() == 1) {
10153     switch (Constraint[0]) {
10154     case 'r':
10155       // TODO: Support fixed vectors up to XLen for P extension?
10156       if (VT.isVector())
10157         break;
10158       return std::make_pair(0U, &RISCV::GPRRegClass);
10159     case 'f':
10160       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10161         return std::make_pair(0U, &RISCV::FPR16RegClass);
10162       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10163         return std::make_pair(0U, &RISCV::FPR32RegClass);
10164       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10165         return std::make_pair(0U, &RISCV::FPR64RegClass);
10166       break;
10167     default:
10168       break;
10169     }
10170   } else if (Constraint == "vr") {
10171     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10172                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10173       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10174         return std::make_pair(0U, RC);
10175     }
10176   } else if (Constraint == "vm") {
10177     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10178       return std::make_pair(0U, &RISCV::VMV0RegClass);
10179   }
10180 
10181   // Clang will correctly decode the usage of register name aliases into their
10182   // official names. However, other frontends like `rustc` do not. This allows
10183   // users of these frontends to use the ABI names for registers in LLVM-style
10184   // register constraints.
10185   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10186                                .Case("{zero}", RISCV::X0)
10187                                .Case("{ra}", RISCV::X1)
10188                                .Case("{sp}", RISCV::X2)
10189                                .Case("{gp}", RISCV::X3)
10190                                .Case("{tp}", RISCV::X4)
10191                                .Case("{t0}", RISCV::X5)
10192                                .Case("{t1}", RISCV::X6)
10193                                .Case("{t2}", RISCV::X7)
10194                                .Cases("{s0}", "{fp}", RISCV::X8)
10195                                .Case("{s1}", RISCV::X9)
10196                                .Case("{a0}", RISCV::X10)
10197                                .Case("{a1}", RISCV::X11)
10198                                .Case("{a2}", RISCV::X12)
10199                                .Case("{a3}", RISCV::X13)
10200                                .Case("{a4}", RISCV::X14)
10201                                .Case("{a5}", RISCV::X15)
10202                                .Case("{a6}", RISCV::X16)
10203                                .Case("{a7}", RISCV::X17)
10204                                .Case("{s2}", RISCV::X18)
10205                                .Case("{s3}", RISCV::X19)
10206                                .Case("{s4}", RISCV::X20)
10207                                .Case("{s5}", RISCV::X21)
10208                                .Case("{s6}", RISCV::X22)
10209                                .Case("{s7}", RISCV::X23)
10210                                .Case("{s8}", RISCV::X24)
10211                                .Case("{s9}", RISCV::X25)
10212                                .Case("{s10}", RISCV::X26)
10213                                .Case("{s11}", RISCV::X27)
10214                                .Case("{t3}", RISCV::X28)
10215                                .Case("{t4}", RISCV::X29)
10216                                .Case("{t5}", RISCV::X30)
10217                                .Case("{t6}", RISCV::X31)
10218                                .Default(RISCV::NoRegister);
10219   if (XRegFromAlias != RISCV::NoRegister)
10220     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10221 
10222   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10223   // TableGen record rather than the AsmName to choose registers for InlineAsm
10224   // constraints, plus we want to match those names to the widest floating point
10225   // register type available, manually select floating point registers here.
10226   //
10227   // The second case is the ABI name of the register, so that frontends can also
10228   // use the ABI names in register constraint lists.
10229   if (Subtarget.hasStdExtF()) {
10230     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10231                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10232                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10233                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10234                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10235                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10236                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10237                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10238                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10239                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10240                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10241                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10242                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10243                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10244                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10245                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10246                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10247                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10248                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10249                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10250                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10251                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10252                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10253                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10254                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10255                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10256                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10257                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10258                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10259                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10260                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10261                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10262                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10263                         .Default(RISCV::NoRegister);
10264     if (FReg != RISCV::NoRegister) {
10265       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10266       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10267         unsigned RegNo = FReg - RISCV::F0_F;
10268         unsigned DReg = RISCV::F0_D + RegNo;
10269         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10270       }
10271       if (VT == MVT::f32 || VT == MVT::Other)
10272         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10273       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10274         unsigned RegNo = FReg - RISCV::F0_F;
10275         unsigned HReg = RISCV::F0_H + RegNo;
10276         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10277       }
10278     }
10279   }
10280 
10281   if (Subtarget.hasVInstructions()) {
10282     Register VReg = StringSwitch<Register>(Constraint.lower())
10283                         .Case("{v0}", RISCV::V0)
10284                         .Case("{v1}", RISCV::V1)
10285                         .Case("{v2}", RISCV::V2)
10286                         .Case("{v3}", RISCV::V3)
10287                         .Case("{v4}", RISCV::V4)
10288                         .Case("{v5}", RISCV::V5)
10289                         .Case("{v6}", RISCV::V6)
10290                         .Case("{v7}", RISCV::V7)
10291                         .Case("{v8}", RISCV::V8)
10292                         .Case("{v9}", RISCV::V9)
10293                         .Case("{v10}", RISCV::V10)
10294                         .Case("{v11}", RISCV::V11)
10295                         .Case("{v12}", RISCV::V12)
10296                         .Case("{v13}", RISCV::V13)
10297                         .Case("{v14}", RISCV::V14)
10298                         .Case("{v15}", RISCV::V15)
10299                         .Case("{v16}", RISCV::V16)
10300                         .Case("{v17}", RISCV::V17)
10301                         .Case("{v18}", RISCV::V18)
10302                         .Case("{v19}", RISCV::V19)
10303                         .Case("{v20}", RISCV::V20)
10304                         .Case("{v21}", RISCV::V21)
10305                         .Case("{v22}", RISCV::V22)
10306                         .Case("{v23}", RISCV::V23)
10307                         .Case("{v24}", RISCV::V24)
10308                         .Case("{v25}", RISCV::V25)
10309                         .Case("{v26}", RISCV::V26)
10310                         .Case("{v27}", RISCV::V27)
10311                         .Case("{v28}", RISCV::V28)
10312                         .Case("{v29}", RISCV::V29)
10313                         .Case("{v30}", RISCV::V30)
10314                         .Case("{v31}", RISCV::V31)
10315                         .Default(RISCV::NoRegister);
10316     if (VReg != RISCV::NoRegister) {
10317       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10318         return std::make_pair(VReg, &RISCV::VMRegClass);
10319       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10320         return std::make_pair(VReg, &RISCV::VRRegClass);
10321       for (const auto *RC :
10322            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10323         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10324           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10325           return std::make_pair(VReg, RC);
10326         }
10327       }
10328     }
10329   }
10330 
10331   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10332 }
10333 
10334 unsigned
10335 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10336   // Currently only support length 1 constraints.
10337   if (ConstraintCode.size() == 1) {
10338     switch (ConstraintCode[0]) {
10339     case 'A':
10340       return InlineAsm::Constraint_A;
10341     default:
10342       break;
10343     }
10344   }
10345 
10346   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10347 }
10348 
10349 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10350     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10351     SelectionDAG &DAG) const {
10352   // Currently only support length 1 constraints.
10353   if (Constraint.length() == 1) {
10354     switch (Constraint[0]) {
10355     case 'I':
10356       // Validate & create a 12-bit signed immediate operand.
10357       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10358         uint64_t CVal = C->getSExtValue();
10359         if (isInt<12>(CVal))
10360           Ops.push_back(
10361               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10362       }
10363       return;
10364     case 'J':
10365       // Validate & create an integer zero operand.
10366       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10367         if (C->getZExtValue() == 0)
10368           Ops.push_back(
10369               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10370       return;
10371     case 'K':
10372       // Validate & create a 5-bit unsigned immediate operand.
10373       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10374         uint64_t CVal = C->getZExtValue();
10375         if (isUInt<5>(CVal))
10376           Ops.push_back(
10377               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10378       }
10379       return;
10380     case 'S':
10381       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10382         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10383                                                  GA->getValueType(0)));
10384       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10385         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10386                                                 BA->getValueType(0)));
10387       }
10388       return;
10389     default:
10390       break;
10391     }
10392   }
10393   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10394 }
10395 
10396 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10397                                                    Instruction *Inst,
10398                                                    AtomicOrdering Ord) const {
10399   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10400     return Builder.CreateFence(Ord);
10401   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10402     return Builder.CreateFence(AtomicOrdering::Release);
10403   return nullptr;
10404 }
10405 
10406 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10407                                                     Instruction *Inst,
10408                                                     AtomicOrdering Ord) const {
10409   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10410     return Builder.CreateFence(AtomicOrdering::Acquire);
10411   return nullptr;
10412 }
10413 
10414 TargetLowering::AtomicExpansionKind
10415 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10416   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10417   // point operations can't be used in an lr/sc sequence without breaking the
10418   // forward-progress guarantee.
10419   if (AI->isFloatingPointOperation())
10420     return AtomicExpansionKind::CmpXChg;
10421 
10422   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10423   if (Size == 8 || Size == 16)
10424     return AtomicExpansionKind::MaskedIntrinsic;
10425   return AtomicExpansionKind::None;
10426 }
10427 
10428 static Intrinsic::ID
10429 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10430   if (XLen == 32) {
10431     switch (BinOp) {
10432     default:
10433       llvm_unreachable("Unexpected AtomicRMW BinOp");
10434     case AtomicRMWInst::Xchg:
10435       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10436     case AtomicRMWInst::Add:
10437       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10438     case AtomicRMWInst::Sub:
10439       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10440     case AtomicRMWInst::Nand:
10441       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10442     case AtomicRMWInst::Max:
10443       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10444     case AtomicRMWInst::Min:
10445       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10446     case AtomicRMWInst::UMax:
10447       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10448     case AtomicRMWInst::UMin:
10449       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10450     }
10451   }
10452 
10453   if (XLen == 64) {
10454     switch (BinOp) {
10455     default:
10456       llvm_unreachable("Unexpected AtomicRMW BinOp");
10457     case AtomicRMWInst::Xchg:
10458       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10459     case AtomicRMWInst::Add:
10460       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10461     case AtomicRMWInst::Sub:
10462       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10463     case AtomicRMWInst::Nand:
10464       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10465     case AtomicRMWInst::Max:
10466       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10467     case AtomicRMWInst::Min:
10468       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10469     case AtomicRMWInst::UMax:
10470       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10471     case AtomicRMWInst::UMin:
10472       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
10473     }
10474   }
10475 
10476   llvm_unreachable("Unexpected XLen\n");
10477 }
10478 
10479 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10480     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10481     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10482   unsigned XLen = Subtarget.getXLen();
10483   Value *Ordering =
10484       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10485   Type *Tys[] = {AlignedAddr->getType()};
10486   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10487       AI->getModule(),
10488       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10489 
10490   if (XLen == 64) {
10491     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10492     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10493     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10494   }
10495 
10496   Value *Result;
10497 
10498   // Must pass the shift amount needed to sign extend the loaded value prior
10499   // to performing a signed comparison for min/max. ShiftAmt is the number of
10500   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10501   // is the number of bits to left+right shift the value in order to
10502   // sign-extend.
10503   if (AI->getOperation() == AtomicRMWInst::Min ||
10504       AI->getOperation() == AtomicRMWInst::Max) {
10505     const DataLayout &DL = AI->getModule()->getDataLayout();
10506     unsigned ValWidth =
10507         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10508     Value *SextShamt =
10509         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10510     Result = Builder.CreateCall(LrwOpScwLoop,
10511                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10512   } else {
10513     Result =
10514         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10515   }
10516 
10517   if (XLen == 64)
10518     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10519   return Result;
10520 }
10521 
10522 TargetLowering::AtomicExpansionKind
10523 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10524     AtomicCmpXchgInst *CI) const {
10525   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10526   if (Size == 8 || Size == 16)
10527     return AtomicExpansionKind::MaskedIntrinsic;
10528   return AtomicExpansionKind::None;
10529 }
10530 
10531 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10532     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10533     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10534   unsigned XLen = Subtarget.getXLen();
10535   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10536   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10537   if (XLen == 64) {
10538     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10539     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10540     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10541     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10542   }
10543   Type *Tys[] = {AlignedAddr->getType()};
10544   Function *MaskedCmpXchg =
10545       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10546   Value *Result = Builder.CreateCall(
10547       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10548   if (XLen == 64)
10549     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10550   return Result;
10551 }
10552 
10553 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10554   return false;
10555 }
10556 
10557 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10558                                                EVT VT) const {
10559   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10560     return false;
10561 
10562   switch (FPVT.getSimpleVT().SimpleTy) {
10563   case MVT::f16:
10564     return Subtarget.hasStdExtZfh();
10565   case MVT::f32:
10566     return Subtarget.hasStdExtF();
10567   case MVT::f64:
10568     return Subtarget.hasStdExtD();
10569   default:
10570     return false;
10571   }
10572 }
10573 
10574 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
10575   // If we are using the small code model, we can reduce size of jump table
10576   // entry to 4 bytes.
10577   if (Subtarget.is64Bit() && !isPositionIndependent() &&
10578       getTargetMachine().getCodeModel() == CodeModel::Small) {
10579     return MachineJumpTableInfo::EK_Custom32;
10580   }
10581   return TargetLowering::getJumpTableEncoding();
10582 }
10583 
10584 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
10585     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
10586     unsigned uid, MCContext &Ctx) const {
10587   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
10588          getTargetMachine().getCodeModel() == CodeModel::Small);
10589   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
10590 }
10591 
10592 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10593                                                      EVT VT) const {
10594   VT = VT.getScalarType();
10595 
10596   if (!VT.isSimple())
10597     return false;
10598 
10599   switch (VT.getSimpleVT().SimpleTy) {
10600   case MVT::f16:
10601     return Subtarget.hasStdExtZfh();
10602   case MVT::f32:
10603     return Subtarget.hasStdExtF();
10604   case MVT::f64:
10605     return Subtarget.hasStdExtD();
10606   default:
10607     break;
10608   }
10609 
10610   return false;
10611 }
10612 
10613 Register RISCVTargetLowering::getExceptionPointerRegister(
10614     const Constant *PersonalityFn) const {
10615   return RISCV::X10;
10616 }
10617 
10618 Register RISCVTargetLowering::getExceptionSelectorRegister(
10619     const Constant *PersonalityFn) const {
10620   return RISCV::X11;
10621 }
10622 
10623 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10624   // Return false to suppress the unnecessary extensions if the LibCall
10625   // arguments or return value is f32 type for LP64 ABI.
10626   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10627   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10628     return false;
10629 
10630   return true;
10631 }
10632 
10633 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10634   if (Subtarget.is64Bit() && Type == MVT::i32)
10635     return true;
10636 
10637   return IsSigned;
10638 }
10639 
10640 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10641                                                  SDValue C) const {
10642   // Check integral scalar types.
10643   if (VT.isScalarInteger()) {
10644     // Omit the optimization if the sub target has the M extension and the data
10645     // size exceeds XLen.
10646     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10647       return false;
10648     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10649       // Break the MUL to a SLLI and an ADD/SUB.
10650       const APInt &Imm = ConstNode->getAPIntValue();
10651       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10652           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10653         return true;
10654       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10655       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10656           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10657            (Imm - 8).isPowerOf2()))
10658         return true;
10659       // Omit the following optimization if the sub target has the M extension
10660       // and the data size >= XLen.
10661       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10662         return false;
10663       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10664       // a pair of LUI/ADDI.
10665       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10666         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10667         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10668             (1 - ImmS).isPowerOf2())
10669         return true;
10670       }
10671     }
10672   }
10673 
10674   return false;
10675 }
10676 
10677 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10678     const SDValue &AddNode, const SDValue &ConstNode) const {
10679   // Let the DAGCombiner decide for vectors.
10680   EVT VT = AddNode.getValueType();
10681   if (VT.isVector())
10682     return true;
10683 
10684   // Let the DAGCombiner decide for larger types.
10685   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10686     return true;
10687 
10688   // It is worse if c1 is simm12 while c1*c2 is not.
10689   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10690   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10691   const APInt &C1 = C1Node->getAPIntValue();
10692   const APInt &C2 = C2Node->getAPIntValue();
10693   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10694     return false;
10695 
10696   // Default to true and let the DAGCombiner decide.
10697   return true;
10698 }
10699 
10700 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10701     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10702     bool *Fast) const {
10703   if (!VT.isVector())
10704     return false;
10705 
10706   EVT ElemVT = VT.getVectorElementType();
10707   if (Alignment >= ElemVT.getStoreSize()) {
10708     if (Fast)
10709       *Fast = true;
10710     return true;
10711   }
10712 
10713   return false;
10714 }
10715 
10716 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10717     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10718     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10719   bool IsABIRegCopy = CC.hasValue();
10720   EVT ValueVT = Val.getValueType();
10721   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10722     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10723     // and cast to f32.
10724     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10725     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10726     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10727                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10728     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10729     Parts[0] = Val;
10730     return true;
10731   }
10732 
10733   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10734     LLVMContext &Context = *DAG.getContext();
10735     EVT ValueEltVT = ValueVT.getVectorElementType();
10736     EVT PartEltVT = PartVT.getVectorElementType();
10737     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10738     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10739     if (PartVTBitSize % ValueVTBitSize == 0) {
10740       assert(PartVTBitSize >= ValueVTBitSize);
10741       // If the element types are different, bitcast to the same element type of
10742       // PartVT first.
10743       // Give an example here, we want copy a <vscale x 1 x i8> value to
10744       // <vscale x 4 x i16>.
10745       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10746       // subvector, then we can bitcast to <vscale x 4 x i16>.
10747       if (ValueEltVT != PartEltVT) {
10748         if (PartVTBitSize > ValueVTBitSize) {
10749           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10750           assert(Count != 0 && "The number of element should not be zero.");
10751           EVT SameEltTypeVT =
10752               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10753           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10754                             DAG.getUNDEF(SameEltTypeVT), Val,
10755                             DAG.getVectorIdxConstant(0, DL));
10756         }
10757         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10758       } else {
10759         Val =
10760             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10761                         Val, DAG.getVectorIdxConstant(0, DL));
10762       }
10763       Parts[0] = Val;
10764       return true;
10765     }
10766   }
10767   return false;
10768 }
10769 
10770 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10771     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10772     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10773   bool IsABIRegCopy = CC.hasValue();
10774   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10775     SDValue Val = Parts[0];
10776 
10777     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10778     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10779     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10780     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10781     return Val;
10782   }
10783 
10784   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10785     LLVMContext &Context = *DAG.getContext();
10786     SDValue Val = Parts[0];
10787     EVT ValueEltVT = ValueVT.getVectorElementType();
10788     EVT PartEltVT = PartVT.getVectorElementType();
10789     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10790     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10791     if (PartVTBitSize % ValueVTBitSize == 0) {
10792       assert(PartVTBitSize >= ValueVTBitSize);
10793       EVT SameEltTypeVT = ValueVT;
10794       // If the element types are different, convert it to the same element type
10795       // of PartVT.
10796       // Give an example here, we want copy a <vscale x 1 x i8> value from
10797       // <vscale x 4 x i16>.
10798       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10799       // then we can extract <vscale x 1 x i8>.
10800       if (ValueEltVT != PartEltVT) {
10801         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10802         assert(Count != 0 && "The number of element should not be zero.");
10803         SameEltTypeVT =
10804             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10805         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10806       }
10807       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10808                         DAG.getVectorIdxConstant(0, DL));
10809       return Val;
10810     }
10811   }
10812   return SDValue();
10813 }
10814 
10815 SDValue
10816 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10817                                    SelectionDAG &DAG,
10818                                    SmallVectorImpl<SDNode *> &Created) const {
10819   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10820   if (isIntDivCheap(N->getValueType(0), Attr))
10821     return SDValue(N, 0); // Lower SDIV as SDIV
10822 
10823   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
10824          "Unexpected divisor!");
10825 
10826   // Conditional move is needed, so do the transformation iff Zbt is enabled.
10827   if (!Subtarget.hasStdExtZbt())
10828     return SDValue();
10829 
10830   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
10831   // Besides, more critical path instructions will be generated when dividing
10832   // by 2. So we keep using the original DAGs for these cases.
10833   unsigned Lg2 = Divisor.countTrailingZeros();
10834   if (Lg2 == 1 || Lg2 >= 12)
10835     return SDValue();
10836 
10837   // fold (sdiv X, pow2)
10838   EVT VT = N->getValueType(0);
10839   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
10840     return SDValue();
10841 
10842   SDLoc DL(N);
10843   SDValue N0 = N->getOperand(0);
10844   SDValue Zero = DAG.getConstant(0, DL, VT);
10845   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10846 
10847   // Add (N0 < 0) ? Pow2 - 1 : 0;
10848   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
10849   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10850   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
10851 
10852   Created.push_back(Cmp.getNode());
10853   Created.push_back(Add.getNode());
10854   Created.push_back(Sel.getNode());
10855 
10856   // Divide by pow2.
10857   SDValue SRA =
10858       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
10859 
10860   // If we're dividing by a positive value, we're done.  Otherwise, we must
10861   // negate the result.
10862   if (Divisor.isNonNegative())
10863     return SRA;
10864 
10865   Created.push_back(SRA.getNode());
10866   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10867 }
10868 
10869 #define GET_REGISTER_MATCHER
10870 #include "RISCVGenAsmMatcher.inc"
10871 
10872 Register
10873 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10874                                        const MachineFunction &MF) const {
10875   Register Reg = MatchRegisterAltName(RegName);
10876   if (Reg == RISCV::NoRegister)
10877     Reg = MatchRegisterName(RegName);
10878   if (Reg == RISCV::NoRegister)
10879     report_fatal_error(
10880         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10881   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10882   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10883     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10884                              StringRef(RegName) + "\"."));
10885   return Reg;
10886 }
10887 
10888 namespace llvm {
10889 namespace RISCVVIntrinsicsTable {
10890 
10891 #define GET_RISCVVIntrinsicsTable_IMPL
10892 #include "RISCVGenSearchableTables.inc"
10893 
10894 } // namespace RISCVVIntrinsicsTable
10895 
10896 } // namespace llvm
10897