1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
174     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
185   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction(ISD::VAARG, MVT::Other, Expand);
189   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190   setOperationAction(ISD::VAEND, MVT::Other, Expand);
191 
192   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193   if (!Subtarget.hasStdExtZbb()) {
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
195     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
196   }
197 
198   if (Subtarget.is64Bit()) {
199     setOperationAction(ISD::ADD, MVT::i32, Custom);
200     setOperationAction(ISD::SUB, MVT::i32, Custom);
201     setOperationAction(ISD::SHL, MVT::i32, Custom);
202     setOperationAction(ISD::SRA, MVT::i32, Custom);
203     setOperationAction(ISD::SRL, MVT::i32, Custom);
204 
205     setOperationAction(ISD::UADDO, MVT::i32, Custom);
206     setOperationAction(ISD::USUBO, MVT::i32, Custom);
207     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
208     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
209   } else {
210     setLibcallName(RTLIB::SHL_I128, nullptr);
211     setLibcallName(RTLIB::SRL_I128, nullptr);
212     setLibcallName(RTLIB::SRA_I128, nullptr);
213     setLibcallName(RTLIB::MUL_I128, nullptr);
214     setLibcallName(RTLIB::MULO_I64, nullptr);
215   }
216 
217   if (!Subtarget.hasStdExtM()) {
218     setOperationAction(ISD::MUL, XLenVT, Expand);
219     setOperationAction(ISD::MULHS, XLenVT, Expand);
220     setOperationAction(ISD::MULHU, XLenVT, Expand);
221     setOperationAction(ISD::SDIV, XLenVT, Expand);
222     setOperationAction(ISD::UDIV, XLenVT, Expand);
223     setOperationAction(ISD::SREM, XLenVT, Expand);
224     setOperationAction(ISD::UREM, XLenVT, Expand);
225   } else {
226     if (Subtarget.is64Bit()) {
227       setOperationAction(ISD::MUL, MVT::i32, Custom);
228       setOperationAction(ISD::MUL, MVT::i128, Custom);
229 
230       setOperationAction(ISD::SDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UDIV, MVT::i8, Custom);
232       setOperationAction(ISD::UREM, MVT::i8, Custom);
233       setOperationAction(ISD::SDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UDIV, MVT::i16, Custom);
235       setOperationAction(ISD::UREM, MVT::i16, Custom);
236       setOperationAction(ISD::SDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UDIV, MVT::i32, Custom);
238       setOperationAction(ISD::UREM, MVT::i32, Custom);
239     } else {
240       setOperationAction(ISD::MUL, MVT::i64, Custom);
241     }
242   }
243 
244   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
246   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
247   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
248 
249   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
251   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
252 
253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
254       Subtarget.hasStdExtZbkb()) {
255     if (Subtarget.is64Bit()) {
256       setOperationAction(ISD::ROTL, MVT::i32, Custom);
257       setOperationAction(ISD::ROTR, MVT::i32, Custom);
258     }
259   } else {
260     setOperationAction(ISD::ROTL, XLenVT, Expand);
261     setOperationAction(ISD::ROTR, XLenVT, Expand);
262   }
263 
264   if (Subtarget.hasStdExtZbp()) {
265     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
266     // more combining.
267     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
268     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
269     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
270     // BSWAP i8 doesn't exist.
271     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
272     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
273 
274     if (Subtarget.is64Bit()) {
275       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
276       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
277     }
278   } else {
279     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
280     // pattern match it directly in isel.
281     setOperationAction(ISD::BSWAP, XLenVT,
282                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
283                            ? Legal
284                            : Expand);
285     // Zbkb can use rev8+brev8 to implement bitreverse.
286     setOperationAction(ISD::BITREVERSE, XLenVT,
287                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
288   }
289 
290   if (Subtarget.hasStdExtZbb()) {
291     setOperationAction(ISD::SMIN, XLenVT, Legal);
292     setOperationAction(ISD::SMAX, XLenVT, Legal);
293     setOperationAction(ISD::UMIN, XLenVT, Legal);
294     setOperationAction(ISD::UMAX, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit()) {
297       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
298       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
299       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
300       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
301     }
302   } else {
303     setOperationAction(ISD::CTTZ, XLenVT, Expand);
304     setOperationAction(ISD::CTLZ, XLenVT, Expand);
305     setOperationAction(ISD::CTPOP, XLenVT, Expand);
306   }
307 
308   if (Subtarget.hasStdExtZbt()) {
309     setOperationAction(ISD::FSHL, XLenVT, Custom);
310     setOperationAction(ISD::FSHR, XLenVT, Custom);
311     setOperationAction(ISD::SELECT, XLenVT, Legal);
312 
313     if (Subtarget.is64Bit()) {
314       setOperationAction(ISD::FSHL, MVT::i32, Custom);
315       setOperationAction(ISD::FSHR, MVT::i32, Custom);
316     }
317   } else {
318     setOperationAction(ISD::SELECT, XLenVT, Custom);
319   }
320 
321   static const ISD::CondCode FPCCToExpand[] = {
322       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
323       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
324       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
325 
326   static const ISD::NodeType FPOpToExpand[] = {
327       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
328       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
329 
330   if (Subtarget.hasStdExtZfh())
331     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
332 
333   if (Subtarget.hasStdExtZfh()) {
334     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
335     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
336     setOperationAction(ISD::LRINT, MVT::f16, Legal);
337     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
338     setOperationAction(ISD::LROUND, MVT::f16, Legal);
339     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
340     setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal);
341     setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal);
342     setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal);
343     setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal);
344     setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal);
345     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
346     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
348     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
349     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
350     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
352     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal);
353     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal);
354     for (auto CC : FPCCToExpand)
355       setCondCodeAction(CC, MVT::f16, Expand);
356     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
357     setOperationAction(ISD::SELECT, MVT::f16, Custom);
358     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
359 
360     setOperationAction(ISD::FREM,       MVT::f16, Promote);
361     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
362     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
363     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
364     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
365     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
366     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
367     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
368     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
369     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
370     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
371     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
372     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
373     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
374     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
375     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
376     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
377     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
378 
379     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
380     // complete support for all operations in LegalizeDAG.
381 
382     // We need to custom promote this.
383     if (Subtarget.is64Bit())
384       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
385   }
386 
387   if (Subtarget.hasStdExtF()) {
388     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
389     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
390     setOperationAction(ISD::LRINT, MVT::f32, Legal);
391     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
392     setOperationAction(ISD::LROUND, MVT::f32, Legal);
393     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
394     setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal);
395     setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal);
396     setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal);
397     setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal);
398     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
399     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
400     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
401     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
402     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
403     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
404     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
405     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
406     for (auto CC : FPCCToExpand)
407       setCondCodeAction(CC, MVT::f32, Expand);
408     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
409     setOperationAction(ISD::SELECT, MVT::f32, Custom);
410     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
411     for (auto Op : FPOpToExpand)
412       setOperationAction(Op, MVT::f32, Expand);
413     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
414     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
415   }
416 
417   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
418     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
419 
420   if (Subtarget.hasStdExtD()) {
421     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
422     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
423     setOperationAction(ISD::LRINT, MVT::f64, Legal);
424     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
425     setOperationAction(ISD::LROUND, MVT::f64, Legal);
426     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
427     setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal);
428     setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal);
429     setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal);
430     setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal);
431     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
432     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
433     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
434     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
435     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
436     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
437     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
438     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
439     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
440     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
441     for (auto CC : FPCCToExpand)
442       setCondCodeAction(CC, MVT::f64, Expand);
443     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
444     setOperationAction(ISD::SELECT, MVT::f64, Custom);
445     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
446     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
447     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
448     for (auto Op : FPOpToExpand)
449       setOperationAction(Op, MVT::f64, Expand);
450     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
451     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
452   }
453 
454   if (Subtarget.is64Bit()) {
455     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
456     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
457     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
458     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
459   }
460 
461   if (Subtarget.hasStdExtF()) {
462     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
463     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
464 
465     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
466     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
467     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
468     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
469 
470     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
471     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
472   }
473 
474   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
475   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
476   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
477   setOperationAction(ISD::JumpTable, XLenVT, Custom);
478 
479   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
480 
481   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
482   // Unfortunately this can't be determined just from the ISA naming string.
483   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
484                      Subtarget.is64Bit() ? Legal : Custom);
485 
486   setOperationAction(ISD::TRAP, MVT::Other, Legal);
487   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
488   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
489   if (Subtarget.is64Bit())
490     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
491 
492   if (Subtarget.hasStdExtA()) {
493     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
494     setMinCmpXchgSizeInBits(32);
495   } else {
496     setMaxAtomicSizeInBitsSupported(0);
497   }
498 
499   setBooleanContents(ZeroOrOneBooleanContent);
500 
501   if (Subtarget.hasVInstructions()) {
502     setBooleanVectorContents(ZeroOrOneBooleanContent);
503 
504     setOperationAction(ISD::VSCALE, XLenVT, Custom);
505 
506     // RVV intrinsics may have illegal operands.
507     // We also need to custom legalize vmv.x.s.
508     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
509     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
510     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
511     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
512     if (Subtarget.is64Bit()) {
513       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
514     } else {
515       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
516       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
517     }
518 
519     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
520     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
521 
522     static const unsigned IntegerVPOps[] = {
523         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
524         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
525         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
526         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
527         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
528         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
529         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
530         ISD::VP_MERGE,       ISD::VP_SELECT};
531 
532     static const unsigned FloatingPointVPOps[] = {
533         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
534         ISD::VP_FDIV,        ISD::VP_FNEG,        ISD::VP_FMA,
535         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN,
536         ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,       ISD::VP_SELECT};
537 
538     if (!Subtarget.is64Bit()) {
539       // We must custom-lower certain vXi64 operations on RV32 due to the vector
540       // element type being illegal.
541       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
543 
544       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
545       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
546       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
547       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
548       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
549       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
550       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
551       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
552 
553       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
554       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
555       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
556       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
557       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
558       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
559       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
560       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
561     }
562 
563     for (MVT VT : BoolVecVTs) {
564       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
565 
566       // Mask VTs are custom-expanded into a series of standard nodes
567       setOperationAction(ISD::TRUNCATE, VT, Custom);
568       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
569       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
570       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
571 
572       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
573       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
574 
575       setOperationAction(ISD::SELECT, VT, Custom);
576       setOperationAction(ISD::SELECT_CC, VT, Expand);
577       setOperationAction(ISD::VSELECT, VT, Expand);
578       setOperationAction(ISD::VP_MERGE, VT, Expand);
579       setOperationAction(ISD::VP_SELECT, VT, Expand);
580 
581       setOperationAction(ISD::VP_AND, VT, Custom);
582       setOperationAction(ISD::VP_OR, VT, Custom);
583       setOperationAction(ISD::VP_XOR, VT, Custom);
584 
585       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
586       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
587       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
588 
589       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
590       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
591       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
592 
593       // RVV has native int->float & float->int conversions where the
594       // element type sizes are within one power-of-two of each other. Any
595       // wider distances between type sizes have to be lowered as sequences
596       // which progressively narrow the gap in stages.
597       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
598       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
599       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
600       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
601 
602       // Expand all extending loads to types larger than this, and truncating
603       // stores from types larger than this.
604       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
605         setTruncStoreAction(OtherVT, VT, Expand);
606         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
607         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
608         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
609       }
610     }
611 
612     for (MVT VT : IntVecVTs) {
613       if (VT.getVectorElementType() == MVT::i64 &&
614           !Subtarget.hasVInstructionsI64())
615         continue;
616 
617       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
618       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
619 
620       // Vectors implement MULHS/MULHU.
621       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
622       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
623 
624       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
625       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
626         setOperationAction(ISD::MULHU, VT, Expand);
627         setOperationAction(ISD::MULHS, VT, Expand);
628       }
629 
630       setOperationAction(ISD::SMIN, VT, Legal);
631       setOperationAction(ISD::SMAX, VT, Legal);
632       setOperationAction(ISD::UMIN, VT, Legal);
633       setOperationAction(ISD::UMAX, VT, Legal);
634 
635       setOperationAction(ISD::ROTL, VT, Expand);
636       setOperationAction(ISD::ROTR, VT, Expand);
637 
638       setOperationAction(ISD::CTTZ, VT, Expand);
639       setOperationAction(ISD::CTLZ, VT, Expand);
640       setOperationAction(ISD::CTPOP, VT, Expand);
641 
642       setOperationAction(ISD::BSWAP, VT, Expand);
643 
644       // Custom-lower extensions and truncations from/to mask types.
645       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
646       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
647       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
648 
649       // RVV has native int->float & float->int conversions where the
650       // element type sizes are within one power-of-two of each other. Any
651       // wider distances between type sizes have to be lowered as sequences
652       // which progressively narrow the gap in stages.
653       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
654       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
655       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
656       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
657 
658       setOperationAction(ISD::SADDSAT, VT, Legal);
659       setOperationAction(ISD::UADDSAT, VT, Legal);
660       setOperationAction(ISD::SSUBSAT, VT, Legal);
661       setOperationAction(ISD::USUBSAT, VT, Legal);
662 
663       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
664       // nodes which truncate by one power of two at a time.
665       setOperationAction(ISD::TRUNCATE, VT, Custom);
666 
667       // Custom-lower insert/extract operations to simplify patterns.
668       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
669       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
670 
671       // Custom-lower reduction operations to set up the corresponding custom
672       // nodes' operands.
673       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
674       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
675       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
676       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
677       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
678       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
679       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
680       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
681 
682       for (unsigned VPOpc : IntegerVPOps)
683         setOperationAction(VPOpc, VT, Custom);
684 
685       setOperationAction(ISD::LOAD, VT, Custom);
686       setOperationAction(ISD::STORE, VT, Custom);
687 
688       setOperationAction(ISD::MLOAD, VT, Custom);
689       setOperationAction(ISD::MSTORE, VT, Custom);
690       setOperationAction(ISD::MGATHER, VT, Custom);
691       setOperationAction(ISD::MSCATTER, VT, Custom);
692 
693       setOperationAction(ISD::VP_LOAD, VT, Custom);
694       setOperationAction(ISD::VP_STORE, VT, Custom);
695       setOperationAction(ISD::VP_GATHER, VT, Custom);
696       setOperationAction(ISD::VP_SCATTER, VT, Custom);
697 
698       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
699       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
700       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
701 
702       setOperationAction(ISD::SELECT, VT, Custom);
703       setOperationAction(ISD::SELECT_CC, VT, Expand);
704 
705       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
706       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
707 
708       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
709         setTruncStoreAction(VT, OtherVT, Expand);
710         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
711         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
712         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
713       }
714 
715       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
716       // type that can represent the value exactly.
717       if (VT.getVectorElementType() != MVT::i64) {
718         MVT FloatEltVT =
719             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
720         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
721         if (isTypeLegal(FloatVT)) {
722           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
723           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
724         }
725       }
726     }
727 
728     // Expand various CCs to best match the RVV ISA, which natively supports UNE
729     // but no other unordered comparisons, and supports all ordered comparisons
730     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
731     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
732     // and we pattern-match those back to the "original", swapping operands once
733     // more. This way we catch both operations and both "vf" and "fv" forms with
734     // fewer patterns.
735     static const ISD::CondCode VFPCCToExpand[] = {
736         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
737         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
738         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
739     };
740 
741     // Sets common operation actions on RVV floating-point vector types.
742     const auto SetCommonVFPActions = [&](MVT VT) {
743       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
744       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
745       // sizes are within one power-of-two of each other. Therefore conversions
746       // between vXf16 and vXf64 must be lowered as sequences which convert via
747       // vXf32.
748       setOperationAction(ISD::FP_ROUND, VT, Custom);
749       setOperationAction(ISD::FP_EXTEND, VT, Custom);
750       // Custom-lower insert/extract operations to simplify patterns.
751       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
752       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
753       // Expand various condition codes (explained above).
754       for (auto CC : VFPCCToExpand)
755         setCondCodeAction(CC, VT, Expand);
756 
757       setOperationAction(ISD::FMINNUM, VT, Legal);
758       setOperationAction(ISD::FMAXNUM, VT, Legal);
759 
760       setOperationAction(ISD::FTRUNC, VT, Custom);
761       setOperationAction(ISD::FCEIL, VT, Custom);
762       setOperationAction(ISD::FFLOOR, VT, Custom);
763       setOperationAction(ISD::FROUND, VT, Custom);
764 
765       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
766       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
767       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
768       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
769 
770       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
771 
772       setOperationAction(ISD::LOAD, VT, Custom);
773       setOperationAction(ISD::STORE, VT, Custom);
774 
775       setOperationAction(ISD::MLOAD, VT, Custom);
776       setOperationAction(ISD::MSTORE, VT, Custom);
777       setOperationAction(ISD::MGATHER, VT, Custom);
778       setOperationAction(ISD::MSCATTER, VT, Custom);
779 
780       setOperationAction(ISD::VP_LOAD, VT, Custom);
781       setOperationAction(ISD::VP_STORE, VT, Custom);
782       setOperationAction(ISD::VP_GATHER, VT, Custom);
783       setOperationAction(ISD::VP_SCATTER, VT, Custom);
784 
785       setOperationAction(ISD::SELECT, VT, Custom);
786       setOperationAction(ISD::SELECT_CC, VT, Expand);
787 
788       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
789       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
790       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
791 
792       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
793 
794       for (unsigned VPOpc : FloatingPointVPOps)
795         setOperationAction(VPOpc, VT, Custom);
796     };
797 
798     // Sets common extload/truncstore actions on RVV floating-point vector
799     // types.
800     const auto SetCommonVFPExtLoadTruncStoreActions =
801         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
802           for (auto SmallVT : SmallerVTs) {
803             setTruncStoreAction(VT, SmallVT, Expand);
804             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
805           }
806         };
807 
808     if (Subtarget.hasVInstructionsF16())
809       for (MVT VT : F16VecVTs)
810         SetCommonVFPActions(VT);
811 
812     for (MVT VT : F32VecVTs) {
813       if (Subtarget.hasVInstructionsF32())
814         SetCommonVFPActions(VT);
815       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
816     }
817 
818     for (MVT VT : F64VecVTs) {
819       if (Subtarget.hasVInstructionsF64())
820         SetCommonVFPActions(VT);
821       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
822       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
823     }
824 
825     if (Subtarget.useRVVForFixedLengthVectors()) {
826       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
827         if (!useRVVForFixedLengthVectorVT(VT))
828           continue;
829 
830         // By default everything must be expanded.
831         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
832           setOperationAction(Op, VT, Expand);
833         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
834           setTruncStoreAction(VT, OtherVT, Expand);
835           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
836           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
837           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
838         }
839 
840         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
841         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
842         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
843 
844         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
845         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
846 
847         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
848         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
849 
850         setOperationAction(ISD::LOAD, VT, Custom);
851         setOperationAction(ISD::STORE, VT, Custom);
852 
853         setOperationAction(ISD::SETCC, VT, Custom);
854 
855         setOperationAction(ISD::SELECT, VT, Custom);
856 
857         setOperationAction(ISD::TRUNCATE, VT, Custom);
858 
859         setOperationAction(ISD::BITCAST, VT, Custom);
860 
861         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
862         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
863         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
864 
865         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
866         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
867         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
868 
869         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
870         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
871         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
872         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
873 
874         // Operations below are different for between masks and other vectors.
875         if (VT.getVectorElementType() == MVT::i1) {
876           setOperationAction(ISD::VP_AND, VT, Custom);
877           setOperationAction(ISD::VP_OR, VT, Custom);
878           setOperationAction(ISD::VP_XOR, VT, Custom);
879           setOperationAction(ISD::AND, VT, Custom);
880           setOperationAction(ISD::OR, VT, Custom);
881           setOperationAction(ISD::XOR, VT, Custom);
882           continue;
883         }
884 
885         // Use SPLAT_VECTOR to prevent type legalization from destroying the
886         // splats when type legalizing i64 scalar on RV32.
887         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
888         // improvements first.
889         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
890           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
891           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
892         }
893 
894         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
895         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
896 
897         setOperationAction(ISD::MLOAD, VT, Custom);
898         setOperationAction(ISD::MSTORE, VT, Custom);
899         setOperationAction(ISD::MGATHER, VT, Custom);
900         setOperationAction(ISD::MSCATTER, VT, Custom);
901 
902         setOperationAction(ISD::VP_LOAD, VT, Custom);
903         setOperationAction(ISD::VP_STORE, VT, Custom);
904         setOperationAction(ISD::VP_GATHER, VT, Custom);
905         setOperationAction(ISD::VP_SCATTER, VT, Custom);
906 
907         setOperationAction(ISD::ADD, VT, Custom);
908         setOperationAction(ISD::MUL, VT, Custom);
909         setOperationAction(ISD::SUB, VT, Custom);
910         setOperationAction(ISD::AND, VT, Custom);
911         setOperationAction(ISD::OR, VT, Custom);
912         setOperationAction(ISD::XOR, VT, Custom);
913         setOperationAction(ISD::SDIV, VT, Custom);
914         setOperationAction(ISD::SREM, VT, Custom);
915         setOperationAction(ISD::UDIV, VT, Custom);
916         setOperationAction(ISD::UREM, VT, Custom);
917         setOperationAction(ISD::SHL, VT, Custom);
918         setOperationAction(ISD::SRA, VT, Custom);
919         setOperationAction(ISD::SRL, VT, Custom);
920 
921         setOperationAction(ISD::SMIN, VT, Custom);
922         setOperationAction(ISD::SMAX, VT, Custom);
923         setOperationAction(ISD::UMIN, VT, Custom);
924         setOperationAction(ISD::UMAX, VT, Custom);
925         setOperationAction(ISD::ABS,  VT, Custom);
926 
927         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
928         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
929           setOperationAction(ISD::MULHS, VT, Custom);
930           setOperationAction(ISD::MULHU, VT, Custom);
931         }
932 
933         setOperationAction(ISD::SADDSAT, VT, Custom);
934         setOperationAction(ISD::UADDSAT, VT, Custom);
935         setOperationAction(ISD::SSUBSAT, VT, Custom);
936         setOperationAction(ISD::USUBSAT, VT, Custom);
937 
938         setOperationAction(ISD::VSELECT, VT, Custom);
939         setOperationAction(ISD::SELECT_CC, VT, Expand);
940 
941         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
942         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
943         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
944 
945         // Custom-lower reduction operations to set up the corresponding custom
946         // nodes' operands.
947         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
948         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
949         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
950         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
951         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
952 
953         for (unsigned VPOpc : IntegerVPOps)
954           setOperationAction(VPOpc, VT, Custom);
955 
956         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
957         // type that can represent the value exactly.
958         if (VT.getVectorElementType() != MVT::i64) {
959           MVT FloatEltVT =
960               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
961           EVT FloatVT =
962               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
963           if (isTypeLegal(FloatVT)) {
964             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
965             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
966           }
967         }
968       }
969 
970       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
971         if (!useRVVForFixedLengthVectorVT(VT))
972           continue;
973 
974         // By default everything must be expanded.
975         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
976           setOperationAction(Op, VT, Expand);
977         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
978           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
979           setTruncStoreAction(VT, OtherVT, Expand);
980         }
981 
982         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
983         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
984         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
985 
986         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
987         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
988         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
989         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
990         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
991 
992         setOperationAction(ISD::LOAD, VT, Custom);
993         setOperationAction(ISD::STORE, VT, Custom);
994         setOperationAction(ISD::MLOAD, VT, Custom);
995         setOperationAction(ISD::MSTORE, VT, Custom);
996         setOperationAction(ISD::MGATHER, VT, Custom);
997         setOperationAction(ISD::MSCATTER, VT, Custom);
998 
999         setOperationAction(ISD::VP_LOAD, VT, Custom);
1000         setOperationAction(ISD::VP_STORE, VT, Custom);
1001         setOperationAction(ISD::VP_GATHER, VT, Custom);
1002         setOperationAction(ISD::VP_SCATTER, VT, Custom);
1003 
1004         setOperationAction(ISD::FADD, VT, Custom);
1005         setOperationAction(ISD::FSUB, VT, Custom);
1006         setOperationAction(ISD::FMUL, VT, Custom);
1007         setOperationAction(ISD::FDIV, VT, Custom);
1008         setOperationAction(ISD::FNEG, VT, Custom);
1009         setOperationAction(ISD::FABS, VT, Custom);
1010         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1011         setOperationAction(ISD::FSQRT, VT, Custom);
1012         setOperationAction(ISD::FMA, VT, Custom);
1013         setOperationAction(ISD::FMINNUM, VT, Custom);
1014         setOperationAction(ISD::FMAXNUM, VT, Custom);
1015 
1016         setOperationAction(ISD::FP_ROUND, VT, Custom);
1017         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1018 
1019         setOperationAction(ISD::FTRUNC, VT, Custom);
1020         setOperationAction(ISD::FCEIL, VT, Custom);
1021         setOperationAction(ISD::FFLOOR, VT, Custom);
1022         setOperationAction(ISD::FROUND, VT, Custom);
1023 
1024         for (auto CC : VFPCCToExpand)
1025           setCondCodeAction(CC, VT, Expand);
1026 
1027         setOperationAction(ISD::VSELECT, VT, Custom);
1028         setOperationAction(ISD::SELECT, VT, Custom);
1029         setOperationAction(ISD::SELECT_CC, VT, Expand);
1030 
1031         setOperationAction(ISD::BITCAST, VT, Custom);
1032 
1033         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1034         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1035         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1036         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1037 
1038         for (unsigned VPOpc : FloatingPointVPOps)
1039           setOperationAction(VPOpc, VT, Custom);
1040       }
1041 
1042       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1043       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1044       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1045       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1046       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1047       if (Subtarget.hasStdExtZfh())
1048         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1049       if (Subtarget.hasStdExtF())
1050         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1051       if (Subtarget.hasStdExtD())
1052         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1053     }
1054   }
1055 
1056   // Function alignments.
1057   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1058   setMinFunctionAlignment(FunctionAlignment);
1059   setPrefFunctionAlignment(FunctionAlignment);
1060 
1061   setMinimumJumpTableEntries(5);
1062 
1063   // Jumps are expensive, compared to logic
1064   setJumpIsExpensive();
1065 
1066   setTargetDAGCombine(ISD::ADD);
1067   setTargetDAGCombine(ISD::SUB);
1068   setTargetDAGCombine(ISD::AND);
1069   setTargetDAGCombine(ISD::OR);
1070   setTargetDAGCombine(ISD::XOR);
1071   setTargetDAGCombine(ISD::ROTL);
1072   setTargetDAGCombine(ISD::ROTR);
1073   setTargetDAGCombine(ISD::ANY_EXTEND);
1074   if (Subtarget.hasStdExtF()) {
1075     setTargetDAGCombine(ISD::ZERO_EXTEND);
1076     setTargetDAGCombine(ISD::FP_TO_SINT);
1077     setTargetDAGCombine(ISD::FP_TO_UINT);
1078     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1079     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1080   }
1081   if (Subtarget.hasVInstructions()) {
1082     setTargetDAGCombine(ISD::FCOPYSIGN);
1083     setTargetDAGCombine(ISD::MGATHER);
1084     setTargetDAGCombine(ISD::MSCATTER);
1085     setTargetDAGCombine(ISD::VP_GATHER);
1086     setTargetDAGCombine(ISD::VP_SCATTER);
1087     setTargetDAGCombine(ISD::SRA);
1088     setTargetDAGCombine(ISD::SRL);
1089     setTargetDAGCombine(ISD::SHL);
1090     setTargetDAGCombine(ISD::STORE);
1091     setTargetDAGCombine(ISD::SPLAT_VECTOR);
1092   }
1093 
1094   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1095   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1096 }
1097 
1098 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1099                                             LLVMContext &Context,
1100                                             EVT VT) const {
1101   if (!VT.isVector())
1102     return getPointerTy(DL);
1103   if (Subtarget.hasVInstructions() &&
1104       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1105     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1106   return VT.changeVectorElementTypeToInteger();
1107 }
1108 
1109 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1110   return Subtarget.getXLenVT();
1111 }
1112 
1113 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1114                                              const CallInst &I,
1115                                              MachineFunction &MF,
1116                                              unsigned Intrinsic) const {
1117   auto &DL = I.getModule()->getDataLayout();
1118   switch (Intrinsic) {
1119   default:
1120     return false;
1121   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1122   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1123   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1124   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1125   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1126   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1127   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1128   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1129   case Intrinsic::riscv_masked_cmpxchg_i32:
1130     Info.opc = ISD::INTRINSIC_W_CHAIN;
1131     Info.memVT = MVT::i32;
1132     Info.ptrVal = I.getArgOperand(0);
1133     Info.offset = 0;
1134     Info.align = Align(4);
1135     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1136                  MachineMemOperand::MOVolatile;
1137     return true;
1138   case Intrinsic::riscv_masked_strided_load:
1139     Info.opc = ISD::INTRINSIC_W_CHAIN;
1140     Info.ptrVal = I.getArgOperand(1);
1141     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1142     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1143     Info.size = MemoryLocation::UnknownSize;
1144     Info.flags |= MachineMemOperand::MOLoad;
1145     return true;
1146   case Intrinsic::riscv_masked_strided_store:
1147     Info.opc = ISD::INTRINSIC_VOID;
1148     Info.ptrVal = I.getArgOperand(1);
1149     Info.memVT =
1150         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1151     Info.align = Align(
1152         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1153         8);
1154     Info.size = MemoryLocation::UnknownSize;
1155     Info.flags |= MachineMemOperand::MOStore;
1156     return true;
1157   }
1158 }
1159 
1160 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1161                                                 const AddrMode &AM, Type *Ty,
1162                                                 unsigned AS,
1163                                                 Instruction *I) const {
1164   // No global is ever allowed as a base.
1165   if (AM.BaseGV)
1166     return false;
1167 
1168   // Require a 12-bit signed offset.
1169   if (!isInt<12>(AM.BaseOffs))
1170     return false;
1171 
1172   switch (AM.Scale) {
1173   case 0: // "r+i" or just "i", depending on HasBaseReg.
1174     break;
1175   case 1:
1176     if (!AM.HasBaseReg) // allow "r+i".
1177       break;
1178     return false; // disallow "r+r" or "r+r+i".
1179   default:
1180     return false;
1181   }
1182 
1183   return true;
1184 }
1185 
1186 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1187   return isInt<12>(Imm);
1188 }
1189 
1190 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1191   return isInt<12>(Imm);
1192 }
1193 
1194 // On RV32, 64-bit integers are split into their high and low parts and held
1195 // in two different registers, so the trunc is free since the low register can
1196 // just be used.
1197 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1198   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1199     return false;
1200   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1201   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1202   return (SrcBits == 64 && DestBits == 32);
1203 }
1204 
1205 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1206   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1207       !SrcVT.isInteger() || !DstVT.isInteger())
1208     return false;
1209   unsigned SrcBits = SrcVT.getSizeInBits();
1210   unsigned DestBits = DstVT.getSizeInBits();
1211   return (SrcBits == 64 && DestBits == 32);
1212 }
1213 
1214 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1215   // Zexts are free if they can be combined with a load.
1216   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1217   // poorly with type legalization of compares preferring sext.
1218   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1219     EVT MemVT = LD->getMemoryVT();
1220     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1221         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1222          LD->getExtensionType() == ISD::ZEXTLOAD))
1223       return true;
1224   }
1225 
1226   return TargetLowering::isZExtFree(Val, VT2);
1227 }
1228 
1229 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1230   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1231 }
1232 
1233 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1234   return Subtarget.hasStdExtZbb();
1235 }
1236 
1237 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1238   return Subtarget.hasStdExtZbb();
1239 }
1240 
1241 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1242   EVT VT = Y.getValueType();
1243 
1244   // FIXME: Support vectors once we have tests.
1245   if (VT.isVector())
1246     return false;
1247 
1248   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1249           Subtarget.hasStdExtZbkb()) &&
1250          !isa<ConstantSDNode>(Y);
1251 }
1252 
1253 /// Check if sinking \p I's operands to I's basic block is profitable, because
1254 /// the operands can be folded into a target instruction, e.g.
1255 /// splats of scalars can fold into vector instructions.
1256 bool RISCVTargetLowering::shouldSinkOperands(
1257     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1258   using namespace llvm::PatternMatch;
1259 
1260   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1261     return false;
1262 
1263   auto IsSinker = [&](Instruction *I, int Operand) {
1264     switch (I->getOpcode()) {
1265     case Instruction::Add:
1266     case Instruction::Sub:
1267     case Instruction::Mul:
1268     case Instruction::And:
1269     case Instruction::Or:
1270     case Instruction::Xor:
1271     case Instruction::FAdd:
1272     case Instruction::FSub:
1273     case Instruction::FMul:
1274     case Instruction::FDiv:
1275     case Instruction::ICmp:
1276     case Instruction::FCmp:
1277       return true;
1278     case Instruction::Shl:
1279     case Instruction::LShr:
1280     case Instruction::AShr:
1281     case Instruction::UDiv:
1282     case Instruction::SDiv:
1283     case Instruction::URem:
1284     case Instruction::SRem:
1285       return Operand == 1;
1286     case Instruction::Call:
1287       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1288         switch (II->getIntrinsicID()) {
1289         case Intrinsic::fma:
1290           return Operand == 0 || Operand == 1;
1291         // FIXME: Our patterns can only match vx/vf instructions when the splat
1292         // it on the RHS, because TableGen doesn't recognize our VP operations
1293         // as commutative.
1294         case Intrinsic::vp_add:
1295         case Intrinsic::vp_mul:
1296         case Intrinsic::vp_and:
1297         case Intrinsic::vp_or:
1298         case Intrinsic::vp_xor:
1299         case Intrinsic::vp_fadd:
1300         case Intrinsic::vp_fmul:
1301         case Intrinsic::vp_shl:
1302         case Intrinsic::vp_lshr:
1303         case Intrinsic::vp_ashr:
1304         case Intrinsic::vp_udiv:
1305         case Intrinsic::vp_sdiv:
1306         case Intrinsic::vp_urem:
1307         case Intrinsic::vp_srem:
1308           return Operand == 1;
1309         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1310         // explicit patterns for both LHS and RHS (as 'vr' versions).
1311         case Intrinsic::vp_sub:
1312         case Intrinsic::vp_fsub:
1313         case Intrinsic::vp_fdiv:
1314           return Operand == 0 || Operand == 1;
1315         default:
1316           return false;
1317         }
1318       }
1319       return false;
1320     default:
1321       return false;
1322     }
1323   };
1324 
1325   for (auto OpIdx : enumerate(I->operands())) {
1326     if (!IsSinker(I, OpIdx.index()))
1327       continue;
1328 
1329     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1330     // Make sure we are not already sinking this operand
1331     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1332       continue;
1333 
1334     // We are looking for a splat that can be sunk.
1335     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1336                              m_Undef(), m_ZeroMask())))
1337       continue;
1338 
1339     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1340     // and vector registers
1341     for (Use &U : Op->uses()) {
1342       Instruction *Insn = cast<Instruction>(U.getUser());
1343       if (!IsSinker(Insn, U.getOperandNo()))
1344         return false;
1345     }
1346 
1347     Ops.push_back(&Op->getOperandUse(0));
1348     Ops.push_back(&OpIdx.value());
1349   }
1350   return true;
1351 }
1352 
1353 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1354                                        bool ForCodeSize) const {
1355   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1356   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1357     return false;
1358   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1359     return false;
1360   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1361     return false;
1362   return Imm.isZero();
1363 }
1364 
1365 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1366   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1367          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1368          (VT == MVT::f64 && Subtarget.hasStdExtD());
1369 }
1370 
1371 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1372                                                       CallingConv::ID CC,
1373                                                       EVT VT) const {
1374   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1375   // We might still end up using a GPR but that will be decided based on ABI.
1376   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1377   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1378     return MVT::f32;
1379 
1380   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1381 }
1382 
1383 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1384                                                            CallingConv::ID CC,
1385                                                            EVT VT) const {
1386   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1387   // We might still end up using a GPR but that will be decided based on ABI.
1388   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1389   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1390     return 1;
1391 
1392   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1393 }
1394 
1395 // Changes the condition code and swaps operands if necessary, so the SetCC
1396 // operation matches one of the comparisons supported directly by branches
1397 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1398 // with 1/-1.
1399 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1400                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1401   // Convert X > -1 to X >= 0.
1402   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1403     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1404     CC = ISD::SETGE;
1405     return;
1406   }
1407   // Convert X < 1 to 0 >= X.
1408   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1409     RHS = LHS;
1410     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1411     CC = ISD::SETGE;
1412     return;
1413   }
1414 
1415   switch (CC) {
1416   default:
1417     break;
1418   case ISD::SETGT:
1419   case ISD::SETLE:
1420   case ISD::SETUGT:
1421   case ISD::SETULE:
1422     CC = ISD::getSetCCSwappedOperands(CC);
1423     std::swap(LHS, RHS);
1424     break;
1425   }
1426 }
1427 
1428 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1429   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1430   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1431   if (VT.getVectorElementType() == MVT::i1)
1432     KnownSize *= 8;
1433 
1434   switch (KnownSize) {
1435   default:
1436     llvm_unreachable("Invalid LMUL.");
1437   case 8:
1438     return RISCVII::VLMUL::LMUL_F8;
1439   case 16:
1440     return RISCVII::VLMUL::LMUL_F4;
1441   case 32:
1442     return RISCVII::VLMUL::LMUL_F2;
1443   case 64:
1444     return RISCVII::VLMUL::LMUL_1;
1445   case 128:
1446     return RISCVII::VLMUL::LMUL_2;
1447   case 256:
1448     return RISCVII::VLMUL::LMUL_4;
1449   case 512:
1450     return RISCVII::VLMUL::LMUL_8;
1451   }
1452 }
1453 
1454 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1455   switch (LMul) {
1456   default:
1457     llvm_unreachable("Invalid LMUL.");
1458   case RISCVII::VLMUL::LMUL_F8:
1459   case RISCVII::VLMUL::LMUL_F4:
1460   case RISCVII::VLMUL::LMUL_F2:
1461   case RISCVII::VLMUL::LMUL_1:
1462     return RISCV::VRRegClassID;
1463   case RISCVII::VLMUL::LMUL_2:
1464     return RISCV::VRM2RegClassID;
1465   case RISCVII::VLMUL::LMUL_4:
1466     return RISCV::VRM4RegClassID;
1467   case RISCVII::VLMUL::LMUL_8:
1468     return RISCV::VRM8RegClassID;
1469   }
1470 }
1471 
1472 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1473   RISCVII::VLMUL LMUL = getLMUL(VT);
1474   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1475       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1476       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1477       LMUL == RISCVII::VLMUL::LMUL_1) {
1478     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1479                   "Unexpected subreg numbering");
1480     return RISCV::sub_vrm1_0 + Index;
1481   }
1482   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1483     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1484                   "Unexpected subreg numbering");
1485     return RISCV::sub_vrm2_0 + Index;
1486   }
1487   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1488     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1489                   "Unexpected subreg numbering");
1490     return RISCV::sub_vrm4_0 + Index;
1491   }
1492   llvm_unreachable("Invalid vector type.");
1493 }
1494 
1495 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1496   if (VT.getVectorElementType() == MVT::i1)
1497     return RISCV::VRRegClassID;
1498   return getRegClassIDForLMUL(getLMUL(VT));
1499 }
1500 
1501 // Attempt to decompose a subvector insert/extract between VecVT and
1502 // SubVecVT via subregister indices. Returns the subregister index that
1503 // can perform the subvector insert/extract with the given element index, as
1504 // well as the index corresponding to any leftover subvectors that must be
1505 // further inserted/extracted within the register class for SubVecVT.
1506 std::pair<unsigned, unsigned>
1507 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1508     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1509     const RISCVRegisterInfo *TRI) {
1510   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1511                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1512                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1513                 "Register classes not ordered");
1514   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1515   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1516   // Try to compose a subregister index that takes us from the incoming
1517   // LMUL>1 register class down to the outgoing one. At each step we half
1518   // the LMUL:
1519   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1520   // Note that this is not guaranteed to find a subregister index, such as
1521   // when we are extracting from one VR type to another.
1522   unsigned SubRegIdx = RISCV::NoSubRegister;
1523   for (const unsigned RCID :
1524        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1525     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1526       VecVT = VecVT.getHalfNumVectorElementsVT();
1527       bool IsHi =
1528           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1529       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1530                                             getSubregIndexByMVT(VecVT, IsHi));
1531       if (IsHi)
1532         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1533     }
1534   return {SubRegIdx, InsertExtractIdx};
1535 }
1536 
1537 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1538 // stores for those types.
1539 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1540   return !Subtarget.useRVVForFixedLengthVectors() ||
1541          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1542 }
1543 
1544 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1545   if (ScalarTy->isPointerTy())
1546     return true;
1547 
1548   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1549       ScalarTy->isIntegerTy(32))
1550     return true;
1551 
1552   if (ScalarTy->isIntegerTy(64))
1553     return Subtarget.hasVInstructionsI64();
1554 
1555   if (ScalarTy->isHalfTy())
1556     return Subtarget.hasVInstructionsF16();
1557   if (ScalarTy->isFloatTy())
1558     return Subtarget.hasVInstructionsF32();
1559   if (ScalarTy->isDoubleTy())
1560     return Subtarget.hasVInstructionsF64();
1561 
1562   return false;
1563 }
1564 
1565 static SDValue getVLOperand(SDValue Op) {
1566   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1567           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1568          "Unexpected opcode");
1569   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1570   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1571   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1572       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1573   if (!II)
1574     return SDValue();
1575   return Op.getOperand(II->VLOperand + 1 + HasChain);
1576 }
1577 
1578 static bool useRVVForFixedLengthVectorVT(MVT VT,
1579                                          const RISCVSubtarget &Subtarget) {
1580   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1581   if (!Subtarget.useRVVForFixedLengthVectors())
1582     return false;
1583 
1584   // We only support a set of vector types with a consistent maximum fixed size
1585   // across all supported vector element types to avoid legalization issues.
1586   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1587   // fixed-length vector type we support is 1024 bytes.
1588   if (VT.getFixedSizeInBits() > 1024 * 8)
1589     return false;
1590 
1591   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1592 
1593   MVT EltVT = VT.getVectorElementType();
1594 
1595   // Don't use RVV for vectors we cannot scalarize if required.
1596   switch (EltVT.SimpleTy) {
1597   // i1 is supported but has different rules.
1598   default:
1599     return false;
1600   case MVT::i1:
1601     // Masks can only use a single register.
1602     if (VT.getVectorNumElements() > MinVLen)
1603       return false;
1604     MinVLen /= 8;
1605     break;
1606   case MVT::i8:
1607   case MVT::i16:
1608   case MVT::i32:
1609     break;
1610   case MVT::i64:
1611     if (!Subtarget.hasVInstructionsI64())
1612       return false;
1613     break;
1614   case MVT::f16:
1615     if (!Subtarget.hasVInstructionsF16())
1616       return false;
1617     break;
1618   case MVT::f32:
1619     if (!Subtarget.hasVInstructionsF32())
1620       return false;
1621     break;
1622   case MVT::f64:
1623     if (!Subtarget.hasVInstructionsF64())
1624       return false;
1625     break;
1626   }
1627 
1628   // Reject elements larger than ELEN.
1629   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1630     return false;
1631 
1632   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1633   // Don't use RVV for types that don't fit.
1634   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1635     return false;
1636 
1637   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1638   // the base fixed length RVV support in place.
1639   if (!VT.isPow2VectorType())
1640     return false;
1641 
1642   return true;
1643 }
1644 
1645 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1646   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1647 }
1648 
1649 // Return the largest legal scalable vector type that matches VT's element type.
1650 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1651                                             const RISCVSubtarget &Subtarget) {
1652   // This may be called before legal types are setup.
1653   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1654           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1655          "Expected legal fixed length vector!");
1656 
1657   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1658   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1659 
1660   MVT EltVT = VT.getVectorElementType();
1661   switch (EltVT.SimpleTy) {
1662   default:
1663     llvm_unreachable("unexpected element type for RVV container");
1664   case MVT::i1:
1665   case MVT::i8:
1666   case MVT::i16:
1667   case MVT::i32:
1668   case MVT::i64:
1669   case MVT::f16:
1670   case MVT::f32:
1671   case MVT::f64: {
1672     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1673     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1674     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1675     unsigned NumElts =
1676         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1677     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1678     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1679     return MVT::getScalableVectorVT(EltVT, NumElts);
1680   }
1681   }
1682 }
1683 
1684 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1685                                             const RISCVSubtarget &Subtarget) {
1686   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1687                                           Subtarget);
1688 }
1689 
1690 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1691   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1692 }
1693 
1694 // Grow V to consume an entire RVV register.
1695 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1696                                        const RISCVSubtarget &Subtarget) {
1697   assert(VT.isScalableVector() &&
1698          "Expected to convert into a scalable vector!");
1699   assert(V.getValueType().isFixedLengthVector() &&
1700          "Expected a fixed length vector operand!");
1701   SDLoc DL(V);
1702   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1703   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1704 }
1705 
1706 // Shrink V so it's just big enough to maintain a VT's worth of data.
1707 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1708                                          const RISCVSubtarget &Subtarget) {
1709   assert(VT.isFixedLengthVector() &&
1710          "Expected to convert into a fixed length vector!");
1711   assert(V.getValueType().isScalableVector() &&
1712          "Expected a scalable vector operand!");
1713   SDLoc DL(V);
1714   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1715   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1716 }
1717 
1718 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1719 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1720 // the vector type that it is contained in.
1721 static std::pair<SDValue, SDValue>
1722 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1723                 const RISCVSubtarget &Subtarget) {
1724   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1725   MVT XLenVT = Subtarget.getXLenVT();
1726   SDValue VL = VecVT.isFixedLengthVector()
1727                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1728                    : DAG.getRegister(RISCV::X0, XLenVT);
1729   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1730   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1731   return {Mask, VL};
1732 }
1733 
1734 // As above but assuming the given type is a scalable vector type.
1735 static std::pair<SDValue, SDValue>
1736 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1737                         const RISCVSubtarget &Subtarget) {
1738   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1739   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1740 }
1741 
1742 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1743 // of either is (currently) supported. This can get us into an infinite loop
1744 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1745 // as a ..., etc.
1746 // Until either (or both) of these can reliably lower any node, reporting that
1747 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1748 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1749 // which is not desirable.
1750 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1751     EVT VT, unsigned DefinedValues) const {
1752   return false;
1753 }
1754 
1755 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1756                                   const RISCVSubtarget &Subtarget) {
1757   // RISCV FP-to-int conversions saturate to the destination register size, but
1758   // don't produce 0 for nan. We can use a conversion instruction and fix the
1759   // nan case with a compare and a select.
1760   SDValue Src = Op.getOperand(0);
1761 
1762   EVT DstVT = Op.getValueType();
1763   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1764 
1765   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1766   unsigned Opc;
1767   if (SatVT == DstVT)
1768     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1769   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1770     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1771   else
1772     return SDValue();
1773   // FIXME: Support other SatVTs by clamping before or after the conversion.
1774 
1775   SDLoc DL(Op);
1776   SDValue FpToInt = DAG.getNode(
1777       Opc, DL, DstVT, Src,
1778       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1779 
1780   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1781   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1782 }
1783 
1784 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1785 // and back. Taking care to avoid converting values that are nan or already
1786 // correct.
1787 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1788 // have FRM dependencies modeled yet.
1789 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1790   MVT VT = Op.getSimpleValueType();
1791   assert(VT.isVector() && "Unexpected type");
1792 
1793   SDLoc DL(Op);
1794 
1795   // Freeze the source since we are increasing the number of uses.
1796   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1797 
1798   // Truncate to integer and convert back to FP.
1799   MVT IntVT = VT.changeVectorElementTypeToInteger();
1800   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1801   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1802 
1803   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1804 
1805   if (Op.getOpcode() == ISD::FCEIL) {
1806     // If the truncated value is the greater than or equal to the original
1807     // value, we've computed the ceil. Otherwise, we went the wrong way and
1808     // need to increase by 1.
1809     // FIXME: This should use a masked operation. Handle here or in isel?
1810     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1811                                  DAG.getConstantFP(1.0, DL, VT));
1812     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1813     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1814   } else if (Op.getOpcode() == ISD::FFLOOR) {
1815     // If the truncated value is the less than or equal to the original value,
1816     // we've computed the floor. Otherwise, we went the wrong way and need to
1817     // decrease by 1.
1818     // FIXME: This should use a masked operation. Handle here or in isel?
1819     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1820                                  DAG.getConstantFP(1.0, DL, VT));
1821     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1822     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1823   }
1824 
1825   // Restore the original sign so that -0.0 is preserved.
1826   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1827 
1828   // Determine the largest integer that can be represented exactly. This and
1829   // values larger than it don't have any fractional bits so don't need to
1830   // be converted.
1831   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1832   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1833   APFloat MaxVal = APFloat(FltSem);
1834   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1835                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1836   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1837 
1838   // If abs(Src) was larger than MaxVal or nan, keep it.
1839   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1840   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1841   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1842 }
1843 
1844 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1845 // This mode isn't supported in vector hardware on RISCV. But as long as we
1846 // aren't compiling with trapping math, we can emulate this with
1847 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1848 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1849 // dependencies modeled yet.
1850 // FIXME: Use masked operations to avoid final merge.
1851 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1852   MVT VT = Op.getSimpleValueType();
1853   assert(VT.isVector() && "Unexpected type");
1854 
1855   SDLoc DL(Op);
1856 
1857   // Freeze the source since we are increasing the number of uses.
1858   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1859 
1860   // We do the conversion on the absolute value and fix the sign at the end.
1861   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1862 
1863   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1864   bool Ignored;
1865   APFloat Point5Pred = APFloat(0.5f);
1866   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1867   Point5Pred.next(/*nextDown*/ true);
1868 
1869   // Add the adjustment.
1870   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1871                                DAG.getConstantFP(Point5Pred, DL, VT));
1872 
1873   // Truncate to integer and convert back to fp.
1874   MVT IntVT = VT.changeVectorElementTypeToInteger();
1875   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1876   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1877 
1878   // Restore the original sign.
1879   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1880 
1881   // Determine the largest integer that can be represented exactly. This and
1882   // values larger than it don't have any fractional bits so don't need to
1883   // be converted.
1884   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1885   APFloat MaxVal = APFloat(FltSem);
1886   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1887                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1888   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1889 
1890   // If abs(Src) was larger than MaxVal or nan, keep it.
1891   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1892   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1893   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1894 }
1895 
1896 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1897                                  const RISCVSubtarget &Subtarget) {
1898   MVT VT = Op.getSimpleValueType();
1899   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1900 
1901   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1902 
1903   SDLoc DL(Op);
1904   SDValue Mask, VL;
1905   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1906 
1907   unsigned Opc =
1908       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1909   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1910   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1911 }
1912 
1913 struct VIDSequence {
1914   int64_t StepNumerator;
1915   unsigned StepDenominator;
1916   int64_t Addend;
1917 };
1918 
1919 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1920 // to the (non-zero) step S and start value X. This can be then lowered as the
1921 // RVV sequence (VID * S) + X, for example.
1922 // The step S is represented as an integer numerator divided by a positive
1923 // denominator. Note that the implementation currently only identifies
1924 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1925 // cannot detect 2/3, for example.
1926 // Note that this method will also match potentially unappealing index
1927 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1928 // determine whether this is worth generating code for.
1929 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1930   unsigned NumElts = Op.getNumOperands();
1931   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1932   if (!Op.getValueType().isInteger())
1933     return None;
1934 
1935   Optional<unsigned> SeqStepDenom;
1936   Optional<int64_t> SeqStepNum, SeqAddend;
1937   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1938   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1939   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1940     // Assume undef elements match the sequence; we just have to be careful
1941     // when interpolating across them.
1942     if (Op.getOperand(Idx).isUndef())
1943       continue;
1944     // The BUILD_VECTOR must be all constants.
1945     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1946       return None;
1947 
1948     uint64_t Val = Op.getConstantOperandVal(Idx) &
1949                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1950 
1951     if (PrevElt) {
1952       // Calculate the step since the last non-undef element, and ensure
1953       // it's consistent across the entire sequence.
1954       unsigned IdxDiff = Idx - PrevElt->second;
1955       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1956 
1957       // A zero-value value difference means that we're somewhere in the middle
1958       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1959       // step change before evaluating the sequence.
1960       if (ValDiff != 0) {
1961         int64_t Remainder = ValDiff % IdxDiff;
1962         // Normalize the step if it's greater than 1.
1963         if (Remainder != ValDiff) {
1964           // The difference must cleanly divide the element span.
1965           if (Remainder != 0)
1966             return None;
1967           ValDiff /= IdxDiff;
1968           IdxDiff = 1;
1969         }
1970 
1971         if (!SeqStepNum)
1972           SeqStepNum = ValDiff;
1973         else if (ValDiff != SeqStepNum)
1974           return None;
1975 
1976         if (!SeqStepDenom)
1977           SeqStepDenom = IdxDiff;
1978         else if (IdxDiff != *SeqStepDenom)
1979           return None;
1980       }
1981     }
1982 
1983     // Record and/or check any addend.
1984     if (SeqStepNum && SeqStepDenom) {
1985       uint64_t ExpectedVal =
1986           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1987       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1988       if (!SeqAddend)
1989         SeqAddend = Addend;
1990       else if (SeqAddend != Addend)
1991         return None;
1992     }
1993 
1994     // Record this non-undef element for later.
1995     if (!PrevElt || PrevElt->first != Val)
1996       PrevElt = std::make_pair(Val, Idx);
1997   }
1998   // We need to have logged both a step and an addend for this to count as
1999   // a legal index sequence.
2000   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
2001     return None;
2002 
2003   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
2004 }
2005 
2006 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
2007 // and lower it as a VRGATHER_VX_VL from the source vector.
2008 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
2009                                   SelectionDAG &DAG,
2010                                   const RISCVSubtarget &Subtarget) {
2011   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2012     return SDValue();
2013   SDValue Vec = SplatVal.getOperand(0);
2014   // Only perform this optimization on vectors of the same size for simplicity.
2015   if (Vec.getValueType() != VT)
2016     return SDValue();
2017   SDValue Idx = SplatVal.getOperand(1);
2018   // The index must be a legal type.
2019   if (Idx.getValueType() != Subtarget.getXLenVT())
2020     return SDValue();
2021 
2022   MVT ContainerVT = VT;
2023   if (VT.isFixedLengthVector()) {
2024     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2025     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2026   }
2027 
2028   SDValue Mask, VL;
2029   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2030 
2031   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2032                                Idx, Mask, VL);
2033 
2034   if (!VT.isFixedLengthVector())
2035     return Gather;
2036 
2037   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2038 }
2039 
2040 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2041                                  const RISCVSubtarget &Subtarget) {
2042   MVT VT = Op.getSimpleValueType();
2043   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2044 
2045   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2046 
2047   SDLoc DL(Op);
2048   SDValue Mask, VL;
2049   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2050 
2051   MVT XLenVT = Subtarget.getXLenVT();
2052   unsigned NumElts = Op.getNumOperands();
2053 
2054   if (VT.getVectorElementType() == MVT::i1) {
2055     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2056       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2057       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2058     }
2059 
2060     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2061       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2062       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2063     }
2064 
2065     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2066     // scalar integer chunks whose bit-width depends on the number of mask
2067     // bits and XLEN.
2068     // First, determine the most appropriate scalar integer type to use. This
2069     // is at most XLenVT, but may be shrunk to a smaller vector element type
2070     // according to the size of the final vector - use i8 chunks rather than
2071     // XLenVT if we're producing a v8i1. This results in more consistent
2072     // codegen across RV32 and RV64.
2073     unsigned NumViaIntegerBits =
2074         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2075     NumViaIntegerBits = std::min(NumViaIntegerBits,
2076                                  Subtarget.getMaxELENForFixedLengthVectors());
2077     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2078       // If we have to use more than one INSERT_VECTOR_ELT then this
2079       // optimization is likely to increase code size; avoid peforming it in
2080       // such a case. We can use a load from a constant pool in this case.
2081       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2082         return SDValue();
2083       // Now we can create our integer vector type. Note that it may be larger
2084       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2085       MVT IntegerViaVecVT =
2086           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2087                            divideCeil(NumElts, NumViaIntegerBits));
2088 
2089       uint64_t Bits = 0;
2090       unsigned BitPos = 0, IntegerEltIdx = 0;
2091       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2092 
2093       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2094         // Once we accumulate enough bits to fill our scalar type, insert into
2095         // our vector and clear our accumulated data.
2096         if (I != 0 && I % NumViaIntegerBits == 0) {
2097           if (NumViaIntegerBits <= 32)
2098             Bits = SignExtend64(Bits, 32);
2099           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2100           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2101                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2102           Bits = 0;
2103           BitPos = 0;
2104           IntegerEltIdx++;
2105         }
2106         SDValue V = Op.getOperand(I);
2107         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2108         Bits |= ((uint64_t)BitValue << BitPos);
2109       }
2110 
2111       // Insert the (remaining) scalar value into position in our integer
2112       // vector type.
2113       if (NumViaIntegerBits <= 32)
2114         Bits = SignExtend64(Bits, 32);
2115       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2116       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2117                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2118 
2119       if (NumElts < NumViaIntegerBits) {
2120         // If we're producing a smaller vector than our minimum legal integer
2121         // type, bitcast to the equivalent (known-legal) mask type, and extract
2122         // our final mask.
2123         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2124         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2125         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2126                           DAG.getConstant(0, DL, XLenVT));
2127       } else {
2128         // Else we must have produced an integer type with the same size as the
2129         // mask type; bitcast for the final result.
2130         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2131         Vec = DAG.getBitcast(VT, Vec);
2132       }
2133 
2134       return Vec;
2135     }
2136 
2137     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2138     // vector type, we have a legal equivalently-sized i8 type, so we can use
2139     // that.
2140     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2141     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2142 
2143     SDValue WideVec;
2144     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2145       // For a splat, perform a scalar truncate before creating the wider
2146       // vector.
2147       assert(Splat.getValueType() == XLenVT &&
2148              "Unexpected type for i1 splat value");
2149       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2150                           DAG.getConstant(1, DL, XLenVT));
2151       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2152     } else {
2153       SmallVector<SDValue, 8> Ops(Op->op_values());
2154       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2155       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2156       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2157     }
2158 
2159     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2160   }
2161 
2162   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2163     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2164       return Gather;
2165     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2166                                         : RISCVISD::VMV_V_X_VL;
2167     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2168     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2169   }
2170 
2171   // Try and match index sequences, which we can lower to the vid instruction
2172   // with optional modifications. An all-undef vector is matched by
2173   // getSplatValue, above.
2174   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2175     int64_t StepNumerator = SimpleVID->StepNumerator;
2176     unsigned StepDenominator = SimpleVID->StepDenominator;
2177     int64_t Addend = SimpleVID->Addend;
2178 
2179     assert(StepNumerator != 0 && "Invalid step");
2180     bool Negate = false;
2181     int64_t SplatStepVal = StepNumerator;
2182     unsigned StepOpcode = ISD::MUL;
2183     if (StepNumerator != 1) {
2184       if (isPowerOf2_64(std::abs(StepNumerator))) {
2185         Negate = StepNumerator < 0;
2186         StepOpcode = ISD::SHL;
2187         SplatStepVal = Log2_64(std::abs(StepNumerator));
2188       }
2189     }
2190 
2191     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2192     // threshold since it's the immediate value many RVV instructions accept.
2193     // There is no vmul.vi instruction so ensure multiply constant can fit in
2194     // a single addi instruction.
2195     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2196          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2197         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2198       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2199       // Convert right out of the scalable type so we can use standard ISD
2200       // nodes for the rest of the computation. If we used scalable types with
2201       // these, we'd lose the fixed-length vector info and generate worse
2202       // vsetvli code.
2203       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2204       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2205           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2206         SDValue SplatStep = DAG.getSplatVector(
2207             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2208         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2209       }
2210       if (StepDenominator != 1) {
2211         SDValue SplatStep = DAG.getSplatVector(
2212             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2213         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2214       }
2215       if (Addend != 0 || Negate) {
2216         SDValue SplatAddend =
2217             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2218         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2219       }
2220       return VID;
2221     }
2222   }
2223 
2224   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2225   // when re-interpreted as a vector with a larger element type. For example,
2226   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2227   // could be instead splat as
2228   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2229   // TODO: This optimization could also work on non-constant splats, but it
2230   // would require bit-manipulation instructions to construct the splat value.
2231   SmallVector<SDValue> Sequence;
2232   unsigned EltBitSize = VT.getScalarSizeInBits();
2233   const auto *BV = cast<BuildVectorSDNode>(Op);
2234   if (VT.isInteger() && EltBitSize < 64 &&
2235       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2236       BV->getRepeatedSequence(Sequence) &&
2237       (Sequence.size() * EltBitSize) <= 64) {
2238     unsigned SeqLen = Sequence.size();
2239     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2240     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2241     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2242             ViaIntVT == MVT::i64) &&
2243            "Unexpected sequence type");
2244 
2245     unsigned EltIdx = 0;
2246     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2247     uint64_t SplatValue = 0;
2248     // Construct the amalgamated value which can be splatted as this larger
2249     // vector type.
2250     for (const auto &SeqV : Sequence) {
2251       if (!SeqV.isUndef())
2252         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2253                        << (EltIdx * EltBitSize));
2254       EltIdx++;
2255     }
2256 
2257     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2258     // achieve better constant materializion.
2259     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2260       SplatValue = SignExtend64(SplatValue, 32);
2261 
2262     // Since we can't introduce illegal i64 types at this stage, we can only
2263     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2264     // way we can use RVV instructions to splat.
2265     assert((ViaIntVT.bitsLE(XLenVT) ||
2266             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2267            "Unexpected bitcast sequence");
2268     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2269       SDValue ViaVL =
2270           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2271       MVT ViaContainerVT =
2272           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2273       SDValue Splat =
2274           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2275                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2276       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2277       return DAG.getBitcast(VT, Splat);
2278     }
2279   }
2280 
2281   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2282   // which constitute a large proportion of the elements. In such cases we can
2283   // splat a vector with the dominant element and make up the shortfall with
2284   // INSERT_VECTOR_ELTs.
2285   // Note that this includes vectors of 2 elements by association. The
2286   // upper-most element is the "dominant" one, allowing us to use a splat to
2287   // "insert" the upper element, and an insert of the lower element at position
2288   // 0, which improves codegen.
2289   SDValue DominantValue;
2290   unsigned MostCommonCount = 0;
2291   DenseMap<SDValue, unsigned> ValueCounts;
2292   unsigned NumUndefElts =
2293       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2294 
2295   // Track the number of scalar loads we know we'd be inserting, estimated as
2296   // any non-zero floating-point constant. Other kinds of element are either
2297   // already in registers or are materialized on demand. The threshold at which
2298   // a vector load is more desirable than several scalar materializion and
2299   // vector-insertion instructions is not known.
2300   unsigned NumScalarLoads = 0;
2301 
2302   for (SDValue V : Op->op_values()) {
2303     if (V.isUndef())
2304       continue;
2305 
2306     ValueCounts.insert(std::make_pair(V, 0));
2307     unsigned &Count = ValueCounts[V];
2308 
2309     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2310       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2311 
2312     // Is this value dominant? In case of a tie, prefer the highest element as
2313     // it's cheaper to insert near the beginning of a vector than it is at the
2314     // end.
2315     if (++Count >= MostCommonCount) {
2316       DominantValue = V;
2317       MostCommonCount = Count;
2318     }
2319   }
2320 
2321   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2322   unsigned NumDefElts = NumElts - NumUndefElts;
2323   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2324 
2325   // Don't perform this optimization when optimizing for size, since
2326   // materializing elements and inserting them tends to cause code bloat.
2327   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2328       ((MostCommonCount > DominantValueCountThreshold) ||
2329        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2330     // Start by splatting the most common element.
2331     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2332 
2333     DenseSet<SDValue> Processed{DominantValue};
2334     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2335     for (const auto &OpIdx : enumerate(Op->ops())) {
2336       const SDValue &V = OpIdx.value();
2337       if (V.isUndef() || !Processed.insert(V).second)
2338         continue;
2339       if (ValueCounts[V] == 1) {
2340         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2341                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2342       } else {
2343         // Blend in all instances of this value using a VSELECT, using a
2344         // mask where each bit signals whether that element is the one
2345         // we're after.
2346         SmallVector<SDValue> Ops;
2347         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2348           return DAG.getConstant(V == V1, DL, XLenVT);
2349         });
2350         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2351                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2352                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2353       }
2354     }
2355 
2356     return Vec;
2357   }
2358 
2359   return SDValue();
2360 }
2361 
2362 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2363                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2364   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2365     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2366     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2367     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2368     // node in order to try and match RVV vector/scalar instructions.
2369     if ((LoC >> 31) == HiC)
2370       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2371 
2372     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2373     // vmv.v.x whose EEW = 32 to lower it.
2374     auto *Const = dyn_cast<ConstantSDNode>(VL);
2375     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2376       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2377       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2378       // access the subtarget here now.
2379       auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo,
2380                                   DAG.getRegister(RISCV::X0, MVT::i32));
2381       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2382     }
2383   }
2384 
2385   // Fall back to a stack store and stride x0 vector load.
2386   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2387 }
2388 
2389 // Called by type legalization to handle splat of i64 on RV32.
2390 // FIXME: We can optimize this when the type has sign or zero bits in one
2391 // of the halves.
2392 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2393                                    SDValue VL, SelectionDAG &DAG) {
2394   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2395   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2396                            DAG.getConstant(0, DL, MVT::i32));
2397   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2398                            DAG.getConstant(1, DL, MVT::i32));
2399   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2400 }
2401 
2402 // This function lowers a splat of a scalar operand Splat with the vector
2403 // length VL. It ensures the final sequence is type legal, which is useful when
2404 // lowering a splat after type legalization.
2405 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2406                                 SelectionDAG &DAG,
2407                                 const RISCVSubtarget &Subtarget) {
2408   if (VT.isFloatingPoint()) {
2409     // If VL is 1, we could use vfmv.s.f.
2410     if (isOneConstant(VL))
2411       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2412                          Scalar, VL);
2413     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2414   }
2415 
2416   MVT XLenVT = Subtarget.getXLenVT();
2417 
2418   // Simplest case is that the operand needs to be promoted to XLenVT.
2419   if (Scalar.getValueType().bitsLE(XLenVT)) {
2420     // If the operand is a constant, sign extend to increase our chances
2421     // of being able to use a .vi instruction. ANY_EXTEND would become a
2422     // a zero extend and the simm5 check in isel would fail.
2423     // FIXME: Should we ignore the upper bits in isel instead?
2424     unsigned ExtOpc =
2425         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2426     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2427     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2428     // If VL is 1 and the scalar value won't benefit from immediate, we could
2429     // use vmv.s.x.
2430     if (isOneConstant(VL) &&
2431         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2432       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2433                          VL);
2434     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2435   }
2436 
2437   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2438          "Unexpected scalar for splat lowering!");
2439 
2440   if (isOneConstant(VL) && isNullConstant(Scalar))
2441     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2442                        DAG.getConstant(0, DL, XLenVT), VL);
2443 
2444   // Otherwise use the more complicated splatting algorithm.
2445   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2446 }
2447 
2448 // Is the mask a slidedown that shifts in undefs.
2449 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2450   int Size = Mask.size();
2451 
2452   // Elements shifted in should be undef.
2453   auto CheckUndefs = [&](int Shift) {
2454     for (int i = Size - Shift; i != Size; ++i)
2455       if (Mask[i] >= 0)
2456         return false;
2457     return true;
2458   };
2459 
2460   // Elements should be shifted or undef.
2461   auto MatchShift = [&](int Shift) {
2462     for (int i = 0; i != Size - Shift; ++i)
2463        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2464          return false;
2465     return true;
2466   };
2467 
2468   // Try all possible shifts.
2469   for (int Shift = 1; Shift != Size; ++Shift)
2470     if (CheckUndefs(Shift) && MatchShift(Shift))
2471       return Shift;
2472 
2473   // No match.
2474   return -1;
2475 }
2476 
2477 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2478                                 const RISCVSubtarget &Subtarget) {
2479   // We need to be able to widen elements to the next larger integer type.
2480   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2481     return false;
2482 
2483   int Size = Mask.size();
2484   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2485 
2486   int Srcs[] = {-1, -1};
2487   for (int i = 0; i != Size; ++i) {
2488     // Ignore undef elements.
2489     if (Mask[i] < 0)
2490       continue;
2491 
2492     // Is this an even or odd element.
2493     int Pol = i % 2;
2494 
2495     // Ensure we consistently use the same source for this element polarity.
2496     int Src = Mask[i] / Size;
2497     if (Srcs[Pol] < 0)
2498       Srcs[Pol] = Src;
2499     if (Srcs[Pol] != Src)
2500       return false;
2501 
2502     // Make sure the element within the source is appropriate for this element
2503     // in the destination.
2504     int Elt = Mask[i] % Size;
2505     if (Elt != i / 2)
2506       return false;
2507   }
2508 
2509   // We need to find a source for each polarity and they can't be the same.
2510   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2511     return false;
2512 
2513   // Swap the sources if the second source was in the even polarity.
2514   SwapSources = Srcs[0] > Srcs[1];
2515 
2516   return true;
2517 }
2518 
2519 static int isElementRotate(SDValue &V1, SDValue &V2, ArrayRef<int> Mask) {
2520   int Size = Mask.size();
2521 
2522   // We need to detect various ways of spelling a rotation:
2523   //   [11, 12, 13, 14, 15,  0,  1,  2]
2524   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2525   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2526   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2527   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2528   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2529   int Rotation = 0;
2530   SDValue Lo, Hi;
2531   for (int i = 0; i != Size; ++i) {
2532     int M = Mask[i];
2533     if (M < 0)
2534       continue;
2535 
2536     // Determine where a rotate vector would have started.
2537     int StartIdx = i - (M % Size);
2538     // The identity rotation isn't interesting, stop.
2539     if (StartIdx == 0)
2540       return -1;
2541 
2542     // If we found the tail of a vector the rotation must be the missing
2543     // front. If we found the head of a vector, it must be how much of the
2544     // head.
2545     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2546 
2547     if (Rotation == 0)
2548       Rotation = CandidateRotation;
2549     else if (Rotation != CandidateRotation)
2550       // The rotations don't match, so we can't match this mask.
2551       return -1;
2552 
2553     // Compute which value this mask is pointing at.
2554     SDValue MaskV = M < Size ? V1 : V2;
2555 
2556     // Compute which of the two target values this index should be assigned to.
2557     // This reflects whether the high elements are remaining or the low elemnts
2558     // are remaining.
2559     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
2560 
2561     // Either set up this value if we've not encountered it before, or check
2562     // that it remains consistent.
2563     if (!TargetV)
2564       TargetV = MaskV;
2565     else if (TargetV != MaskV)
2566       // This may be a rotation, but it pulls from the inputs in some
2567       // unsupported interleaving.
2568       return -1;
2569   }
2570 
2571   // Check that we successfully analyzed the mask, and normalize the results.
2572   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2573   assert((Lo || Hi) && "Failed to find a rotated input vector!");
2574 
2575   // Make sure we've found a value for both halves.
2576   if (!Lo || !Hi)
2577     return -1;
2578 
2579   V1 = Lo;
2580   V2 = Hi;
2581 
2582   return Rotation;
2583 }
2584 
2585 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2586                                    const RISCVSubtarget &Subtarget) {
2587   SDValue V1 = Op.getOperand(0);
2588   SDValue V2 = Op.getOperand(1);
2589   SDLoc DL(Op);
2590   MVT XLenVT = Subtarget.getXLenVT();
2591   MVT VT = Op.getSimpleValueType();
2592   unsigned NumElts = VT.getVectorNumElements();
2593   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2594 
2595   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2596 
2597   SDValue TrueMask, VL;
2598   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2599 
2600   if (SVN->isSplat()) {
2601     const int Lane = SVN->getSplatIndex();
2602     if (Lane >= 0) {
2603       MVT SVT = VT.getVectorElementType();
2604 
2605       // Turn splatted vector load into a strided load with an X0 stride.
2606       SDValue V = V1;
2607       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2608       // with undef.
2609       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2610       int Offset = Lane;
2611       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2612         int OpElements =
2613             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2614         V = V.getOperand(Offset / OpElements);
2615         Offset %= OpElements;
2616       }
2617 
2618       // We need to ensure the load isn't atomic or volatile.
2619       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2620         auto *Ld = cast<LoadSDNode>(V);
2621         Offset *= SVT.getStoreSize();
2622         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2623                                                    TypeSize::Fixed(Offset), DL);
2624 
2625         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2626         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2627           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2628           SDValue IntID =
2629               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2630           SDValue Ops[] = {Ld->getChain(),
2631                            IntID,
2632                            DAG.getUNDEF(ContainerVT),
2633                            NewAddr,
2634                            DAG.getRegister(RISCV::X0, XLenVT),
2635                            VL};
2636           SDValue NewLoad = DAG.getMemIntrinsicNode(
2637               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2638               DAG.getMachineFunction().getMachineMemOperand(
2639                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2640           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2641           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2642         }
2643 
2644         // Otherwise use a scalar load and splat. This will give the best
2645         // opportunity to fold a splat into the operation. ISel can turn it into
2646         // the x0 strided load if we aren't able to fold away the select.
2647         if (SVT.isFloatingPoint())
2648           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2649                           Ld->getPointerInfo().getWithOffset(Offset),
2650                           Ld->getOriginalAlign(),
2651                           Ld->getMemOperand()->getFlags());
2652         else
2653           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2654                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2655                              Ld->getOriginalAlign(),
2656                              Ld->getMemOperand()->getFlags());
2657         DAG.makeEquivalentMemoryOrdering(Ld, V);
2658 
2659         unsigned Opc =
2660             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2661         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2662         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2663       }
2664 
2665       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2666       assert(Lane < (int)NumElts && "Unexpected lane!");
2667       SDValue Gather =
2668           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2669                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2670       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2671     }
2672   }
2673 
2674   ArrayRef<int> Mask = SVN->getMask();
2675 
2676   // Try to match as a slidedown.
2677   int SlideAmt = matchShuffleAsSlideDown(Mask);
2678   if (SlideAmt >= 0) {
2679     // TODO: Should we reduce the VL to account for the upper undef elements?
2680     // Requires additional vsetvlis, but might be faster to execute.
2681     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2682     SDValue SlideDown =
2683         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2684                     DAG.getUNDEF(ContainerVT), V1,
2685                     DAG.getConstant(SlideAmt, DL, XLenVT),
2686                     TrueMask, VL);
2687     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2688   }
2689 
2690   // Match shuffles that concatenate two vectors, rotate the concatenation,
2691   // and then extract the original number of elements from the rotated result.
2692   // This is equivalent to vector.splice or X86's PALIGNR instruction. Lower
2693   // it to a SLIDEDOWN and a SLIDEUP.
2694   // FIXME: We don't really need it to be a concatenation. We just need two
2695   // regions with contiguous elements that need to be shifted down and up.
2696   int Rotation = isElementRotate(V1, V2, Mask);
2697   if (Rotation > 0) {
2698     // We found a rotation. We need to slide V1 down by Rotation. Using
2699     // (NumElts - Rotation) for VL. Then we need to slide V2 up by
2700     // (NumElts - Rotation) using NumElts for VL.
2701     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2702     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2703 
2704     unsigned InvRotate = NumElts - Rotation;
2705     SDValue SlideDown =
2706         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2707                     DAG.getUNDEF(ContainerVT), V2,
2708                     DAG.getConstant(Rotation, DL, XLenVT),
2709                     TrueMask, DAG.getConstant(InvRotate, DL, XLenVT));
2710     SDValue SlideUp =
2711         DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, SlideDown, V1,
2712                     DAG.getConstant(InvRotate, DL, XLenVT),
2713                     TrueMask, VL);
2714     return convertFromScalableVector(VT, SlideUp, DAG, Subtarget);
2715   }
2716 
2717   // Detect an interleave shuffle and lower to
2718   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2719   bool SwapSources;
2720   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2721     // Swap sources if needed.
2722     if (SwapSources)
2723       std::swap(V1, V2);
2724 
2725     // Extract the lower half of the vectors.
2726     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2727     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2728                      DAG.getConstant(0, DL, XLenVT));
2729     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2730                      DAG.getConstant(0, DL, XLenVT));
2731 
2732     // Double the element width and halve the number of elements in an int type.
2733     unsigned EltBits = VT.getScalarSizeInBits();
2734     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2735     MVT WideIntVT =
2736         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2737     // Convert this to a scalable vector. We need to base this on the
2738     // destination size to ensure there's always a type with a smaller LMUL.
2739     MVT WideIntContainerVT =
2740         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2741 
2742     // Convert sources to scalable vectors with the same element count as the
2743     // larger type.
2744     MVT HalfContainerVT = MVT::getVectorVT(
2745         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2746     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2747     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2748 
2749     // Cast sources to integer.
2750     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2751     MVT IntHalfVT =
2752         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2753     V1 = DAG.getBitcast(IntHalfVT, V1);
2754     V2 = DAG.getBitcast(IntHalfVT, V2);
2755 
2756     // Freeze V2 since we use it twice and we need to be sure that the add and
2757     // multiply see the same value.
2758     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2759 
2760     // Recreate TrueMask using the widened type's element count.
2761     MVT MaskVT =
2762         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2763     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2764 
2765     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2766     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2767                               V2, TrueMask, VL);
2768     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2769     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2770                                      DAG.getAllOnesConstant(DL, XLenVT));
2771     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2772                                    V2, Multiplier, TrueMask, VL);
2773     // Add the new copies to our previous addition giving us 2^eltbits copies of
2774     // V2. This is equivalent to shifting V2 left by eltbits. This should
2775     // combine with the vwmulu.vv above to form vwmaccu.vv.
2776     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2777                       TrueMask, VL);
2778     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2779     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2780     // vector VT.
2781     ContainerVT =
2782         MVT::getVectorVT(VT.getVectorElementType(),
2783                          WideIntContainerVT.getVectorElementCount() * 2);
2784     Add = DAG.getBitcast(ContainerVT, Add);
2785     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2786   }
2787 
2788   // Detect shuffles which can be re-expressed as vector selects; these are
2789   // shuffles in which each element in the destination is taken from an element
2790   // at the corresponding index in either source vectors.
2791   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2792     int MaskIndex = MaskIdx.value();
2793     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2794   });
2795 
2796   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2797 
2798   SmallVector<SDValue> MaskVals;
2799   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2800   // merged with a second vrgather.
2801   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2802 
2803   // By default we preserve the original operand order, and use a mask to
2804   // select LHS as true and RHS as false. However, since RVV vector selects may
2805   // feature splats but only on the LHS, we may choose to invert our mask and
2806   // instead select between RHS and LHS.
2807   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2808   bool InvertMask = IsSelect == SwapOps;
2809 
2810   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2811   // half.
2812   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2813 
2814   // Now construct the mask that will be used by the vselect or blended
2815   // vrgather operation. For vrgathers, construct the appropriate indices into
2816   // each vector.
2817   for (int MaskIndex : Mask) {
2818     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2819     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2820     if (!IsSelect) {
2821       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2822       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2823                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2824                                      : DAG.getUNDEF(XLenVT));
2825       GatherIndicesRHS.push_back(
2826           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2827                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2828       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2829         ++LHSIndexCounts[MaskIndex];
2830       if (!IsLHSOrUndefIndex)
2831         ++RHSIndexCounts[MaskIndex - NumElts];
2832     }
2833   }
2834 
2835   if (SwapOps) {
2836     std::swap(V1, V2);
2837     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2838   }
2839 
2840   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2841   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2842   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2843 
2844   if (IsSelect)
2845     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2846 
2847   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2848     // On such a large vector we're unable to use i8 as the index type.
2849     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2850     // may involve vector splitting if we're already at LMUL=8, or our
2851     // user-supplied maximum fixed-length LMUL.
2852     return SDValue();
2853   }
2854 
2855   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2856   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2857   MVT IndexVT = VT.changeTypeToInteger();
2858   // Since we can't introduce illegal index types at this stage, use i16 and
2859   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2860   // than XLenVT.
2861   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2862     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2863     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2864   }
2865 
2866   MVT IndexContainerVT =
2867       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2868 
2869   SDValue Gather;
2870   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2871   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2872   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2873     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2874   } else {
2875     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2876     // If only one index is used, we can use a "splat" vrgather.
2877     // TODO: We can splat the most-common index and fix-up any stragglers, if
2878     // that's beneficial.
2879     if (LHSIndexCounts.size() == 1) {
2880       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2881       Gather =
2882           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2883                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2884     } else {
2885       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2886       LHSIndices =
2887           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2888 
2889       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2890                            TrueMask, VL);
2891     }
2892   }
2893 
2894   // If a second vector operand is used by this shuffle, blend it in with an
2895   // additional vrgather.
2896   if (!V2.isUndef()) {
2897     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2898     // If only one index is used, we can use a "splat" vrgather.
2899     // TODO: We can splat the most-common index and fix-up any stragglers, if
2900     // that's beneficial.
2901     if (RHSIndexCounts.size() == 1) {
2902       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2903       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2904                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2905     } else {
2906       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2907       RHSIndices =
2908           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2909       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2910                        VL);
2911     }
2912 
2913     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2914     SelectMask =
2915         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2916 
2917     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2918                          Gather, VL);
2919   }
2920 
2921   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2922 }
2923 
2924 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2925   // Support splats for any type. These should type legalize well.
2926   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2927     return true;
2928 
2929   // Only support legal VTs for other shuffles for now.
2930   if (!isTypeLegal(VT))
2931     return false;
2932 
2933   MVT SVT = VT.getSimpleVT();
2934 
2935   bool SwapSources;
2936   return (matchShuffleAsSlideDown(M) >= 0) ||
2937          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2938 }
2939 
2940 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2941                                      SDLoc DL, SelectionDAG &DAG,
2942                                      const RISCVSubtarget &Subtarget) {
2943   if (VT.isScalableVector())
2944     return DAG.getFPExtendOrRound(Op, DL, VT);
2945   assert(VT.isFixedLengthVector() &&
2946          "Unexpected value type for RVV FP extend/round lowering");
2947   SDValue Mask, VL;
2948   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2949   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2950                         ? RISCVISD::FP_EXTEND_VL
2951                         : RISCVISD::FP_ROUND_VL;
2952   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2953 }
2954 
2955 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2956 // the exponent.
2957 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2958   MVT VT = Op.getSimpleValueType();
2959   unsigned EltSize = VT.getScalarSizeInBits();
2960   SDValue Src = Op.getOperand(0);
2961   SDLoc DL(Op);
2962 
2963   // We need a FP type that can represent the value.
2964   // TODO: Use f16 for i8 when possible?
2965   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2966   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2967 
2968   // Legal types should have been checked in the RISCVTargetLowering
2969   // constructor.
2970   // TODO: Splitting may make sense in some cases.
2971   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2972          "Expected legal float type!");
2973 
2974   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2975   // The trailing zero count is equal to log2 of this single bit value.
2976   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2977     SDValue Neg =
2978         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2979     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2980   }
2981 
2982   // We have a legal FP type, convert to it.
2983   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2984   // Bitcast to integer and shift the exponent to the LSB.
2985   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2986   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2987   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2988   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2989                               DAG.getConstant(ShiftAmt, DL, IntVT));
2990   // Truncate back to original type to allow vnsrl.
2991   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2992   // The exponent contains log2 of the value in biased form.
2993   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2994 
2995   // For trailing zeros, we just need to subtract the bias.
2996   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2997     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2998                        DAG.getConstant(ExponentBias, DL, VT));
2999 
3000   // For leading zeros, we need to remove the bias and convert from log2 to
3001   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
3002   unsigned Adjust = ExponentBias + (EltSize - 1);
3003   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
3004 }
3005 
3006 // While RVV has alignment restrictions, we should always be able to load as a
3007 // legal equivalently-sized byte-typed vector instead. This method is
3008 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
3009 // the load is already correctly-aligned, it returns SDValue().
3010 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
3011                                                     SelectionDAG &DAG) const {
3012   auto *Load = cast<LoadSDNode>(Op);
3013   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
3014 
3015   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3016                                      Load->getMemoryVT(),
3017                                      *Load->getMemOperand()))
3018     return SDValue();
3019 
3020   SDLoc DL(Op);
3021   MVT VT = Op.getSimpleValueType();
3022   unsigned EltSizeBits = VT.getScalarSizeInBits();
3023   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3024          "Unexpected unaligned RVV load type");
3025   MVT NewVT =
3026       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3027   assert(NewVT.isValid() &&
3028          "Expecting equally-sized RVV vector types to be legal");
3029   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3030                           Load->getPointerInfo(), Load->getOriginalAlign(),
3031                           Load->getMemOperand()->getFlags());
3032   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3033 }
3034 
3035 // While RVV has alignment restrictions, we should always be able to store as a
3036 // legal equivalently-sized byte-typed vector instead. This method is
3037 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3038 // returns SDValue() if the store is already correctly aligned.
3039 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3040                                                      SelectionDAG &DAG) const {
3041   auto *Store = cast<StoreSDNode>(Op);
3042   assert(Store && Store->getValue().getValueType().isVector() &&
3043          "Expected vector store");
3044 
3045   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3046                                      Store->getMemoryVT(),
3047                                      *Store->getMemOperand()))
3048     return SDValue();
3049 
3050   SDLoc DL(Op);
3051   SDValue StoredVal = Store->getValue();
3052   MVT VT = StoredVal.getSimpleValueType();
3053   unsigned EltSizeBits = VT.getScalarSizeInBits();
3054   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3055          "Unexpected unaligned RVV store type");
3056   MVT NewVT =
3057       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3058   assert(NewVT.isValid() &&
3059          "Expecting equally-sized RVV vector types to be legal");
3060   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3061   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3062                       Store->getPointerInfo(), Store->getOriginalAlign(),
3063                       Store->getMemOperand()->getFlags());
3064 }
3065 
3066 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3067                                             SelectionDAG &DAG) const {
3068   switch (Op.getOpcode()) {
3069   default:
3070     report_fatal_error("unimplemented operand");
3071   case ISD::GlobalAddress:
3072     return lowerGlobalAddress(Op, DAG);
3073   case ISD::BlockAddress:
3074     return lowerBlockAddress(Op, DAG);
3075   case ISD::ConstantPool:
3076     return lowerConstantPool(Op, DAG);
3077   case ISD::JumpTable:
3078     return lowerJumpTable(Op, DAG);
3079   case ISD::GlobalTLSAddress:
3080     return lowerGlobalTLSAddress(Op, DAG);
3081   case ISD::SELECT:
3082     return lowerSELECT(Op, DAG);
3083   case ISD::BRCOND:
3084     return lowerBRCOND(Op, DAG);
3085   case ISD::VASTART:
3086     return lowerVASTART(Op, DAG);
3087   case ISD::FRAMEADDR:
3088     return lowerFRAMEADDR(Op, DAG);
3089   case ISD::RETURNADDR:
3090     return lowerRETURNADDR(Op, DAG);
3091   case ISD::SHL_PARTS:
3092     return lowerShiftLeftParts(Op, DAG);
3093   case ISD::SRA_PARTS:
3094     return lowerShiftRightParts(Op, DAG, true);
3095   case ISD::SRL_PARTS:
3096     return lowerShiftRightParts(Op, DAG, false);
3097   case ISD::BITCAST: {
3098     SDLoc DL(Op);
3099     EVT VT = Op.getValueType();
3100     SDValue Op0 = Op.getOperand(0);
3101     EVT Op0VT = Op0.getValueType();
3102     MVT XLenVT = Subtarget.getXLenVT();
3103     if (VT.isFixedLengthVector()) {
3104       // We can handle fixed length vector bitcasts with a simple replacement
3105       // in isel.
3106       if (Op0VT.isFixedLengthVector())
3107         return Op;
3108       // When bitcasting from scalar to fixed-length vector, insert the scalar
3109       // into a one-element vector of the result type, and perform a vector
3110       // bitcast.
3111       if (!Op0VT.isVector()) {
3112         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3113         if (!isTypeLegal(BVT))
3114           return SDValue();
3115         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3116                                               DAG.getUNDEF(BVT), Op0,
3117                                               DAG.getConstant(0, DL, XLenVT)));
3118       }
3119       return SDValue();
3120     }
3121     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3122     // thus: bitcast the vector to a one-element vector type whose element type
3123     // is the same as the result type, and extract the first element.
3124     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3125       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3126       if (!isTypeLegal(BVT))
3127         return SDValue();
3128       SDValue BVec = DAG.getBitcast(BVT, Op0);
3129       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3130                          DAG.getConstant(0, DL, XLenVT));
3131     }
3132     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3133       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3134       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3135       return FPConv;
3136     }
3137     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3138         Subtarget.hasStdExtF()) {
3139       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3140       SDValue FPConv =
3141           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3142       return FPConv;
3143     }
3144     return SDValue();
3145   }
3146   case ISD::INTRINSIC_WO_CHAIN:
3147     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3148   case ISD::INTRINSIC_W_CHAIN:
3149     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3150   case ISD::INTRINSIC_VOID:
3151     return LowerINTRINSIC_VOID(Op, DAG);
3152   case ISD::BSWAP:
3153   case ISD::BITREVERSE: {
3154     MVT VT = Op.getSimpleValueType();
3155     SDLoc DL(Op);
3156     if (Subtarget.hasStdExtZbp()) {
3157       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3158       // Start with the maximum immediate value which is the bitwidth - 1.
3159       unsigned Imm = VT.getSizeInBits() - 1;
3160       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3161       if (Op.getOpcode() == ISD::BSWAP)
3162         Imm &= ~0x7U;
3163       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3164                          DAG.getConstant(Imm, DL, VT));
3165     }
3166     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3167     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3168     // Expand bitreverse to a bswap(rev8) followed by brev8.
3169     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3170     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3171     // as brev8 by an isel pattern.
3172     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3173                        DAG.getConstant(7, DL, VT));
3174   }
3175   case ISD::FSHL:
3176   case ISD::FSHR: {
3177     MVT VT = Op.getSimpleValueType();
3178     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3179     SDLoc DL(Op);
3180     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3181     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3182     // accidentally setting the extra bit.
3183     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3184     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3185                                 DAG.getConstant(ShAmtWidth, DL, VT));
3186     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3187     // instruction use different orders. fshl will return its first operand for
3188     // shift of zero, fshr will return its second operand. fsl and fsr both
3189     // return rs1 so the ISD nodes need to have different operand orders.
3190     // Shift amount is in rs2.
3191     SDValue Op0 = Op.getOperand(0);
3192     SDValue Op1 = Op.getOperand(1);
3193     unsigned Opc = RISCVISD::FSL;
3194     if (Op.getOpcode() == ISD::FSHR) {
3195       std::swap(Op0, Op1);
3196       Opc = RISCVISD::FSR;
3197     }
3198     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3199   }
3200   case ISD::TRUNCATE: {
3201     SDLoc DL(Op);
3202     MVT VT = Op.getSimpleValueType();
3203     // Only custom-lower vector truncates
3204     if (!VT.isVector())
3205       return Op;
3206 
3207     // Truncates to mask types are handled differently
3208     if (VT.getVectorElementType() == MVT::i1)
3209       return lowerVectorMaskTrunc(Op, DAG);
3210 
3211     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3212     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3213     // truncate by one power of two at a time.
3214     MVT DstEltVT = VT.getVectorElementType();
3215 
3216     SDValue Src = Op.getOperand(0);
3217     MVT SrcVT = Src.getSimpleValueType();
3218     MVT SrcEltVT = SrcVT.getVectorElementType();
3219 
3220     assert(DstEltVT.bitsLT(SrcEltVT) &&
3221            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3222            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3223            "Unexpected vector truncate lowering");
3224 
3225     MVT ContainerVT = SrcVT;
3226     if (SrcVT.isFixedLengthVector()) {
3227       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3228       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3229     }
3230 
3231     SDValue Result = Src;
3232     SDValue Mask, VL;
3233     std::tie(Mask, VL) =
3234         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3235     LLVMContext &Context = *DAG.getContext();
3236     const ElementCount Count = ContainerVT.getVectorElementCount();
3237     do {
3238       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3239       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3240       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3241                            Mask, VL);
3242     } while (SrcEltVT != DstEltVT);
3243 
3244     if (SrcVT.isFixedLengthVector())
3245       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3246 
3247     return Result;
3248   }
3249   case ISD::ANY_EXTEND:
3250   case ISD::ZERO_EXTEND:
3251     if (Op.getOperand(0).getValueType().isVector() &&
3252         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3253       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3254     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3255   case ISD::SIGN_EXTEND:
3256     if (Op.getOperand(0).getValueType().isVector() &&
3257         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3258       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3259     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3260   case ISD::SPLAT_VECTOR_PARTS:
3261     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3262   case ISD::INSERT_VECTOR_ELT:
3263     return lowerINSERT_VECTOR_ELT(Op, DAG);
3264   case ISD::EXTRACT_VECTOR_ELT:
3265     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3266   case ISD::VSCALE: {
3267     MVT VT = Op.getSimpleValueType();
3268     SDLoc DL(Op);
3269     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3270     // We define our scalable vector types for lmul=1 to use a 64 bit known
3271     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3272     // vscale as VLENB / 8.
3273     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3274     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3275       report_fatal_error("Support for VLEN==32 is incomplete.");
3276     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3277       // We assume VLENB is a multiple of 8. We manually choose the best shift
3278       // here because SimplifyDemandedBits isn't always able to simplify it.
3279       uint64_t Val = Op.getConstantOperandVal(0);
3280       if (isPowerOf2_64(Val)) {
3281         uint64_t Log2 = Log2_64(Val);
3282         if (Log2 < 3)
3283           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3284                              DAG.getConstant(3 - Log2, DL, VT));
3285         if (Log2 > 3)
3286           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3287                              DAG.getConstant(Log2 - 3, DL, VT));
3288         return VLENB;
3289       }
3290       // If the multiplier is a multiple of 8, scale it down to avoid needing
3291       // to shift the VLENB value.
3292       if ((Val % 8) == 0)
3293         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3294                            DAG.getConstant(Val / 8, DL, VT));
3295     }
3296 
3297     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3298                                  DAG.getConstant(3, DL, VT));
3299     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3300   }
3301   case ISD::FPOWI: {
3302     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3303     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3304     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3305         Op.getOperand(1).getValueType() == MVT::i32) {
3306       SDLoc DL(Op);
3307       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3308       SDValue Powi =
3309           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3310       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3311                          DAG.getIntPtrConstant(0, DL));
3312     }
3313     return SDValue();
3314   }
3315   case ISD::FP_EXTEND: {
3316     // RVV can only do fp_extend to types double the size as the source. We
3317     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3318     // via f32.
3319     SDLoc DL(Op);
3320     MVT VT = Op.getSimpleValueType();
3321     SDValue Src = Op.getOperand(0);
3322     MVT SrcVT = Src.getSimpleValueType();
3323 
3324     // Prepare any fixed-length vector operands.
3325     MVT ContainerVT = VT;
3326     if (SrcVT.isFixedLengthVector()) {
3327       ContainerVT = getContainerForFixedLengthVector(VT);
3328       MVT SrcContainerVT =
3329           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3330       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3331     }
3332 
3333     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3334         SrcVT.getVectorElementType() != MVT::f16) {
3335       // For scalable vectors, we only need to close the gap between
3336       // vXf16->vXf64.
3337       if (!VT.isFixedLengthVector())
3338         return Op;
3339       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3340       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3341       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3342     }
3343 
3344     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3345     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3346     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3347         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3348 
3349     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3350                                            DL, DAG, Subtarget);
3351     if (VT.isFixedLengthVector())
3352       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3353     return Extend;
3354   }
3355   case ISD::FP_ROUND: {
3356     // RVV can only do fp_round to types half the size as the source. We
3357     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3358     // conversion instruction.
3359     SDLoc DL(Op);
3360     MVT VT = Op.getSimpleValueType();
3361     SDValue Src = Op.getOperand(0);
3362     MVT SrcVT = Src.getSimpleValueType();
3363 
3364     // Prepare any fixed-length vector operands.
3365     MVT ContainerVT = VT;
3366     if (VT.isFixedLengthVector()) {
3367       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3368       ContainerVT =
3369           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3370       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3371     }
3372 
3373     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3374         SrcVT.getVectorElementType() != MVT::f64) {
3375       // For scalable vectors, we only need to close the gap between
3376       // vXf64<->vXf16.
3377       if (!VT.isFixedLengthVector())
3378         return Op;
3379       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3380       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3381       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3382     }
3383 
3384     SDValue Mask, VL;
3385     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3386 
3387     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3388     SDValue IntermediateRound =
3389         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3390     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3391                                           DL, DAG, Subtarget);
3392 
3393     if (VT.isFixedLengthVector())
3394       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3395     return Round;
3396   }
3397   case ISD::FP_TO_SINT:
3398   case ISD::FP_TO_UINT:
3399   case ISD::SINT_TO_FP:
3400   case ISD::UINT_TO_FP: {
3401     // RVV can only do fp<->int conversions to types half/double the size as
3402     // the source. We custom-lower any conversions that do two hops into
3403     // sequences.
3404     MVT VT = Op.getSimpleValueType();
3405     if (!VT.isVector())
3406       return Op;
3407     SDLoc DL(Op);
3408     SDValue Src = Op.getOperand(0);
3409     MVT EltVT = VT.getVectorElementType();
3410     MVT SrcVT = Src.getSimpleValueType();
3411     MVT SrcEltVT = SrcVT.getVectorElementType();
3412     unsigned EltSize = EltVT.getSizeInBits();
3413     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3414     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3415            "Unexpected vector element types");
3416 
3417     bool IsInt2FP = SrcEltVT.isInteger();
3418     // Widening conversions
3419     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3420       if (IsInt2FP) {
3421         // Do a regular integer sign/zero extension then convert to float.
3422         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3423                                       VT.getVectorElementCount());
3424         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3425                                  ? ISD::ZERO_EXTEND
3426                                  : ISD::SIGN_EXTEND;
3427         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3428         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3429       }
3430       // FP2Int
3431       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3432       // Do one doubling fp_extend then complete the operation by converting
3433       // to int.
3434       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3435       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3436       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3437     }
3438 
3439     // Narrowing conversions
3440     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3441       if (IsInt2FP) {
3442         // One narrowing int_to_fp, then an fp_round.
3443         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3444         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3445         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3446         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3447       }
3448       // FP2Int
3449       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3450       // representable by the integer, the result is poison.
3451       MVT IVecVT =
3452           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3453                            VT.getVectorElementCount());
3454       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3455       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3456     }
3457 
3458     // Scalable vectors can exit here. Patterns will handle equally-sized
3459     // conversions halving/doubling ones.
3460     if (!VT.isFixedLengthVector())
3461       return Op;
3462 
3463     // For fixed-length vectors we lower to a custom "VL" node.
3464     unsigned RVVOpc = 0;
3465     switch (Op.getOpcode()) {
3466     default:
3467       llvm_unreachable("Impossible opcode");
3468     case ISD::FP_TO_SINT:
3469       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3470       break;
3471     case ISD::FP_TO_UINT:
3472       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3473       break;
3474     case ISD::SINT_TO_FP:
3475       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3476       break;
3477     case ISD::UINT_TO_FP:
3478       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3479       break;
3480     }
3481 
3482     MVT ContainerVT, SrcContainerVT;
3483     // Derive the reference container type from the larger vector type.
3484     if (SrcEltSize > EltSize) {
3485       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3486       ContainerVT =
3487           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3488     } else {
3489       ContainerVT = getContainerForFixedLengthVector(VT);
3490       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3491     }
3492 
3493     SDValue Mask, VL;
3494     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3495 
3496     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3497     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3498     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3499   }
3500   case ISD::FP_TO_SINT_SAT:
3501   case ISD::FP_TO_UINT_SAT:
3502     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3503   case ISD::FTRUNC:
3504   case ISD::FCEIL:
3505   case ISD::FFLOOR:
3506     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3507   case ISD::FROUND:
3508     return lowerFROUND(Op, DAG);
3509   case ISD::VECREDUCE_ADD:
3510   case ISD::VECREDUCE_UMAX:
3511   case ISD::VECREDUCE_SMAX:
3512   case ISD::VECREDUCE_UMIN:
3513   case ISD::VECREDUCE_SMIN:
3514     return lowerVECREDUCE(Op, DAG);
3515   case ISD::VECREDUCE_AND:
3516   case ISD::VECREDUCE_OR:
3517   case ISD::VECREDUCE_XOR:
3518     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3519       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3520     return lowerVECREDUCE(Op, DAG);
3521   case ISD::VECREDUCE_FADD:
3522   case ISD::VECREDUCE_SEQ_FADD:
3523   case ISD::VECREDUCE_FMIN:
3524   case ISD::VECREDUCE_FMAX:
3525     return lowerFPVECREDUCE(Op, DAG);
3526   case ISD::VP_REDUCE_ADD:
3527   case ISD::VP_REDUCE_UMAX:
3528   case ISD::VP_REDUCE_SMAX:
3529   case ISD::VP_REDUCE_UMIN:
3530   case ISD::VP_REDUCE_SMIN:
3531   case ISD::VP_REDUCE_FADD:
3532   case ISD::VP_REDUCE_SEQ_FADD:
3533   case ISD::VP_REDUCE_FMIN:
3534   case ISD::VP_REDUCE_FMAX:
3535     return lowerVPREDUCE(Op, DAG);
3536   case ISD::VP_REDUCE_AND:
3537   case ISD::VP_REDUCE_OR:
3538   case ISD::VP_REDUCE_XOR:
3539     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3540       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3541     return lowerVPREDUCE(Op, DAG);
3542   case ISD::INSERT_SUBVECTOR:
3543     return lowerINSERT_SUBVECTOR(Op, DAG);
3544   case ISD::EXTRACT_SUBVECTOR:
3545     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3546   case ISD::STEP_VECTOR:
3547     return lowerSTEP_VECTOR(Op, DAG);
3548   case ISD::VECTOR_REVERSE:
3549     return lowerVECTOR_REVERSE(Op, DAG);
3550   case ISD::BUILD_VECTOR:
3551     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3552   case ISD::SPLAT_VECTOR:
3553     if (Op.getValueType().getVectorElementType() == MVT::i1)
3554       return lowerVectorMaskSplat(Op, DAG);
3555     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3556   case ISD::VECTOR_SHUFFLE:
3557     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3558   case ISD::CONCAT_VECTORS: {
3559     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3560     // better than going through the stack, as the default expansion does.
3561     SDLoc DL(Op);
3562     MVT VT = Op.getSimpleValueType();
3563     unsigned NumOpElts =
3564         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3565     SDValue Vec = DAG.getUNDEF(VT);
3566     for (const auto &OpIdx : enumerate(Op->ops())) {
3567       SDValue SubVec = OpIdx.value();
3568       // Don't insert undef subvectors.
3569       if (SubVec.isUndef())
3570         continue;
3571       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3572                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3573     }
3574     return Vec;
3575   }
3576   case ISD::LOAD:
3577     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3578       return V;
3579     if (Op.getValueType().isFixedLengthVector())
3580       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3581     return Op;
3582   case ISD::STORE:
3583     if (auto V = expandUnalignedRVVStore(Op, DAG))
3584       return V;
3585     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3586       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3587     return Op;
3588   case ISD::MLOAD:
3589   case ISD::VP_LOAD:
3590     return lowerMaskedLoad(Op, DAG);
3591   case ISD::MSTORE:
3592   case ISD::VP_STORE:
3593     return lowerMaskedStore(Op, DAG);
3594   case ISD::SETCC:
3595     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3596   case ISD::ADD:
3597     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3598   case ISD::SUB:
3599     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3600   case ISD::MUL:
3601     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3602   case ISD::MULHS:
3603     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3604   case ISD::MULHU:
3605     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3606   case ISD::AND:
3607     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3608                                               RISCVISD::AND_VL);
3609   case ISD::OR:
3610     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3611                                               RISCVISD::OR_VL);
3612   case ISD::XOR:
3613     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3614                                               RISCVISD::XOR_VL);
3615   case ISD::SDIV:
3616     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3617   case ISD::SREM:
3618     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3619   case ISD::UDIV:
3620     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3621   case ISD::UREM:
3622     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3623   case ISD::SHL:
3624   case ISD::SRA:
3625   case ISD::SRL:
3626     if (Op.getSimpleValueType().isFixedLengthVector())
3627       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3628     // This can be called for an i32 shift amount that needs to be promoted.
3629     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3630            "Unexpected custom legalisation");
3631     return SDValue();
3632   case ISD::SADDSAT:
3633     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3634   case ISD::UADDSAT:
3635     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3636   case ISD::SSUBSAT:
3637     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3638   case ISD::USUBSAT:
3639     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3640   case ISD::FADD:
3641     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3642   case ISD::FSUB:
3643     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3644   case ISD::FMUL:
3645     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3646   case ISD::FDIV:
3647     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3648   case ISD::FNEG:
3649     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3650   case ISD::FABS:
3651     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3652   case ISD::FSQRT:
3653     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3654   case ISD::FMA:
3655     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3656   case ISD::SMIN:
3657     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3658   case ISD::SMAX:
3659     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3660   case ISD::UMIN:
3661     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3662   case ISD::UMAX:
3663     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3664   case ISD::FMINNUM:
3665     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3666   case ISD::FMAXNUM:
3667     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3668   case ISD::ABS:
3669     return lowerABS(Op, DAG);
3670   case ISD::CTLZ_ZERO_UNDEF:
3671   case ISD::CTTZ_ZERO_UNDEF:
3672     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3673   case ISD::VSELECT:
3674     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3675   case ISD::FCOPYSIGN:
3676     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3677   case ISD::MGATHER:
3678   case ISD::VP_GATHER:
3679     return lowerMaskedGather(Op, DAG);
3680   case ISD::MSCATTER:
3681   case ISD::VP_SCATTER:
3682     return lowerMaskedScatter(Op, DAG);
3683   case ISD::FLT_ROUNDS_:
3684     return lowerGET_ROUNDING(Op, DAG);
3685   case ISD::SET_ROUNDING:
3686     return lowerSET_ROUNDING(Op, DAG);
3687   case ISD::VP_SELECT:
3688     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3689   case ISD::VP_MERGE:
3690     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3691   case ISD::VP_ADD:
3692     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3693   case ISD::VP_SUB:
3694     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3695   case ISD::VP_MUL:
3696     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3697   case ISD::VP_SDIV:
3698     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3699   case ISD::VP_UDIV:
3700     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3701   case ISD::VP_SREM:
3702     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3703   case ISD::VP_UREM:
3704     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3705   case ISD::VP_AND:
3706     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3707   case ISD::VP_OR:
3708     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3709   case ISD::VP_XOR:
3710     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3711   case ISD::VP_ASHR:
3712     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3713   case ISD::VP_LSHR:
3714     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3715   case ISD::VP_SHL:
3716     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3717   case ISD::VP_FADD:
3718     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3719   case ISD::VP_FSUB:
3720     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3721   case ISD::VP_FMUL:
3722     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3723   case ISD::VP_FDIV:
3724     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3725   case ISD::VP_FNEG:
3726     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3727   case ISD::VP_FMA:
3728     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3729   }
3730 }
3731 
3732 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3733                              SelectionDAG &DAG, unsigned Flags) {
3734   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3735 }
3736 
3737 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3738                              SelectionDAG &DAG, unsigned Flags) {
3739   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3740                                    Flags);
3741 }
3742 
3743 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3744                              SelectionDAG &DAG, unsigned Flags) {
3745   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3746                                    N->getOffset(), Flags);
3747 }
3748 
3749 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3750                              SelectionDAG &DAG, unsigned Flags) {
3751   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3752 }
3753 
3754 template <class NodeTy>
3755 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3756                                      bool IsLocal) const {
3757   SDLoc DL(N);
3758   EVT Ty = getPointerTy(DAG.getDataLayout());
3759 
3760   if (isPositionIndependent()) {
3761     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3762     if (IsLocal)
3763       // Use PC-relative addressing to access the symbol. This generates the
3764       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3765       // %pcrel_lo(auipc)).
3766       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3767 
3768     // Use PC-relative addressing to access the GOT for this symbol, then load
3769     // the address from the GOT. This generates the pattern (PseudoLA sym),
3770     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3771     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3772   }
3773 
3774   switch (getTargetMachine().getCodeModel()) {
3775   default:
3776     report_fatal_error("Unsupported code model for lowering");
3777   case CodeModel::Small: {
3778     // Generate a sequence for accessing addresses within the first 2 GiB of
3779     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3780     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3781     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3782     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3783     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3784   }
3785   case CodeModel::Medium: {
3786     // Generate a sequence for accessing addresses within any 2GiB range within
3787     // the address space. This generates the pattern (PseudoLLA sym), which
3788     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3789     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3790     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3791   }
3792   }
3793 }
3794 
3795 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3796                                                 SelectionDAG &DAG) const {
3797   SDLoc DL(Op);
3798   EVT Ty = Op.getValueType();
3799   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3800   int64_t Offset = N->getOffset();
3801   MVT XLenVT = Subtarget.getXLenVT();
3802 
3803   const GlobalValue *GV = N->getGlobal();
3804   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3805   SDValue Addr = getAddr(N, DAG, IsLocal);
3806 
3807   // In order to maximise the opportunity for common subexpression elimination,
3808   // emit a separate ADD node for the global address offset instead of folding
3809   // it in the global address node. Later peephole optimisations may choose to
3810   // fold it back in when profitable.
3811   if (Offset != 0)
3812     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3813                        DAG.getConstant(Offset, DL, XLenVT));
3814   return Addr;
3815 }
3816 
3817 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3818                                                SelectionDAG &DAG) const {
3819   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3820 
3821   return getAddr(N, DAG);
3822 }
3823 
3824 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3825                                                SelectionDAG &DAG) const {
3826   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3827 
3828   return getAddr(N, DAG);
3829 }
3830 
3831 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3832                                             SelectionDAG &DAG) const {
3833   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3834 
3835   return getAddr(N, DAG);
3836 }
3837 
3838 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3839                                               SelectionDAG &DAG,
3840                                               bool UseGOT) const {
3841   SDLoc DL(N);
3842   EVT Ty = getPointerTy(DAG.getDataLayout());
3843   const GlobalValue *GV = N->getGlobal();
3844   MVT XLenVT = Subtarget.getXLenVT();
3845 
3846   if (UseGOT) {
3847     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3848     // load the address from the GOT and add the thread pointer. This generates
3849     // the pattern (PseudoLA_TLS_IE sym), which expands to
3850     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3851     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3852     SDValue Load =
3853         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3854 
3855     // Add the thread pointer.
3856     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3857     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3858   }
3859 
3860   // Generate a sequence for accessing the address relative to the thread
3861   // pointer, with the appropriate adjustment for the thread pointer offset.
3862   // This generates the pattern
3863   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3864   SDValue AddrHi =
3865       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3866   SDValue AddrAdd =
3867       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3868   SDValue AddrLo =
3869       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3870 
3871   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3872   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3873   SDValue MNAdd = SDValue(
3874       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3875       0);
3876   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3877 }
3878 
3879 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3880                                                SelectionDAG &DAG) const {
3881   SDLoc DL(N);
3882   EVT Ty = getPointerTy(DAG.getDataLayout());
3883   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3884   const GlobalValue *GV = N->getGlobal();
3885 
3886   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3887   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3888   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3889   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3890   SDValue Load =
3891       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3892 
3893   // Prepare argument list to generate call.
3894   ArgListTy Args;
3895   ArgListEntry Entry;
3896   Entry.Node = Load;
3897   Entry.Ty = CallTy;
3898   Args.push_back(Entry);
3899 
3900   // Setup call to __tls_get_addr.
3901   TargetLowering::CallLoweringInfo CLI(DAG);
3902   CLI.setDebugLoc(DL)
3903       .setChain(DAG.getEntryNode())
3904       .setLibCallee(CallingConv::C, CallTy,
3905                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3906                     std::move(Args));
3907 
3908   return LowerCallTo(CLI).first;
3909 }
3910 
3911 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3912                                                    SelectionDAG &DAG) const {
3913   SDLoc DL(Op);
3914   EVT Ty = Op.getValueType();
3915   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3916   int64_t Offset = N->getOffset();
3917   MVT XLenVT = Subtarget.getXLenVT();
3918 
3919   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3920 
3921   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3922       CallingConv::GHC)
3923     report_fatal_error("In GHC calling convention TLS is not supported");
3924 
3925   SDValue Addr;
3926   switch (Model) {
3927   case TLSModel::LocalExec:
3928     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3929     break;
3930   case TLSModel::InitialExec:
3931     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3932     break;
3933   case TLSModel::LocalDynamic:
3934   case TLSModel::GeneralDynamic:
3935     Addr = getDynamicTLSAddr(N, DAG);
3936     break;
3937   }
3938 
3939   // In order to maximise the opportunity for common subexpression elimination,
3940   // emit a separate ADD node for the global address offset instead of folding
3941   // it in the global address node. Later peephole optimisations may choose to
3942   // fold it back in when profitable.
3943   if (Offset != 0)
3944     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3945                        DAG.getConstant(Offset, DL, XLenVT));
3946   return Addr;
3947 }
3948 
3949 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3950   SDValue CondV = Op.getOperand(0);
3951   SDValue TrueV = Op.getOperand(1);
3952   SDValue FalseV = Op.getOperand(2);
3953   SDLoc DL(Op);
3954   MVT VT = Op.getSimpleValueType();
3955   MVT XLenVT = Subtarget.getXLenVT();
3956 
3957   // Lower vector SELECTs to VSELECTs by splatting the condition.
3958   if (VT.isVector()) {
3959     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3960     SDValue CondSplat = VT.isScalableVector()
3961                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3962                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3963     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3964   }
3965 
3966   // If the result type is XLenVT and CondV is the output of a SETCC node
3967   // which also operated on XLenVT inputs, then merge the SETCC node into the
3968   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3969   // compare+branch instructions. i.e.:
3970   // (select (setcc lhs, rhs, cc), truev, falsev)
3971   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3972   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3973       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3974     SDValue LHS = CondV.getOperand(0);
3975     SDValue RHS = CondV.getOperand(1);
3976     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3977     ISD::CondCode CCVal = CC->get();
3978 
3979     // Special case for a select of 2 constants that have a diffence of 1.
3980     // Normally this is done by DAGCombine, but if the select is introduced by
3981     // type legalization or op legalization, we miss it. Restricting to SETLT
3982     // case for now because that is what signed saturating add/sub need.
3983     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3984     // but we would probably want to swap the true/false values if the condition
3985     // is SETGE/SETLE to avoid an XORI.
3986     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3987         CCVal == ISD::SETLT) {
3988       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3989       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3990       if (TrueVal - 1 == FalseVal)
3991         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3992       if (TrueVal + 1 == FalseVal)
3993         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3994     }
3995 
3996     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3997 
3998     SDValue TargetCC = DAG.getCondCode(CCVal);
3999     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
4000     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4001   }
4002 
4003   // Otherwise:
4004   // (select condv, truev, falsev)
4005   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
4006   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4007   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
4008 
4009   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
4010 
4011   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4012 }
4013 
4014 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4015   SDValue CondV = Op.getOperand(1);
4016   SDLoc DL(Op);
4017   MVT XLenVT = Subtarget.getXLenVT();
4018 
4019   if (CondV.getOpcode() == ISD::SETCC &&
4020       CondV.getOperand(0).getValueType() == XLenVT) {
4021     SDValue LHS = CondV.getOperand(0);
4022     SDValue RHS = CondV.getOperand(1);
4023     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
4024 
4025     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4026 
4027     SDValue TargetCC = DAG.getCondCode(CCVal);
4028     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4029                        LHS, RHS, TargetCC, Op.getOperand(2));
4030   }
4031 
4032   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4033                      CondV, DAG.getConstant(0, DL, XLenVT),
4034                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4035 }
4036 
4037 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4038   MachineFunction &MF = DAG.getMachineFunction();
4039   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4040 
4041   SDLoc DL(Op);
4042   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4043                                  getPointerTy(MF.getDataLayout()));
4044 
4045   // vastart just stores the address of the VarArgsFrameIndex slot into the
4046   // memory location argument.
4047   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4048   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4049                       MachinePointerInfo(SV));
4050 }
4051 
4052 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4053                                             SelectionDAG &DAG) const {
4054   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4055   MachineFunction &MF = DAG.getMachineFunction();
4056   MachineFrameInfo &MFI = MF.getFrameInfo();
4057   MFI.setFrameAddressIsTaken(true);
4058   Register FrameReg = RI.getFrameRegister(MF);
4059   int XLenInBytes = Subtarget.getXLen() / 8;
4060 
4061   EVT VT = Op.getValueType();
4062   SDLoc DL(Op);
4063   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4064   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4065   while (Depth--) {
4066     int Offset = -(XLenInBytes * 2);
4067     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4068                               DAG.getIntPtrConstant(Offset, DL));
4069     FrameAddr =
4070         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4071   }
4072   return FrameAddr;
4073 }
4074 
4075 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4076                                              SelectionDAG &DAG) const {
4077   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4078   MachineFunction &MF = DAG.getMachineFunction();
4079   MachineFrameInfo &MFI = MF.getFrameInfo();
4080   MFI.setReturnAddressIsTaken(true);
4081   MVT XLenVT = Subtarget.getXLenVT();
4082   int XLenInBytes = Subtarget.getXLen() / 8;
4083 
4084   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4085     return SDValue();
4086 
4087   EVT VT = Op.getValueType();
4088   SDLoc DL(Op);
4089   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4090   if (Depth) {
4091     int Off = -XLenInBytes;
4092     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4093     SDValue Offset = DAG.getConstant(Off, DL, VT);
4094     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4095                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4096                        MachinePointerInfo());
4097   }
4098 
4099   // Return the value of the return address register, marking it an implicit
4100   // live-in.
4101   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4102   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4103 }
4104 
4105 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4106                                                  SelectionDAG &DAG) const {
4107   SDLoc DL(Op);
4108   SDValue Lo = Op.getOperand(0);
4109   SDValue Hi = Op.getOperand(1);
4110   SDValue Shamt = Op.getOperand(2);
4111   EVT VT = Lo.getValueType();
4112 
4113   // if Shamt-XLEN < 0: // Shamt < XLEN
4114   //   Lo = Lo << Shamt
4115   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
4116   // else:
4117   //   Lo = 0
4118   //   Hi = Lo << (Shamt-XLEN)
4119 
4120   SDValue Zero = DAG.getConstant(0, DL, VT);
4121   SDValue One = DAG.getConstant(1, DL, VT);
4122   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4123   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4124   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4125   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
4126 
4127   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4128   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4129   SDValue ShiftRightLo =
4130       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4131   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4132   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4133   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4134 
4135   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4136 
4137   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4138   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4139 
4140   SDValue Parts[2] = {Lo, Hi};
4141   return DAG.getMergeValues(Parts, DL);
4142 }
4143 
4144 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4145                                                   bool IsSRA) const {
4146   SDLoc DL(Op);
4147   SDValue Lo = Op.getOperand(0);
4148   SDValue Hi = Op.getOperand(1);
4149   SDValue Shamt = Op.getOperand(2);
4150   EVT VT = Lo.getValueType();
4151 
4152   // SRA expansion:
4153   //   if Shamt-XLEN < 0: // Shamt < XLEN
4154   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
4155   //     Hi = Hi >>s Shamt
4156   //   else:
4157   //     Lo = Hi >>s (Shamt-XLEN);
4158   //     Hi = Hi >>s (XLEN-1)
4159   //
4160   // SRL expansion:
4161   //   if Shamt-XLEN < 0: // Shamt < XLEN
4162   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
4163   //     Hi = Hi >>u Shamt
4164   //   else:
4165   //     Lo = Hi >>u (Shamt-XLEN);
4166   //     Hi = 0;
4167 
4168   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4169 
4170   SDValue Zero = DAG.getConstant(0, DL, VT);
4171   SDValue One = DAG.getConstant(1, DL, VT);
4172   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4173   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4174   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4175   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
4176 
4177   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4178   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4179   SDValue ShiftLeftHi =
4180       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4181   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4182   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4183   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4184   SDValue HiFalse =
4185       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4186 
4187   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4188 
4189   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4190   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4191 
4192   SDValue Parts[2] = {Lo, Hi};
4193   return DAG.getMergeValues(Parts, DL);
4194 }
4195 
4196 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4197 // legal equivalently-sized i8 type, so we can use that as a go-between.
4198 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4199                                                   SelectionDAG &DAG) const {
4200   SDLoc DL(Op);
4201   MVT VT = Op.getSimpleValueType();
4202   SDValue SplatVal = Op.getOperand(0);
4203   // All-zeros or all-ones splats are handled specially.
4204   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4205     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4206     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4207   }
4208   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4209     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4210     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4211   }
4212   MVT XLenVT = Subtarget.getXLenVT();
4213   assert(SplatVal.getValueType() == XLenVT &&
4214          "Unexpected type for i1 splat value");
4215   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4216   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4217                          DAG.getConstant(1, DL, XLenVT));
4218   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4219   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4220   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4221 }
4222 
4223 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4224 // illegal (currently only vXi64 RV32).
4225 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4226 // them to VMV_V_X_VL.
4227 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4228                                                      SelectionDAG &DAG) const {
4229   SDLoc DL(Op);
4230   MVT VecVT = Op.getSimpleValueType();
4231   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4232          "Unexpected SPLAT_VECTOR_PARTS lowering");
4233 
4234   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4235   SDValue Lo = Op.getOperand(0);
4236   SDValue Hi = Op.getOperand(1);
4237 
4238   if (VecVT.isFixedLengthVector()) {
4239     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4240     SDLoc DL(Op);
4241     SDValue Mask, VL;
4242     std::tie(Mask, VL) =
4243         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4244 
4245     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
4246     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4247   }
4248 
4249   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4250     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4251     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4252     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4253     // node in order to try and match RVV vector/scalar instructions.
4254     if ((LoC >> 31) == HiC)
4255       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, Lo,
4256                          DAG.getRegister(RISCV::X0, MVT::i32));
4257   }
4258 
4259   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4260   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4261       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4262       Hi.getConstantOperandVal(1) == 31)
4263     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, Lo,
4264                        DAG.getRegister(RISCV::X0, MVT::i32));
4265 
4266   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4267   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
4268                      DAG.getRegister(RISCV::X0, MVT::i32));
4269 }
4270 
4271 // Custom-lower extensions from mask vectors by using a vselect either with 1
4272 // for zero/any-extension or -1 for sign-extension:
4273 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4274 // Note that any-extension is lowered identically to zero-extension.
4275 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4276                                                 int64_t ExtTrueVal) const {
4277   SDLoc DL(Op);
4278   MVT VecVT = Op.getSimpleValueType();
4279   SDValue Src = Op.getOperand(0);
4280   // Only custom-lower extensions from mask types
4281   assert(Src.getValueType().isVector() &&
4282          Src.getValueType().getVectorElementType() == MVT::i1);
4283 
4284   MVT XLenVT = Subtarget.getXLenVT();
4285   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4286   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4287 
4288   if (VecVT.isScalableVector()) {
4289     // Be careful not to introduce illegal scalar types at this stage, and be
4290     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4291     // illegal and must be expanded. Since we know that the constants are
4292     // sign-extended 32-bit values, we use VMV_V_X_VL directly.
4293     bool IsRV32E64 =
4294         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4295 
4296     if (!IsRV32E64) {
4297       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4298       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4299     } else {
4300       SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, SplatZero,
4301                               DAG.getRegister(RISCV::X0, XLenVT));
4302       SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, SplatTrueVal,
4303                                  DAG.getRegister(RISCV::X0, XLenVT));
4304     }
4305 
4306     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4307   }
4308 
4309   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4310   MVT I1ContainerVT =
4311       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4312 
4313   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4314 
4315   SDValue Mask, VL;
4316   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4317 
4318   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
4319   SplatTrueVal =
4320       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
4321   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4322                                SplatTrueVal, SplatZero, VL);
4323 
4324   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4325 }
4326 
4327 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4328     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4329   MVT ExtVT = Op.getSimpleValueType();
4330   // Only custom-lower extensions from fixed-length vector types.
4331   if (!ExtVT.isFixedLengthVector())
4332     return Op;
4333   MVT VT = Op.getOperand(0).getSimpleValueType();
4334   // Grab the canonical container type for the extended type. Infer the smaller
4335   // type from that to ensure the same number of vector elements, as we know
4336   // the LMUL will be sufficient to hold the smaller type.
4337   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4338   // Get the extended container type manually to ensure the same number of
4339   // vector elements between source and dest.
4340   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4341                                      ContainerExtVT.getVectorElementCount());
4342 
4343   SDValue Op1 =
4344       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4345 
4346   SDLoc DL(Op);
4347   SDValue Mask, VL;
4348   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4349 
4350   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4351 
4352   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4353 }
4354 
4355 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4356 // setcc operation:
4357 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4358 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4359                                                   SelectionDAG &DAG) const {
4360   SDLoc DL(Op);
4361   EVT MaskVT = Op.getValueType();
4362   // Only expect to custom-lower truncations to mask types
4363   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4364          "Unexpected type for vector mask lowering");
4365   SDValue Src = Op.getOperand(0);
4366   MVT VecVT = Src.getSimpleValueType();
4367 
4368   // If this is a fixed vector, we need to convert it to a scalable vector.
4369   MVT ContainerVT = VecVT;
4370   if (VecVT.isFixedLengthVector()) {
4371     ContainerVT = getContainerForFixedLengthVector(VecVT);
4372     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4373   }
4374 
4375   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4376   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4377 
4378   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
4379   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
4380 
4381   if (VecVT.isScalableVector()) {
4382     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4383     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4384   }
4385 
4386   SDValue Mask, VL;
4387   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4388 
4389   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4390   SDValue Trunc =
4391       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4392   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4393                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4394   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4395 }
4396 
4397 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4398 // first position of a vector, and that vector is slid up to the insert index.
4399 // By limiting the active vector length to index+1 and merging with the
4400 // original vector (with an undisturbed tail policy for elements >= VL), we
4401 // achieve the desired result of leaving all elements untouched except the one
4402 // at VL-1, which is replaced with the desired value.
4403 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4404                                                     SelectionDAG &DAG) const {
4405   SDLoc DL(Op);
4406   MVT VecVT = Op.getSimpleValueType();
4407   SDValue Vec = Op.getOperand(0);
4408   SDValue Val = Op.getOperand(1);
4409   SDValue Idx = Op.getOperand(2);
4410 
4411   if (VecVT.getVectorElementType() == MVT::i1) {
4412     // FIXME: For now we just promote to an i8 vector and insert into that,
4413     // but this is probably not optimal.
4414     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4415     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4416     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4417     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4418   }
4419 
4420   MVT ContainerVT = VecVT;
4421   // If the operand is a fixed-length vector, convert to a scalable one.
4422   if (VecVT.isFixedLengthVector()) {
4423     ContainerVT = getContainerForFixedLengthVector(VecVT);
4424     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4425   }
4426 
4427   MVT XLenVT = Subtarget.getXLenVT();
4428 
4429   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4430   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4431   // Even i64-element vectors on RV32 can be lowered without scalar
4432   // legalization if the most-significant 32 bits of the value are not affected
4433   // by the sign-extension of the lower 32 bits.
4434   // TODO: We could also catch sign extensions of a 32-bit value.
4435   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4436     const auto *CVal = cast<ConstantSDNode>(Val);
4437     if (isInt<32>(CVal->getSExtValue())) {
4438       IsLegalInsert = true;
4439       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4440     }
4441   }
4442 
4443   SDValue Mask, VL;
4444   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4445 
4446   SDValue ValInVec;
4447 
4448   if (IsLegalInsert) {
4449     unsigned Opc =
4450         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4451     if (isNullConstant(Idx)) {
4452       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4453       if (!VecVT.isFixedLengthVector())
4454         return Vec;
4455       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4456     }
4457     ValInVec =
4458         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4459   } else {
4460     // On RV32, i64-element vectors must be specially handled to place the
4461     // value at element 0, by using two vslide1up instructions in sequence on
4462     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4463     // this.
4464     SDValue One = DAG.getConstant(1, DL, XLenVT);
4465     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4466     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4467     MVT I32ContainerVT =
4468         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4469     SDValue I32Mask =
4470         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4471     // Limit the active VL to two.
4472     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4473     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4474     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4475     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4476                            InsertI64VL);
4477     // First slide in the hi value, then the lo in underneath it.
4478     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4479                            ValHi, I32Mask, InsertI64VL);
4480     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4481                            ValLo, I32Mask, InsertI64VL);
4482     // Bitcast back to the right container type.
4483     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4484   }
4485 
4486   // Now that the value is in a vector, slide it into position.
4487   SDValue InsertVL =
4488       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4489   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4490                                 ValInVec, Idx, Mask, InsertVL);
4491   if (!VecVT.isFixedLengthVector())
4492     return Slideup;
4493   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4494 }
4495 
4496 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4497 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4498 // types this is done using VMV_X_S to allow us to glean information about the
4499 // sign bits of the result.
4500 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4501                                                      SelectionDAG &DAG) const {
4502   SDLoc DL(Op);
4503   SDValue Idx = Op.getOperand(1);
4504   SDValue Vec = Op.getOperand(0);
4505   EVT EltVT = Op.getValueType();
4506   MVT VecVT = Vec.getSimpleValueType();
4507   MVT XLenVT = Subtarget.getXLenVT();
4508 
4509   if (VecVT.getVectorElementType() == MVT::i1) {
4510     if (VecVT.isFixedLengthVector()) {
4511       unsigned NumElts = VecVT.getVectorNumElements();
4512       if (NumElts >= 8) {
4513         MVT WideEltVT;
4514         unsigned WidenVecLen;
4515         SDValue ExtractElementIdx;
4516         SDValue ExtractBitIdx;
4517         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4518         MVT LargestEltVT = MVT::getIntegerVT(
4519             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4520         if (NumElts <= LargestEltVT.getSizeInBits()) {
4521           assert(isPowerOf2_32(NumElts) &&
4522                  "the number of elements should be power of 2");
4523           WideEltVT = MVT::getIntegerVT(NumElts);
4524           WidenVecLen = 1;
4525           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4526           ExtractBitIdx = Idx;
4527         } else {
4528           WideEltVT = LargestEltVT;
4529           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4530           // extract element index = index / element width
4531           ExtractElementIdx = DAG.getNode(
4532               ISD::SRL, DL, XLenVT, Idx,
4533               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4534           // mask bit index = index % element width
4535           ExtractBitIdx = DAG.getNode(
4536               ISD::AND, DL, XLenVT, Idx,
4537               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4538         }
4539         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4540         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4541         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4542                                          Vec, ExtractElementIdx);
4543         // Extract the bit from GPR.
4544         SDValue ShiftRight =
4545             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4546         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4547                            DAG.getConstant(1, DL, XLenVT));
4548       }
4549     }
4550     // Otherwise, promote to an i8 vector and extract from that.
4551     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4552     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4553     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4554   }
4555 
4556   // If this is a fixed vector, we need to convert it to a scalable vector.
4557   MVT ContainerVT = VecVT;
4558   if (VecVT.isFixedLengthVector()) {
4559     ContainerVT = getContainerForFixedLengthVector(VecVT);
4560     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4561   }
4562 
4563   // If the index is 0, the vector is already in the right position.
4564   if (!isNullConstant(Idx)) {
4565     // Use a VL of 1 to avoid processing more elements than we need.
4566     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4567     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4568     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4569     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4570                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4571   }
4572 
4573   if (!EltVT.isInteger()) {
4574     // Floating-point extracts are handled in TableGen.
4575     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4576                        DAG.getConstant(0, DL, XLenVT));
4577   }
4578 
4579   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4580   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4581 }
4582 
4583 // Some RVV intrinsics may claim that they want an integer operand to be
4584 // promoted or expanded.
4585 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4586                                           const RISCVSubtarget &Subtarget) {
4587   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4588           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4589          "Unexpected opcode");
4590 
4591   if (!Subtarget.hasVInstructions())
4592     return SDValue();
4593 
4594   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4595   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4596   SDLoc DL(Op);
4597 
4598   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4599       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4600   if (!II || !II->hasSplatOperand())
4601     return SDValue();
4602 
4603   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4604   assert(SplatOp < Op.getNumOperands());
4605 
4606   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4607   SDValue &ScalarOp = Operands[SplatOp];
4608   MVT OpVT = ScalarOp.getSimpleValueType();
4609   MVT XLenVT = Subtarget.getXLenVT();
4610 
4611   // If this isn't a scalar, or its type is XLenVT we're done.
4612   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4613     return SDValue();
4614 
4615   // Simplest case is that the operand needs to be promoted to XLenVT.
4616   if (OpVT.bitsLT(XLenVT)) {
4617     // If the operand is a constant, sign extend to increase our chances
4618     // of being able to use a .vi instruction. ANY_EXTEND would become a
4619     // a zero extend and the simm5 check in isel would fail.
4620     // FIXME: Should we ignore the upper bits in isel instead?
4621     unsigned ExtOpc =
4622         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4623     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4624     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4625   }
4626 
4627   // Use the previous operand to get the vXi64 VT. The result might be a mask
4628   // VT for compares. Using the previous operand assumes that the previous
4629   // operand will never have a smaller element size than a scalar operand and
4630   // that a widening operation never uses SEW=64.
4631   // NOTE: If this fails the below assert, we can probably just find the
4632   // element count from any operand or result and use it to construct the VT.
4633   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4634   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4635 
4636   // The more complex case is when the scalar is larger than XLenVT.
4637   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4638          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4639 
4640   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4641   // on the instruction to sign-extend since SEW>XLEN.
4642   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4643     if (isInt<32>(CVal->getSExtValue())) {
4644       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4645       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4646     }
4647   }
4648 
4649   // We need to convert the scalar to a splat vector.
4650   // FIXME: Can we implicitly truncate the scalar if it is known to
4651   // be sign extended?
4652   SDValue VL = getVLOperand(Op);
4653   assert(VL.getValueType() == XLenVT);
4654   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4655   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4656 }
4657 
4658 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4659                                                      SelectionDAG &DAG) const {
4660   unsigned IntNo = Op.getConstantOperandVal(0);
4661   SDLoc DL(Op);
4662   MVT XLenVT = Subtarget.getXLenVT();
4663 
4664   switch (IntNo) {
4665   default:
4666     break; // Don't custom lower most intrinsics.
4667   case Intrinsic::thread_pointer: {
4668     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4669     return DAG.getRegister(RISCV::X4, PtrVT);
4670   }
4671   case Intrinsic::riscv_orc_b:
4672   case Intrinsic::riscv_brev8: {
4673     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4674     unsigned Opc =
4675         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4676     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4677                        DAG.getConstant(7, DL, XLenVT));
4678   }
4679   case Intrinsic::riscv_grev:
4680   case Intrinsic::riscv_gorc: {
4681     unsigned Opc =
4682         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4683     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4684   }
4685   case Intrinsic::riscv_zip:
4686   case Intrinsic::riscv_unzip: {
4687     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4688     // For i32 the immdiate is 15. For i64 the immediate is 31.
4689     unsigned Opc =
4690         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4691     unsigned BitWidth = Op.getValueSizeInBits();
4692     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4693     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4694                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4695   }
4696   case Intrinsic::riscv_shfl:
4697   case Intrinsic::riscv_unshfl: {
4698     unsigned Opc =
4699         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4700     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4701   }
4702   case Intrinsic::riscv_bcompress:
4703   case Intrinsic::riscv_bdecompress: {
4704     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4705                                                        : RISCVISD::BDECOMPRESS;
4706     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4707   }
4708   case Intrinsic::riscv_bfp:
4709     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4710                        Op.getOperand(2));
4711   case Intrinsic::riscv_fsl:
4712     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4713                        Op.getOperand(2), Op.getOperand(3));
4714   case Intrinsic::riscv_fsr:
4715     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4716                        Op.getOperand(2), Op.getOperand(3));
4717   case Intrinsic::riscv_vmv_x_s:
4718     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4719     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4720                        Op.getOperand(1));
4721   case Intrinsic::riscv_vmv_v_x:
4722     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4723                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4724   case Intrinsic::riscv_vfmv_v_f:
4725     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4726                        Op.getOperand(1), Op.getOperand(2));
4727   case Intrinsic::riscv_vmv_s_x: {
4728     SDValue Scalar = Op.getOperand(2);
4729 
4730     if (Scalar.getValueType().bitsLE(XLenVT)) {
4731       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4732       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4733                          Op.getOperand(1), Scalar, Op.getOperand(3));
4734     }
4735 
4736     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4737 
4738     // This is an i64 value that lives in two scalar registers. We have to
4739     // insert this in a convoluted way. First we build vXi64 splat containing
4740     // the/ two values that we assemble using some bit math. Next we'll use
4741     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4742     // to merge element 0 from our splat into the source vector.
4743     // FIXME: This is probably not the best way to do this, but it is
4744     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4745     // point.
4746     //   sw lo, (a0)
4747     //   sw hi, 4(a0)
4748     //   vlse vX, (a0)
4749     //
4750     //   vid.v      vVid
4751     //   vmseq.vx   mMask, vVid, 0
4752     //   vmerge.vvm vDest, vSrc, vVal, mMask
4753     MVT VT = Op.getSimpleValueType();
4754     SDValue Vec = Op.getOperand(1);
4755     SDValue VL = getVLOperand(Op);
4756 
4757     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4758     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4759                                       DAG.getConstant(0, DL, MVT::i32), VL);
4760 
4761     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4762     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4763     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4764     SDValue SelectCond =
4765         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4766                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4767     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4768                        Vec, VL);
4769   }
4770   case Intrinsic::riscv_vslide1up:
4771   case Intrinsic::riscv_vslide1down:
4772   case Intrinsic::riscv_vslide1up_mask:
4773   case Intrinsic::riscv_vslide1down_mask: {
4774     // We need to special case these when the scalar is larger than XLen.
4775     unsigned NumOps = Op.getNumOperands();
4776     bool IsMasked = NumOps == 7;
4777     unsigned OpOffset = IsMasked ? 1 : 0;
4778     SDValue Scalar = Op.getOperand(2 + OpOffset);
4779     if (Scalar.getValueType().bitsLE(XLenVT))
4780       break;
4781 
4782     // Splatting a sign extended constant is fine.
4783     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4784       if (isInt<32>(CVal->getSExtValue()))
4785         break;
4786 
4787     MVT VT = Op.getSimpleValueType();
4788     assert(VT.getVectorElementType() == MVT::i64 &&
4789            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4790 
4791     // Convert the vector source to the equivalent nxvXi32 vector.
4792     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4793     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4794 
4795     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4796                                    DAG.getConstant(0, DL, XLenVT));
4797     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4798                                    DAG.getConstant(1, DL, XLenVT));
4799 
4800     // Double the VL since we halved SEW.
4801     SDValue VL = getVLOperand(Op);
4802     SDValue I32VL =
4803         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4804 
4805     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4806     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4807 
4808     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4809     // instructions.
4810     if (IntNo == Intrinsic::riscv_vslide1up ||
4811         IntNo == Intrinsic::riscv_vslide1up_mask) {
4812       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4813                         I32Mask, I32VL);
4814       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4815                         I32Mask, I32VL);
4816     } else {
4817       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4818                         I32Mask, I32VL);
4819       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4820                         I32Mask, I32VL);
4821     }
4822 
4823     // Convert back to nxvXi64.
4824     Vec = DAG.getBitcast(VT, Vec);
4825 
4826     if (!IsMasked)
4827       return Vec;
4828 
4829     // Apply mask after the operation.
4830     SDValue Mask = Op.getOperand(NumOps - 3);
4831     SDValue MaskedOff = Op.getOperand(1);
4832     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4833   }
4834   }
4835 
4836   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4837 }
4838 
4839 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4840                                                     SelectionDAG &DAG) const {
4841   unsigned IntNo = Op.getConstantOperandVal(1);
4842   switch (IntNo) {
4843   default:
4844     break;
4845   case Intrinsic::riscv_masked_strided_load: {
4846     SDLoc DL(Op);
4847     MVT XLenVT = Subtarget.getXLenVT();
4848 
4849     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4850     // the selection of the masked intrinsics doesn't do this for us.
4851     SDValue Mask = Op.getOperand(5);
4852     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4853 
4854     MVT VT = Op->getSimpleValueType(0);
4855     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4856 
4857     SDValue PassThru = Op.getOperand(2);
4858     if (!IsUnmasked) {
4859       MVT MaskVT =
4860           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4861       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4862       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4863     }
4864 
4865     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4866 
4867     SDValue IntID = DAG.getTargetConstant(
4868         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4869         XLenVT);
4870 
4871     auto *Load = cast<MemIntrinsicSDNode>(Op);
4872     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4873     if (IsUnmasked)
4874       Ops.push_back(DAG.getUNDEF(ContainerVT));
4875     else
4876       Ops.push_back(PassThru);
4877     Ops.push_back(Op.getOperand(3)); // Ptr
4878     Ops.push_back(Op.getOperand(4)); // Stride
4879     if (!IsUnmasked)
4880       Ops.push_back(Mask);
4881     Ops.push_back(VL);
4882     if (!IsUnmasked) {
4883       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4884       Ops.push_back(Policy);
4885     }
4886 
4887     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4888     SDValue Result =
4889         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4890                                 Load->getMemoryVT(), Load->getMemOperand());
4891     SDValue Chain = Result.getValue(1);
4892     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4893     return DAG.getMergeValues({Result, Chain}, DL);
4894   }
4895   }
4896 
4897   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4898 }
4899 
4900 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4901                                                  SelectionDAG &DAG) const {
4902   unsigned IntNo = Op.getConstantOperandVal(1);
4903   switch (IntNo) {
4904   default:
4905     break;
4906   case Intrinsic::riscv_masked_strided_store: {
4907     SDLoc DL(Op);
4908     MVT XLenVT = Subtarget.getXLenVT();
4909 
4910     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4911     // the selection of the masked intrinsics doesn't do this for us.
4912     SDValue Mask = Op.getOperand(5);
4913     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4914 
4915     SDValue Val = Op.getOperand(2);
4916     MVT VT = Val.getSimpleValueType();
4917     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4918 
4919     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4920     if (!IsUnmasked) {
4921       MVT MaskVT =
4922           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4923       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4924     }
4925 
4926     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4927 
4928     SDValue IntID = DAG.getTargetConstant(
4929         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4930         XLenVT);
4931 
4932     auto *Store = cast<MemIntrinsicSDNode>(Op);
4933     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4934     Ops.push_back(Val);
4935     Ops.push_back(Op.getOperand(3)); // Ptr
4936     Ops.push_back(Op.getOperand(4)); // Stride
4937     if (!IsUnmasked)
4938       Ops.push_back(Mask);
4939     Ops.push_back(VL);
4940 
4941     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4942                                    Ops, Store->getMemoryVT(),
4943                                    Store->getMemOperand());
4944   }
4945   }
4946 
4947   return SDValue();
4948 }
4949 
4950 static MVT getLMUL1VT(MVT VT) {
4951   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4952          "Unexpected vector MVT");
4953   return MVT::getScalableVectorVT(
4954       VT.getVectorElementType(),
4955       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4956 }
4957 
4958 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4959   switch (ISDOpcode) {
4960   default:
4961     llvm_unreachable("Unhandled reduction");
4962   case ISD::VECREDUCE_ADD:
4963     return RISCVISD::VECREDUCE_ADD_VL;
4964   case ISD::VECREDUCE_UMAX:
4965     return RISCVISD::VECREDUCE_UMAX_VL;
4966   case ISD::VECREDUCE_SMAX:
4967     return RISCVISD::VECREDUCE_SMAX_VL;
4968   case ISD::VECREDUCE_UMIN:
4969     return RISCVISD::VECREDUCE_UMIN_VL;
4970   case ISD::VECREDUCE_SMIN:
4971     return RISCVISD::VECREDUCE_SMIN_VL;
4972   case ISD::VECREDUCE_AND:
4973     return RISCVISD::VECREDUCE_AND_VL;
4974   case ISD::VECREDUCE_OR:
4975     return RISCVISD::VECREDUCE_OR_VL;
4976   case ISD::VECREDUCE_XOR:
4977     return RISCVISD::VECREDUCE_XOR_VL;
4978   }
4979 }
4980 
4981 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4982                                                          SelectionDAG &DAG,
4983                                                          bool IsVP) const {
4984   SDLoc DL(Op);
4985   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4986   MVT VecVT = Vec.getSimpleValueType();
4987   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4988           Op.getOpcode() == ISD::VECREDUCE_OR ||
4989           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4990           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4991           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4992           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4993          "Unexpected reduction lowering");
4994 
4995   MVT XLenVT = Subtarget.getXLenVT();
4996   assert(Op.getValueType() == XLenVT &&
4997          "Expected reduction output to be legalized to XLenVT");
4998 
4999   MVT ContainerVT = VecVT;
5000   if (VecVT.isFixedLengthVector()) {
5001     ContainerVT = getContainerForFixedLengthVector(VecVT);
5002     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5003   }
5004 
5005   SDValue Mask, VL;
5006   if (IsVP) {
5007     Mask = Op.getOperand(2);
5008     VL = Op.getOperand(3);
5009   } else {
5010     std::tie(Mask, VL) =
5011         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5012   }
5013 
5014   unsigned BaseOpc;
5015   ISD::CondCode CC;
5016   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5017 
5018   switch (Op.getOpcode()) {
5019   default:
5020     llvm_unreachable("Unhandled reduction");
5021   case ISD::VECREDUCE_AND:
5022   case ISD::VP_REDUCE_AND: {
5023     // vcpop ~x == 0
5024     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5025     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5026     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5027     CC = ISD::SETEQ;
5028     BaseOpc = ISD::AND;
5029     break;
5030   }
5031   case ISD::VECREDUCE_OR:
5032   case ISD::VP_REDUCE_OR:
5033     // vcpop x != 0
5034     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5035     CC = ISD::SETNE;
5036     BaseOpc = ISD::OR;
5037     break;
5038   case ISD::VECREDUCE_XOR:
5039   case ISD::VP_REDUCE_XOR: {
5040     // ((vcpop x) & 1) != 0
5041     SDValue One = DAG.getConstant(1, DL, XLenVT);
5042     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5043     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5044     CC = ISD::SETNE;
5045     BaseOpc = ISD::XOR;
5046     break;
5047   }
5048   }
5049 
5050   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5051 
5052   if (!IsVP)
5053     return SetCC;
5054 
5055   // Now include the start value in the operation.
5056   // Note that we must return the start value when no elements are operated
5057   // upon. The vcpop instructions we've emitted in each case above will return
5058   // 0 for an inactive vector, and so we've already received the neutral value:
5059   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5060   // can simply include the start value.
5061   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5062 }
5063 
5064 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5065                                             SelectionDAG &DAG) const {
5066   SDLoc DL(Op);
5067   SDValue Vec = Op.getOperand(0);
5068   EVT VecEVT = Vec.getValueType();
5069 
5070   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5071 
5072   // Due to ordering in legalize types we may have a vector type that needs to
5073   // be split. Do that manually so we can get down to a legal type.
5074   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5075          TargetLowering::TypeSplitVector) {
5076     SDValue Lo, Hi;
5077     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5078     VecEVT = Lo.getValueType();
5079     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5080   }
5081 
5082   // TODO: The type may need to be widened rather than split. Or widened before
5083   // it can be split.
5084   if (!isTypeLegal(VecEVT))
5085     return SDValue();
5086 
5087   MVT VecVT = VecEVT.getSimpleVT();
5088   MVT VecEltVT = VecVT.getVectorElementType();
5089   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5090 
5091   MVT ContainerVT = VecVT;
5092   if (VecVT.isFixedLengthVector()) {
5093     ContainerVT = getContainerForFixedLengthVector(VecVT);
5094     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5095   }
5096 
5097   MVT M1VT = getLMUL1VT(ContainerVT);
5098   MVT XLenVT = Subtarget.getXLenVT();
5099 
5100   SDValue Mask, VL;
5101   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5102 
5103   SDValue NeutralElem =
5104       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5105   SDValue IdentitySplat = lowerScalarSplat(
5106       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
5107   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5108                                   IdentitySplat, Mask, VL);
5109   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5110                              DAG.getConstant(0, DL, XLenVT));
5111   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5112 }
5113 
5114 // Given a reduction op, this function returns the matching reduction opcode,
5115 // the vector SDValue and the scalar SDValue required to lower this to a
5116 // RISCVISD node.
5117 static std::tuple<unsigned, SDValue, SDValue>
5118 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5119   SDLoc DL(Op);
5120   auto Flags = Op->getFlags();
5121   unsigned Opcode = Op.getOpcode();
5122   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5123   switch (Opcode) {
5124   default:
5125     llvm_unreachable("Unhandled reduction");
5126   case ISD::VECREDUCE_FADD: {
5127     // Use positive zero if we can. It is cheaper to materialize.
5128     SDValue Zero =
5129         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5130     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5131   }
5132   case ISD::VECREDUCE_SEQ_FADD:
5133     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5134                            Op.getOperand(0));
5135   case ISD::VECREDUCE_FMIN:
5136     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5137                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5138   case ISD::VECREDUCE_FMAX:
5139     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5140                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5141   }
5142 }
5143 
5144 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5145                                               SelectionDAG &DAG) const {
5146   SDLoc DL(Op);
5147   MVT VecEltVT = Op.getSimpleValueType();
5148 
5149   unsigned RVVOpcode;
5150   SDValue VectorVal, ScalarVal;
5151   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5152       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5153   MVT VecVT = VectorVal.getSimpleValueType();
5154 
5155   MVT ContainerVT = VecVT;
5156   if (VecVT.isFixedLengthVector()) {
5157     ContainerVT = getContainerForFixedLengthVector(VecVT);
5158     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5159   }
5160 
5161   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5162   MVT XLenVT = Subtarget.getXLenVT();
5163 
5164   SDValue Mask, VL;
5165   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5166 
5167   SDValue ScalarSplat = lowerScalarSplat(
5168       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
5169   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5170                                   VectorVal, ScalarSplat, Mask, VL);
5171   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5172                      DAG.getConstant(0, DL, XLenVT));
5173 }
5174 
5175 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5176   switch (ISDOpcode) {
5177   default:
5178     llvm_unreachable("Unhandled reduction");
5179   case ISD::VP_REDUCE_ADD:
5180     return RISCVISD::VECREDUCE_ADD_VL;
5181   case ISD::VP_REDUCE_UMAX:
5182     return RISCVISD::VECREDUCE_UMAX_VL;
5183   case ISD::VP_REDUCE_SMAX:
5184     return RISCVISD::VECREDUCE_SMAX_VL;
5185   case ISD::VP_REDUCE_UMIN:
5186     return RISCVISD::VECREDUCE_UMIN_VL;
5187   case ISD::VP_REDUCE_SMIN:
5188     return RISCVISD::VECREDUCE_SMIN_VL;
5189   case ISD::VP_REDUCE_AND:
5190     return RISCVISD::VECREDUCE_AND_VL;
5191   case ISD::VP_REDUCE_OR:
5192     return RISCVISD::VECREDUCE_OR_VL;
5193   case ISD::VP_REDUCE_XOR:
5194     return RISCVISD::VECREDUCE_XOR_VL;
5195   case ISD::VP_REDUCE_FADD:
5196     return RISCVISD::VECREDUCE_FADD_VL;
5197   case ISD::VP_REDUCE_SEQ_FADD:
5198     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5199   case ISD::VP_REDUCE_FMAX:
5200     return RISCVISD::VECREDUCE_FMAX_VL;
5201   case ISD::VP_REDUCE_FMIN:
5202     return RISCVISD::VECREDUCE_FMIN_VL;
5203   }
5204 }
5205 
5206 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5207                                            SelectionDAG &DAG) const {
5208   SDLoc DL(Op);
5209   SDValue Vec = Op.getOperand(1);
5210   EVT VecEVT = Vec.getValueType();
5211 
5212   // TODO: The type may need to be widened rather than split. Or widened before
5213   // it can be split.
5214   if (!isTypeLegal(VecEVT))
5215     return SDValue();
5216 
5217   MVT VecVT = VecEVT.getSimpleVT();
5218   MVT VecEltVT = VecVT.getVectorElementType();
5219   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5220 
5221   MVT ContainerVT = VecVT;
5222   if (VecVT.isFixedLengthVector()) {
5223     ContainerVT = getContainerForFixedLengthVector(VecVT);
5224     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5225   }
5226 
5227   SDValue VL = Op.getOperand(3);
5228   SDValue Mask = Op.getOperand(2);
5229 
5230   MVT M1VT = getLMUL1VT(ContainerVT);
5231   MVT XLenVT = Subtarget.getXLenVT();
5232   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5233 
5234   SDValue StartSplat =
5235       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
5236                        DL, DAG, Subtarget);
5237   SDValue Reduction =
5238       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5239   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5240                              DAG.getConstant(0, DL, XLenVT));
5241   if (!VecVT.isInteger())
5242     return Elt0;
5243   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5244 }
5245 
5246 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5247                                                    SelectionDAG &DAG) const {
5248   SDValue Vec = Op.getOperand(0);
5249   SDValue SubVec = Op.getOperand(1);
5250   MVT VecVT = Vec.getSimpleValueType();
5251   MVT SubVecVT = SubVec.getSimpleValueType();
5252 
5253   SDLoc DL(Op);
5254   MVT XLenVT = Subtarget.getXLenVT();
5255   unsigned OrigIdx = Op.getConstantOperandVal(2);
5256   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5257 
5258   // We don't have the ability to slide mask vectors up indexed by their i1
5259   // elements; the smallest we can do is i8. Often we are able to bitcast to
5260   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5261   // into a scalable one, we might not necessarily have enough scalable
5262   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5263   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5264       (OrigIdx != 0 || !Vec.isUndef())) {
5265     if (VecVT.getVectorMinNumElements() >= 8 &&
5266         SubVecVT.getVectorMinNumElements() >= 8) {
5267       assert(OrigIdx % 8 == 0 && "Invalid index");
5268       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5269              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5270              "Unexpected mask vector lowering");
5271       OrigIdx /= 8;
5272       SubVecVT =
5273           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5274                            SubVecVT.isScalableVector());
5275       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5276                                VecVT.isScalableVector());
5277       Vec = DAG.getBitcast(VecVT, Vec);
5278       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5279     } else {
5280       // We can't slide this mask vector up indexed by its i1 elements.
5281       // This poses a problem when we wish to insert a scalable vector which
5282       // can't be re-expressed as a larger type. Just choose the slow path and
5283       // extend to a larger type, then truncate back down.
5284       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5285       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5286       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5287       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5288       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5289                         Op.getOperand(2));
5290       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5291       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5292     }
5293   }
5294 
5295   // If the subvector vector is a fixed-length type, we cannot use subregister
5296   // manipulation to simplify the codegen; we don't know which register of a
5297   // LMUL group contains the specific subvector as we only know the minimum
5298   // register size. Therefore we must slide the vector group up the full
5299   // amount.
5300   if (SubVecVT.isFixedLengthVector()) {
5301     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5302       return Op;
5303     MVT ContainerVT = VecVT;
5304     if (VecVT.isFixedLengthVector()) {
5305       ContainerVT = getContainerForFixedLengthVector(VecVT);
5306       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5307     }
5308     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5309                          DAG.getUNDEF(ContainerVT), SubVec,
5310                          DAG.getConstant(0, DL, XLenVT));
5311     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5312       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5313       return DAG.getBitcast(Op.getValueType(), SubVec);
5314     }
5315     SDValue Mask =
5316         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5317     // Set the vector length to only the number of elements we care about. Note
5318     // that for slideup this includes the offset.
5319     SDValue VL =
5320         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5321     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5322     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5323                                   SubVec, SlideupAmt, Mask, VL);
5324     if (VecVT.isFixedLengthVector())
5325       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5326     return DAG.getBitcast(Op.getValueType(), Slideup);
5327   }
5328 
5329   unsigned SubRegIdx, RemIdx;
5330   std::tie(SubRegIdx, RemIdx) =
5331       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5332           VecVT, SubVecVT, OrigIdx, TRI);
5333 
5334   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5335   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5336                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5337                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5338 
5339   // 1. If the Idx has been completely eliminated and this subvector's size is
5340   // a vector register or a multiple thereof, or the surrounding elements are
5341   // undef, then this is a subvector insert which naturally aligns to a vector
5342   // register. These can easily be handled using subregister manipulation.
5343   // 2. If the subvector is smaller than a vector register, then the insertion
5344   // must preserve the undisturbed elements of the register. We do this by
5345   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5346   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5347   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5348   // LMUL=1 type back into the larger vector (resolving to another subregister
5349   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5350   // to avoid allocating a large register group to hold our subvector.
5351   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5352     return Op;
5353 
5354   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5355   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5356   // (in our case undisturbed). This means we can set up a subvector insertion
5357   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5358   // size of the subvector.
5359   MVT InterSubVT = VecVT;
5360   SDValue AlignedExtract = Vec;
5361   unsigned AlignedIdx = OrigIdx - RemIdx;
5362   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5363     InterSubVT = getLMUL1VT(VecVT);
5364     // Extract a subvector equal to the nearest full vector register type. This
5365     // should resolve to a EXTRACT_SUBREG instruction.
5366     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5367                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5368   }
5369 
5370   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5371   // For scalable vectors this must be further multiplied by vscale.
5372   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5373 
5374   SDValue Mask, VL;
5375   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5376 
5377   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5378   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5379   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5380   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5381 
5382   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5383                        DAG.getUNDEF(InterSubVT), SubVec,
5384                        DAG.getConstant(0, DL, XLenVT));
5385 
5386   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5387                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5388 
5389   // If required, insert this subvector back into the correct vector register.
5390   // This should resolve to an INSERT_SUBREG instruction.
5391   if (VecVT.bitsGT(InterSubVT))
5392     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5393                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5394 
5395   // We might have bitcast from a mask type: cast back to the original type if
5396   // required.
5397   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5398 }
5399 
5400 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5401                                                     SelectionDAG &DAG) const {
5402   SDValue Vec = Op.getOperand(0);
5403   MVT SubVecVT = Op.getSimpleValueType();
5404   MVT VecVT = Vec.getSimpleValueType();
5405 
5406   SDLoc DL(Op);
5407   MVT XLenVT = Subtarget.getXLenVT();
5408   unsigned OrigIdx = Op.getConstantOperandVal(1);
5409   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5410 
5411   // We don't have the ability to slide mask vectors down indexed by their i1
5412   // elements; the smallest we can do is i8. Often we are able to bitcast to
5413   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5414   // from a scalable one, we might not necessarily have enough scalable
5415   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5416   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5417     if (VecVT.getVectorMinNumElements() >= 8 &&
5418         SubVecVT.getVectorMinNumElements() >= 8) {
5419       assert(OrigIdx % 8 == 0 && "Invalid index");
5420       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5421              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5422              "Unexpected mask vector lowering");
5423       OrigIdx /= 8;
5424       SubVecVT =
5425           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5426                            SubVecVT.isScalableVector());
5427       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5428                                VecVT.isScalableVector());
5429       Vec = DAG.getBitcast(VecVT, Vec);
5430     } else {
5431       // We can't slide this mask vector down, indexed by its i1 elements.
5432       // This poses a problem when we wish to extract a scalable vector which
5433       // can't be re-expressed as a larger type. Just choose the slow path and
5434       // extend to a larger type, then truncate back down.
5435       // TODO: We could probably improve this when extracting certain fixed
5436       // from fixed, where we can extract as i8 and shift the correct element
5437       // right to reach the desired subvector?
5438       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5439       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5440       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5441       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5442                         Op.getOperand(1));
5443       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5444       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5445     }
5446   }
5447 
5448   // If the subvector vector is a fixed-length type, we cannot use subregister
5449   // manipulation to simplify the codegen; we don't know which register of a
5450   // LMUL group contains the specific subvector as we only know the minimum
5451   // register size. Therefore we must slide the vector group down the full
5452   // amount.
5453   if (SubVecVT.isFixedLengthVector()) {
5454     // With an index of 0 this is a cast-like subvector, which can be performed
5455     // with subregister operations.
5456     if (OrigIdx == 0)
5457       return Op;
5458     MVT ContainerVT = VecVT;
5459     if (VecVT.isFixedLengthVector()) {
5460       ContainerVT = getContainerForFixedLengthVector(VecVT);
5461       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5462     }
5463     SDValue Mask =
5464         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5465     // Set the vector length to only the number of elements we care about. This
5466     // avoids sliding down elements we're going to discard straight away.
5467     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5468     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5469     SDValue Slidedown =
5470         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5471                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5472     // Now we can use a cast-like subvector extract to get the result.
5473     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5474                             DAG.getConstant(0, DL, XLenVT));
5475     return DAG.getBitcast(Op.getValueType(), Slidedown);
5476   }
5477 
5478   unsigned SubRegIdx, RemIdx;
5479   std::tie(SubRegIdx, RemIdx) =
5480       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5481           VecVT, SubVecVT, OrigIdx, TRI);
5482 
5483   // If the Idx has been completely eliminated then this is a subvector extract
5484   // which naturally aligns to a vector register. These can easily be handled
5485   // using subregister manipulation.
5486   if (RemIdx == 0)
5487     return Op;
5488 
5489   // Else we must shift our vector register directly to extract the subvector.
5490   // Do this using VSLIDEDOWN.
5491 
5492   // If the vector type is an LMUL-group type, extract a subvector equal to the
5493   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5494   // instruction.
5495   MVT InterSubVT = VecVT;
5496   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5497     InterSubVT = getLMUL1VT(VecVT);
5498     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5499                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5500   }
5501 
5502   // Slide this vector register down by the desired number of elements in order
5503   // to place the desired subvector starting at element 0.
5504   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5505   // For scalable vectors this must be further multiplied by vscale.
5506   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5507 
5508   SDValue Mask, VL;
5509   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5510   SDValue Slidedown =
5511       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5512                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5513 
5514   // Now the vector is in the right position, extract our final subvector. This
5515   // should resolve to a COPY.
5516   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5517                           DAG.getConstant(0, DL, XLenVT));
5518 
5519   // We might have bitcast from a mask type: cast back to the original type if
5520   // required.
5521   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5522 }
5523 
5524 // Lower step_vector to the vid instruction. Any non-identity step value must
5525 // be accounted for my manual expansion.
5526 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5527                                               SelectionDAG &DAG) const {
5528   SDLoc DL(Op);
5529   MVT VT = Op.getSimpleValueType();
5530   MVT XLenVT = Subtarget.getXLenVT();
5531   SDValue Mask, VL;
5532   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5533   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5534   uint64_t StepValImm = Op.getConstantOperandVal(0);
5535   if (StepValImm != 1) {
5536     if (isPowerOf2_64(StepValImm)) {
5537       SDValue StepVal =
5538           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5539                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5540       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5541     } else {
5542       SDValue StepVal = lowerScalarSplat(
5543           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5544           DL, DAG, Subtarget);
5545       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5546     }
5547   }
5548   return StepVec;
5549 }
5550 
5551 // Implement vector_reverse using vrgather.vv with indices determined by
5552 // subtracting the id of each element from (VLMAX-1). This will convert
5553 // the indices like so:
5554 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5555 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5556 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5557                                                  SelectionDAG &DAG) const {
5558   SDLoc DL(Op);
5559   MVT VecVT = Op.getSimpleValueType();
5560   unsigned EltSize = VecVT.getScalarSizeInBits();
5561   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5562 
5563   unsigned MaxVLMAX = 0;
5564   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5565   if (VectorBitsMax != 0)
5566     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5567 
5568   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5569   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5570 
5571   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5572   // to use vrgatherei16.vv.
5573   // TODO: It's also possible to use vrgatherei16.vv for other types to
5574   // decrease register width for the index calculation.
5575   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5576     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5577     // Reverse each half, then reassemble them in reverse order.
5578     // NOTE: It's also possible that after splitting that VLMAX no longer
5579     // requires vrgatherei16.vv.
5580     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5581       SDValue Lo, Hi;
5582       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5583       EVT LoVT, HiVT;
5584       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5585       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5586       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5587       // Reassemble the low and high pieces reversed.
5588       // FIXME: This is a CONCAT_VECTORS.
5589       SDValue Res =
5590           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5591                       DAG.getIntPtrConstant(0, DL));
5592       return DAG.getNode(
5593           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5594           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5595     }
5596 
5597     // Just promote the int type to i16 which will double the LMUL.
5598     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5599     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5600   }
5601 
5602   MVT XLenVT = Subtarget.getXLenVT();
5603   SDValue Mask, VL;
5604   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5605 
5606   // Calculate VLMAX-1 for the desired SEW.
5607   unsigned MinElts = VecVT.getVectorMinNumElements();
5608   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5609                               DAG.getConstant(MinElts, DL, XLenVT));
5610   SDValue VLMinus1 =
5611       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5612 
5613   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5614   bool IsRV32E64 =
5615       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5616   SDValue SplatVL;
5617   if (!IsRV32E64)
5618     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5619   else
5620     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, VLMinus1,
5621                           DAG.getRegister(RISCV::X0, XLenVT));
5622 
5623   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5624   SDValue Indices =
5625       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5626 
5627   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5628 }
5629 
5630 SDValue
5631 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5632                                                      SelectionDAG &DAG) const {
5633   SDLoc DL(Op);
5634   auto *Load = cast<LoadSDNode>(Op);
5635 
5636   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5637                                         Load->getMemoryVT(),
5638                                         *Load->getMemOperand()) &&
5639          "Expecting a correctly-aligned load");
5640 
5641   MVT VT = Op.getSimpleValueType();
5642   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5643 
5644   SDValue VL =
5645       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5646 
5647   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5648   SDValue NewLoad = DAG.getMemIntrinsicNode(
5649       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5650       Load->getMemoryVT(), Load->getMemOperand());
5651 
5652   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5653   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5654 }
5655 
5656 SDValue
5657 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5658                                                       SelectionDAG &DAG) const {
5659   SDLoc DL(Op);
5660   auto *Store = cast<StoreSDNode>(Op);
5661 
5662   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5663                                         Store->getMemoryVT(),
5664                                         *Store->getMemOperand()) &&
5665          "Expecting a correctly-aligned store");
5666 
5667   SDValue StoreVal = Store->getValue();
5668   MVT VT = StoreVal.getSimpleValueType();
5669 
5670   // If the size less than a byte, we need to pad with zeros to make a byte.
5671   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5672     VT = MVT::v8i1;
5673     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5674                            DAG.getConstant(0, DL, VT), StoreVal,
5675                            DAG.getIntPtrConstant(0, DL));
5676   }
5677 
5678   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5679 
5680   SDValue VL =
5681       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5682 
5683   SDValue NewValue =
5684       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5685   return DAG.getMemIntrinsicNode(
5686       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5687       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5688       Store->getMemoryVT(), Store->getMemOperand());
5689 }
5690 
5691 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5692                                              SelectionDAG &DAG) const {
5693   SDLoc DL(Op);
5694   MVT VT = Op.getSimpleValueType();
5695 
5696   const auto *MemSD = cast<MemSDNode>(Op);
5697   EVT MemVT = MemSD->getMemoryVT();
5698   MachineMemOperand *MMO = MemSD->getMemOperand();
5699   SDValue Chain = MemSD->getChain();
5700   SDValue BasePtr = MemSD->getBasePtr();
5701 
5702   SDValue Mask, PassThru, VL;
5703   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5704     Mask = VPLoad->getMask();
5705     PassThru = DAG.getUNDEF(VT);
5706     VL = VPLoad->getVectorLength();
5707   } else {
5708     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5709     Mask = MLoad->getMask();
5710     PassThru = MLoad->getPassThru();
5711   }
5712 
5713   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5714 
5715   MVT XLenVT = Subtarget.getXLenVT();
5716 
5717   MVT ContainerVT = VT;
5718   if (VT.isFixedLengthVector()) {
5719     ContainerVT = getContainerForFixedLengthVector(VT);
5720     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5721     if (!IsUnmasked) {
5722       MVT MaskVT =
5723           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5724       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5725     }
5726   }
5727 
5728   if (!VL)
5729     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5730 
5731   unsigned IntID =
5732       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5733   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5734   if (IsUnmasked)
5735     Ops.push_back(DAG.getUNDEF(ContainerVT));
5736   else
5737     Ops.push_back(PassThru);
5738   Ops.push_back(BasePtr);
5739   if (!IsUnmasked)
5740     Ops.push_back(Mask);
5741   Ops.push_back(VL);
5742   if (!IsUnmasked)
5743     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5744 
5745   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5746 
5747   SDValue Result =
5748       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5749   Chain = Result.getValue(1);
5750 
5751   if (VT.isFixedLengthVector())
5752     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5753 
5754   return DAG.getMergeValues({Result, Chain}, DL);
5755 }
5756 
5757 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5758                                               SelectionDAG &DAG) const {
5759   SDLoc DL(Op);
5760 
5761   const auto *MemSD = cast<MemSDNode>(Op);
5762   EVT MemVT = MemSD->getMemoryVT();
5763   MachineMemOperand *MMO = MemSD->getMemOperand();
5764   SDValue Chain = MemSD->getChain();
5765   SDValue BasePtr = MemSD->getBasePtr();
5766   SDValue Val, Mask, VL;
5767 
5768   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5769     Val = VPStore->getValue();
5770     Mask = VPStore->getMask();
5771     VL = VPStore->getVectorLength();
5772   } else {
5773     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5774     Val = MStore->getValue();
5775     Mask = MStore->getMask();
5776   }
5777 
5778   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5779 
5780   MVT VT = Val.getSimpleValueType();
5781   MVT XLenVT = Subtarget.getXLenVT();
5782 
5783   MVT ContainerVT = VT;
5784   if (VT.isFixedLengthVector()) {
5785     ContainerVT = getContainerForFixedLengthVector(VT);
5786 
5787     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5788     if (!IsUnmasked) {
5789       MVT MaskVT =
5790           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5791       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5792     }
5793   }
5794 
5795   if (!VL)
5796     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5797 
5798   unsigned IntID =
5799       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5800   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5801   Ops.push_back(Val);
5802   Ops.push_back(BasePtr);
5803   if (!IsUnmasked)
5804     Ops.push_back(Mask);
5805   Ops.push_back(VL);
5806 
5807   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5808                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5809 }
5810 
5811 SDValue
5812 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5813                                                       SelectionDAG &DAG) const {
5814   MVT InVT = Op.getOperand(0).getSimpleValueType();
5815   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5816 
5817   MVT VT = Op.getSimpleValueType();
5818 
5819   SDValue Op1 =
5820       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5821   SDValue Op2 =
5822       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5823 
5824   SDLoc DL(Op);
5825   SDValue VL =
5826       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5827 
5828   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5829   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5830 
5831   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5832                             Op.getOperand(2), Mask, VL);
5833 
5834   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5835 }
5836 
5837 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5838     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5839   MVT VT = Op.getSimpleValueType();
5840 
5841   if (VT.getVectorElementType() == MVT::i1)
5842     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5843 
5844   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5845 }
5846 
5847 SDValue
5848 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5849                                                       SelectionDAG &DAG) const {
5850   unsigned Opc;
5851   switch (Op.getOpcode()) {
5852   default: llvm_unreachable("Unexpected opcode!");
5853   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5854   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5855   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5856   }
5857 
5858   return lowerToScalableOp(Op, DAG, Opc);
5859 }
5860 
5861 // Lower vector ABS to smax(X, sub(0, X)).
5862 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5863   SDLoc DL(Op);
5864   MVT VT = Op.getSimpleValueType();
5865   SDValue X = Op.getOperand(0);
5866 
5867   assert(VT.isFixedLengthVector() && "Unexpected type");
5868 
5869   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5870   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5871 
5872   SDValue Mask, VL;
5873   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5874 
5875   SDValue SplatZero =
5876       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5877                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5878   SDValue NegX =
5879       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5880   SDValue Max =
5881       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5882 
5883   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5884 }
5885 
5886 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5887     SDValue Op, SelectionDAG &DAG) const {
5888   SDLoc DL(Op);
5889   MVT VT = Op.getSimpleValueType();
5890   SDValue Mag = Op.getOperand(0);
5891   SDValue Sign = Op.getOperand(1);
5892   assert(Mag.getValueType() == Sign.getValueType() &&
5893          "Can only handle COPYSIGN with matching types.");
5894 
5895   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5896   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5897   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5898 
5899   SDValue Mask, VL;
5900   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5901 
5902   SDValue CopySign =
5903       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5904 
5905   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5906 }
5907 
5908 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5909     SDValue Op, SelectionDAG &DAG) const {
5910   MVT VT = Op.getSimpleValueType();
5911   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5912 
5913   MVT I1ContainerVT =
5914       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5915 
5916   SDValue CC =
5917       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5918   SDValue Op1 =
5919       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5920   SDValue Op2 =
5921       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5922 
5923   SDLoc DL(Op);
5924   SDValue Mask, VL;
5925   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5926 
5927   SDValue Select =
5928       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5929 
5930   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5931 }
5932 
5933 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5934                                                unsigned NewOpc,
5935                                                bool HasMask) const {
5936   MVT VT = Op.getSimpleValueType();
5937   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5938 
5939   // Create list of operands by converting existing ones to scalable types.
5940   SmallVector<SDValue, 6> Ops;
5941   for (const SDValue &V : Op->op_values()) {
5942     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5943 
5944     // Pass through non-vector operands.
5945     if (!V.getValueType().isVector()) {
5946       Ops.push_back(V);
5947       continue;
5948     }
5949 
5950     // "cast" fixed length vector to a scalable vector.
5951     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5952            "Only fixed length vectors are supported!");
5953     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5954   }
5955 
5956   SDLoc DL(Op);
5957   SDValue Mask, VL;
5958   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5959   if (HasMask)
5960     Ops.push_back(Mask);
5961   Ops.push_back(VL);
5962 
5963   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5964   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5965 }
5966 
5967 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5968 // * Operands of each node are assumed to be in the same order.
5969 // * The EVL operand is promoted from i32 to i64 on RV64.
5970 // * Fixed-length vectors are converted to their scalable-vector container
5971 //   types.
5972 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5973                                        unsigned RISCVISDOpc) const {
5974   SDLoc DL(Op);
5975   MVT VT = Op.getSimpleValueType();
5976   SmallVector<SDValue, 4> Ops;
5977 
5978   for (const auto &OpIdx : enumerate(Op->ops())) {
5979     SDValue V = OpIdx.value();
5980     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5981     // Pass through operands which aren't fixed-length vectors.
5982     if (!V.getValueType().isFixedLengthVector()) {
5983       Ops.push_back(V);
5984       continue;
5985     }
5986     // "cast" fixed length vector to a scalable vector.
5987     MVT OpVT = V.getSimpleValueType();
5988     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5989     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5990            "Only fixed length vectors are supported!");
5991     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5992   }
5993 
5994   if (!VT.isFixedLengthVector())
5995     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5996 
5997   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5998 
5999   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6000 
6001   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6002 }
6003 
6004 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6005                                             unsigned MaskOpc,
6006                                             unsigned VecOpc) const {
6007   MVT VT = Op.getSimpleValueType();
6008   if (VT.getVectorElementType() != MVT::i1)
6009     return lowerVPOp(Op, DAG, VecOpc);
6010 
6011   // It is safe to drop mask parameter as masked-off elements are undef.
6012   SDValue Op1 = Op->getOperand(0);
6013   SDValue Op2 = Op->getOperand(1);
6014   SDValue VL = Op->getOperand(3);
6015 
6016   MVT ContainerVT = VT;
6017   const bool IsFixed = VT.isFixedLengthVector();
6018   if (IsFixed) {
6019     ContainerVT = getContainerForFixedLengthVector(VT);
6020     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6021     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6022   }
6023 
6024   SDLoc DL(Op);
6025   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6026   if (!IsFixed)
6027     return Val;
6028   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6029 }
6030 
6031 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6032 // matched to a RVV indexed load. The RVV indexed load instructions only
6033 // support the "unsigned unscaled" addressing mode; indices are implicitly
6034 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6035 // signed or scaled indexing is extended to the XLEN value type and scaled
6036 // accordingly.
6037 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6038                                                SelectionDAG &DAG) const {
6039   SDLoc DL(Op);
6040   MVT VT = Op.getSimpleValueType();
6041 
6042   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6043   EVT MemVT = MemSD->getMemoryVT();
6044   MachineMemOperand *MMO = MemSD->getMemOperand();
6045   SDValue Chain = MemSD->getChain();
6046   SDValue BasePtr = MemSD->getBasePtr();
6047 
6048   ISD::LoadExtType LoadExtType;
6049   SDValue Index, Mask, PassThru, VL;
6050 
6051   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6052     Index = VPGN->getIndex();
6053     Mask = VPGN->getMask();
6054     PassThru = DAG.getUNDEF(VT);
6055     VL = VPGN->getVectorLength();
6056     // VP doesn't support extending loads.
6057     LoadExtType = ISD::NON_EXTLOAD;
6058   } else {
6059     // Else it must be a MGATHER.
6060     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6061     Index = MGN->getIndex();
6062     Mask = MGN->getMask();
6063     PassThru = MGN->getPassThru();
6064     LoadExtType = MGN->getExtensionType();
6065   }
6066 
6067   MVT IndexVT = Index.getSimpleValueType();
6068   MVT XLenVT = Subtarget.getXLenVT();
6069 
6070   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6071          "Unexpected VTs!");
6072   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6073   // Targets have to explicitly opt-in for extending vector loads.
6074   assert(LoadExtType == ISD::NON_EXTLOAD &&
6075          "Unexpected extending MGATHER/VP_GATHER");
6076   (void)LoadExtType;
6077 
6078   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6079   // the selection of the masked intrinsics doesn't do this for us.
6080   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6081 
6082   MVT ContainerVT = VT;
6083   if (VT.isFixedLengthVector()) {
6084     // We need to use the larger of the result and index type to determine the
6085     // scalable type to use so we don't increase LMUL for any operand/result.
6086     if (VT.bitsGE(IndexVT)) {
6087       ContainerVT = getContainerForFixedLengthVector(VT);
6088       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6089                                  ContainerVT.getVectorElementCount());
6090     } else {
6091       IndexVT = getContainerForFixedLengthVector(IndexVT);
6092       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6093                                      IndexVT.getVectorElementCount());
6094     }
6095 
6096     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6097 
6098     if (!IsUnmasked) {
6099       MVT MaskVT =
6100           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6101       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6102       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6103     }
6104   }
6105 
6106   if (!VL)
6107     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6108 
6109   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6110     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6111     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6112                                    VL);
6113     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6114                         TrueMask, VL);
6115   }
6116 
6117   unsigned IntID =
6118       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6119   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6120   if (IsUnmasked)
6121     Ops.push_back(DAG.getUNDEF(ContainerVT));
6122   else
6123     Ops.push_back(PassThru);
6124   Ops.push_back(BasePtr);
6125   Ops.push_back(Index);
6126   if (!IsUnmasked)
6127     Ops.push_back(Mask);
6128   Ops.push_back(VL);
6129   if (!IsUnmasked)
6130     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6131 
6132   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6133   SDValue Result =
6134       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6135   Chain = Result.getValue(1);
6136 
6137   if (VT.isFixedLengthVector())
6138     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6139 
6140   return DAG.getMergeValues({Result, Chain}, DL);
6141 }
6142 
6143 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6144 // matched to a RVV indexed store. The RVV indexed store instructions only
6145 // support the "unsigned unscaled" addressing mode; indices are implicitly
6146 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6147 // signed or scaled indexing is extended to the XLEN value type and scaled
6148 // accordingly.
6149 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6150                                                 SelectionDAG &DAG) const {
6151   SDLoc DL(Op);
6152   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6153   EVT MemVT = MemSD->getMemoryVT();
6154   MachineMemOperand *MMO = MemSD->getMemOperand();
6155   SDValue Chain = MemSD->getChain();
6156   SDValue BasePtr = MemSD->getBasePtr();
6157 
6158   bool IsTruncatingStore = false;
6159   SDValue Index, Mask, Val, VL;
6160 
6161   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6162     Index = VPSN->getIndex();
6163     Mask = VPSN->getMask();
6164     Val = VPSN->getValue();
6165     VL = VPSN->getVectorLength();
6166     // VP doesn't support truncating stores.
6167     IsTruncatingStore = false;
6168   } else {
6169     // Else it must be a MSCATTER.
6170     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6171     Index = MSN->getIndex();
6172     Mask = MSN->getMask();
6173     Val = MSN->getValue();
6174     IsTruncatingStore = MSN->isTruncatingStore();
6175   }
6176 
6177   MVT VT = Val.getSimpleValueType();
6178   MVT IndexVT = Index.getSimpleValueType();
6179   MVT XLenVT = Subtarget.getXLenVT();
6180 
6181   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6182          "Unexpected VTs!");
6183   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6184   // Targets have to explicitly opt-in for extending vector loads and
6185   // truncating vector stores.
6186   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6187   (void)IsTruncatingStore;
6188 
6189   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6190   // the selection of the masked intrinsics doesn't do this for us.
6191   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6192 
6193   MVT ContainerVT = VT;
6194   if (VT.isFixedLengthVector()) {
6195     // We need to use the larger of the value and index type to determine the
6196     // scalable type to use so we don't increase LMUL for any operand/result.
6197     if (VT.bitsGE(IndexVT)) {
6198       ContainerVT = getContainerForFixedLengthVector(VT);
6199       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6200                                  ContainerVT.getVectorElementCount());
6201     } else {
6202       IndexVT = getContainerForFixedLengthVector(IndexVT);
6203       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6204                                      IndexVT.getVectorElementCount());
6205     }
6206 
6207     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6208     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6209 
6210     if (!IsUnmasked) {
6211       MVT MaskVT =
6212           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6213       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6214     }
6215   }
6216 
6217   if (!VL)
6218     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6219 
6220   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6221     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6222     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6223                                    VL);
6224     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6225                         TrueMask, VL);
6226   }
6227 
6228   unsigned IntID =
6229       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6230   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6231   Ops.push_back(Val);
6232   Ops.push_back(BasePtr);
6233   Ops.push_back(Index);
6234   if (!IsUnmasked)
6235     Ops.push_back(Mask);
6236   Ops.push_back(VL);
6237 
6238   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6239                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6240 }
6241 
6242 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6243                                                SelectionDAG &DAG) const {
6244   const MVT XLenVT = Subtarget.getXLenVT();
6245   SDLoc DL(Op);
6246   SDValue Chain = Op->getOperand(0);
6247   SDValue SysRegNo = DAG.getTargetConstant(
6248       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6249   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6250   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6251 
6252   // Encoding used for rounding mode in RISCV differs from that used in
6253   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6254   // table, which consists of a sequence of 4-bit fields, each representing
6255   // corresponding FLT_ROUNDS mode.
6256   static const int Table =
6257       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6258       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6259       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6260       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6261       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6262 
6263   SDValue Shift =
6264       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6265   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6266                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6267   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6268                                DAG.getConstant(7, DL, XLenVT));
6269 
6270   return DAG.getMergeValues({Masked, Chain}, DL);
6271 }
6272 
6273 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6274                                                SelectionDAG &DAG) const {
6275   const MVT XLenVT = Subtarget.getXLenVT();
6276   SDLoc DL(Op);
6277   SDValue Chain = Op->getOperand(0);
6278   SDValue RMValue = Op->getOperand(1);
6279   SDValue SysRegNo = DAG.getTargetConstant(
6280       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6281 
6282   // Encoding used for rounding mode in RISCV differs from that used in
6283   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6284   // a table, which consists of a sequence of 4-bit fields, each representing
6285   // corresponding RISCV mode.
6286   static const unsigned Table =
6287       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6288       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6289       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6290       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6291       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6292 
6293   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6294                               DAG.getConstant(2, DL, XLenVT));
6295   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6296                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6297   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6298                         DAG.getConstant(0x7, DL, XLenVT));
6299   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6300                      RMValue);
6301 }
6302 
6303 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6304   switch (IntNo) {
6305   default:
6306     llvm_unreachable("Unexpected Intrinsic");
6307   case Intrinsic::riscv_grev:
6308     return RISCVISD::GREVW;
6309   case Intrinsic::riscv_gorc:
6310     return RISCVISD::GORCW;
6311   case Intrinsic::riscv_bcompress:
6312     return RISCVISD::BCOMPRESSW;
6313   case Intrinsic::riscv_bdecompress:
6314     return RISCVISD::BDECOMPRESSW;
6315   case Intrinsic::riscv_bfp:
6316     return RISCVISD::BFPW;
6317   case Intrinsic::riscv_fsl:
6318     return RISCVISD::FSLW;
6319   case Intrinsic::riscv_fsr:
6320     return RISCVISD::FSRW;
6321   }
6322 }
6323 
6324 // Converts the given intrinsic to a i64 operation with any extension.
6325 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6326                                          unsigned IntNo) {
6327   SDLoc DL(N);
6328   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6329   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6330   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6331   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6332   // ReplaceNodeResults requires we maintain the same type for the return value.
6333   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6334 }
6335 
6336 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6337 // form of the given Opcode.
6338 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6339   switch (Opcode) {
6340   default:
6341     llvm_unreachable("Unexpected opcode");
6342   case ISD::SHL:
6343     return RISCVISD::SLLW;
6344   case ISD::SRA:
6345     return RISCVISD::SRAW;
6346   case ISD::SRL:
6347     return RISCVISD::SRLW;
6348   case ISD::SDIV:
6349     return RISCVISD::DIVW;
6350   case ISD::UDIV:
6351     return RISCVISD::DIVUW;
6352   case ISD::UREM:
6353     return RISCVISD::REMUW;
6354   case ISD::ROTL:
6355     return RISCVISD::ROLW;
6356   case ISD::ROTR:
6357     return RISCVISD::RORW;
6358   case RISCVISD::GREV:
6359     return RISCVISD::GREVW;
6360   case RISCVISD::GORC:
6361     return RISCVISD::GORCW;
6362   }
6363 }
6364 
6365 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6366 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6367 // otherwise be promoted to i64, making it difficult to select the
6368 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6369 // type i8/i16/i32 is lost.
6370 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6371                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6372   SDLoc DL(N);
6373   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6374   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6375   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6376   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6377   // ReplaceNodeResults requires we maintain the same type for the return value.
6378   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6379 }
6380 
6381 // Converts the given 32-bit operation to a i64 operation with signed extension
6382 // semantic to reduce the signed extension instructions.
6383 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6384   SDLoc DL(N);
6385   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6386   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6387   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6388   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6389                                DAG.getValueType(MVT::i32));
6390   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6391 }
6392 
6393 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6394                                              SmallVectorImpl<SDValue> &Results,
6395                                              SelectionDAG &DAG) const {
6396   SDLoc DL(N);
6397   switch (N->getOpcode()) {
6398   default:
6399     llvm_unreachable("Don't know how to custom type legalize this operation!");
6400   case ISD::STRICT_FP_TO_SINT:
6401   case ISD::STRICT_FP_TO_UINT:
6402   case ISD::FP_TO_SINT:
6403   case ISD::FP_TO_UINT: {
6404     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6405            "Unexpected custom legalisation");
6406     bool IsStrict = N->isStrictFPOpcode();
6407     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6408                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6409     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6410     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6411         TargetLowering::TypeSoftenFloat) {
6412       if (!isTypeLegal(Op0.getValueType()))
6413         return;
6414       if (IsStrict) {
6415         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6416                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6417         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6418         SDValue Res = DAG.getNode(
6419             Opc, DL, VTs, N->getOperand(0), Op0,
6420             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6421         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6422         Results.push_back(Res.getValue(1));
6423         return;
6424       }
6425       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6426       SDValue Res =
6427           DAG.getNode(Opc, DL, MVT::i64, Op0,
6428                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6429       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6430       return;
6431     }
6432     // If the FP type needs to be softened, emit a library call using the 'si'
6433     // version. If we left it to default legalization we'd end up with 'di'. If
6434     // the FP type doesn't need to be softened just let generic type
6435     // legalization promote the result type.
6436     RTLIB::Libcall LC;
6437     if (IsSigned)
6438       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6439     else
6440       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6441     MakeLibCallOptions CallOptions;
6442     EVT OpVT = Op0.getValueType();
6443     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6444     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6445     SDValue Result;
6446     std::tie(Result, Chain) =
6447         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6448     Results.push_back(Result);
6449     if (IsStrict)
6450       Results.push_back(Chain);
6451     break;
6452   }
6453   case ISD::READCYCLECOUNTER: {
6454     assert(!Subtarget.is64Bit() &&
6455            "READCYCLECOUNTER only has custom type legalization on riscv32");
6456 
6457     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6458     SDValue RCW =
6459         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6460 
6461     Results.push_back(
6462         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6463     Results.push_back(RCW.getValue(2));
6464     break;
6465   }
6466   case ISD::MUL: {
6467     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6468     unsigned XLen = Subtarget.getXLen();
6469     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6470     if (Size > XLen) {
6471       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6472       SDValue LHS = N->getOperand(0);
6473       SDValue RHS = N->getOperand(1);
6474       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6475 
6476       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6477       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6478       // We need exactly one side to be unsigned.
6479       if (LHSIsU == RHSIsU)
6480         return;
6481 
6482       auto MakeMULPair = [&](SDValue S, SDValue U) {
6483         MVT XLenVT = Subtarget.getXLenVT();
6484         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6485         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6486         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6487         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6488         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6489       };
6490 
6491       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6492       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6493 
6494       // The other operand should be signed, but still prefer MULH when
6495       // possible.
6496       if (RHSIsU && LHSIsS && !RHSIsS)
6497         Results.push_back(MakeMULPair(LHS, RHS));
6498       else if (LHSIsU && RHSIsS && !LHSIsS)
6499         Results.push_back(MakeMULPair(RHS, LHS));
6500 
6501       return;
6502     }
6503     LLVM_FALLTHROUGH;
6504   }
6505   case ISD::ADD:
6506   case ISD::SUB:
6507     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6508            "Unexpected custom legalisation");
6509     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6510     break;
6511   case ISD::SHL:
6512   case ISD::SRA:
6513   case ISD::SRL:
6514     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6515            "Unexpected custom legalisation");
6516     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6517       Results.push_back(customLegalizeToWOp(N, DAG));
6518       break;
6519     }
6520 
6521     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6522     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6523     // shift amount.
6524     if (N->getOpcode() == ISD::SHL) {
6525       SDLoc DL(N);
6526       SDValue NewOp0 =
6527           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6528       SDValue NewOp1 =
6529           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6530       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6531       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6532                                    DAG.getValueType(MVT::i32));
6533       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6534     }
6535 
6536     break;
6537   case ISD::ROTL:
6538   case ISD::ROTR:
6539     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6540            "Unexpected custom legalisation");
6541     Results.push_back(customLegalizeToWOp(N, DAG));
6542     break;
6543   case ISD::CTTZ:
6544   case ISD::CTTZ_ZERO_UNDEF:
6545   case ISD::CTLZ:
6546   case ISD::CTLZ_ZERO_UNDEF: {
6547     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6548            "Unexpected custom legalisation");
6549 
6550     SDValue NewOp0 =
6551         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6552     bool IsCTZ =
6553         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6554     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6555     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6556     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6557     return;
6558   }
6559   case ISD::SDIV:
6560   case ISD::UDIV:
6561   case ISD::UREM: {
6562     MVT VT = N->getSimpleValueType(0);
6563     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6564            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6565            "Unexpected custom legalisation");
6566     // Don't promote division/remainder by constant since we should expand those
6567     // to multiply by magic constant.
6568     // FIXME: What if the expansion is disabled for minsize.
6569     if (N->getOperand(1).getOpcode() == ISD::Constant)
6570       return;
6571 
6572     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6573     // the upper 32 bits. For other types we need to sign or zero extend
6574     // based on the opcode.
6575     unsigned ExtOpc = ISD::ANY_EXTEND;
6576     if (VT != MVT::i32)
6577       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6578                                            : ISD::ZERO_EXTEND;
6579 
6580     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6581     break;
6582   }
6583   case ISD::UADDO:
6584   case ISD::USUBO: {
6585     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6586            "Unexpected custom legalisation");
6587     bool IsAdd = N->getOpcode() == ISD::UADDO;
6588     // Create an ADDW or SUBW.
6589     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6590     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6591     SDValue Res =
6592         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6593     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6594                       DAG.getValueType(MVT::i32));
6595 
6596     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6597     // Since the inputs are sign extended from i32, this is equivalent to
6598     // comparing the lower 32 bits.
6599     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6600     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6601                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6602 
6603     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6604     Results.push_back(Overflow);
6605     return;
6606   }
6607   case ISD::UADDSAT:
6608   case ISD::USUBSAT: {
6609     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6610            "Unexpected custom legalisation");
6611     if (Subtarget.hasStdExtZbb()) {
6612       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6613       // sign extend allows overflow of the lower 32 bits to be detected on
6614       // the promoted size.
6615       SDValue LHS =
6616           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6617       SDValue RHS =
6618           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6619       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6620       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6621       return;
6622     }
6623 
6624     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6625     // promotion for UADDO/USUBO.
6626     Results.push_back(expandAddSubSat(N, DAG));
6627     return;
6628   }
6629   case ISD::BITCAST: {
6630     EVT VT = N->getValueType(0);
6631     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6632     SDValue Op0 = N->getOperand(0);
6633     EVT Op0VT = Op0.getValueType();
6634     MVT XLenVT = Subtarget.getXLenVT();
6635     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6636       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6637       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6638     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6639                Subtarget.hasStdExtF()) {
6640       SDValue FPConv =
6641           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6642       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6643     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6644                isTypeLegal(Op0VT)) {
6645       // Custom-legalize bitcasts from fixed-length vector types to illegal
6646       // scalar types in order to improve codegen. Bitcast the vector to a
6647       // one-element vector type whose element type is the same as the result
6648       // type, and extract the first element.
6649       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6650       if (isTypeLegal(BVT)) {
6651         SDValue BVec = DAG.getBitcast(BVT, Op0);
6652         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6653                                       DAG.getConstant(0, DL, XLenVT)));
6654       }
6655     }
6656     break;
6657   }
6658   case RISCVISD::GREV:
6659   case RISCVISD::GORC: {
6660     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6661            "Unexpected custom legalisation");
6662     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6663     // This is similar to customLegalizeToWOp, except that we pass the second
6664     // operand (a TargetConstant) straight through: it is already of type
6665     // XLenVT.
6666     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6667     SDValue NewOp0 =
6668         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6669     SDValue NewOp1 =
6670         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6671     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6672     // ReplaceNodeResults requires we maintain the same type for the return
6673     // value.
6674     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6675     break;
6676   }
6677   case RISCVISD::SHFL: {
6678     // There is no SHFLIW instruction, but we can just promote the operation.
6679     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6680            "Unexpected custom legalisation");
6681     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6682     SDValue NewOp0 =
6683         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6684     SDValue NewOp1 =
6685         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6686     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6687     // ReplaceNodeResults requires we maintain the same type for the return
6688     // value.
6689     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6690     break;
6691   }
6692   case ISD::BSWAP:
6693   case ISD::BITREVERSE: {
6694     MVT VT = N->getSimpleValueType(0);
6695     MVT XLenVT = Subtarget.getXLenVT();
6696     assert((VT == MVT::i8 || VT == MVT::i16 ||
6697             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6698            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6699     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6700     unsigned Imm = VT.getSizeInBits() - 1;
6701     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6702     if (N->getOpcode() == ISD::BSWAP)
6703       Imm &= ~0x7U;
6704     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6705     SDValue GREVI =
6706         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6707     // ReplaceNodeResults requires we maintain the same type for the return
6708     // value.
6709     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6710     break;
6711   }
6712   case ISD::FSHL:
6713   case ISD::FSHR: {
6714     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6715            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6716     SDValue NewOp0 =
6717         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6718     SDValue NewOp1 =
6719         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6720     SDValue NewShAmt =
6721         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6722     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6723     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6724     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6725                            DAG.getConstant(0x1f, DL, MVT::i64));
6726     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6727     // instruction use different orders. fshl will return its first operand for
6728     // shift of zero, fshr will return its second operand. fsl and fsr both
6729     // return rs1 so the ISD nodes need to have different operand orders.
6730     // Shift amount is in rs2.
6731     unsigned Opc = RISCVISD::FSLW;
6732     if (N->getOpcode() == ISD::FSHR) {
6733       std::swap(NewOp0, NewOp1);
6734       Opc = RISCVISD::FSRW;
6735     }
6736     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6737     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6738     break;
6739   }
6740   case ISD::EXTRACT_VECTOR_ELT: {
6741     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6742     // type is illegal (currently only vXi64 RV32).
6743     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6744     // transferred to the destination register. We issue two of these from the
6745     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6746     // first element.
6747     SDValue Vec = N->getOperand(0);
6748     SDValue Idx = N->getOperand(1);
6749 
6750     // The vector type hasn't been legalized yet so we can't issue target
6751     // specific nodes if it needs legalization.
6752     // FIXME: We would manually legalize if it's important.
6753     if (!isTypeLegal(Vec.getValueType()))
6754       return;
6755 
6756     MVT VecVT = Vec.getSimpleValueType();
6757 
6758     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6759            VecVT.getVectorElementType() == MVT::i64 &&
6760            "Unexpected EXTRACT_VECTOR_ELT legalization");
6761 
6762     // If this is a fixed vector, we need to convert it to a scalable vector.
6763     MVT ContainerVT = VecVT;
6764     if (VecVT.isFixedLengthVector()) {
6765       ContainerVT = getContainerForFixedLengthVector(VecVT);
6766       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6767     }
6768 
6769     MVT XLenVT = Subtarget.getXLenVT();
6770 
6771     // Use a VL of 1 to avoid processing more elements than we need.
6772     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6773     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6774     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6775 
6776     // Unless the index is known to be 0, we must slide the vector down to get
6777     // the desired element into index 0.
6778     if (!isNullConstant(Idx)) {
6779       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6780                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6781     }
6782 
6783     // Extract the lower XLEN bits of the correct vector element.
6784     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6785 
6786     // To extract the upper XLEN bits of the vector element, shift the first
6787     // element right by 32 bits and re-extract the lower XLEN bits.
6788     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6789                                      DAG.getConstant(32, DL, XLenVT), VL);
6790     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6791                                  ThirtyTwoV, Mask, VL);
6792 
6793     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6794 
6795     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6796     break;
6797   }
6798   case ISD::INTRINSIC_WO_CHAIN: {
6799     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6800     switch (IntNo) {
6801     default:
6802       llvm_unreachable(
6803           "Don't know how to custom type legalize this intrinsic!");
6804     case Intrinsic::riscv_grev:
6805     case Intrinsic::riscv_gorc:
6806     case Intrinsic::riscv_bcompress:
6807     case Intrinsic::riscv_bdecompress:
6808     case Intrinsic::riscv_bfp: {
6809       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6810              "Unexpected custom legalisation");
6811       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6812       break;
6813     }
6814     case Intrinsic::riscv_fsl:
6815     case Intrinsic::riscv_fsr: {
6816       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6817              "Unexpected custom legalisation");
6818       SDValue NewOp1 =
6819           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6820       SDValue NewOp2 =
6821           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6822       SDValue NewOp3 =
6823           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6824       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6825       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6826       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6827       break;
6828     }
6829     case Intrinsic::riscv_orc_b: {
6830       // Lower to the GORCI encoding for orc.b with the operand extended.
6831       SDValue NewOp =
6832           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6833       // If Zbp is enabled, use GORCIW which will sign extend the result.
6834       unsigned Opc =
6835           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6836       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6837                                 DAG.getConstant(7, DL, MVT::i64));
6838       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6839       return;
6840     }
6841     case Intrinsic::riscv_shfl:
6842     case Intrinsic::riscv_unshfl: {
6843       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6844              "Unexpected custom legalisation");
6845       SDValue NewOp1 =
6846           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6847       SDValue NewOp2 =
6848           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6849       unsigned Opc =
6850           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6851       // There is no (UN)SHFLIW. If the control word is a constant, we can use
6852       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
6853       // will be shuffled the same way as the lower 32 bit half, but the two
6854       // halves won't cross.
6855       if (isa<ConstantSDNode>(NewOp2)) {
6856         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6857                              DAG.getConstant(0xf, DL, MVT::i64));
6858         Opc =
6859             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6860       }
6861       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6862       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6863       break;
6864     }
6865     case Intrinsic::riscv_vmv_x_s: {
6866       EVT VT = N->getValueType(0);
6867       MVT XLenVT = Subtarget.getXLenVT();
6868       if (VT.bitsLT(XLenVT)) {
6869         // Simple case just extract using vmv.x.s and truncate.
6870         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6871                                       Subtarget.getXLenVT(), N->getOperand(1));
6872         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6873         return;
6874       }
6875 
6876       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6877              "Unexpected custom legalization");
6878 
6879       // We need to do the move in two steps.
6880       SDValue Vec = N->getOperand(1);
6881       MVT VecVT = Vec.getSimpleValueType();
6882 
6883       // First extract the lower XLEN bits of the element.
6884       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6885 
6886       // To extract the upper XLEN bits of the vector element, shift the first
6887       // element right by 32 bits and re-extract the lower XLEN bits.
6888       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6889       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6890       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6891       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6892                                        DAG.getConstant(32, DL, XLenVT), VL);
6893       SDValue LShr32 =
6894           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6895       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6896 
6897       Results.push_back(
6898           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6899       break;
6900     }
6901     }
6902     break;
6903   }
6904   case ISD::VECREDUCE_ADD:
6905   case ISD::VECREDUCE_AND:
6906   case ISD::VECREDUCE_OR:
6907   case ISD::VECREDUCE_XOR:
6908   case ISD::VECREDUCE_SMAX:
6909   case ISD::VECREDUCE_UMAX:
6910   case ISD::VECREDUCE_SMIN:
6911   case ISD::VECREDUCE_UMIN:
6912     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6913       Results.push_back(V);
6914     break;
6915   case ISD::VP_REDUCE_ADD:
6916   case ISD::VP_REDUCE_AND:
6917   case ISD::VP_REDUCE_OR:
6918   case ISD::VP_REDUCE_XOR:
6919   case ISD::VP_REDUCE_SMAX:
6920   case ISD::VP_REDUCE_UMAX:
6921   case ISD::VP_REDUCE_SMIN:
6922   case ISD::VP_REDUCE_UMIN:
6923     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6924       Results.push_back(V);
6925     break;
6926   case ISD::FLT_ROUNDS_: {
6927     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6928     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6929     Results.push_back(Res.getValue(0));
6930     Results.push_back(Res.getValue(1));
6931     break;
6932   }
6933   }
6934 }
6935 
6936 // A structure to hold one of the bit-manipulation patterns below. Together, a
6937 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6938 //   (or (and (shl x, 1), 0xAAAAAAAA),
6939 //       (and (srl x, 1), 0x55555555))
6940 struct RISCVBitmanipPat {
6941   SDValue Op;
6942   unsigned ShAmt;
6943   bool IsSHL;
6944 
6945   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6946     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6947   }
6948 };
6949 
6950 // Matches patterns of the form
6951 //   (and (shl x, C2), (C1 << C2))
6952 //   (and (srl x, C2), C1)
6953 //   (shl (and x, C1), C2)
6954 //   (srl (and x, (C1 << C2)), C2)
6955 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6956 // The expected masks for each shift amount are specified in BitmanipMasks where
6957 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6958 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6959 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6960 // XLen is 64.
6961 static Optional<RISCVBitmanipPat>
6962 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6963   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6964          "Unexpected number of masks");
6965   Optional<uint64_t> Mask;
6966   // Optionally consume a mask around the shift operation.
6967   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6968     Mask = Op.getConstantOperandVal(1);
6969     Op = Op.getOperand(0);
6970   }
6971   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6972     return None;
6973   bool IsSHL = Op.getOpcode() == ISD::SHL;
6974 
6975   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6976     return None;
6977   uint64_t ShAmt = Op.getConstantOperandVal(1);
6978 
6979   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6980   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6981     return None;
6982   // If we don't have enough masks for 64 bit, then we must be trying to
6983   // match SHFL so we're only allowed to shift 1/4 of the width.
6984   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6985     return None;
6986 
6987   SDValue Src = Op.getOperand(0);
6988 
6989   // The expected mask is shifted left when the AND is found around SHL
6990   // patterns.
6991   //   ((x >> 1) & 0x55555555)
6992   //   ((x << 1) & 0xAAAAAAAA)
6993   bool SHLExpMask = IsSHL;
6994 
6995   if (!Mask) {
6996     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6997     // the mask is all ones: consume that now.
6998     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6999       Mask = Src.getConstantOperandVal(1);
7000       Src = Src.getOperand(0);
7001       // The expected mask is now in fact shifted left for SRL, so reverse the
7002       // decision.
7003       //   ((x & 0xAAAAAAAA) >> 1)
7004       //   ((x & 0x55555555) << 1)
7005       SHLExpMask = !SHLExpMask;
7006     } else {
7007       // Use a default shifted mask of all-ones if there's no AND, truncated
7008       // down to the expected width. This simplifies the logic later on.
7009       Mask = maskTrailingOnes<uint64_t>(Width);
7010       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7011     }
7012   }
7013 
7014   unsigned MaskIdx = Log2_32(ShAmt);
7015   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7016 
7017   if (SHLExpMask)
7018     ExpMask <<= ShAmt;
7019 
7020   if (Mask != ExpMask)
7021     return None;
7022 
7023   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7024 }
7025 
7026 // Matches any of the following bit-manipulation patterns:
7027 //   (and (shl x, 1), (0x55555555 << 1))
7028 //   (and (srl x, 1), 0x55555555)
7029 //   (shl (and x, 0x55555555), 1)
7030 //   (srl (and x, (0x55555555 << 1)), 1)
7031 // where the shift amount and mask may vary thus:
7032 //   [1]  = 0x55555555 / 0xAAAAAAAA
7033 //   [2]  = 0x33333333 / 0xCCCCCCCC
7034 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7035 //   [8]  = 0x00FF00FF / 0xFF00FF00
7036 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7037 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7038 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7039   // These are the unshifted masks which we use to match bit-manipulation
7040   // patterns. They may be shifted left in certain circumstances.
7041   static const uint64_t BitmanipMasks[] = {
7042       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7043       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7044 
7045   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7046 }
7047 
7048 // Match the following pattern as a GREVI(W) operation
7049 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7050 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7051                                const RISCVSubtarget &Subtarget) {
7052   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7053   EVT VT = Op.getValueType();
7054 
7055   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7056     auto LHS = matchGREVIPat(Op.getOperand(0));
7057     auto RHS = matchGREVIPat(Op.getOperand(1));
7058     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7059       SDLoc DL(Op);
7060       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7061                          DAG.getConstant(LHS->ShAmt, DL, VT));
7062     }
7063   }
7064   return SDValue();
7065 }
7066 
7067 // Matches any the following pattern as a GORCI(W) operation
7068 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7069 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7070 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7071 // Note that with the variant of 3.,
7072 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7073 // the inner pattern will first be matched as GREVI and then the outer
7074 // pattern will be matched to GORC via the first rule above.
7075 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7076 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7077                                const RISCVSubtarget &Subtarget) {
7078   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7079   EVT VT = Op.getValueType();
7080 
7081   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7082     SDLoc DL(Op);
7083     SDValue Op0 = Op.getOperand(0);
7084     SDValue Op1 = Op.getOperand(1);
7085 
7086     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7087       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7088           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7089           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7090         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7091       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7092       if ((Reverse.getOpcode() == ISD::ROTL ||
7093            Reverse.getOpcode() == ISD::ROTR) &&
7094           Reverse.getOperand(0) == X &&
7095           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7096         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7097         if (RotAmt == (VT.getSizeInBits() / 2))
7098           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7099                              DAG.getConstant(RotAmt, DL, VT));
7100       }
7101       return SDValue();
7102     };
7103 
7104     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7105     if (SDValue V = MatchOROfReverse(Op0, Op1))
7106       return V;
7107     if (SDValue V = MatchOROfReverse(Op1, Op0))
7108       return V;
7109 
7110     // OR is commutable so canonicalize its OR operand to the left
7111     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7112       std::swap(Op0, Op1);
7113     if (Op0.getOpcode() != ISD::OR)
7114       return SDValue();
7115     SDValue OrOp0 = Op0.getOperand(0);
7116     SDValue OrOp1 = Op0.getOperand(1);
7117     auto LHS = matchGREVIPat(OrOp0);
7118     // OR is commutable so swap the operands and try again: x might have been
7119     // on the left
7120     if (!LHS) {
7121       std::swap(OrOp0, OrOp1);
7122       LHS = matchGREVIPat(OrOp0);
7123     }
7124     auto RHS = matchGREVIPat(Op1);
7125     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7126       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7127                          DAG.getConstant(LHS->ShAmt, DL, VT));
7128     }
7129   }
7130   return SDValue();
7131 }
7132 
7133 // Matches any of the following bit-manipulation patterns:
7134 //   (and (shl x, 1), (0x22222222 << 1))
7135 //   (and (srl x, 1), 0x22222222)
7136 //   (shl (and x, 0x22222222), 1)
7137 //   (srl (and x, (0x22222222 << 1)), 1)
7138 // where the shift amount and mask may vary thus:
7139 //   [1]  = 0x22222222 / 0x44444444
7140 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7141 //   [4]  = 0x00F000F0 / 0x0F000F00
7142 //   [8]  = 0x0000FF00 / 0x00FF0000
7143 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7144 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7145   // These are the unshifted masks which we use to match bit-manipulation
7146   // patterns. They may be shifted left in certain circumstances.
7147   static const uint64_t BitmanipMasks[] = {
7148       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7149       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7150 
7151   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7152 }
7153 
7154 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7155 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7156                                const RISCVSubtarget &Subtarget) {
7157   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7158   EVT VT = Op.getValueType();
7159 
7160   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7161     return SDValue();
7162 
7163   SDValue Op0 = Op.getOperand(0);
7164   SDValue Op1 = Op.getOperand(1);
7165 
7166   // Or is commutable so canonicalize the second OR to the LHS.
7167   if (Op0.getOpcode() != ISD::OR)
7168     std::swap(Op0, Op1);
7169   if (Op0.getOpcode() != ISD::OR)
7170     return SDValue();
7171 
7172   // We found an inner OR, so our operands are the operands of the inner OR
7173   // and the other operand of the outer OR.
7174   SDValue A = Op0.getOperand(0);
7175   SDValue B = Op0.getOperand(1);
7176   SDValue C = Op1;
7177 
7178   auto Match1 = matchSHFLPat(A);
7179   auto Match2 = matchSHFLPat(B);
7180 
7181   // If neither matched, we failed.
7182   if (!Match1 && !Match2)
7183     return SDValue();
7184 
7185   // We had at least one match. if one failed, try the remaining C operand.
7186   if (!Match1) {
7187     std::swap(A, C);
7188     Match1 = matchSHFLPat(A);
7189     if (!Match1)
7190       return SDValue();
7191   } else if (!Match2) {
7192     std::swap(B, C);
7193     Match2 = matchSHFLPat(B);
7194     if (!Match2)
7195       return SDValue();
7196   }
7197   assert(Match1 && Match2);
7198 
7199   // Make sure our matches pair up.
7200   if (!Match1->formsPairWith(*Match2))
7201     return SDValue();
7202 
7203   // All the remains is to make sure C is an AND with the same input, that masks
7204   // out the bits that are being shuffled.
7205   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7206       C.getOperand(0) != Match1->Op)
7207     return SDValue();
7208 
7209   uint64_t Mask = C.getConstantOperandVal(1);
7210 
7211   static const uint64_t BitmanipMasks[] = {
7212       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7213       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7214   };
7215 
7216   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7217   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7218   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7219 
7220   if (Mask != ExpMask)
7221     return SDValue();
7222 
7223   SDLoc DL(Op);
7224   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7225                      DAG.getConstant(Match1->ShAmt, DL, VT));
7226 }
7227 
7228 // Optimize (add (shl x, c0), (shl y, c1)) ->
7229 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7230 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7231                                   const RISCVSubtarget &Subtarget) {
7232   // Perform this optimization only in the zba extension.
7233   if (!Subtarget.hasStdExtZba())
7234     return SDValue();
7235 
7236   // Skip for vector types and larger types.
7237   EVT VT = N->getValueType(0);
7238   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7239     return SDValue();
7240 
7241   // The two operand nodes must be SHL and have no other use.
7242   SDValue N0 = N->getOperand(0);
7243   SDValue N1 = N->getOperand(1);
7244   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7245       !N0->hasOneUse() || !N1->hasOneUse())
7246     return SDValue();
7247 
7248   // Check c0 and c1.
7249   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7250   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7251   if (!N0C || !N1C)
7252     return SDValue();
7253   int64_t C0 = N0C->getSExtValue();
7254   int64_t C1 = N1C->getSExtValue();
7255   if (C0 <= 0 || C1 <= 0)
7256     return SDValue();
7257 
7258   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7259   int64_t Bits = std::min(C0, C1);
7260   int64_t Diff = std::abs(C0 - C1);
7261   if (Diff != 1 && Diff != 2 && Diff != 3)
7262     return SDValue();
7263 
7264   // Build nodes.
7265   SDLoc DL(N);
7266   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7267   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7268   SDValue NA0 =
7269       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7270   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7271   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7272 }
7273 
7274 // Combine
7275 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8)
7276 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8)
7277 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8)
7278 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8)
7279 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG) {
7280   SDValue Src = N->getOperand(0);
7281   SDLoc DL(N);
7282   unsigned Opc;
7283 
7284   if ((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL) &&
7285       Src.getOpcode() == RISCVISD::GREV)
7286     Opc = RISCVISD::GREV;
7287   else if ((N->getOpcode() == RISCVISD::RORW ||
7288             N->getOpcode() == RISCVISD::ROLW) &&
7289            Src.getOpcode() == RISCVISD::GREVW)
7290     Opc = RISCVISD::GREVW;
7291   else
7292     return SDValue();
7293 
7294   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7295       !isa<ConstantSDNode>(Src.getOperand(1)))
7296     return SDValue();
7297 
7298   unsigned ShAmt1 = N->getConstantOperandVal(1);
7299   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7300   if (ShAmt1 != 16 && ShAmt2 != 24)
7301     return SDValue();
7302 
7303   Src = Src.getOperand(0);
7304   return DAG.getNode(Opc, DL, N->getValueType(0), Src,
7305                      DAG.getConstant(8, DL, N->getOperand(1).getValueType()));
7306 }
7307 
7308 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7309 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7310 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7311 // not undo itself, but they are redundant.
7312 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7313   SDValue Src = N->getOperand(0);
7314 
7315   if (Src.getOpcode() != N->getOpcode())
7316     return SDValue();
7317 
7318   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7319       !isa<ConstantSDNode>(Src.getOperand(1)))
7320     return SDValue();
7321 
7322   unsigned ShAmt1 = N->getConstantOperandVal(1);
7323   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7324   Src = Src.getOperand(0);
7325 
7326   unsigned CombinedShAmt;
7327   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7328     CombinedShAmt = ShAmt1 | ShAmt2;
7329   else
7330     CombinedShAmt = ShAmt1 ^ ShAmt2;
7331 
7332   if (CombinedShAmt == 0)
7333     return Src;
7334 
7335   SDLoc DL(N);
7336   return DAG.getNode(
7337       N->getOpcode(), DL, N->getValueType(0), Src,
7338       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7339 }
7340 
7341 // Combine a constant select operand into its use:
7342 //
7343 // (and (select cond, -1, c), x)
7344 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7345 // (or  (select cond, 0, c), x)
7346 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7347 // (xor (select cond, 0, c), x)
7348 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7349 // (add (select cond, 0, c), x)
7350 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7351 // (sub x, (select cond, 0, c))
7352 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7353 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7354                                    SelectionDAG &DAG, bool AllOnes) {
7355   EVT VT = N->getValueType(0);
7356 
7357   // Skip vectors.
7358   if (VT.isVector())
7359     return SDValue();
7360 
7361   if ((Slct.getOpcode() != ISD::SELECT &&
7362        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7363       !Slct.hasOneUse())
7364     return SDValue();
7365 
7366   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7367     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7368   };
7369 
7370   bool SwapSelectOps;
7371   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7372   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7373   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7374   SDValue NonConstantVal;
7375   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7376     SwapSelectOps = false;
7377     NonConstantVal = FalseVal;
7378   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7379     SwapSelectOps = true;
7380     NonConstantVal = TrueVal;
7381   } else
7382     return SDValue();
7383 
7384   // Slct is now know to be the desired identity constant when CC is true.
7385   TrueVal = OtherOp;
7386   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7387   // Unless SwapSelectOps says the condition should be false.
7388   if (SwapSelectOps)
7389     std::swap(TrueVal, FalseVal);
7390 
7391   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7392     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7393                        {Slct.getOperand(0), Slct.getOperand(1),
7394                         Slct.getOperand(2), TrueVal, FalseVal});
7395 
7396   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7397                      {Slct.getOperand(0), TrueVal, FalseVal});
7398 }
7399 
7400 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7401 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7402                                               bool AllOnes) {
7403   SDValue N0 = N->getOperand(0);
7404   SDValue N1 = N->getOperand(1);
7405   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7406     return Result;
7407   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7408     return Result;
7409   return SDValue();
7410 }
7411 
7412 // Transform (add (mul x, c0), c1) ->
7413 //           (add (mul (add x, c1/c0), c0), c1%c0).
7414 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7415 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7416 // to an infinite loop in DAGCombine if transformed.
7417 // Or transform (add (mul x, c0), c1) ->
7418 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7419 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7420 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7421 // lead to an infinite loop in DAGCombine if transformed.
7422 // Or transform (add (mul x, c0), c1) ->
7423 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7424 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7425 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7426 // lead to an infinite loop in DAGCombine if transformed.
7427 // Or transform (add (mul x, c0), c1) ->
7428 //              (mul (add x, c1/c0), c0).
7429 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7430 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7431                                      const RISCVSubtarget &Subtarget) {
7432   // Skip for vector types and larger types.
7433   EVT VT = N->getValueType(0);
7434   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7435     return SDValue();
7436   // The first operand node must be a MUL and has no other use.
7437   SDValue N0 = N->getOperand(0);
7438   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7439     return SDValue();
7440   // Check if c0 and c1 match above conditions.
7441   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7442   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7443   if (!N0C || !N1C)
7444     return SDValue();
7445   int64_t C0 = N0C->getSExtValue();
7446   int64_t C1 = N1C->getSExtValue();
7447   int64_t CA, CB;
7448   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7449     return SDValue();
7450   // Search for proper CA (non-zero) and CB that both are simm12.
7451   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7452       !isInt<12>(C0 * (C1 / C0))) {
7453     CA = C1 / C0;
7454     CB = C1 % C0;
7455   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7456              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7457     CA = C1 / C0 + 1;
7458     CB = C1 % C0 - C0;
7459   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7460              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7461     CA = C1 / C0 - 1;
7462     CB = C1 % C0 + C0;
7463   } else
7464     return SDValue();
7465   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7466   SDLoc DL(N);
7467   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7468                              DAG.getConstant(CA, DL, VT));
7469   SDValue New1 =
7470       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7471   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7472 }
7473 
7474 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7475                                  const RISCVSubtarget &Subtarget) {
7476   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7477     return V;
7478   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7479     return V;
7480   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7481   //      (select lhs, rhs, cc, x, (add x, y))
7482   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7483 }
7484 
7485 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7486   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7487   //      (select lhs, rhs, cc, x, (sub x, y))
7488   SDValue N0 = N->getOperand(0);
7489   SDValue N1 = N->getOperand(1);
7490   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7491 }
7492 
7493 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7494   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7495   //      (select lhs, rhs, cc, x, (and x, y))
7496   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7497 }
7498 
7499 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7500                                 const RISCVSubtarget &Subtarget) {
7501   if (Subtarget.hasStdExtZbp()) {
7502     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7503       return GREV;
7504     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7505       return GORC;
7506     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7507       return SHFL;
7508   }
7509 
7510   // fold (or (select cond, 0, y), x) ->
7511   //      (select cond, x, (or x, y))
7512   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7513 }
7514 
7515 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7516   // fold (xor (select cond, 0, y), x) ->
7517   //      (select cond, x, (xor x, y))
7518   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7519 }
7520 
7521 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7522 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7523 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7524 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7525 // ADDW/SUBW/MULW.
7526 static SDValue performANY_EXTENDCombine(SDNode *N,
7527                                         TargetLowering::DAGCombinerInfo &DCI,
7528                                         const RISCVSubtarget &Subtarget) {
7529   if (!Subtarget.is64Bit())
7530     return SDValue();
7531 
7532   SelectionDAG &DAG = DCI.DAG;
7533 
7534   SDValue Src = N->getOperand(0);
7535   EVT VT = N->getValueType(0);
7536   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7537     return SDValue();
7538 
7539   // The opcode must be one that can implicitly sign_extend.
7540   // FIXME: Additional opcodes.
7541   switch (Src.getOpcode()) {
7542   default:
7543     return SDValue();
7544   case ISD::MUL:
7545     if (!Subtarget.hasStdExtM())
7546       return SDValue();
7547     LLVM_FALLTHROUGH;
7548   case ISD::ADD:
7549   case ISD::SUB:
7550     break;
7551   }
7552 
7553   // Only handle cases where the result is used by a CopyToReg. That likely
7554   // means the value is a liveout of the basic block. This helps prevent
7555   // infinite combine loops like PR51206.
7556   if (none_of(N->uses(),
7557               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7558     return SDValue();
7559 
7560   SmallVector<SDNode *, 4> SetCCs;
7561   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7562                             UE = Src.getNode()->use_end();
7563        UI != UE; ++UI) {
7564     SDNode *User = *UI;
7565     if (User == N)
7566       continue;
7567     if (UI.getUse().getResNo() != Src.getResNo())
7568       continue;
7569     // All i32 setccs are legalized by sign extending operands.
7570     if (User->getOpcode() == ISD::SETCC) {
7571       SetCCs.push_back(User);
7572       continue;
7573     }
7574     // We don't know if we can extend this user.
7575     break;
7576   }
7577 
7578   // If we don't have any SetCCs, this isn't worthwhile.
7579   if (SetCCs.empty())
7580     return SDValue();
7581 
7582   SDLoc DL(N);
7583   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7584   DCI.CombineTo(N, SExt);
7585 
7586   // Promote all the setccs.
7587   for (SDNode *SetCC : SetCCs) {
7588     SmallVector<SDValue, 4> Ops;
7589 
7590     for (unsigned j = 0; j != 2; ++j) {
7591       SDValue SOp = SetCC->getOperand(j);
7592       if (SOp == Src)
7593         Ops.push_back(SExt);
7594       else
7595         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7596     }
7597 
7598     Ops.push_back(SetCC->getOperand(2));
7599     DCI.CombineTo(SetCC,
7600                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7601   }
7602   return SDValue(N, 0);
7603 }
7604 
7605 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7606 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7607 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7608                                              bool Commute = false) {
7609   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7610           N->getOpcode() == RISCVISD::SUB_VL) &&
7611          "Unexpected opcode");
7612   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7613   SDValue Op0 = N->getOperand(0);
7614   SDValue Op1 = N->getOperand(1);
7615   if (Commute)
7616     std::swap(Op0, Op1);
7617 
7618   MVT VT = N->getSimpleValueType(0);
7619 
7620   // Determine the narrow size for a widening add/sub.
7621   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7622   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7623                                   VT.getVectorElementCount());
7624 
7625   SDValue Mask = N->getOperand(2);
7626   SDValue VL = N->getOperand(3);
7627 
7628   SDLoc DL(N);
7629 
7630   // If the RHS is a sext or zext, we can form a widening op.
7631   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7632        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7633       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7634     unsigned ExtOpc = Op1.getOpcode();
7635     Op1 = Op1.getOperand(0);
7636     // Re-introduce narrower extends if needed.
7637     if (Op1.getValueType() != NarrowVT)
7638       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7639 
7640     unsigned WOpc;
7641     if (ExtOpc == RISCVISD::VSEXT_VL)
7642       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7643     else
7644       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7645 
7646     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7647   }
7648 
7649   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7650   // sext/zext?
7651 
7652   return SDValue();
7653 }
7654 
7655 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7656 // vwsub(u).vv/vx.
7657 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7658   SDValue Op0 = N->getOperand(0);
7659   SDValue Op1 = N->getOperand(1);
7660   SDValue Mask = N->getOperand(2);
7661   SDValue VL = N->getOperand(3);
7662 
7663   MVT VT = N->getSimpleValueType(0);
7664   MVT NarrowVT = Op1.getSimpleValueType();
7665   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7666 
7667   unsigned VOpc;
7668   switch (N->getOpcode()) {
7669   default: llvm_unreachable("Unexpected opcode");
7670   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7671   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7672   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7673   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7674   }
7675 
7676   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7677                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7678 
7679   SDLoc DL(N);
7680 
7681   // If the LHS is a sext or zext, we can narrow this op to the same size as
7682   // the RHS.
7683   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7684        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7685       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7686     unsigned ExtOpc = Op0.getOpcode();
7687     Op0 = Op0.getOperand(0);
7688     // Re-introduce narrower extends if needed.
7689     if (Op0.getValueType() != NarrowVT)
7690       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7691     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7692   }
7693 
7694   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7695                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7696 
7697   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7698   // to commute and use a vwadd(u).vx instead.
7699   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7700       Op0.getOperand(1) == VL) {
7701     Op0 = Op0.getOperand(0);
7702 
7703     // See if have enough sign bits or zero bits in the scalar to use a
7704     // widening add/sub by splatting to smaller element size.
7705     unsigned EltBits = VT.getScalarSizeInBits();
7706     unsigned ScalarBits = Op0.getValueSizeInBits();
7707     // Make sure we're getting all element bits from the scalar register.
7708     // FIXME: Support implicit sign extension of vmv.v.x?
7709     if (ScalarBits < EltBits)
7710       return SDValue();
7711 
7712     if (IsSigned) {
7713       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7714         return SDValue();
7715     } else {
7716       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7717       if (!DAG.MaskedValueIsZero(Op0, Mask))
7718         return SDValue();
7719     }
7720 
7721     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op0, VL);
7722     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7723   }
7724 
7725   return SDValue();
7726 }
7727 
7728 // Try to form VWMUL, VWMULU or VWMULSU.
7729 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7730 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7731                                        bool Commute) {
7732   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7733   SDValue Op0 = N->getOperand(0);
7734   SDValue Op1 = N->getOperand(1);
7735   if (Commute)
7736     std::swap(Op0, Op1);
7737 
7738   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7739   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7740   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7741   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7742     return SDValue();
7743 
7744   SDValue Mask = N->getOperand(2);
7745   SDValue VL = N->getOperand(3);
7746 
7747   // Make sure the mask and VL match.
7748   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7749     return SDValue();
7750 
7751   MVT VT = N->getSimpleValueType(0);
7752 
7753   // Determine the narrow size for a widening multiply.
7754   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7755   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7756                                   VT.getVectorElementCount());
7757 
7758   SDLoc DL(N);
7759 
7760   // See if the other operand is the same opcode.
7761   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7762     if (!Op1.hasOneUse())
7763       return SDValue();
7764 
7765     // Make sure the mask and VL match.
7766     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7767       return SDValue();
7768 
7769     Op1 = Op1.getOperand(0);
7770   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7771     // The operand is a splat of a scalar.
7772 
7773     // The VL must be the same.
7774     if (Op1.getOperand(1) != VL)
7775       return SDValue();
7776 
7777     // Get the scalar value.
7778     Op1 = Op1.getOperand(0);
7779 
7780     // See if have enough sign bits or zero bits in the scalar to use a
7781     // widening multiply by splatting to smaller element size.
7782     unsigned EltBits = VT.getScalarSizeInBits();
7783     unsigned ScalarBits = Op1.getValueSizeInBits();
7784     // Make sure we're getting all element bits from the scalar register.
7785     // FIXME: Support implicit sign extension of vmv.v.x?
7786     if (ScalarBits < EltBits)
7787       return SDValue();
7788 
7789     // If the LHS is a sign extend, try to use vwmul.
7790     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
7791       // Can use vwmul.
7792     } else {
7793       // Otherwise try to use vwmulu or vwmulsu.
7794       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7795       if (DAG.MaskedValueIsZero(Op1, Mask))
7796         IsVWMULSU = IsSignExt;
7797       else
7798         return SDValue();
7799     }
7800 
7801     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7802   } else
7803     return SDValue();
7804 
7805   Op0 = Op0.getOperand(0);
7806 
7807   // Re-introduce narrower extends if needed.
7808   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7809   if (Op0.getValueType() != NarrowVT)
7810     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7811   // vwmulsu requires second operand to be zero extended.
7812   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
7813   if (Op1.getValueType() != NarrowVT)
7814     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7815 
7816   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7817   if (!IsVWMULSU)
7818     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7819   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7820 }
7821 
7822 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7823   switch (Op.getOpcode()) {
7824   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7825   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7826   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7827   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7828   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7829   }
7830 
7831   return RISCVFPRndMode::Invalid;
7832 }
7833 
7834 // Fold
7835 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7836 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7837 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7838 //   (fp_to_int (fceil X))      -> fcvt X, rup
7839 //   (fp_to_int (fround X))     -> fcvt X, rmm
7840 static SDValue performFP_TO_INTCombine(SDNode *N,
7841                                        TargetLowering::DAGCombinerInfo &DCI,
7842                                        const RISCVSubtarget &Subtarget) {
7843   SelectionDAG &DAG = DCI.DAG;
7844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7845   MVT XLenVT = Subtarget.getXLenVT();
7846 
7847   // Only handle XLen or i32 types. Other types narrower than XLen will
7848   // eventually be legalized to XLenVT.
7849   EVT VT = N->getValueType(0);
7850   if (VT != MVT::i32 && VT != XLenVT)
7851     return SDValue();
7852 
7853   SDValue Src = N->getOperand(0);
7854 
7855   // Ensure the FP type is also legal.
7856   if (!TLI.isTypeLegal(Src.getValueType()))
7857     return SDValue();
7858 
7859   // Don't do this for f16 with Zfhmin and not Zfh.
7860   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7861     return SDValue();
7862 
7863   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7864   if (FRM == RISCVFPRndMode::Invalid)
7865     return SDValue();
7866 
7867   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7868 
7869   unsigned Opc;
7870   if (VT == XLenVT)
7871     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7872   else
7873     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7874 
7875   SDLoc DL(N);
7876   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7877                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7878   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7879 }
7880 
7881 // Fold
7882 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7883 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7884 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7885 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7886 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7887 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7888                                        TargetLowering::DAGCombinerInfo &DCI,
7889                                        const RISCVSubtarget &Subtarget) {
7890   SelectionDAG &DAG = DCI.DAG;
7891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7892   MVT XLenVT = Subtarget.getXLenVT();
7893 
7894   // Only handle XLen types. Other types narrower than XLen will eventually be
7895   // legalized to XLenVT.
7896   EVT DstVT = N->getValueType(0);
7897   if (DstVT != XLenVT)
7898     return SDValue();
7899 
7900   SDValue Src = N->getOperand(0);
7901 
7902   // Ensure the FP type is also legal.
7903   if (!TLI.isTypeLegal(Src.getValueType()))
7904     return SDValue();
7905 
7906   // Don't do this for f16 with Zfhmin and not Zfh.
7907   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7908     return SDValue();
7909 
7910   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7911 
7912   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7913   if (FRM == RISCVFPRndMode::Invalid)
7914     return SDValue();
7915 
7916   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7917 
7918   unsigned Opc;
7919   if (SatVT == DstVT)
7920     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7921   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7922     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7923   else
7924     return SDValue();
7925   // FIXME: Support other SatVTs by clamping before or after the conversion.
7926 
7927   Src = Src.getOperand(0);
7928 
7929   SDLoc DL(N);
7930   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7931                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7932 
7933   // RISCV FP-to-int conversions saturate to the destination register size, but
7934   // don't produce 0 for nan.
7935   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7936   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7937 }
7938 
7939 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7940                                                DAGCombinerInfo &DCI) const {
7941   SelectionDAG &DAG = DCI.DAG;
7942 
7943   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7944   // bits are demanded. N will be added to the Worklist if it was not deleted.
7945   // Caller should return SDValue(N, 0) if this returns true.
7946   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7947     SDValue Op = N->getOperand(OpNo);
7948     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7949     if (!SimplifyDemandedBits(Op, Mask, DCI))
7950       return false;
7951 
7952     if (N->getOpcode() != ISD::DELETED_NODE)
7953       DCI.AddToWorklist(N);
7954     return true;
7955   };
7956 
7957   switch (N->getOpcode()) {
7958   default:
7959     break;
7960   case RISCVISD::SplitF64: {
7961     SDValue Op0 = N->getOperand(0);
7962     // If the input to SplitF64 is just BuildPairF64 then the operation is
7963     // redundant. Instead, use BuildPairF64's operands directly.
7964     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7965       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7966 
7967     if (Op0->isUndef()) {
7968       SDValue Lo = DAG.getUNDEF(MVT::i32);
7969       SDValue Hi = DAG.getUNDEF(MVT::i32);
7970       return DCI.CombineTo(N, Lo, Hi);
7971     }
7972 
7973     SDLoc DL(N);
7974 
7975     // It's cheaper to materialise two 32-bit integers than to load a double
7976     // from the constant pool and transfer it to integer registers through the
7977     // stack.
7978     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7979       APInt V = C->getValueAPF().bitcastToAPInt();
7980       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7981       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7982       return DCI.CombineTo(N, Lo, Hi);
7983     }
7984 
7985     // This is a target-specific version of a DAGCombine performed in
7986     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7987     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7988     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7989     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7990         !Op0.getNode()->hasOneUse())
7991       break;
7992     SDValue NewSplitF64 =
7993         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7994                     Op0.getOperand(0));
7995     SDValue Lo = NewSplitF64.getValue(0);
7996     SDValue Hi = NewSplitF64.getValue(1);
7997     APInt SignBit = APInt::getSignMask(32);
7998     if (Op0.getOpcode() == ISD::FNEG) {
7999       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8000                                   DAG.getConstant(SignBit, DL, MVT::i32));
8001       return DCI.CombineTo(N, Lo, NewHi);
8002     }
8003     assert(Op0.getOpcode() == ISD::FABS);
8004     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8005                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8006     return DCI.CombineTo(N, Lo, NewHi);
8007   }
8008   case RISCVISD::SLLW:
8009   case RISCVISD::SRAW:
8010   case RISCVISD::SRLW:
8011   case RISCVISD::ROLW:
8012   case RISCVISD::RORW: {
8013     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8014     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8015         SimplifyDemandedLowBitsHelper(1, 5))
8016       return SDValue(N, 0);
8017 
8018     return combineROTR_ROTL_RORW_ROLW(N, DAG);
8019   }
8020   case ISD::ROTR:
8021   case ISD::ROTL:
8022     return combineROTR_ROTL_RORW_ROLW(N, DAG);
8023   case RISCVISD::CLZW:
8024   case RISCVISD::CTZW: {
8025     // Only the lower 32 bits of the first operand are read
8026     if (SimplifyDemandedLowBitsHelper(0, 32))
8027       return SDValue(N, 0);
8028     break;
8029   }
8030   case RISCVISD::GREV:
8031   case RISCVISD::GORC: {
8032     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8033     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8034     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8035     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8036       return SDValue(N, 0);
8037 
8038     return combineGREVI_GORCI(N, DAG);
8039   }
8040   case RISCVISD::GREVW:
8041   case RISCVISD::GORCW: {
8042     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8043     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8044         SimplifyDemandedLowBitsHelper(1, 5))
8045       return SDValue(N, 0);
8046 
8047     return combineGREVI_GORCI(N, DAG);
8048   }
8049   case RISCVISD::SHFL:
8050   case RISCVISD::UNSHFL: {
8051     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8052     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8053     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8054     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8055       return SDValue(N, 0);
8056 
8057     break;
8058   }
8059   case RISCVISD::SHFLW:
8060   case RISCVISD::UNSHFLW: {
8061     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8062     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8063         SimplifyDemandedLowBitsHelper(1, 4))
8064       return SDValue(N, 0);
8065 
8066     break;
8067   }
8068   case RISCVISD::BCOMPRESSW:
8069   case RISCVISD::BDECOMPRESSW: {
8070     // Only the lower 32 bits of LHS and RHS are read.
8071     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8072         SimplifyDemandedLowBitsHelper(1, 32))
8073       return SDValue(N, 0);
8074 
8075     break;
8076   }
8077   case RISCVISD::FMV_X_ANYEXTH:
8078   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8079     SDLoc DL(N);
8080     SDValue Op0 = N->getOperand(0);
8081     MVT VT = N->getSimpleValueType(0);
8082     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8083     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8084     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8085     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8086          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8087         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8088          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8089       assert(Op0.getOperand(0).getValueType() == VT &&
8090              "Unexpected value type!");
8091       return Op0.getOperand(0);
8092     }
8093 
8094     // This is a target-specific version of a DAGCombine performed in
8095     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8096     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8097     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8098     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8099         !Op0.getNode()->hasOneUse())
8100       break;
8101     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8102     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8103     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8104     if (Op0.getOpcode() == ISD::FNEG)
8105       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8106                          DAG.getConstant(SignBit, DL, VT));
8107 
8108     assert(Op0.getOpcode() == ISD::FABS);
8109     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8110                        DAG.getConstant(~SignBit, DL, VT));
8111   }
8112   case ISD::ADD:
8113     return performADDCombine(N, DAG, Subtarget);
8114   case ISD::SUB:
8115     return performSUBCombine(N, DAG);
8116   case ISD::AND:
8117     return performANDCombine(N, DAG);
8118   case ISD::OR:
8119     return performORCombine(N, DAG, Subtarget);
8120   case ISD::XOR:
8121     return performXORCombine(N, DAG);
8122   case ISD::ANY_EXTEND:
8123     return performANY_EXTENDCombine(N, DCI, Subtarget);
8124   case ISD::ZERO_EXTEND:
8125     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8126     // type legalization. This is safe because fp_to_uint produces poison if
8127     // it overflows.
8128     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8129       SDValue Src = N->getOperand(0);
8130       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8131           isTypeLegal(Src.getOperand(0).getValueType()))
8132         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8133                            Src.getOperand(0));
8134       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8135           isTypeLegal(Src.getOperand(1).getValueType())) {
8136         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8137         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8138                                   Src.getOperand(0), Src.getOperand(1));
8139         DCI.CombineTo(N, Res);
8140         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8141         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8142         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8143       }
8144     }
8145     return SDValue();
8146   case RISCVISD::SELECT_CC: {
8147     // Transform
8148     SDValue LHS = N->getOperand(0);
8149     SDValue RHS = N->getOperand(1);
8150     SDValue TrueV = N->getOperand(3);
8151     SDValue FalseV = N->getOperand(4);
8152 
8153     // If the True and False values are the same, we don't need a select_cc.
8154     if (TrueV == FalseV)
8155       return TrueV;
8156 
8157     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8158     if (!ISD::isIntEqualitySetCC(CCVal))
8159       break;
8160 
8161     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8162     //      (select_cc X, Y, lt, trueV, falseV)
8163     // Sometimes the setcc is introduced after select_cc has been formed.
8164     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8165         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8166       // If we're looking for eq 0 instead of ne 0, we need to invert the
8167       // condition.
8168       bool Invert = CCVal == ISD::SETEQ;
8169       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8170       if (Invert)
8171         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8172 
8173       SDLoc DL(N);
8174       RHS = LHS.getOperand(1);
8175       LHS = LHS.getOperand(0);
8176       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8177 
8178       SDValue TargetCC = DAG.getCondCode(CCVal);
8179       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8180                          {LHS, RHS, TargetCC, TrueV, FalseV});
8181     }
8182 
8183     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8184     //      (select_cc X, Y, eq/ne, trueV, falseV)
8185     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8186       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8187                          {LHS.getOperand(0), LHS.getOperand(1),
8188                           N->getOperand(2), TrueV, FalseV});
8189     // (select_cc X, 1, setne, trueV, falseV) ->
8190     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8191     // This can occur when legalizing some floating point comparisons.
8192     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8193     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8194       SDLoc DL(N);
8195       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8196       SDValue TargetCC = DAG.getCondCode(CCVal);
8197       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8198       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8199                          {LHS, RHS, TargetCC, TrueV, FalseV});
8200     }
8201 
8202     break;
8203   }
8204   case RISCVISD::BR_CC: {
8205     SDValue LHS = N->getOperand(1);
8206     SDValue RHS = N->getOperand(2);
8207     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8208     if (!ISD::isIntEqualitySetCC(CCVal))
8209       break;
8210 
8211     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8212     //      (br_cc X, Y, lt, dest)
8213     // Sometimes the setcc is introduced after br_cc has been formed.
8214     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8215         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8216       // If we're looking for eq 0 instead of ne 0, we need to invert the
8217       // condition.
8218       bool Invert = CCVal == ISD::SETEQ;
8219       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8220       if (Invert)
8221         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8222 
8223       SDLoc DL(N);
8224       RHS = LHS.getOperand(1);
8225       LHS = LHS.getOperand(0);
8226       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8227 
8228       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8229                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8230                          N->getOperand(4));
8231     }
8232 
8233     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8234     //      (br_cc X, Y, eq/ne, trueV, falseV)
8235     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8236       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8237                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8238                          N->getOperand(3), N->getOperand(4));
8239 
8240     // (br_cc X, 1, setne, br_cc) ->
8241     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8242     // This can occur when legalizing some floating point comparisons.
8243     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8244     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8245       SDLoc DL(N);
8246       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8247       SDValue TargetCC = DAG.getCondCode(CCVal);
8248       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8249       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8250                          N->getOperand(0), LHS, RHS, TargetCC,
8251                          N->getOperand(4));
8252     }
8253     break;
8254   }
8255   case ISD::FP_TO_SINT:
8256   case ISD::FP_TO_UINT:
8257     return performFP_TO_INTCombine(N, DCI, Subtarget);
8258   case ISD::FP_TO_SINT_SAT:
8259   case ISD::FP_TO_UINT_SAT:
8260     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8261   case ISD::FCOPYSIGN: {
8262     EVT VT = N->getValueType(0);
8263     if (!VT.isVector())
8264       break;
8265     // There is a form of VFSGNJ which injects the negated sign of its second
8266     // operand. Try and bubble any FNEG up after the extend/round to produce
8267     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8268     // TRUNC=1.
8269     SDValue In2 = N->getOperand(1);
8270     // Avoid cases where the extend/round has multiple uses, as duplicating
8271     // those is typically more expensive than removing a fneg.
8272     if (!In2.hasOneUse())
8273       break;
8274     if (In2.getOpcode() != ISD::FP_EXTEND &&
8275         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8276       break;
8277     In2 = In2.getOperand(0);
8278     if (In2.getOpcode() != ISD::FNEG)
8279       break;
8280     SDLoc DL(N);
8281     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8282     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8283                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8284   }
8285   case ISD::MGATHER:
8286   case ISD::MSCATTER:
8287   case ISD::VP_GATHER:
8288   case ISD::VP_SCATTER: {
8289     if (!DCI.isBeforeLegalize())
8290       break;
8291     SDValue Index, ScaleOp;
8292     bool IsIndexScaled = false;
8293     bool IsIndexSigned = false;
8294     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8295       Index = VPGSN->getIndex();
8296       ScaleOp = VPGSN->getScale();
8297       IsIndexScaled = VPGSN->isIndexScaled();
8298       IsIndexSigned = VPGSN->isIndexSigned();
8299     } else {
8300       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8301       Index = MGSN->getIndex();
8302       ScaleOp = MGSN->getScale();
8303       IsIndexScaled = MGSN->isIndexScaled();
8304       IsIndexSigned = MGSN->isIndexSigned();
8305     }
8306     EVT IndexVT = Index.getValueType();
8307     MVT XLenVT = Subtarget.getXLenVT();
8308     // RISCV indexed loads only support the "unsigned unscaled" addressing
8309     // mode, so anything else must be manually legalized.
8310     bool NeedsIdxLegalization =
8311         IsIndexScaled ||
8312         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8313     if (!NeedsIdxLegalization)
8314       break;
8315 
8316     SDLoc DL(N);
8317 
8318     // Any index legalization should first promote to XLenVT, so we don't lose
8319     // bits when scaling. This may create an illegal index type so we let
8320     // LLVM's legalization take care of the splitting.
8321     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8322     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8323       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8324       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8325                           DL, IndexVT, Index);
8326     }
8327 
8328     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8329     if (IsIndexScaled && Scale != 1) {
8330       // Manually scale the indices by the element size.
8331       // TODO: Sanitize the scale operand here?
8332       // TODO: For VP nodes, should we use VP_SHL here?
8333       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8334       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8335       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8336     }
8337 
8338     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8339     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8340       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8341                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8342                               VPGN->getScale(), VPGN->getMask(),
8343                               VPGN->getVectorLength()},
8344                              VPGN->getMemOperand(), NewIndexTy);
8345     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8346       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8347                               {VPSN->getChain(), VPSN->getValue(),
8348                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8349                                VPSN->getMask(), VPSN->getVectorLength()},
8350                               VPSN->getMemOperand(), NewIndexTy);
8351     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8352       return DAG.getMaskedGather(
8353           N->getVTList(), MGN->getMemoryVT(), DL,
8354           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8355            MGN->getBasePtr(), Index, MGN->getScale()},
8356           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8357     const auto *MSN = cast<MaskedScatterSDNode>(N);
8358     return DAG.getMaskedScatter(
8359         N->getVTList(), MSN->getMemoryVT(), DL,
8360         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8361          Index, MSN->getScale()},
8362         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8363   }
8364   case RISCVISD::SRA_VL:
8365   case RISCVISD::SRL_VL:
8366   case RISCVISD::SHL_VL: {
8367     SDValue ShAmt = N->getOperand(1);
8368     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8369       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8370       SDLoc DL(N);
8371       SDValue VL = N->getOperand(3);
8372       EVT VT = N->getValueType(0);
8373       ShAmt =
8374           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
8375       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8376                          N->getOperand(2), N->getOperand(3));
8377     }
8378     break;
8379   }
8380   case ISD::SRA:
8381   case ISD::SRL:
8382   case ISD::SHL: {
8383     SDValue ShAmt = N->getOperand(1);
8384     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8385       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8386       SDLoc DL(N);
8387       EVT VT = N->getValueType(0);
8388       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0),
8389                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8390       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8391     }
8392     break;
8393   }
8394   case RISCVISD::ADD_VL:
8395     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8396       return V;
8397     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8398   case RISCVISD::SUB_VL:
8399     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8400   case RISCVISD::VWADD_W_VL:
8401   case RISCVISD::VWADDU_W_VL:
8402   case RISCVISD::VWSUB_W_VL:
8403   case RISCVISD::VWSUBU_W_VL:
8404     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8405   case RISCVISD::MUL_VL:
8406     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8407       return V;
8408     // Mul is commutative.
8409     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8410   case ISD::STORE: {
8411     auto *Store = cast<StoreSDNode>(N);
8412     SDValue Val = Store->getValue();
8413     // Combine store of vmv.x.s to vse with VL of 1.
8414     // FIXME: Support FP.
8415     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8416       SDValue Src = Val.getOperand(0);
8417       EVT VecVT = Src.getValueType();
8418       EVT MemVT = Store->getMemoryVT();
8419       // The memory VT and the element type must match.
8420       if (VecVT.getVectorElementType() == MemVT) {
8421         SDLoc DL(N);
8422         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8423         return DAG.getStoreVP(
8424             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8425             DAG.getConstant(1, DL, MaskVT),
8426             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8427             Store->getMemOperand(), Store->getAddressingMode(),
8428             Store->isTruncatingStore(), /*IsCompress*/ false);
8429       }
8430     }
8431 
8432     break;
8433   }
8434   case ISD::SPLAT_VECTOR: {
8435     EVT VT = N->getValueType(0);
8436     // Only perform this combine on legal MVT types.
8437     if (!isTypeLegal(VT))
8438       break;
8439     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8440                                          DAG, Subtarget))
8441       return Gather;
8442     break;
8443   }
8444   case RISCVISD::VMV_V_X_VL: {
8445     // VMV.V.X only demands the vector element bitwidth from the scalar input.
8446     unsigned ScalarSize = N->getOperand(0).getValueSizeInBits();
8447     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8448     if (ScalarSize > EltWidth)
8449       if (SimplifyDemandedLowBitsHelper(0, EltWidth))
8450         return SDValue(N, 0);
8451 
8452     break;
8453   }
8454   }
8455 
8456   return SDValue();
8457 }
8458 
8459 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8460     const SDNode *N, CombineLevel Level) const {
8461   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8462   // materialised in fewer instructions than `(OP _, c1)`:
8463   //
8464   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8465   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8466   SDValue N0 = N->getOperand(0);
8467   EVT Ty = N0.getValueType();
8468   if (Ty.isScalarInteger() &&
8469       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8470     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8471     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8472     if (C1 && C2) {
8473       const APInt &C1Int = C1->getAPIntValue();
8474       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8475 
8476       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8477       // and the combine should happen, to potentially allow further combines
8478       // later.
8479       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8480           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8481         return true;
8482 
8483       // We can materialise `c1` in an add immediate, so it's "free", and the
8484       // combine should be prevented.
8485       if (C1Int.getMinSignedBits() <= 64 &&
8486           isLegalAddImmediate(C1Int.getSExtValue()))
8487         return false;
8488 
8489       // Neither constant will fit into an immediate, so find materialisation
8490       // costs.
8491       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8492                                               Subtarget.getFeatureBits(),
8493                                               /*CompressionCost*/true);
8494       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8495           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8496           /*CompressionCost*/true);
8497 
8498       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8499       // combine should be prevented.
8500       if (C1Cost < ShiftedC1Cost)
8501         return false;
8502     }
8503   }
8504   return true;
8505 }
8506 
8507 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8508     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8509     TargetLoweringOpt &TLO) const {
8510   // Delay this optimization as late as possible.
8511   if (!TLO.LegalOps)
8512     return false;
8513 
8514   EVT VT = Op.getValueType();
8515   if (VT.isVector())
8516     return false;
8517 
8518   // Only handle AND for now.
8519   if (Op.getOpcode() != ISD::AND)
8520     return false;
8521 
8522   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8523   if (!C)
8524     return false;
8525 
8526   const APInt &Mask = C->getAPIntValue();
8527 
8528   // Clear all non-demanded bits initially.
8529   APInt ShrunkMask = Mask & DemandedBits;
8530 
8531   // Try to make a smaller immediate by setting undemanded bits.
8532 
8533   APInt ExpandedMask = Mask | ~DemandedBits;
8534 
8535   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8536     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8537   };
8538   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8539     if (NewMask == Mask)
8540       return true;
8541     SDLoc DL(Op);
8542     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8543     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8544     return TLO.CombineTo(Op, NewOp);
8545   };
8546 
8547   // If the shrunk mask fits in sign extended 12 bits, let the target
8548   // independent code apply it.
8549   if (ShrunkMask.isSignedIntN(12))
8550     return false;
8551 
8552   // Preserve (and X, 0xffff) when zext.h is supported.
8553   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8554     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8555     if (IsLegalMask(NewMask))
8556       return UseMask(NewMask);
8557   }
8558 
8559   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8560   if (VT == MVT::i64) {
8561     APInt NewMask = APInt(64, 0xffffffff);
8562     if (IsLegalMask(NewMask))
8563       return UseMask(NewMask);
8564   }
8565 
8566   // For the remaining optimizations, we need to be able to make a negative
8567   // number through a combination of mask and undemanded bits.
8568   if (!ExpandedMask.isNegative())
8569     return false;
8570 
8571   // What is the fewest number of bits we need to represent the negative number.
8572   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8573 
8574   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8575   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8576   APInt NewMask = ShrunkMask;
8577   if (MinSignedBits <= 12)
8578     NewMask.setBitsFrom(11);
8579   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8580     NewMask.setBitsFrom(31);
8581   else
8582     return false;
8583 
8584   // Check that our new mask is a subset of the demanded mask.
8585   assert(IsLegalMask(NewMask));
8586   return UseMask(NewMask);
8587 }
8588 
8589 static void computeGREV(APInt &Src, unsigned ShAmt) {
8590   ShAmt &= Src.getBitWidth() - 1;
8591   uint64_t x = Src.getZExtValue();
8592   if (ShAmt & 1)
8593     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8594   if (ShAmt & 2)
8595     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8596   if (ShAmt & 4)
8597     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8598   if (ShAmt & 8)
8599     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8600   if (ShAmt & 16)
8601     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8602   if (ShAmt & 32)
8603     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8604   Src = x;
8605 }
8606 
8607 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8608                                                         KnownBits &Known,
8609                                                         const APInt &DemandedElts,
8610                                                         const SelectionDAG &DAG,
8611                                                         unsigned Depth) const {
8612   unsigned BitWidth = Known.getBitWidth();
8613   unsigned Opc = Op.getOpcode();
8614   assert((Opc >= ISD::BUILTIN_OP_END ||
8615           Opc == ISD::INTRINSIC_WO_CHAIN ||
8616           Opc == ISD::INTRINSIC_W_CHAIN ||
8617           Opc == ISD::INTRINSIC_VOID) &&
8618          "Should use MaskedValueIsZero if you don't know whether Op"
8619          " is a target node!");
8620 
8621   Known.resetAll();
8622   switch (Opc) {
8623   default: break;
8624   case RISCVISD::SELECT_CC: {
8625     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8626     // If we don't know any bits, early out.
8627     if (Known.isUnknown())
8628       break;
8629     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8630 
8631     // Only known if known in both the LHS and RHS.
8632     Known = KnownBits::commonBits(Known, Known2);
8633     break;
8634   }
8635   case RISCVISD::REMUW: {
8636     KnownBits Known2;
8637     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8638     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8639     // We only care about the lower 32 bits.
8640     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8641     // Restore the original width by sign extending.
8642     Known = Known.sext(BitWidth);
8643     break;
8644   }
8645   case RISCVISD::DIVUW: {
8646     KnownBits Known2;
8647     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8648     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8649     // We only care about the lower 32 bits.
8650     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8651     // Restore the original width by sign extending.
8652     Known = Known.sext(BitWidth);
8653     break;
8654   }
8655   case RISCVISD::CTZW: {
8656     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8657     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8658     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8659     Known.Zero.setBitsFrom(LowBits);
8660     break;
8661   }
8662   case RISCVISD::CLZW: {
8663     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8664     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8665     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8666     Known.Zero.setBitsFrom(LowBits);
8667     break;
8668   }
8669   case RISCVISD::GREV:
8670   case RISCVISD::GREVW: {
8671     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8672       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8673       if (Opc == RISCVISD::GREVW)
8674         Known = Known.trunc(32);
8675       unsigned ShAmt = C->getZExtValue();
8676       computeGREV(Known.Zero, ShAmt);
8677       computeGREV(Known.One, ShAmt);
8678       if (Opc == RISCVISD::GREVW)
8679         Known = Known.sext(BitWidth);
8680     }
8681     break;
8682   }
8683   case RISCVISD::READ_VLENB: {
8684     // If we know the minimum VLen from Zvl extensions, we can use that to
8685     // determine the trailing zeros of VLENB.
8686     // FIXME: Limit to 128 bit vectors until we have more testing.
8687     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8688     if (MinVLenB > 0)
8689       Known.Zero.setLowBits(Log2_32(MinVLenB));
8690     // We assume VLENB is no more than 65536 / 8 bytes.
8691     Known.Zero.setBitsFrom(14);
8692     break;
8693   }
8694   case ISD::INTRINSIC_W_CHAIN:
8695   case ISD::INTRINSIC_WO_CHAIN: {
8696     unsigned IntNo =
8697         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8698     switch (IntNo) {
8699     default:
8700       // We can't do anything for most intrinsics.
8701       break;
8702     case Intrinsic::riscv_vsetvli:
8703     case Intrinsic::riscv_vsetvlimax:
8704     case Intrinsic::riscv_vsetvli_opt:
8705     case Intrinsic::riscv_vsetvlimax_opt:
8706       // Assume that VL output is positive and would fit in an int32_t.
8707       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8708       if (BitWidth >= 32)
8709         Known.Zero.setBitsFrom(31);
8710       break;
8711     }
8712     break;
8713   }
8714   }
8715 }
8716 
8717 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8718     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8719     unsigned Depth) const {
8720   switch (Op.getOpcode()) {
8721   default:
8722     break;
8723   case RISCVISD::SELECT_CC: {
8724     unsigned Tmp =
8725         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8726     if (Tmp == 1) return 1;  // Early out.
8727     unsigned Tmp2 =
8728         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8729     return std::min(Tmp, Tmp2);
8730   }
8731   case RISCVISD::SLLW:
8732   case RISCVISD::SRAW:
8733   case RISCVISD::SRLW:
8734   case RISCVISD::DIVW:
8735   case RISCVISD::DIVUW:
8736   case RISCVISD::REMUW:
8737   case RISCVISD::ROLW:
8738   case RISCVISD::RORW:
8739   case RISCVISD::GREVW:
8740   case RISCVISD::GORCW:
8741   case RISCVISD::FSLW:
8742   case RISCVISD::FSRW:
8743   case RISCVISD::SHFLW:
8744   case RISCVISD::UNSHFLW:
8745   case RISCVISD::BCOMPRESSW:
8746   case RISCVISD::BDECOMPRESSW:
8747   case RISCVISD::BFPW:
8748   case RISCVISD::FCVT_W_RV64:
8749   case RISCVISD::FCVT_WU_RV64:
8750   case RISCVISD::STRICT_FCVT_W_RV64:
8751   case RISCVISD::STRICT_FCVT_WU_RV64:
8752     // TODO: As the result is sign-extended, this is conservatively correct. A
8753     // more precise answer could be calculated for SRAW depending on known
8754     // bits in the shift amount.
8755     return 33;
8756   case RISCVISD::SHFL:
8757   case RISCVISD::UNSHFL: {
8758     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8759     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8760     // will stay within the upper 32 bits. If there were more than 32 sign bits
8761     // before there will be at least 33 sign bits after.
8762     if (Op.getValueType() == MVT::i64 &&
8763         isa<ConstantSDNode>(Op.getOperand(1)) &&
8764         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8765       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8766       if (Tmp > 32)
8767         return 33;
8768     }
8769     break;
8770   }
8771   case RISCVISD::VMV_X_S: {
8772     // The number of sign bits of the scalar result is computed by obtaining the
8773     // element type of the input vector operand, subtracting its width from the
8774     // XLEN, and then adding one (sign bit within the element type). If the
8775     // element type is wider than XLen, the least-significant XLEN bits are
8776     // taken.
8777     unsigned XLen = Subtarget.getXLen();
8778     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8779     if (EltBits <= XLen)
8780       return XLen - EltBits + 1;
8781     break;
8782   }
8783   }
8784 
8785   return 1;
8786 }
8787 
8788 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8789                                                   MachineBasicBlock *BB) {
8790   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8791 
8792   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8793   // Should the count have wrapped while it was being read, we need to try
8794   // again.
8795   // ...
8796   // read:
8797   // rdcycleh x3 # load high word of cycle
8798   // rdcycle  x2 # load low word of cycle
8799   // rdcycleh x4 # load high word of cycle
8800   // bne x3, x4, read # check if high word reads match, otherwise try again
8801   // ...
8802 
8803   MachineFunction &MF = *BB->getParent();
8804   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8805   MachineFunction::iterator It = ++BB->getIterator();
8806 
8807   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8808   MF.insert(It, LoopMBB);
8809 
8810   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8811   MF.insert(It, DoneMBB);
8812 
8813   // Transfer the remainder of BB and its successor edges to DoneMBB.
8814   DoneMBB->splice(DoneMBB->begin(), BB,
8815                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8816   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8817 
8818   BB->addSuccessor(LoopMBB);
8819 
8820   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8821   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8822   Register LoReg = MI.getOperand(0).getReg();
8823   Register HiReg = MI.getOperand(1).getReg();
8824   DebugLoc DL = MI.getDebugLoc();
8825 
8826   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8827   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8828       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8829       .addReg(RISCV::X0);
8830   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8831       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8832       .addReg(RISCV::X0);
8833   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8834       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8835       .addReg(RISCV::X0);
8836 
8837   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8838       .addReg(HiReg)
8839       .addReg(ReadAgainReg)
8840       .addMBB(LoopMBB);
8841 
8842   LoopMBB->addSuccessor(LoopMBB);
8843   LoopMBB->addSuccessor(DoneMBB);
8844 
8845   MI.eraseFromParent();
8846 
8847   return DoneMBB;
8848 }
8849 
8850 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8851                                              MachineBasicBlock *BB) {
8852   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8853 
8854   MachineFunction &MF = *BB->getParent();
8855   DebugLoc DL = MI.getDebugLoc();
8856   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8857   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8858   Register LoReg = MI.getOperand(0).getReg();
8859   Register HiReg = MI.getOperand(1).getReg();
8860   Register SrcReg = MI.getOperand(2).getReg();
8861   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8862   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8863 
8864   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8865                           RI);
8866   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8867   MachineMemOperand *MMOLo =
8868       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8869   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8870       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8871   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8872       .addFrameIndex(FI)
8873       .addImm(0)
8874       .addMemOperand(MMOLo);
8875   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8876       .addFrameIndex(FI)
8877       .addImm(4)
8878       .addMemOperand(MMOHi);
8879   MI.eraseFromParent(); // The pseudo instruction is gone now.
8880   return BB;
8881 }
8882 
8883 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8884                                                  MachineBasicBlock *BB) {
8885   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8886          "Unexpected instruction");
8887 
8888   MachineFunction &MF = *BB->getParent();
8889   DebugLoc DL = MI.getDebugLoc();
8890   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8891   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8892   Register DstReg = MI.getOperand(0).getReg();
8893   Register LoReg = MI.getOperand(1).getReg();
8894   Register HiReg = MI.getOperand(2).getReg();
8895   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8896   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8897 
8898   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8899   MachineMemOperand *MMOLo =
8900       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8901   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8902       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8903   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8904       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8905       .addFrameIndex(FI)
8906       .addImm(0)
8907       .addMemOperand(MMOLo);
8908   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8909       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8910       .addFrameIndex(FI)
8911       .addImm(4)
8912       .addMemOperand(MMOHi);
8913   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8914   MI.eraseFromParent(); // The pseudo instruction is gone now.
8915   return BB;
8916 }
8917 
8918 static bool isSelectPseudo(MachineInstr &MI) {
8919   switch (MI.getOpcode()) {
8920   default:
8921     return false;
8922   case RISCV::Select_GPR_Using_CC_GPR:
8923   case RISCV::Select_FPR16_Using_CC_GPR:
8924   case RISCV::Select_FPR32_Using_CC_GPR:
8925   case RISCV::Select_FPR64_Using_CC_GPR:
8926     return true;
8927   }
8928 }
8929 
8930 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8931                                         unsigned RelOpcode, unsigned EqOpcode,
8932                                         const RISCVSubtarget &Subtarget) {
8933   DebugLoc DL = MI.getDebugLoc();
8934   Register DstReg = MI.getOperand(0).getReg();
8935   Register Src1Reg = MI.getOperand(1).getReg();
8936   Register Src2Reg = MI.getOperand(2).getReg();
8937   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8938   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8939   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8940 
8941   // Save the current FFLAGS.
8942   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8943 
8944   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8945                  .addReg(Src1Reg)
8946                  .addReg(Src2Reg);
8947   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8948     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8949 
8950   // Restore the FFLAGS.
8951   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8952       .addReg(SavedFFlags, RegState::Kill);
8953 
8954   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8955   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8956                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8957                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8958   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8959     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8960 
8961   // Erase the pseudoinstruction.
8962   MI.eraseFromParent();
8963   return BB;
8964 }
8965 
8966 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8967                                            MachineBasicBlock *BB,
8968                                            const RISCVSubtarget &Subtarget) {
8969   // To "insert" Select_* instructions, we actually have to insert the triangle
8970   // control-flow pattern.  The incoming instructions know the destination vreg
8971   // to set, the condition code register to branch on, the true/false values to
8972   // select between, and the condcode to use to select the appropriate branch.
8973   //
8974   // We produce the following control flow:
8975   //     HeadMBB
8976   //     |  \
8977   //     |  IfFalseMBB
8978   //     | /
8979   //    TailMBB
8980   //
8981   // When we find a sequence of selects we attempt to optimize their emission
8982   // by sharing the control flow. Currently we only handle cases where we have
8983   // multiple selects with the exact same condition (same LHS, RHS and CC).
8984   // The selects may be interleaved with other instructions if the other
8985   // instructions meet some requirements we deem safe:
8986   // - They are debug instructions. Otherwise,
8987   // - They do not have side-effects, do not access memory and their inputs do
8988   //   not depend on the results of the select pseudo-instructions.
8989   // The TrueV/FalseV operands of the selects cannot depend on the result of
8990   // previous selects in the sequence.
8991   // These conditions could be further relaxed. See the X86 target for a
8992   // related approach and more information.
8993   Register LHS = MI.getOperand(1).getReg();
8994   Register RHS = MI.getOperand(2).getReg();
8995   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8996 
8997   SmallVector<MachineInstr *, 4> SelectDebugValues;
8998   SmallSet<Register, 4> SelectDests;
8999   SelectDests.insert(MI.getOperand(0).getReg());
9000 
9001   MachineInstr *LastSelectPseudo = &MI;
9002 
9003   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9004        SequenceMBBI != E; ++SequenceMBBI) {
9005     if (SequenceMBBI->isDebugInstr())
9006       continue;
9007     else if (isSelectPseudo(*SequenceMBBI)) {
9008       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9009           SequenceMBBI->getOperand(2).getReg() != RHS ||
9010           SequenceMBBI->getOperand(3).getImm() != CC ||
9011           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9012           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9013         break;
9014       LastSelectPseudo = &*SequenceMBBI;
9015       SequenceMBBI->collectDebugValues(SelectDebugValues);
9016       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9017     } else {
9018       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9019           SequenceMBBI->mayLoadOrStore())
9020         break;
9021       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9022             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9023           }))
9024         break;
9025     }
9026   }
9027 
9028   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9029   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9030   DebugLoc DL = MI.getDebugLoc();
9031   MachineFunction::iterator I = ++BB->getIterator();
9032 
9033   MachineBasicBlock *HeadMBB = BB;
9034   MachineFunction *F = BB->getParent();
9035   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9036   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9037 
9038   F->insert(I, IfFalseMBB);
9039   F->insert(I, TailMBB);
9040 
9041   // Transfer debug instructions associated with the selects to TailMBB.
9042   for (MachineInstr *DebugInstr : SelectDebugValues) {
9043     TailMBB->push_back(DebugInstr->removeFromParent());
9044   }
9045 
9046   // Move all instructions after the sequence to TailMBB.
9047   TailMBB->splice(TailMBB->end(), HeadMBB,
9048                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9049   // Update machine-CFG edges by transferring all successors of the current
9050   // block to the new block which will contain the Phi nodes for the selects.
9051   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9052   // Set the successors for HeadMBB.
9053   HeadMBB->addSuccessor(IfFalseMBB);
9054   HeadMBB->addSuccessor(TailMBB);
9055 
9056   // Insert appropriate branch.
9057   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9058     .addReg(LHS)
9059     .addReg(RHS)
9060     .addMBB(TailMBB);
9061 
9062   // IfFalseMBB just falls through to TailMBB.
9063   IfFalseMBB->addSuccessor(TailMBB);
9064 
9065   // Create PHIs for all of the select pseudo-instructions.
9066   auto SelectMBBI = MI.getIterator();
9067   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9068   auto InsertionPoint = TailMBB->begin();
9069   while (SelectMBBI != SelectEnd) {
9070     auto Next = std::next(SelectMBBI);
9071     if (isSelectPseudo(*SelectMBBI)) {
9072       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9073       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9074               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9075           .addReg(SelectMBBI->getOperand(4).getReg())
9076           .addMBB(HeadMBB)
9077           .addReg(SelectMBBI->getOperand(5).getReg())
9078           .addMBB(IfFalseMBB);
9079       SelectMBBI->eraseFromParent();
9080     }
9081     SelectMBBI = Next;
9082   }
9083 
9084   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9085   return TailMBB;
9086 }
9087 
9088 MachineBasicBlock *
9089 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9090                                                  MachineBasicBlock *BB) const {
9091   switch (MI.getOpcode()) {
9092   default:
9093     llvm_unreachable("Unexpected instr type to insert");
9094   case RISCV::ReadCycleWide:
9095     assert(!Subtarget.is64Bit() &&
9096            "ReadCycleWrite is only to be used on riscv32");
9097     return emitReadCycleWidePseudo(MI, BB);
9098   case RISCV::Select_GPR_Using_CC_GPR:
9099   case RISCV::Select_FPR16_Using_CC_GPR:
9100   case RISCV::Select_FPR32_Using_CC_GPR:
9101   case RISCV::Select_FPR64_Using_CC_GPR:
9102     return emitSelectPseudo(MI, BB, Subtarget);
9103   case RISCV::BuildPairF64Pseudo:
9104     return emitBuildPairF64Pseudo(MI, BB);
9105   case RISCV::SplitF64Pseudo:
9106     return emitSplitF64Pseudo(MI, BB);
9107   case RISCV::PseudoQuietFLE_H:
9108     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9109   case RISCV::PseudoQuietFLT_H:
9110     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9111   case RISCV::PseudoQuietFLE_S:
9112     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9113   case RISCV::PseudoQuietFLT_S:
9114     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9115   case RISCV::PseudoQuietFLE_D:
9116     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9117   case RISCV::PseudoQuietFLT_D:
9118     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9119   }
9120 }
9121 
9122 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9123                                                         SDNode *Node) const {
9124   // Add FRM dependency to any instructions with dynamic rounding mode.
9125   unsigned Opc = MI.getOpcode();
9126   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9127   if (Idx < 0)
9128     return;
9129   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9130     return;
9131   // If the instruction already reads FRM, don't add another read.
9132   if (MI.readsRegister(RISCV::FRM))
9133     return;
9134   MI.addOperand(
9135       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9136 }
9137 
9138 // Calling Convention Implementation.
9139 // The expectations for frontend ABI lowering vary from target to target.
9140 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9141 // details, but this is a longer term goal. For now, we simply try to keep the
9142 // role of the frontend as simple and well-defined as possible. The rules can
9143 // be summarised as:
9144 // * Never split up large scalar arguments. We handle them here.
9145 // * If a hardfloat calling convention is being used, and the struct may be
9146 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9147 // available, then pass as two separate arguments. If either the GPRs or FPRs
9148 // are exhausted, then pass according to the rule below.
9149 // * If a struct could never be passed in registers or directly in a stack
9150 // slot (as it is larger than 2*XLEN and the floating point rules don't
9151 // apply), then pass it using a pointer with the byval attribute.
9152 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9153 // word-sized array or a 2*XLEN scalar (depending on alignment).
9154 // * The frontend can determine whether a struct is returned by reference or
9155 // not based on its size and fields. If it will be returned by reference, the
9156 // frontend must modify the prototype so a pointer with the sret annotation is
9157 // passed as the first argument. This is not necessary for large scalar
9158 // returns.
9159 // * Struct return values and varargs should be coerced to structs containing
9160 // register-size fields in the same situations they would be for fixed
9161 // arguments.
9162 
9163 static const MCPhysReg ArgGPRs[] = {
9164   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9165   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9166 };
9167 static const MCPhysReg ArgFPR16s[] = {
9168   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9169   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9170 };
9171 static const MCPhysReg ArgFPR32s[] = {
9172   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9173   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9174 };
9175 static const MCPhysReg ArgFPR64s[] = {
9176   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9177   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9178 };
9179 // This is an interim calling convention and it may be changed in the future.
9180 static const MCPhysReg ArgVRs[] = {
9181     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9182     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9183     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9184 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9185                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9186                                      RISCV::V20M2, RISCV::V22M2};
9187 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9188                                      RISCV::V20M4};
9189 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9190 
9191 // Pass a 2*XLEN argument that has been split into two XLEN values through
9192 // registers or the stack as necessary.
9193 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9194                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9195                                 MVT ValVT2, MVT LocVT2,
9196                                 ISD::ArgFlagsTy ArgFlags2) {
9197   unsigned XLenInBytes = XLen / 8;
9198   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9199     // At least one half can be passed via register.
9200     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9201                                      VA1.getLocVT(), CCValAssign::Full));
9202   } else {
9203     // Both halves must be passed on the stack, with proper alignment.
9204     Align StackAlign =
9205         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9206     State.addLoc(
9207         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9208                             State.AllocateStack(XLenInBytes, StackAlign),
9209                             VA1.getLocVT(), CCValAssign::Full));
9210     State.addLoc(CCValAssign::getMem(
9211         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9212         LocVT2, CCValAssign::Full));
9213     return false;
9214   }
9215 
9216   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9217     // The second half can also be passed via register.
9218     State.addLoc(
9219         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9220   } else {
9221     // The second half is passed via the stack, without additional alignment.
9222     State.addLoc(CCValAssign::getMem(
9223         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9224         LocVT2, CCValAssign::Full));
9225   }
9226 
9227   return false;
9228 }
9229 
9230 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9231                                Optional<unsigned> FirstMaskArgument,
9232                                CCState &State, const RISCVTargetLowering &TLI) {
9233   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9234   if (RC == &RISCV::VRRegClass) {
9235     // Assign the first mask argument to V0.
9236     // This is an interim calling convention and it may be changed in the
9237     // future.
9238     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9239       return State.AllocateReg(RISCV::V0);
9240     return State.AllocateReg(ArgVRs);
9241   }
9242   if (RC == &RISCV::VRM2RegClass)
9243     return State.AllocateReg(ArgVRM2s);
9244   if (RC == &RISCV::VRM4RegClass)
9245     return State.AllocateReg(ArgVRM4s);
9246   if (RC == &RISCV::VRM8RegClass)
9247     return State.AllocateReg(ArgVRM8s);
9248   llvm_unreachable("Unhandled register class for ValueType");
9249 }
9250 
9251 // Implements the RISC-V calling convention. Returns true upon failure.
9252 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9253                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9254                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9255                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9256                      Optional<unsigned> FirstMaskArgument) {
9257   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9258   assert(XLen == 32 || XLen == 64);
9259   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9260 
9261   // Any return value split in to more than two values can't be returned
9262   // directly. Vectors are returned via the available vector registers.
9263   if (!LocVT.isVector() && IsRet && ValNo > 1)
9264     return true;
9265 
9266   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9267   // variadic argument, or if no F16/F32 argument registers are available.
9268   bool UseGPRForF16_F32 = true;
9269   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9270   // variadic argument, or if no F64 argument registers are available.
9271   bool UseGPRForF64 = true;
9272 
9273   switch (ABI) {
9274   default:
9275     llvm_unreachable("Unexpected ABI");
9276   case RISCVABI::ABI_ILP32:
9277   case RISCVABI::ABI_LP64:
9278     break;
9279   case RISCVABI::ABI_ILP32F:
9280   case RISCVABI::ABI_LP64F:
9281     UseGPRForF16_F32 = !IsFixed;
9282     break;
9283   case RISCVABI::ABI_ILP32D:
9284   case RISCVABI::ABI_LP64D:
9285     UseGPRForF16_F32 = !IsFixed;
9286     UseGPRForF64 = !IsFixed;
9287     break;
9288   }
9289 
9290   // FPR16, FPR32, and FPR64 alias each other.
9291   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9292     UseGPRForF16_F32 = true;
9293     UseGPRForF64 = true;
9294   }
9295 
9296   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9297   // similar local variables rather than directly checking against the target
9298   // ABI.
9299 
9300   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9301     LocVT = XLenVT;
9302     LocInfo = CCValAssign::BCvt;
9303   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9304     LocVT = MVT::i64;
9305     LocInfo = CCValAssign::BCvt;
9306   }
9307 
9308   // If this is a variadic argument, the RISC-V calling convention requires
9309   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9310   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9311   // be used regardless of whether the original argument was split during
9312   // legalisation or not. The argument will not be passed by registers if the
9313   // original type is larger than 2*XLEN, so the register alignment rule does
9314   // not apply.
9315   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9316   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9317       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9318     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9319     // Skip 'odd' register if necessary.
9320     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9321       State.AllocateReg(ArgGPRs);
9322   }
9323 
9324   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9325   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9326       State.getPendingArgFlags();
9327 
9328   assert(PendingLocs.size() == PendingArgFlags.size() &&
9329          "PendingLocs and PendingArgFlags out of sync");
9330 
9331   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9332   // registers are exhausted.
9333   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9334     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9335            "Can't lower f64 if it is split");
9336     // Depending on available argument GPRS, f64 may be passed in a pair of
9337     // GPRs, split between a GPR and the stack, or passed completely on the
9338     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9339     // cases.
9340     Register Reg = State.AllocateReg(ArgGPRs);
9341     LocVT = MVT::i32;
9342     if (!Reg) {
9343       unsigned StackOffset = State.AllocateStack(8, Align(8));
9344       State.addLoc(
9345           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9346       return false;
9347     }
9348     if (!State.AllocateReg(ArgGPRs))
9349       State.AllocateStack(4, Align(4));
9350     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9351     return false;
9352   }
9353 
9354   // Fixed-length vectors are located in the corresponding scalable-vector
9355   // container types.
9356   if (ValVT.isFixedLengthVector())
9357     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9358 
9359   // Split arguments might be passed indirectly, so keep track of the pending
9360   // values. Split vectors are passed via a mix of registers and indirectly, so
9361   // treat them as we would any other argument.
9362   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9363     LocVT = XLenVT;
9364     LocInfo = CCValAssign::Indirect;
9365     PendingLocs.push_back(
9366         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9367     PendingArgFlags.push_back(ArgFlags);
9368     if (!ArgFlags.isSplitEnd()) {
9369       return false;
9370     }
9371   }
9372 
9373   // If the split argument only had two elements, it should be passed directly
9374   // in registers or on the stack.
9375   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9376       PendingLocs.size() <= 2) {
9377     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9378     // Apply the normal calling convention rules to the first half of the
9379     // split argument.
9380     CCValAssign VA = PendingLocs[0];
9381     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9382     PendingLocs.clear();
9383     PendingArgFlags.clear();
9384     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9385                                ArgFlags);
9386   }
9387 
9388   // Allocate to a register if possible, or else a stack slot.
9389   Register Reg;
9390   unsigned StoreSizeBytes = XLen / 8;
9391   Align StackAlign = Align(XLen / 8);
9392 
9393   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9394     Reg = State.AllocateReg(ArgFPR16s);
9395   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9396     Reg = State.AllocateReg(ArgFPR32s);
9397   else if (ValVT == MVT::f64 && !UseGPRForF64)
9398     Reg = State.AllocateReg(ArgFPR64s);
9399   else if (ValVT.isVector()) {
9400     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9401     if (!Reg) {
9402       // For return values, the vector must be passed fully via registers or
9403       // via the stack.
9404       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9405       // but we're using all of them.
9406       if (IsRet)
9407         return true;
9408       // Try using a GPR to pass the address
9409       if ((Reg = State.AllocateReg(ArgGPRs))) {
9410         LocVT = XLenVT;
9411         LocInfo = CCValAssign::Indirect;
9412       } else if (ValVT.isScalableVector()) {
9413         LocVT = XLenVT;
9414         LocInfo = CCValAssign::Indirect;
9415       } else {
9416         // Pass fixed-length vectors on the stack.
9417         LocVT = ValVT;
9418         StoreSizeBytes = ValVT.getStoreSize();
9419         // Align vectors to their element sizes, being careful for vXi1
9420         // vectors.
9421         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9422       }
9423     }
9424   } else {
9425     Reg = State.AllocateReg(ArgGPRs);
9426   }
9427 
9428   unsigned StackOffset =
9429       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9430 
9431   // If we reach this point and PendingLocs is non-empty, we must be at the
9432   // end of a split argument that must be passed indirectly.
9433   if (!PendingLocs.empty()) {
9434     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9435     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9436 
9437     for (auto &It : PendingLocs) {
9438       if (Reg)
9439         It.convertToReg(Reg);
9440       else
9441         It.convertToMem(StackOffset);
9442       State.addLoc(It);
9443     }
9444     PendingLocs.clear();
9445     PendingArgFlags.clear();
9446     return false;
9447   }
9448 
9449   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9450           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9451          "Expected an XLenVT or vector types at this stage");
9452 
9453   if (Reg) {
9454     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9455     return false;
9456   }
9457 
9458   // When a floating-point value is passed on the stack, no bit-conversion is
9459   // needed.
9460   if (ValVT.isFloatingPoint()) {
9461     LocVT = ValVT;
9462     LocInfo = CCValAssign::Full;
9463   }
9464   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9465   return false;
9466 }
9467 
9468 template <typename ArgTy>
9469 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9470   for (const auto &ArgIdx : enumerate(Args)) {
9471     MVT ArgVT = ArgIdx.value().VT;
9472     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9473       return ArgIdx.index();
9474   }
9475   return None;
9476 }
9477 
9478 void RISCVTargetLowering::analyzeInputArgs(
9479     MachineFunction &MF, CCState &CCInfo,
9480     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9481     RISCVCCAssignFn Fn) const {
9482   unsigned NumArgs = Ins.size();
9483   FunctionType *FType = MF.getFunction().getFunctionType();
9484 
9485   Optional<unsigned> FirstMaskArgument;
9486   if (Subtarget.hasVInstructions())
9487     FirstMaskArgument = preAssignMask(Ins);
9488 
9489   for (unsigned i = 0; i != NumArgs; ++i) {
9490     MVT ArgVT = Ins[i].VT;
9491     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9492 
9493     Type *ArgTy = nullptr;
9494     if (IsRet)
9495       ArgTy = FType->getReturnType();
9496     else if (Ins[i].isOrigArg())
9497       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9498 
9499     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9500     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9501            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9502            FirstMaskArgument)) {
9503       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9504                         << EVT(ArgVT).getEVTString() << '\n');
9505       llvm_unreachable(nullptr);
9506     }
9507   }
9508 }
9509 
9510 void RISCVTargetLowering::analyzeOutputArgs(
9511     MachineFunction &MF, CCState &CCInfo,
9512     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9513     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9514   unsigned NumArgs = Outs.size();
9515 
9516   Optional<unsigned> FirstMaskArgument;
9517   if (Subtarget.hasVInstructions())
9518     FirstMaskArgument = preAssignMask(Outs);
9519 
9520   for (unsigned i = 0; i != NumArgs; i++) {
9521     MVT ArgVT = Outs[i].VT;
9522     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9523     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9524 
9525     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9526     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9527            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9528            FirstMaskArgument)) {
9529       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9530                         << EVT(ArgVT).getEVTString() << "\n");
9531       llvm_unreachable(nullptr);
9532     }
9533   }
9534 }
9535 
9536 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9537 // values.
9538 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9539                                    const CCValAssign &VA, const SDLoc &DL,
9540                                    const RISCVSubtarget &Subtarget) {
9541   switch (VA.getLocInfo()) {
9542   default:
9543     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9544   case CCValAssign::Full:
9545     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9546       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9547     break;
9548   case CCValAssign::BCvt:
9549     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9550       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9551     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9552       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9553     else
9554       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9555     break;
9556   }
9557   return Val;
9558 }
9559 
9560 // The caller is responsible for loading the full value if the argument is
9561 // passed with CCValAssign::Indirect.
9562 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9563                                 const CCValAssign &VA, const SDLoc &DL,
9564                                 const RISCVTargetLowering &TLI) {
9565   MachineFunction &MF = DAG.getMachineFunction();
9566   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9567   EVT LocVT = VA.getLocVT();
9568   SDValue Val;
9569   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9570   Register VReg = RegInfo.createVirtualRegister(RC);
9571   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9572   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9573 
9574   if (VA.getLocInfo() == CCValAssign::Indirect)
9575     return Val;
9576 
9577   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9578 }
9579 
9580 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9581                                    const CCValAssign &VA, const SDLoc &DL,
9582                                    const RISCVSubtarget &Subtarget) {
9583   EVT LocVT = VA.getLocVT();
9584 
9585   switch (VA.getLocInfo()) {
9586   default:
9587     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9588   case CCValAssign::Full:
9589     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9590       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9591     break;
9592   case CCValAssign::BCvt:
9593     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9594       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9595     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9596       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9597     else
9598       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9599     break;
9600   }
9601   return Val;
9602 }
9603 
9604 // The caller is responsible for loading the full value if the argument is
9605 // passed with CCValAssign::Indirect.
9606 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9607                                 const CCValAssign &VA, const SDLoc &DL) {
9608   MachineFunction &MF = DAG.getMachineFunction();
9609   MachineFrameInfo &MFI = MF.getFrameInfo();
9610   EVT LocVT = VA.getLocVT();
9611   EVT ValVT = VA.getValVT();
9612   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9613   if (ValVT.isScalableVector()) {
9614     // When the value is a scalable vector, we save the pointer which points to
9615     // the scalable vector value in the stack. The ValVT will be the pointer
9616     // type, instead of the scalable vector type.
9617     ValVT = LocVT;
9618   }
9619   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9620                                  /*IsImmutable=*/true);
9621   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9622   SDValue Val;
9623 
9624   ISD::LoadExtType ExtType;
9625   switch (VA.getLocInfo()) {
9626   default:
9627     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9628   case CCValAssign::Full:
9629   case CCValAssign::Indirect:
9630   case CCValAssign::BCvt:
9631     ExtType = ISD::NON_EXTLOAD;
9632     break;
9633   }
9634   Val = DAG.getExtLoad(
9635       ExtType, DL, LocVT, Chain, FIN,
9636       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9637   return Val;
9638 }
9639 
9640 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9641                                        const CCValAssign &VA, const SDLoc &DL) {
9642   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9643          "Unexpected VA");
9644   MachineFunction &MF = DAG.getMachineFunction();
9645   MachineFrameInfo &MFI = MF.getFrameInfo();
9646   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9647 
9648   if (VA.isMemLoc()) {
9649     // f64 is passed on the stack.
9650     int FI =
9651         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9652     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9653     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9654                        MachinePointerInfo::getFixedStack(MF, FI));
9655   }
9656 
9657   assert(VA.isRegLoc() && "Expected register VA assignment");
9658 
9659   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9660   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9661   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9662   SDValue Hi;
9663   if (VA.getLocReg() == RISCV::X17) {
9664     // Second half of f64 is passed on the stack.
9665     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9666     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9667     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9668                      MachinePointerInfo::getFixedStack(MF, FI));
9669   } else {
9670     // Second half of f64 is passed in another GPR.
9671     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9672     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9673     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9674   }
9675   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9676 }
9677 
9678 // FastCC has less than 1% performance improvement for some particular
9679 // benchmark. But theoretically, it may has benenfit for some cases.
9680 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9681                             unsigned ValNo, MVT ValVT, MVT LocVT,
9682                             CCValAssign::LocInfo LocInfo,
9683                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9684                             bool IsFixed, bool IsRet, Type *OrigTy,
9685                             const RISCVTargetLowering &TLI,
9686                             Optional<unsigned> FirstMaskArgument) {
9687 
9688   // X5 and X6 might be used for save-restore libcall.
9689   static const MCPhysReg GPRList[] = {
9690       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9691       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9692       RISCV::X29, RISCV::X30, RISCV::X31};
9693 
9694   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9695     if (unsigned Reg = State.AllocateReg(GPRList)) {
9696       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9697       return false;
9698     }
9699   }
9700 
9701   if (LocVT == MVT::f16) {
9702     static const MCPhysReg FPR16List[] = {
9703         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9704         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9705         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9706         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9707     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9708       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9709       return false;
9710     }
9711   }
9712 
9713   if (LocVT == MVT::f32) {
9714     static const MCPhysReg FPR32List[] = {
9715         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9716         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9717         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9718         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9719     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9720       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9721       return false;
9722     }
9723   }
9724 
9725   if (LocVT == MVT::f64) {
9726     static const MCPhysReg FPR64List[] = {
9727         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9728         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9729         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9730         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9731     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9732       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9733       return false;
9734     }
9735   }
9736 
9737   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9738     unsigned Offset4 = State.AllocateStack(4, Align(4));
9739     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9740     return false;
9741   }
9742 
9743   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9744     unsigned Offset5 = State.AllocateStack(8, Align(8));
9745     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9746     return false;
9747   }
9748 
9749   if (LocVT.isVector()) {
9750     if (unsigned Reg =
9751             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9752       // Fixed-length vectors are located in the corresponding scalable-vector
9753       // container types.
9754       if (ValVT.isFixedLengthVector())
9755         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9756       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9757     } else {
9758       // Try and pass the address via a "fast" GPR.
9759       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9760         LocInfo = CCValAssign::Indirect;
9761         LocVT = TLI.getSubtarget().getXLenVT();
9762         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9763       } else if (ValVT.isFixedLengthVector()) {
9764         auto StackAlign =
9765             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9766         unsigned StackOffset =
9767             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9768         State.addLoc(
9769             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9770       } else {
9771         // Can't pass scalable vectors on the stack.
9772         return true;
9773       }
9774     }
9775 
9776     return false;
9777   }
9778 
9779   return true; // CC didn't match.
9780 }
9781 
9782 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9783                          CCValAssign::LocInfo LocInfo,
9784                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9785 
9786   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9787     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9788     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9789     static const MCPhysReg GPRList[] = {
9790         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9791         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9792     if (unsigned Reg = State.AllocateReg(GPRList)) {
9793       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9794       return false;
9795     }
9796   }
9797 
9798   if (LocVT == MVT::f32) {
9799     // Pass in STG registers: F1, ..., F6
9800     //                        fs0 ... fs5
9801     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9802                                           RISCV::F18_F, RISCV::F19_F,
9803                                           RISCV::F20_F, RISCV::F21_F};
9804     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9805       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9806       return false;
9807     }
9808   }
9809 
9810   if (LocVT == MVT::f64) {
9811     // Pass in STG registers: D1, ..., D6
9812     //                        fs6 ... fs11
9813     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9814                                           RISCV::F24_D, RISCV::F25_D,
9815                                           RISCV::F26_D, RISCV::F27_D};
9816     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9817       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9818       return false;
9819     }
9820   }
9821 
9822   report_fatal_error("No registers left in GHC calling convention");
9823   return true;
9824 }
9825 
9826 // Transform physical registers into virtual registers.
9827 SDValue RISCVTargetLowering::LowerFormalArguments(
9828     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9829     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9830     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9831 
9832   MachineFunction &MF = DAG.getMachineFunction();
9833 
9834   switch (CallConv) {
9835   default:
9836     report_fatal_error("Unsupported calling convention");
9837   case CallingConv::C:
9838   case CallingConv::Fast:
9839     break;
9840   case CallingConv::GHC:
9841     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9842         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9843       report_fatal_error(
9844         "GHC calling convention requires the F and D instruction set extensions");
9845   }
9846 
9847   const Function &Func = MF.getFunction();
9848   if (Func.hasFnAttribute("interrupt")) {
9849     if (!Func.arg_empty())
9850       report_fatal_error(
9851         "Functions with the interrupt attribute cannot have arguments!");
9852 
9853     StringRef Kind =
9854       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9855 
9856     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9857       report_fatal_error(
9858         "Function interrupt attribute argument not supported!");
9859   }
9860 
9861   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9862   MVT XLenVT = Subtarget.getXLenVT();
9863   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9864   // Used with vargs to acumulate store chains.
9865   std::vector<SDValue> OutChains;
9866 
9867   // Assign locations to all of the incoming arguments.
9868   SmallVector<CCValAssign, 16> ArgLocs;
9869   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9870 
9871   if (CallConv == CallingConv::GHC)
9872     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9873   else
9874     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9875                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9876                                                    : CC_RISCV);
9877 
9878   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9879     CCValAssign &VA = ArgLocs[i];
9880     SDValue ArgValue;
9881     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9882     // case.
9883     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9884       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9885     else if (VA.isRegLoc())
9886       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9887     else
9888       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9889 
9890     if (VA.getLocInfo() == CCValAssign::Indirect) {
9891       // If the original argument was split and passed by reference (e.g. i128
9892       // on RV32), we need to load all parts of it here (using the same
9893       // address). Vectors may be partly split to registers and partly to the
9894       // stack, in which case the base address is partly offset and subsequent
9895       // stores are relative to that.
9896       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9897                                    MachinePointerInfo()));
9898       unsigned ArgIndex = Ins[i].OrigArgIndex;
9899       unsigned ArgPartOffset = Ins[i].PartOffset;
9900       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9901       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9902         CCValAssign &PartVA = ArgLocs[i + 1];
9903         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9904         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9905         if (PartVA.getValVT().isScalableVector())
9906           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9907         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9908         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9909                                      MachinePointerInfo()));
9910         ++i;
9911       }
9912       continue;
9913     }
9914     InVals.push_back(ArgValue);
9915   }
9916 
9917   if (IsVarArg) {
9918     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9919     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9920     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9921     MachineFrameInfo &MFI = MF.getFrameInfo();
9922     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9923     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9924 
9925     // Offset of the first variable argument from stack pointer, and size of
9926     // the vararg save area. For now, the varargs save area is either zero or
9927     // large enough to hold a0-a7.
9928     int VaArgOffset, VarArgsSaveSize;
9929 
9930     // If all registers are allocated, then all varargs must be passed on the
9931     // stack and we don't need to save any argregs.
9932     if (ArgRegs.size() == Idx) {
9933       VaArgOffset = CCInfo.getNextStackOffset();
9934       VarArgsSaveSize = 0;
9935     } else {
9936       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9937       VaArgOffset = -VarArgsSaveSize;
9938     }
9939 
9940     // Record the frame index of the first variable argument
9941     // which is a value necessary to VASTART.
9942     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9943     RVFI->setVarArgsFrameIndex(FI);
9944 
9945     // If saving an odd number of registers then create an extra stack slot to
9946     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9947     // offsets to even-numbered registered remain 2*XLEN-aligned.
9948     if (Idx % 2) {
9949       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9950       VarArgsSaveSize += XLenInBytes;
9951     }
9952 
9953     // Copy the integer registers that may have been used for passing varargs
9954     // to the vararg save area.
9955     for (unsigned I = Idx; I < ArgRegs.size();
9956          ++I, VaArgOffset += XLenInBytes) {
9957       const Register Reg = RegInfo.createVirtualRegister(RC);
9958       RegInfo.addLiveIn(ArgRegs[I], Reg);
9959       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9960       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9961       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9962       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9963                                    MachinePointerInfo::getFixedStack(MF, FI));
9964       cast<StoreSDNode>(Store.getNode())
9965           ->getMemOperand()
9966           ->setValue((Value *)nullptr);
9967       OutChains.push_back(Store);
9968     }
9969     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9970   }
9971 
9972   // All stores are grouped in one node to allow the matching between
9973   // the size of Ins and InVals. This only happens for vararg functions.
9974   if (!OutChains.empty()) {
9975     OutChains.push_back(Chain);
9976     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9977   }
9978 
9979   return Chain;
9980 }
9981 
9982 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9983 /// for tail call optimization.
9984 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9985 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9986     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9987     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9988 
9989   auto &Callee = CLI.Callee;
9990   auto CalleeCC = CLI.CallConv;
9991   auto &Outs = CLI.Outs;
9992   auto &Caller = MF.getFunction();
9993   auto CallerCC = Caller.getCallingConv();
9994 
9995   // Exception-handling functions need a special set of instructions to
9996   // indicate a return to the hardware. Tail-calling another function would
9997   // probably break this.
9998   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9999   // should be expanded as new function attributes are introduced.
10000   if (Caller.hasFnAttribute("interrupt"))
10001     return false;
10002 
10003   // Do not tail call opt if the stack is used to pass parameters.
10004   if (CCInfo.getNextStackOffset() != 0)
10005     return false;
10006 
10007   // Do not tail call opt if any parameters need to be passed indirectly.
10008   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10009   // passed indirectly. So the address of the value will be passed in a
10010   // register, or if not available, then the address is put on the stack. In
10011   // order to pass indirectly, space on the stack often needs to be allocated
10012   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10013   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10014   // are passed CCValAssign::Indirect.
10015   for (auto &VA : ArgLocs)
10016     if (VA.getLocInfo() == CCValAssign::Indirect)
10017       return false;
10018 
10019   // Do not tail call opt if either caller or callee uses struct return
10020   // semantics.
10021   auto IsCallerStructRet = Caller.hasStructRetAttr();
10022   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10023   if (IsCallerStructRet || IsCalleeStructRet)
10024     return false;
10025 
10026   // Externally-defined functions with weak linkage should not be
10027   // tail-called. The behaviour of branch instructions in this situation (as
10028   // used for tail calls) is implementation-defined, so we cannot rely on the
10029   // linker replacing the tail call with a return.
10030   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10031     const GlobalValue *GV = G->getGlobal();
10032     if (GV->hasExternalWeakLinkage())
10033       return false;
10034   }
10035 
10036   // The callee has to preserve all registers the caller needs to preserve.
10037   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10038   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10039   if (CalleeCC != CallerCC) {
10040     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10041     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10042       return false;
10043   }
10044 
10045   // Byval parameters hand the function a pointer directly into the stack area
10046   // we want to reuse during a tail call. Working around this *is* possible
10047   // but less efficient and uglier in LowerCall.
10048   for (auto &Arg : Outs)
10049     if (Arg.Flags.isByVal())
10050       return false;
10051 
10052   return true;
10053 }
10054 
10055 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10056   return DAG.getDataLayout().getPrefTypeAlign(
10057       VT.getTypeForEVT(*DAG.getContext()));
10058 }
10059 
10060 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10061 // and output parameter nodes.
10062 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10063                                        SmallVectorImpl<SDValue> &InVals) const {
10064   SelectionDAG &DAG = CLI.DAG;
10065   SDLoc &DL = CLI.DL;
10066   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10067   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10068   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10069   SDValue Chain = CLI.Chain;
10070   SDValue Callee = CLI.Callee;
10071   bool &IsTailCall = CLI.IsTailCall;
10072   CallingConv::ID CallConv = CLI.CallConv;
10073   bool IsVarArg = CLI.IsVarArg;
10074   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10075   MVT XLenVT = Subtarget.getXLenVT();
10076 
10077   MachineFunction &MF = DAG.getMachineFunction();
10078 
10079   // Analyze the operands of the call, assigning locations to each operand.
10080   SmallVector<CCValAssign, 16> ArgLocs;
10081   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10082 
10083   if (CallConv == CallingConv::GHC)
10084     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10085   else
10086     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10087                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10088                                                     : CC_RISCV);
10089 
10090   // Check if it's really possible to do a tail call.
10091   if (IsTailCall)
10092     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10093 
10094   if (IsTailCall)
10095     ++NumTailCalls;
10096   else if (CLI.CB && CLI.CB->isMustTailCall())
10097     report_fatal_error("failed to perform tail call elimination on a call "
10098                        "site marked musttail");
10099 
10100   // Get a count of how many bytes are to be pushed on the stack.
10101   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10102 
10103   // Create local copies for byval args
10104   SmallVector<SDValue, 8> ByValArgs;
10105   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10106     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10107     if (!Flags.isByVal())
10108       continue;
10109 
10110     SDValue Arg = OutVals[i];
10111     unsigned Size = Flags.getByValSize();
10112     Align Alignment = Flags.getNonZeroByValAlign();
10113 
10114     int FI =
10115         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10116     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10117     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10118 
10119     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10120                           /*IsVolatile=*/false,
10121                           /*AlwaysInline=*/false, IsTailCall,
10122                           MachinePointerInfo(), MachinePointerInfo());
10123     ByValArgs.push_back(FIPtr);
10124   }
10125 
10126   if (!IsTailCall)
10127     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10128 
10129   // Copy argument values to their designated locations.
10130   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10131   SmallVector<SDValue, 8> MemOpChains;
10132   SDValue StackPtr;
10133   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10134     CCValAssign &VA = ArgLocs[i];
10135     SDValue ArgValue = OutVals[i];
10136     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10137 
10138     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10139     bool IsF64OnRV32DSoftABI =
10140         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10141     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10142       SDValue SplitF64 = DAG.getNode(
10143           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10144       SDValue Lo = SplitF64.getValue(0);
10145       SDValue Hi = SplitF64.getValue(1);
10146 
10147       Register RegLo = VA.getLocReg();
10148       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10149 
10150       if (RegLo == RISCV::X17) {
10151         // Second half of f64 is passed on the stack.
10152         // Work out the address of the stack slot.
10153         if (!StackPtr.getNode())
10154           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10155         // Emit the store.
10156         MemOpChains.push_back(
10157             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10158       } else {
10159         // Second half of f64 is passed in another GPR.
10160         assert(RegLo < RISCV::X31 && "Invalid register pair");
10161         Register RegHigh = RegLo + 1;
10162         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10163       }
10164       continue;
10165     }
10166 
10167     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10168     // as any other MemLoc.
10169 
10170     // Promote the value if needed.
10171     // For now, only handle fully promoted and indirect arguments.
10172     if (VA.getLocInfo() == CCValAssign::Indirect) {
10173       // Store the argument in a stack slot and pass its address.
10174       Align StackAlign =
10175           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10176                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10177       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10178       // If the original argument was split (e.g. i128), we need
10179       // to store the required parts of it here (and pass just one address).
10180       // Vectors may be partly split to registers and partly to the stack, in
10181       // which case the base address is partly offset and subsequent stores are
10182       // relative to that.
10183       unsigned ArgIndex = Outs[i].OrigArgIndex;
10184       unsigned ArgPartOffset = Outs[i].PartOffset;
10185       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10186       // Calculate the total size to store. We don't have access to what we're
10187       // actually storing other than performing the loop and collecting the
10188       // info.
10189       SmallVector<std::pair<SDValue, SDValue>> Parts;
10190       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10191         SDValue PartValue = OutVals[i + 1];
10192         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10193         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10194         EVT PartVT = PartValue.getValueType();
10195         if (PartVT.isScalableVector())
10196           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10197         StoredSize += PartVT.getStoreSize();
10198         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10199         Parts.push_back(std::make_pair(PartValue, Offset));
10200         ++i;
10201       }
10202       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10203       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10204       MemOpChains.push_back(
10205           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10206                        MachinePointerInfo::getFixedStack(MF, FI)));
10207       for (const auto &Part : Parts) {
10208         SDValue PartValue = Part.first;
10209         SDValue PartOffset = Part.second;
10210         SDValue Address =
10211             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10212         MemOpChains.push_back(
10213             DAG.getStore(Chain, DL, PartValue, Address,
10214                          MachinePointerInfo::getFixedStack(MF, FI)));
10215       }
10216       ArgValue = SpillSlot;
10217     } else {
10218       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10219     }
10220 
10221     // Use local copy if it is a byval arg.
10222     if (Flags.isByVal())
10223       ArgValue = ByValArgs[j++];
10224 
10225     if (VA.isRegLoc()) {
10226       // Queue up the argument copies and emit them at the end.
10227       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10228     } else {
10229       assert(VA.isMemLoc() && "Argument not register or memory");
10230       assert(!IsTailCall && "Tail call not allowed if stack is used "
10231                             "for passing parameters");
10232 
10233       // Work out the address of the stack slot.
10234       if (!StackPtr.getNode())
10235         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10236       SDValue Address =
10237           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10238                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10239 
10240       // Emit the store.
10241       MemOpChains.push_back(
10242           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10243     }
10244   }
10245 
10246   // Join the stores, which are independent of one another.
10247   if (!MemOpChains.empty())
10248     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10249 
10250   SDValue Glue;
10251 
10252   // Build a sequence of copy-to-reg nodes, chained and glued together.
10253   for (auto &Reg : RegsToPass) {
10254     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10255     Glue = Chain.getValue(1);
10256   }
10257 
10258   // Validate that none of the argument registers have been marked as
10259   // reserved, if so report an error. Do the same for the return address if this
10260   // is not a tailcall.
10261   validateCCReservedRegs(RegsToPass, MF);
10262   if (!IsTailCall &&
10263       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10264     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10265         MF.getFunction(),
10266         "Return address register required, but has been reserved."});
10267 
10268   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10269   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10270   // split it and then direct call can be matched by PseudoCALL.
10271   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10272     const GlobalValue *GV = S->getGlobal();
10273 
10274     unsigned OpFlags = RISCVII::MO_CALL;
10275     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10276       OpFlags = RISCVII::MO_PLT;
10277 
10278     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10279   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10280     unsigned OpFlags = RISCVII::MO_CALL;
10281 
10282     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10283                                                  nullptr))
10284       OpFlags = RISCVII::MO_PLT;
10285 
10286     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10287   }
10288 
10289   // The first call operand is the chain and the second is the target address.
10290   SmallVector<SDValue, 8> Ops;
10291   Ops.push_back(Chain);
10292   Ops.push_back(Callee);
10293 
10294   // Add argument registers to the end of the list so that they are
10295   // known live into the call.
10296   for (auto &Reg : RegsToPass)
10297     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10298 
10299   if (!IsTailCall) {
10300     // Add a register mask operand representing the call-preserved registers.
10301     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10302     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10303     assert(Mask && "Missing call preserved mask for calling convention");
10304     Ops.push_back(DAG.getRegisterMask(Mask));
10305   }
10306 
10307   // Glue the call to the argument copies, if any.
10308   if (Glue.getNode())
10309     Ops.push_back(Glue);
10310 
10311   // Emit the call.
10312   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10313 
10314   if (IsTailCall) {
10315     MF.getFrameInfo().setHasTailCall();
10316     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10317   }
10318 
10319   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10320   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10321   Glue = Chain.getValue(1);
10322 
10323   // Mark the end of the call, which is glued to the call itself.
10324   Chain = DAG.getCALLSEQ_END(Chain,
10325                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10326                              DAG.getConstant(0, DL, PtrVT, true),
10327                              Glue, DL);
10328   Glue = Chain.getValue(1);
10329 
10330   // Assign locations to each value returned by this call.
10331   SmallVector<CCValAssign, 16> RVLocs;
10332   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10333   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10334 
10335   // Copy all of the result registers out of their specified physreg.
10336   for (auto &VA : RVLocs) {
10337     // Copy the value out
10338     SDValue RetValue =
10339         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10340     // Glue the RetValue to the end of the call sequence
10341     Chain = RetValue.getValue(1);
10342     Glue = RetValue.getValue(2);
10343 
10344     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10345       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10346       SDValue RetValue2 =
10347           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10348       Chain = RetValue2.getValue(1);
10349       Glue = RetValue2.getValue(2);
10350       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10351                              RetValue2);
10352     }
10353 
10354     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10355 
10356     InVals.push_back(RetValue);
10357   }
10358 
10359   return Chain;
10360 }
10361 
10362 bool RISCVTargetLowering::CanLowerReturn(
10363     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10364     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10365   SmallVector<CCValAssign, 16> RVLocs;
10366   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10367 
10368   Optional<unsigned> FirstMaskArgument;
10369   if (Subtarget.hasVInstructions())
10370     FirstMaskArgument = preAssignMask(Outs);
10371 
10372   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10373     MVT VT = Outs[i].VT;
10374     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10375     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10376     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10377                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10378                  *this, FirstMaskArgument))
10379       return false;
10380   }
10381   return true;
10382 }
10383 
10384 SDValue
10385 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10386                                  bool IsVarArg,
10387                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10388                                  const SmallVectorImpl<SDValue> &OutVals,
10389                                  const SDLoc &DL, SelectionDAG &DAG) const {
10390   const MachineFunction &MF = DAG.getMachineFunction();
10391   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10392 
10393   // Stores the assignment of the return value to a location.
10394   SmallVector<CCValAssign, 16> RVLocs;
10395 
10396   // Info about the registers and stack slot.
10397   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10398                  *DAG.getContext());
10399 
10400   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10401                     nullptr, CC_RISCV);
10402 
10403   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10404     report_fatal_error("GHC functions return void only");
10405 
10406   SDValue Glue;
10407   SmallVector<SDValue, 4> RetOps(1, Chain);
10408 
10409   // Copy the result values into the output registers.
10410   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10411     SDValue Val = OutVals[i];
10412     CCValAssign &VA = RVLocs[i];
10413     assert(VA.isRegLoc() && "Can only return in registers!");
10414 
10415     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10416       // Handle returning f64 on RV32D with a soft float ABI.
10417       assert(VA.isRegLoc() && "Expected return via registers");
10418       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10419                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10420       SDValue Lo = SplitF64.getValue(0);
10421       SDValue Hi = SplitF64.getValue(1);
10422       Register RegLo = VA.getLocReg();
10423       assert(RegLo < RISCV::X31 && "Invalid register pair");
10424       Register RegHi = RegLo + 1;
10425 
10426       if (STI.isRegisterReservedByUser(RegLo) ||
10427           STI.isRegisterReservedByUser(RegHi))
10428         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10429             MF.getFunction(),
10430             "Return value register required, but has been reserved."});
10431 
10432       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10433       Glue = Chain.getValue(1);
10434       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10435       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10436       Glue = Chain.getValue(1);
10437       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10438     } else {
10439       // Handle a 'normal' return.
10440       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10441       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10442 
10443       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10444         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10445             MF.getFunction(),
10446             "Return value register required, but has been reserved."});
10447 
10448       // Guarantee that all emitted copies are stuck together.
10449       Glue = Chain.getValue(1);
10450       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10451     }
10452   }
10453 
10454   RetOps[0] = Chain; // Update chain.
10455 
10456   // Add the glue node if we have it.
10457   if (Glue.getNode()) {
10458     RetOps.push_back(Glue);
10459   }
10460 
10461   unsigned RetOpc = RISCVISD::RET_FLAG;
10462   // Interrupt service routines use different return instructions.
10463   const Function &Func = DAG.getMachineFunction().getFunction();
10464   if (Func.hasFnAttribute("interrupt")) {
10465     if (!Func.getReturnType()->isVoidTy())
10466       report_fatal_error(
10467           "Functions with the interrupt attribute must have void return type!");
10468 
10469     MachineFunction &MF = DAG.getMachineFunction();
10470     StringRef Kind =
10471       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10472 
10473     if (Kind == "user")
10474       RetOpc = RISCVISD::URET_FLAG;
10475     else if (Kind == "supervisor")
10476       RetOpc = RISCVISD::SRET_FLAG;
10477     else
10478       RetOpc = RISCVISD::MRET_FLAG;
10479   }
10480 
10481   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10482 }
10483 
10484 void RISCVTargetLowering::validateCCReservedRegs(
10485     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10486     MachineFunction &MF) const {
10487   const Function &F = MF.getFunction();
10488   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10489 
10490   if (llvm::any_of(Regs, [&STI](auto Reg) {
10491         return STI.isRegisterReservedByUser(Reg.first);
10492       }))
10493     F.getContext().diagnose(DiagnosticInfoUnsupported{
10494         F, "Argument register required, but has been reserved."});
10495 }
10496 
10497 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10498   return CI->isTailCall();
10499 }
10500 
10501 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10502 #define NODE_NAME_CASE(NODE)                                                   \
10503   case RISCVISD::NODE:                                                         \
10504     return "RISCVISD::" #NODE;
10505   // clang-format off
10506   switch ((RISCVISD::NodeType)Opcode) {
10507   case RISCVISD::FIRST_NUMBER:
10508     break;
10509   NODE_NAME_CASE(RET_FLAG)
10510   NODE_NAME_CASE(URET_FLAG)
10511   NODE_NAME_CASE(SRET_FLAG)
10512   NODE_NAME_CASE(MRET_FLAG)
10513   NODE_NAME_CASE(CALL)
10514   NODE_NAME_CASE(SELECT_CC)
10515   NODE_NAME_CASE(BR_CC)
10516   NODE_NAME_CASE(BuildPairF64)
10517   NODE_NAME_CASE(SplitF64)
10518   NODE_NAME_CASE(TAIL)
10519   NODE_NAME_CASE(MULHSU)
10520   NODE_NAME_CASE(SLLW)
10521   NODE_NAME_CASE(SRAW)
10522   NODE_NAME_CASE(SRLW)
10523   NODE_NAME_CASE(DIVW)
10524   NODE_NAME_CASE(DIVUW)
10525   NODE_NAME_CASE(REMUW)
10526   NODE_NAME_CASE(ROLW)
10527   NODE_NAME_CASE(RORW)
10528   NODE_NAME_CASE(CLZW)
10529   NODE_NAME_CASE(CTZW)
10530   NODE_NAME_CASE(FSLW)
10531   NODE_NAME_CASE(FSRW)
10532   NODE_NAME_CASE(FSL)
10533   NODE_NAME_CASE(FSR)
10534   NODE_NAME_CASE(FMV_H_X)
10535   NODE_NAME_CASE(FMV_X_ANYEXTH)
10536   NODE_NAME_CASE(FMV_W_X_RV64)
10537   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10538   NODE_NAME_CASE(FCVT_X)
10539   NODE_NAME_CASE(FCVT_XU)
10540   NODE_NAME_CASE(FCVT_W_RV64)
10541   NODE_NAME_CASE(FCVT_WU_RV64)
10542   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10543   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10544   NODE_NAME_CASE(READ_CYCLE_WIDE)
10545   NODE_NAME_CASE(GREV)
10546   NODE_NAME_CASE(GREVW)
10547   NODE_NAME_CASE(GORC)
10548   NODE_NAME_CASE(GORCW)
10549   NODE_NAME_CASE(SHFL)
10550   NODE_NAME_CASE(SHFLW)
10551   NODE_NAME_CASE(UNSHFL)
10552   NODE_NAME_CASE(UNSHFLW)
10553   NODE_NAME_CASE(BFP)
10554   NODE_NAME_CASE(BFPW)
10555   NODE_NAME_CASE(BCOMPRESS)
10556   NODE_NAME_CASE(BCOMPRESSW)
10557   NODE_NAME_CASE(BDECOMPRESS)
10558   NODE_NAME_CASE(BDECOMPRESSW)
10559   NODE_NAME_CASE(VMV_V_X_VL)
10560   NODE_NAME_CASE(VFMV_V_F_VL)
10561   NODE_NAME_CASE(VMV_X_S)
10562   NODE_NAME_CASE(VMV_S_X_VL)
10563   NODE_NAME_CASE(VFMV_S_F_VL)
10564   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10565   NODE_NAME_CASE(READ_VLENB)
10566   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10567   NODE_NAME_CASE(VSLIDEUP_VL)
10568   NODE_NAME_CASE(VSLIDE1UP_VL)
10569   NODE_NAME_CASE(VSLIDEDOWN_VL)
10570   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10571   NODE_NAME_CASE(VID_VL)
10572   NODE_NAME_CASE(VFNCVT_ROD_VL)
10573   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10574   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10575   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10576   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10577   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10578   NODE_NAME_CASE(VECREDUCE_AND_VL)
10579   NODE_NAME_CASE(VECREDUCE_OR_VL)
10580   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10581   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10582   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10583   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10584   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10585   NODE_NAME_CASE(ADD_VL)
10586   NODE_NAME_CASE(AND_VL)
10587   NODE_NAME_CASE(MUL_VL)
10588   NODE_NAME_CASE(OR_VL)
10589   NODE_NAME_CASE(SDIV_VL)
10590   NODE_NAME_CASE(SHL_VL)
10591   NODE_NAME_CASE(SREM_VL)
10592   NODE_NAME_CASE(SRA_VL)
10593   NODE_NAME_CASE(SRL_VL)
10594   NODE_NAME_CASE(SUB_VL)
10595   NODE_NAME_CASE(UDIV_VL)
10596   NODE_NAME_CASE(UREM_VL)
10597   NODE_NAME_CASE(XOR_VL)
10598   NODE_NAME_CASE(SADDSAT_VL)
10599   NODE_NAME_CASE(UADDSAT_VL)
10600   NODE_NAME_CASE(SSUBSAT_VL)
10601   NODE_NAME_CASE(USUBSAT_VL)
10602   NODE_NAME_CASE(FADD_VL)
10603   NODE_NAME_CASE(FSUB_VL)
10604   NODE_NAME_CASE(FMUL_VL)
10605   NODE_NAME_CASE(FDIV_VL)
10606   NODE_NAME_CASE(FNEG_VL)
10607   NODE_NAME_CASE(FABS_VL)
10608   NODE_NAME_CASE(FSQRT_VL)
10609   NODE_NAME_CASE(FMA_VL)
10610   NODE_NAME_CASE(FCOPYSIGN_VL)
10611   NODE_NAME_CASE(SMIN_VL)
10612   NODE_NAME_CASE(SMAX_VL)
10613   NODE_NAME_CASE(UMIN_VL)
10614   NODE_NAME_CASE(UMAX_VL)
10615   NODE_NAME_CASE(FMINNUM_VL)
10616   NODE_NAME_CASE(FMAXNUM_VL)
10617   NODE_NAME_CASE(MULHS_VL)
10618   NODE_NAME_CASE(MULHU_VL)
10619   NODE_NAME_CASE(FP_TO_SINT_VL)
10620   NODE_NAME_CASE(FP_TO_UINT_VL)
10621   NODE_NAME_CASE(SINT_TO_FP_VL)
10622   NODE_NAME_CASE(UINT_TO_FP_VL)
10623   NODE_NAME_CASE(FP_EXTEND_VL)
10624   NODE_NAME_CASE(FP_ROUND_VL)
10625   NODE_NAME_CASE(VWMUL_VL)
10626   NODE_NAME_CASE(VWMULU_VL)
10627   NODE_NAME_CASE(VWMULSU_VL)
10628   NODE_NAME_CASE(VWADD_VL)
10629   NODE_NAME_CASE(VWADDU_VL)
10630   NODE_NAME_CASE(VWSUB_VL)
10631   NODE_NAME_CASE(VWSUBU_VL)
10632   NODE_NAME_CASE(VWADD_W_VL)
10633   NODE_NAME_CASE(VWADDU_W_VL)
10634   NODE_NAME_CASE(VWSUB_W_VL)
10635   NODE_NAME_CASE(VWSUBU_W_VL)
10636   NODE_NAME_CASE(SETCC_VL)
10637   NODE_NAME_CASE(VSELECT_VL)
10638   NODE_NAME_CASE(VP_MERGE_VL)
10639   NODE_NAME_CASE(VMAND_VL)
10640   NODE_NAME_CASE(VMOR_VL)
10641   NODE_NAME_CASE(VMXOR_VL)
10642   NODE_NAME_CASE(VMCLR_VL)
10643   NODE_NAME_CASE(VMSET_VL)
10644   NODE_NAME_CASE(VRGATHER_VX_VL)
10645   NODE_NAME_CASE(VRGATHER_VV_VL)
10646   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10647   NODE_NAME_CASE(VSEXT_VL)
10648   NODE_NAME_CASE(VZEXT_VL)
10649   NODE_NAME_CASE(VCPOP_VL)
10650   NODE_NAME_CASE(VLE_VL)
10651   NODE_NAME_CASE(VSE_VL)
10652   NODE_NAME_CASE(READ_CSR)
10653   NODE_NAME_CASE(WRITE_CSR)
10654   NODE_NAME_CASE(SWAP_CSR)
10655   }
10656   // clang-format on
10657   return nullptr;
10658 #undef NODE_NAME_CASE
10659 }
10660 
10661 /// getConstraintType - Given a constraint letter, return the type of
10662 /// constraint it is for this target.
10663 RISCVTargetLowering::ConstraintType
10664 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10665   if (Constraint.size() == 1) {
10666     switch (Constraint[0]) {
10667     default:
10668       break;
10669     case 'f':
10670       return C_RegisterClass;
10671     case 'I':
10672     case 'J':
10673     case 'K':
10674       return C_Immediate;
10675     case 'A':
10676       return C_Memory;
10677     case 'S': // A symbolic address
10678       return C_Other;
10679     }
10680   } else {
10681     if (Constraint == "vr" || Constraint == "vm")
10682       return C_RegisterClass;
10683   }
10684   return TargetLowering::getConstraintType(Constraint);
10685 }
10686 
10687 std::pair<unsigned, const TargetRegisterClass *>
10688 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10689                                                   StringRef Constraint,
10690                                                   MVT VT) const {
10691   // First, see if this is a constraint that directly corresponds to a
10692   // RISCV register class.
10693   if (Constraint.size() == 1) {
10694     switch (Constraint[0]) {
10695     case 'r':
10696       // TODO: Support fixed vectors up to XLen for P extension?
10697       if (VT.isVector())
10698         break;
10699       return std::make_pair(0U, &RISCV::GPRRegClass);
10700     case 'f':
10701       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10702         return std::make_pair(0U, &RISCV::FPR16RegClass);
10703       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10704         return std::make_pair(0U, &RISCV::FPR32RegClass);
10705       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10706         return std::make_pair(0U, &RISCV::FPR64RegClass);
10707       break;
10708     default:
10709       break;
10710     }
10711   } else if (Constraint == "vr") {
10712     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10713                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10714       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10715         return std::make_pair(0U, RC);
10716     }
10717   } else if (Constraint == "vm") {
10718     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10719       return std::make_pair(0U, &RISCV::VMV0RegClass);
10720   }
10721 
10722   // Clang will correctly decode the usage of register name aliases into their
10723   // official names. However, other frontends like `rustc` do not. This allows
10724   // users of these frontends to use the ABI names for registers in LLVM-style
10725   // register constraints.
10726   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10727                                .Case("{zero}", RISCV::X0)
10728                                .Case("{ra}", RISCV::X1)
10729                                .Case("{sp}", RISCV::X2)
10730                                .Case("{gp}", RISCV::X3)
10731                                .Case("{tp}", RISCV::X4)
10732                                .Case("{t0}", RISCV::X5)
10733                                .Case("{t1}", RISCV::X6)
10734                                .Case("{t2}", RISCV::X7)
10735                                .Cases("{s0}", "{fp}", RISCV::X8)
10736                                .Case("{s1}", RISCV::X9)
10737                                .Case("{a0}", RISCV::X10)
10738                                .Case("{a1}", RISCV::X11)
10739                                .Case("{a2}", RISCV::X12)
10740                                .Case("{a3}", RISCV::X13)
10741                                .Case("{a4}", RISCV::X14)
10742                                .Case("{a5}", RISCV::X15)
10743                                .Case("{a6}", RISCV::X16)
10744                                .Case("{a7}", RISCV::X17)
10745                                .Case("{s2}", RISCV::X18)
10746                                .Case("{s3}", RISCV::X19)
10747                                .Case("{s4}", RISCV::X20)
10748                                .Case("{s5}", RISCV::X21)
10749                                .Case("{s6}", RISCV::X22)
10750                                .Case("{s7}", RISCV::X23)
10751                                .Case("{s8}", RISCV::X24)
10752                                .Case("{s9}", RISCV::X25)
10753                                .Case("{s10}", RISCV::X26)
10754                                .Case("{s11}", RISCV::X27)
10755                                .Case("{t3}", RISCV::X28)
10756                                .Case("{t4}", RISCV::X29)
10757                                .Case("{t5}", RISCV::X30)
10758                                .Case("{t6}", RISCV::X31)
10759                                .Default(RISCV::NoRegister);
10760   if (XRegFromAlias != RISCV::NoRegister)
10761     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10762 
10763   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10764   // TableGen record rather than the AsmName to choose registers for InlineAsm
10765   // constraints, plus we want to match those names to the widest floating point
10766   // register type available, manually select floating point registers here.
10767   //
10768   // The second case is the ABI name of the register, so that frontends can also
10769   // use the ABI names in register constraint lists.
10770   if (Subtarget.hasStdExtF()) {
10771     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10772                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10773                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10774                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10775                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10776                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10777                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10778                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10779                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10780                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10781                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10782                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10783                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10784                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10785                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10786                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10787                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10788                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10789                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10790                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10791                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10792                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10793                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10794                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10795                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10796                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10797                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10798                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10799                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10800                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10801                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10802                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10803                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10804                         .Default(RISCV::NoRegister);
10805     if (FReg != RISCV::NoRegister) {
10806       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10807       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10808         unsigned RegNo = FReg - RISCV::F0_F;
10809         unsigned DReg = RISCV::F0_D + RegNo;
10810         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10811       }
10812       if (VT == MVT::f32 || VT == MVT::Other)
10813         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10814       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10815         unsigned RegNo = FReg - RISCV::F0_F;
10816         unsigned HReg = RISCV::F0_H + RegNo;
10817         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10818       }
10819     }
10820   }
10821 
10822   if (Subtarget.hasVInstructions()) {
10823     Register VReg = StringSwitch<Register>(Constraint.lower())
10824                         .Case("{v0}", RISCV::V0)
10825                         .Case("{v1}", RISCV::V1)
10826                         .Case("{v2}", RISCV::V2)
10827                         .Case("{v3}", RISCV::V3)
10828                         .Case("{v4}", RISCV::V4)
10829                         .Case("{v5}", RISCV::V5)
10830                         .Case("{v6}", RISCV::V6)
10831                         .Case("{v7}", RISCV::V7)
10832                         .Case("{v8}", RISCV::V8)
10833                         .Case("{v9}", RISCV::V9)
10834                         .Case("{v10}", RISCV::V10)
10835                         .Case("{v11}", RISCV::V11)
10836                         .Case("{v12}", RISCV::V12)
10837                         .Case("{v13}", RISCV::V13)
10838                         .Case("{v14}", RISCV::V14)
10839                         .Case("{v15}", RISCV::V15)
10840                         .Case("{v16}", RISCV::V16)
10841                         .Case("{v17}", RISCV::V17)
10842                         .Case("{v18}", RISCV::V18)
10843                         .Case("{v19}", RISCV::V19)
10844                         .Case("{v20}", RISCV::V20)
10845                         .Case("{v21}", RISCV::V21)
10846                         .Case("{v22}", RISCV::V22)
10847                         .Case("{v23}", RISCV::V23)
10848                         .Case("{v24}", RISCV::V24)
10849                         .Case("{v25}", RISCV::V25)
10850                         .Case("{v26}", RISCV::V26)
10851                         .Case("{v27}", RISCV::V27)
10852                         .Case("{v28}", RISCV::V28)
10853                         .Case("{v29}", RISCV::V29)
10854                         .Case("{v30}", RISCV::V30)
10855                         .Case("{v31}", RISCV::V31)
10856                         .Default(RISCV::NoRegister);
10857     if (VReg != RISCV::NoRegister) {
10858       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10859         return std::make_pair(VReg, &RISCV::VMRegClass);
10860       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10861         return std::make_pair(VReg, &RISCV::VRRegClass);
10862       for (const auto *RC :
10863            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10864         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10865           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10866           return std::make_pair(VReg, RC);
10867         }
10868       }
10869     }
10870   }
10871 
10872   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10873 }
10874 
10875 unsigned
10876 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10877   // Currently only support length 1 constraints.
10878   if (ConstraintCode.size() == 1) {
10879     switch (ConstraintCode[0]) {
10880     case 'A':
10881       return InlineAsm::Constraint_A;
10882     default:
10883       break;
10884     }
10885   }
10886 
10887   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10888 }
10889 
10890 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10891     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10892     SelectionDAG &DAG) const {
10893   // Currently only support length 1 constraints.
10894   if (Constraint.length() == 1) {
10895     switch (Constraint[0]) {
10896     case 'I':
10897       // Validate & create a 12-bit signed immediate operand.
10898       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10899         uint64_t CVal = C->getSExtValue();
10900         if (isInt<12>(CVal))
10901           Ops.push_back(
10902               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10903       }
10904       return;
10905     case 'J':
10906       // Validate & create an integer zero operand.
10907       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10908         if (C->getZExtValue() == 0)
10909           Ops.push_back(
10910               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10911       return;
10912     case 'K':
10913       // Validate & create a 5-bit unsigned immediate operand.
10914       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10915         uint64_t CVal = C->getZExtValue();
10916         if (isUInt<5>(CVal))
10917           Ops.push_back(
10918               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10919       }
10920       return;
10921     case 'S':
10922       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10923         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10924                                                  GA->getValueType(0)));
10925       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10926         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10927                                                 BA->getValueType(0)));
10928       }
10929       return;
10930     default:
10931       break;
10932     }
10933   }
10934   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10935 }
10936 
10937 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10938                                                    Instruction *Inst,
10939                                                    AtomicOrdering Ord) const {
10940   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10941     return Builder.CreateFence(Ord);
10942   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10943     return Builder.CreateFence(AtomicOrdering::Release);
10944   return nullptr;
10945 }
10946 
10947 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10948                                                     Instruction *Inst,
10949                                                     AtomicOrdering Ord) const {
10950   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10951     return Builder.CreateFence(AtomicOrdering::Acquire);
10952   return nullptr;
10953 }
10954 
10955 TargetLowering::AtomicExpansionKind
10956 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10957   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10958   // point operations can't be used in an lr/sc sequence without breaking the
10959   // forward-progress guarantee.
10960   if (AI->isFloatingPointOperation())
10961     return AtomicExpansionKind::CmpXChg;
10962 
10963   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10964   if (Size == 8 || Size == 16)
10965     return AtomicExpansionKind::MaskedIntrinsic;
10966   return AtomicExpansionKind::None;
10967 }
10968 
10969 static Intrinsic::ID
10970 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10971   if (XLen == 32) {
10972     switch (BinOp) {
10973     default:
10974       llvm_unreachable("Unexpected AtomicRMW BinOp");
10975     case AtomicRMWInst::Xchg:
10976       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10977     case AtomicRMWInst::Add:
10978       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10979     case AtomicRMWInst::Sub:
10980       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10981     case AtomicRMWInst::Nand:
10982       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10983     case AtomicRMWInst::Max:
10984       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10985     case AtomicRMWInst::Min:
10986       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10987     case AtomicRMWInst::UMax:
10988       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10989     case AtomicRMWInst::UMin:
10990       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10991     }
10992   }
10993 
10994   if (XLen == 64) {
10995     switch (BinOp) {
10996     default:
10997       llvm_unreachable("Unexpected AtomicRMW BinOp");
10998     case AtomicRMWInst::Xchg:
10999       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11000     case AtomicRMWInst::Add:
11001       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11002     case AtomicRMWInst::Sub:
11003       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11004     case AtomicRMWInst::Nand:
11005       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11006     case AtomicRMWInst::Max:
11007       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11008     case AtomicRMWInst::Min:
11009       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11010     case AtomicRMWInst::UMax:
11011       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11012     case AtomicRMWInst::UMin:
11013       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11014     }
11015   }
11016 
11017   llvm_unreachable("Unexpected XLen\n");
11018 }
11019 
11020 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11021     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11022     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11023   unsigned XLen = Subtarget.getXLen();
11024   Value *Ordering =
11025       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11026   Type *Tys[] = {AlignedAddr->getType()};
11027   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11028       AI->getModule(),
11029       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11030 
11031   if (XLen == 64) {
11032     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11033     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11034     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11035   }
11036 
11037   Value *Result;
11038 
11039   // Must pass the shift amount needed to sign extend the loaded value prior
11040   // to performing a signed comparison for min/max. ShiftAmt is the number of
11041   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11042   // is the number of bits to left+right shift the value in order to
11043   // sign-extend.
11044   if (AI->getOperation() == AtomicRMWInst::Min ||
11045       AI->getOperation() == AtomicRMWInst::Max) {
11046     const DataLayout &DL = AI->getModule()->getDataLayout();
11047     unsigned ValWidth =
11048         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11049     Value *SextShamt =
11050         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11051     Result = Builder.CreateCall(LrwOpScwLoop,
11052                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11053   } else {
11054     Result =
11055         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11056   }
11057 
11058   if (XLen == 64)
11059     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11060   return Result;
11061 }
11062 
11063 TargetLowering::AtomicExpansionKind
11064 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11065     AtomicCmpXchgInst *CI) const {
11066   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11067   if (Size == 8 || Size == 16)
11068     return AtomicExpansionKind::MaskedIntrinsic;
11069   return AtomicExpansionKind::None;
11070 }
11071 
11072 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11073     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11074     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11075   unsigned XLen = Subtarget.getXLen();
11076   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11077   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11078   if (XLen == 64) {
11079     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11080     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11081     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11082     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11083   }
11084   Type *Tys[] = {AlignedAddr->getType()};
11085   Function *MaskedCmpXchg =
11086       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11087   Value *Result = Builder.CreateCall(
11088       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11089   if (XLen == 64)
11090     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11091   return Result;
11092 }
11093 
11094 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11095   return false;
11096 }
11097 
11098 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11099                                                EVT VT) const {
11100   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11101     return false;
11102 
11103   switch (FPVT.getSimpleVT().SimpleTy) {
11104   case MVT::f16:
11105     return Subtarget.hasStdExtZfh();
11106   case MVT::f32:
11107     return Subtarget.hasStdExtF();
11108   case MVT::f64:
11109     return Subtarget.hasStdExtD();
11110   default:
11111     return false;
11112   }
11113 }
11114 
11115 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11116   // If we are using the small code model, we can reduce size of jump table
11117   // entry to 4 bytes.
11118   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11119       getTargetMachine().getCodeModel() == CodeModel::Small) {
11120     return MachineJumpTableInfo::EK_Custom32;
11121   }
11122   return TargetLowering::getJumpTableEncoding();
11123 }
11124 
11125 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11126     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11127     unsigned uid, MCContext &Ctx) const {
11128   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11129          getTargetMachine().getCodeModel() == CodeModel::Small);
11130   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11131 }
11132 
11133 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11134                                                      EVT VT) const {
11135   VT = VT.getScalarType();
11136 
11137   if (!VT.isSimple())
11138     return false;
11139 
11140   switch (VT.getSimpleVT().SimpleTy) {
11141   case MVT::f16:
11142     return Subtarget.hasStdExtZfh();
11143   case MVT::f32:
11144     return Subtarget.hasStdExtF();
11145   case MVT::f64:
11146     return Subtarget.hasStdExtD();
11147   default:
11148     break;
11149   }
11150 
11151   return false;
11152 }
11153 
11154 Register RISCVTargetLowering::getExceptionPointerRegister(
11155     const Constant *PersonalityFn) const {
11156   return RISCV::X10;
11157 }
11158 
11159 Register RISCVTargetLowering::getExceptionSelectorRegister(
11160     const Constant *PersonalityFn) const {
11161   return RISCV::X11;
11162 }
11163 
11164 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11165   // Return false to suppress the unnecessary extensions if the LibCall
11166   // arguments or return value is f32 type for LP64 ABI.
11167   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11168   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11169     return false;
11170 
11171   return true;
11172 }
11173 
11174 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11175   if (Subtarget.is64Bit() && Type == MVT::i32)
11176     return true;
11177 
11178   return IsSigned;
11179 }
11180 
11181 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11182                                                  SDValue C) const {
11183   // Check integral scalar types.
11184   if (VT.isScalarInteger()) {
11185     // Omit the optimization if the sub target has the M extension and the data
11186     // size exceeds XLen.
11187     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11188       return false;
11189     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11190       // Break the MUL to a SLLI and an ADD/SUB.
11191       const APInt &Imm = ConstNode->getAPIntValue();
11192       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11193           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11194         return true;
11195       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11196       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11197           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11198            (Imm - 8).isPowerOf2()))
11199         return true;
11200       // Omit the following optimization if the sub target has the M extension
11201       // and the data size >= XLen.
11202       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11203         return false;
11204       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11205       // a pair of LUI/ADDI.
11206       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11207         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11208         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11209             (1 - ImmS).isPowerOf2())
11210         return true;
11211       }
11212     }
11213   }
11214 
11215   return false;
11216 }
11217 
11218 bool RISCVTargetLowering::isMulAddWithConstProfitable(
11219     const SDValue &AddNode, const SDValue &ConstNode) const {
11220   // Let the DAGCombiner decide for vectors.
11221   EVT VT = AddNode.getValueType();
11222   if (VT.isVector())
11223     return true;
11224 
11225   // Let the DAGCombiner decide for larger types.
11226   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11227     return true;
11228 
11229   // It is worse if c1 is simm12 while c1*c2 is not.
11230   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11231   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11232   const APInt &C1 = C1Node->getAPIntValue();
11233   const APInt &C2 = C2Node->getAPIntValue();
11234   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11235     return false;
11236 
11237   // Default to true and let the DAGCombiner decide.
11238   return true;
11239 }
11240 
11241 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11242     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11243     bool *Fast) const {
11244   if (!VT.isVector())
11245     return false;
11246 
11247   EVT ElemVT = VT.getVectorElementType();
11248   if (Alignment >= ElemVT.getStoreSize()) {
11249     if (Fast)
11250       *Fast = true;
11251     return true;
11252   }
11253 
11254   return false;
11255 }
11256 
11257 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11258     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11259     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11260   bool IsABIRegCopy = CC.hasValue();
11261   EVT ValueVT = Val.getValueType();
11262   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11263     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11264     // and cast to f32.
11265     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11266     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11267     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11268                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11269     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11270     Parts[0] = Val;
11271     return true;
11272   }
11273 
11274   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11275     LLVMContext &Context = *DAG.getContext();
11276     EVT ValueEltVT = ValueVT.getVectorElementType();
11277     EVT PartEltVT = PartVT.getVectorElementType();
11278     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11279     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11280     if (PartVTBitSize % ValueVTBitSize == 0) {
11281       assert(PartVTBitSize >= ValueVTBitSize);
11282       // If the element types are different, bitcast to the same element type of
11283       // PartVT first.
11284       // Give an example here, we want copy a <vscale x 1 x i8> value to
11285       // <vscale x 4 x i16>.
11286       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11287       // subvector, then we can bitcast to <vscale x 4 x i16>.
11288       if (ValueEltVT != PartEltVT) {
11289         if (PartVTBitSize > ValueVTBitSize) {
11290           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11291           assert(Count != 0 && "The number of element should not be zero.");
11292           EVT SameEltTypeVT =
11293               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11294           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11295                             DAG.getUNDEF(SameEltTypeVT), Val,
11296                             DAG.getVectorIdxConstant(0, DL));
11297         }
11298         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11299       } else {
11300         Val =
11301             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11302                         Val, DAG.getVectorIdxConstant(0, DL));
11303       }
11304       Parts[0] = Val;
11305       return true;
11306     }
11307   }
11308   return false;
11309 }
11310 
11311 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11312     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11313     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11314   bool IsABIRegCopy = CC.hasValue();
11315   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11316     SDValue Val = Parts[0];
11317 
11318     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11319     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11320     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11321     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11322     return Val;
11323   }
11324 
11325   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11326     LLVMContext &Context = *DAG.getContext();
11327     SDValue Val = Parts[0];
11328     EVT ValueEltVT = ValueVT.getVectorElementType();
11329     EVT PartEltVT = PartVT.getVectorElementType();
11330     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11331     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11332     if (PartVTBitSize % ValueVTBitSize == 0) {
11333       assert(PartVTBitSize >= ValueVTBitSize);
11334       EVT SameEltTypeVT = ValueVT;
11335       // If the element types are different, convert it to the same element type
11336       // of PartVT.
11337       // Give an example here, we want copy a <vscale x 1 x i8> value from
11338       // <vscale x 4 x i16>.
11339       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11340       // then we can extract <vscale x 1 x i8>.
11341       if (ValueEltVT != PartEltVT) {
11342         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11343         assert(Count != 0 && "The number of element should not be zero.");
11344         SameEltTypeVT =
11345             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11346         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11347       }
11348       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11349                         DAG.getVectorIdxConstant(0, DL));
11350       return Val;
11351     }
11352   }
11353   return SDValue();
11354 }
11355 
11356 SDValue
11357 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11358                                    SelectionDAG &DAG,
11359                                    SmallVectorImpl<SDNode *> &Created) const {
11360   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11361   if (isIntDivCheap(N->getValueType(0), Attr))
11362     return SDValue(N, 0); // Lower SDIV as SDIV
11363 
11364   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11365          "Unexpected divisor!");
11366 
11367   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11368   if (!Subtarget.hasStdExtZbt())
11369     return SDValue();
11370 
11371   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11372   // Besides, more critical path instructions will be generated when dividing
11373   // by 2. So we keep using the original DAGs for these cases.
11374   unsigned Lg2 = Divisor.countTrailingZeros();
11375   if (Lg2 == 1 || Lg2 >= 12)
11376     return SDValue();
11377 
11378   // fold (sdiv X, pow2)
11379   EVT VT = N->getValueType(0);
11380   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11381     return SDValue();
11382 
11383   SDLoc DL(N);
11384   SDValue N0 = N->getOperand(0);
11385   SDValue Zero = DAG.getConstant(0, DL, VT);
11386   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11387 
11388   // Add (N0 < 0) ? Pow2 - 1 : 0;
11389   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11390   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11391   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11392 
11393   Created.push_back(Cmp.getNode());
11394   Created.push_back(Add.getNode());
11395   Created.push_back(Sel.getNode());
11396 
11397   // Divide by pow2.
11398   SDValue SRA =
11399       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11400 
11401   // If we're dividing by a positive value, we're done.  Otherwise, we must
11402   // negate the result.
11403   if (Divisor.isNonNegative())
11404     return SRA;
11405 
11406   Created.push_back(SRA.getNode());
11407   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11408 }
11409 
11410 #define GET_REGISTER_MATCHER
11411 #include "RISCVGenAsmMatcher.inc"
11412 
11413 Register
11414 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11415                                        const MachineFunction &MF) const {
11416   Register Reg = MatchRegisterAltName(RegName);
11417   if (Reg == RISCV::NoRegister)
11418     Reg = MatchRegisterName(RegName);
11419   if (Reg == RISCV::NoRegister)
11420     report_fatal_error(
11421         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11422   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11423   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11424     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11425                              StringRef(RegName) + "\"."));
11426   return Reg;
11427 }
11428 
11429 namespace llvm {
11430 namespace RISCVVIntrinsicsTable {
11431 
11432 #define GET_RISCVVIntrinsicsTable_IMPL
11433 #include "RISCVGenSearchableTables.inc"
11434 
11435 } // namespace RISCVVIntrinsicsTable
11436 
11437 } // namespace llvm
11438