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 (IsSignExt) {
7790       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7791         return SDValue();
7792     } else {
7793       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7794       if (!DAG.MaskedValueIsZero(Op1, Mask))
7795         return SDValue();
7796     }
7797 
7798     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7799   } else
7800     return SDValue();
7801 
7802   Op0 = Op0.getOperand(0);
7803 
7804   // Re-introduce narrower extends if needed.
7805   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7806   if (Op0.getValueType() != NarrowVT)
7807     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7808   // vwmulsu requires second operand to be zero extended.
7809   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
7810   if (Op1.getValueType() != NarrowVT)
7811     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7812 
7813   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7814   if (!IsVWMULSU)
7815     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7816   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7817 }
7818 
7819 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7820   switch (Op.getOpcode()) {
7821   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7822   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7823   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7824   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7825   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7826   }
7827 
7828   return RISCVFPRndMode::Invalid;
7829 }
7830 
7831 // Fold
7832 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7833 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7834 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7835 //   (fp_to_int (fceil X))      -> fcvt X, rup
7836 //   (fp_to_int (fround X))     -> fcvt X, rmm
7837 static SDValue performFP_TO_INTCombine(SDNode *N,
7838                                        TargetLowering::DAGCombinerInfo &DCI,
7839                                        const RISCVSubtarget &Subtarget) {
7840   SelectionDAG &DAG = DCI.DAG;
7841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7842   MVT XLenVT = Subtarget.getXLenVT();
7843 
7844   // Only handle XLen or i32 types. Other types narrower than XLen will
7845   // eventually be legalized to XLenVT.
7846   EVT VT = N->getValueType(0);
7847   if (VT != MVT::i32 && VT != XLenVT)
7848     return SDValue();
7849 
7850   SDValue Src = N->getOperand(0);
7851 
7852   // Ensure the FP type is also legal.
7853   if (!TLI.isTypeLegal(Src.getValueType()))
7854     return SDValue();
7855 
7856   // Don't do this for f16 with Zfhmin and not Zfh.
7857   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7858     return SDValue();
7859 
7860   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7861   if (FRM == RISCVFPRndMode::Invalid)
7862     return SDValue();
7863 
7864   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7865 
7866   unsigned Opc;
7867   if (VT == XLenVT)
7868     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7869   else
7870     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7871 
7872   SDLoc DL(N);
7873   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7874                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7875   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7876 }
7877 
7878 // Fold
7879 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7880 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7881 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7882 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7883 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7884 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7885                                        TargetLowering::DAGCombinerInfo &DCI,
7886                                        const RISCVSubtarget &Subtarget) {
7887   SelectionDAG &DAG = DCI.DAG;
7888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7889   MVT XLenVT = Subtarget.getXLenVT();
7890 
7891   // Only handle XLen types. Other types narrower than XLen will eventually be
7892   // legalized to XLenVT.
7893   EVT DstVT = N->getValueType(0);
7894   if (DstVT != XLenVT)
7895     return SDValue();
7896 
7897   SDValue Src = N->getOperand(0);
7898 
7899   // Ensure the FP type is also legal.
7900   if (!TLI.isTypeLegal(Src.getValueType()))
7901     return SDValue();
7902 
7903   // Don't do this for f16 with Zfhmin and not Zfh.
7904   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7905     return SDValue();
7906 
7907   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7908 
7909   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7910   if (FRM == RISCVFPRndMode::Invalid)
7911     return SDValue();
7912 
7913   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7914 
7915   unsigned Opc;
7916   if (SatVT == DstVT)
7917     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7918   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7919     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7920   else
7921     return SDValue();
7922   // FIXME: Support other SatVTs by clamping before or after the conversion.
7923 
7924   Src = Src.getOperand(0);
7925 
7926   SDLoc DL(N);
7927   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7928                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7929 
7930   // RISCV FP-to-int conversions saturate to the destination register size, but
7931   // don't produce 0 for nan.
7932   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7933   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7934 }
7935 
7936 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7937                                                DAGCombinerInfo &DCI) const {
7938   SelectionDAG &DAG = DCI.DAG;
7939 
7940   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7941   // bits are demanded. N will be added to the Worklist if it was not deleted.
7942   // Caller should return SDValue(N, 0) if this returns true.
7943   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7944     SDValue Op = N->getOperand(OpNo);
7945     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7946     if (!SimplifyDemandedBits(Op, Mask, DCI))
7947       return false;
7948 
7949     if (N->getOpcode() != ISD::DELETED_NODE)
7950       DCI.AddToWorklist(N);
7951     return true;
7952   };
7953 
7954   switch (N->getOpcode()) {
7955   default:
7956     break;
7957   case RISCVISD::SplitF64: {
7958     SDValue Op0 = N->getOperand(0);
7959     // If the input to SplitF64 is just BuildPairF64 then the operation is
7960     // redundant. Instead, use BuildPairF64's operands directly.
7961     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7962       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7963 
7964     if (Op0->isUndef()) {
7965       SDValue Lo = DAG.getUNDEF(MVT::i32);
7966       SDValue Hi = DAG.getUNDEF(MVT::i32);
7967       return DCI.CombineTo(N, Lo, Hi);
7968     }
7969 
7970     SDLoc DL(N);
7971 
7972     // It's cheaper to materialise two 32-bit integers than to load a double
7973     // from the constant pool and transfer it to integer registers through the
7974     // stack.
7975     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7976       APInt V = C->getValueAPF().bitcastToAPInt();
7977       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7978       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7979       return DCI.CombineTo(N, Lo, Hi);
7980     }
7981 
7982     // This is a target-specific version of a DAGCombine performed in
7983     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7984     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7985     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7986     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7987         !Op0.getNode()->hasOneUse())
7988       break;
7989     SDValue NewSplitF64 =
7990         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7991                     Op0.getOperand(0));
7992     SDValue Lo = NewSplitF64.getValue(0);
7993     SDValue Hi = NewSplitF64.getValue(1);
7994     APInt SignBit = APInt::getSignMask(32);
7995     if (Op0.getOpcode() == ISD::FNEG) {
7996       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7997                                   DAG.getConstant(SignBit, DL, MVT::i32));
7998       return DCI.CombineTo(N, Lo, NewHi);
7999     }
8000     assert(Op0.getOpcode() == ISD::FABS);
8001     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8002                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8003     return DCI.CombineTo(N, Lo, NewHi);
8004   }
8005   case RISCVISD::SLLW:
8006   case RISCVISD::SRAW:
8007   case RISCVISD::SRLW:
8008   case RISCVISD::ROLW:
8009   case RISCVISD::RORW: {
8010     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8011     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8012         SimplifyDemandedLowBitsHelper(1, 5))
8013       return SDValue(N, 0);
8014 
8015     return combineROTR_ROTL_RORW_ROLW(N, DAG);
8016   }
8017   case ISD::ROTR:
8018   case ISD::ROTL:
8019     return combineROTR_ROTL_RORW_ROLW(N, DAG);
8020   case RISCVISD::CLZW:
8021   case RISCVISD::CTZW: {
8022     // Only the lower 32 bits of the first operand are read
8023     if (SimplifyDemandedLowBitsHelper(0, 32))
8024       return SDValue(N, 0);
8025     break;
8026   }
8027   case RISCVISD::GREV:
8028   case RISCVISD::GORC: {
8029     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8030     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8031     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8032     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8033       return SDValue(N, 0);
8034 
8035     return combineGREVI_GORCI(N, DAG);
8036   }
8037   case RISCVISD::GREVW:
8038   case RISCVISD::GORCW: {
8039     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8040     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8041         SimplifyDemandedLowBitsHelper(1, 5))
8042       return SDValue(N, 0);
8043 
8044     return combineGREVI_GORCI(N, DAG);
8045   }
8046   case RISCVISD::SHFL:
8047   case RISCVISD::UNSHFL: {
8048     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8049     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8050     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8051     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8052       return SDValue(N, 0);
8053 
8054     break;
8055   }
8056   case RISCVISD::SHFLW:
8057   case RISCVISD::UNSHFLW: {
8058     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8059     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8060         SimplifyDemandedLowBitsHelper(1, 4))
8061       return SDValue(N, 0);
8062 
8063     break;
8064   }
8065   case RISCVISD::BCOMPRESSW:
8066   case RISCVISD::BDECOMPRESSW: {
8067     // Only the lower 32 bits of LHS and RHS are read.
8068     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8069         SimplifyDemandedLowBitsHelper(1, 32))
8070       return SDValue(N, 0);
8071 
8072     break;
8073   }
8074   case RISCVISD::FMV_X_ANYEXTH:
8075   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8076     SDLoc DL(N);
8077     SDValue Op0 = N->getOperand(0);
8078     MVT VT = N->getSimpleValueType(0);
8079     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8080     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8081     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8082     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8083          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8084         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8085          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8086       assert(Op0.getOperand(0).getValueType() == VT &&
8087              "Unexpected value type!");
8088       return Op0.getOperand(0);
8089     }
8090 
8091     // This is a target-specific version of a DAGCombine performed in
8092     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8093     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8094     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8095     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8096         !Op0.getNode()->hasOneUse())
8097       break;
8098     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8099     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8100     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8101     if (Op0.getOpcode() == ISD::FNEG)
8102       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8103                          DAG.getConstant(SignBit, DL, VT));
8104 
8105     assert(Op0.getOpcode() == ISD::FABS);
8106     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8107                        DAG.getConstant(~SignBit, DL, VT));
8108   }
8109   case ISD::ADD:
8110     return performADDCombine(N, DAG, Subtarget);
8111   case ISD::SUB:
8112     return performSUBCombine(N, DAG);
8113   case ISD::AND:
8114     return performANDCombine(N, DAG);
8115   case ISD::OR:
8116     return performORCombine(N, DAG, Subtarget);
8117   case ISD::XOR:
8118     return performXORCombine(N, DAG);
8119   case ISD::ANY_EXTEND:
8120     return performANY_EXTENDCombine(N, DCI, Subtarget);
8121   case ISD::ZERO_EXTEND:
8122     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8123     // type legalization. This is safe because fp_to_uint produces poison if
8124     // it overflows.
8125     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8126       SDValue Src = N->getOperand(0);
8127       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8128           isTypeLegal(Src.getOperand(0).getValueType()))
8129         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8130                            Src.getOperand(0));
8131       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8132           isTypeLegal(Src.getOperand(1).getValueType())) {
8133         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8134         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8135                                   Src.getOperand(0), Src.getOperand(1));
8136         DCI.CombineTo(N, Res);
8137         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8138         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8139         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8140       }
8141     }
8142     return SDValue();
8143   case RISCVISD::SELECT_CC: {
8144     // Transform
8145     SDValue LHS = N->getOperand(0);
8146     SDValue RHS = N->getOperand(1);
8147     SDValue TrueV = N->getOperand(3);
8148     SDValue FalseV = N->getOperand(4);
8149 
8150     // If the True and False values are the same, we don't need a select_cc.
8151     if (TrueV == FalseV)
8152       return TrueV;
8153 
8154     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8155     if (!ISD::isIntEqualitySetCC(CCVal))
8156       break;
8157 
8158     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8159     //      (select_cc X, Y, lt, trueV, falseV)
8160     // Sometimes the setcc is introduced after select_cc has been formed.
8161     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8162         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8163       // If we're looking for eq 0 instead of ne 0, we need to invert the
8164       // condition.
8165       bool Invert = CCVal == ISD::SETEQ;
8166       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8167       if (Invert)
8168         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8169 
8170       SDLoc DL(N);
8171       RHS = LHS.getOperand(1);
8172       LHS = LHS.getOperand(0);
8173       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8174 
8175       SDValue TargetCC = DAG.getCondCode(CCVal);
8176       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8177                          {LHS, RHS, TargetCC, TrueV, FalseV});
8178     }
8179 
8180     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8181     //      (select_cc X, Y, eq/ne, trueV, falseV)
8182     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8183       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8184                          {LHS.getOperand(0), LHS.getOperand(1),
8185                           N->getOperand(2), TrueV, FalseV});
8186     // (select_cc X, 1, setne, trueV, falseV) ->
8187     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8188     // This can occur when legalizing some floating point comparisons.
8189     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8190     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8191       SDLoc DL(N);
8192       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8193       SDValue TargetCC = DAG.getCondCode(CCVal);
8194       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8195       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8196                          {LHS, RHS, TargetCC, TrueV, FalseV});
8197     }
8198 
8199     break;
8200   }
8201   case RISCVISD::BR_CC: {
8202     SDValue LHS = N->getOperand(1);
8203     SDValue RHS = N->getOperand(2);
8204     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8205     if (!ISD::isIntEqualitySetCC(CCVal))
8206       break;
8207 
8208     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8209     //      (br_cc X, Y, lt, dest)
8210     // Sometimes the setcc is introduced after br_cc has been formed.
8211     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8212         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8213       // If we're looking for eq 0 instead of ne 0, we need to invert the
8214       // condition.
8215       bool Invert = CCVal == ISD::SETEQ;
8216       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8217       if (Invert)
8218         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8219 
8220       SDLoc DL(N);
8221       RHS = LHS.getOperand(1);
8222       LHS = LHS.getOperand(0);
8223       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8224 
8225       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8226                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8227                          N->getOperand(4));
8228     }
8229 
8230     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8231     //      (br_cc X, Y, eq/ne, trueV, falseV)
8232     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8233       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8234                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8235                          N->getOperand(3), N->getOperand(4));
8236 
8237     // (br_cc X, 1, setne, br_cc) ->
8238     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8239     // This can occur when legalizing some floating point comparisons.
8240     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8241     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8242       SDLoc DL(N);
8243       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8244       SDValue TargetCC = DAG.getCondCode(CCVal);
8245       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8246       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8247                          N->getOperand(0), LHS, RHS, TargetCC,
8248                          N->getOperand(4));
8249     }
8250     break;
8251   }
8252   case ISD::FP_TO_SINT:
8253   case ISD::FP_TO_UINT:
8254     return performFP_TO_INTCombine(N, DCI, Subtarget);
8255   case ISD::FP_TO_SINT_SAT:
8256   case ISD::FP_TO_UINT_SAT:
8257     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8258   case ISD::FCOPYSIGN: {
8259     EVT VT = N->getValueType(0);
8260     if (!VT.isVector())
8261       break;
8262     // There is a form of VFSGNJ which injects the negated sign of its second
8263     // operand. Try and bubble any FNEG up after the extend/round to produce
8264     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8265     // TRUNC=1.
8266     SDValue In2 = N->getOperand(1);
8267     // Avoid cases where the extend/round has multiple uses, as duplicating
8268     // those is typically more expensive than removing a fneg.
8269     if (!In2.hasOneUse())
8270       break;
8271     if (In2.getOpcode() != ISD::FP_EXTEND &&
8272         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8273       break;
8274     In2 = In2.getOperand(0);
8275     if (In2.getOpcode() != ISD::FNEG)
8276       break;
8277     SDLoc DL(N);
8278     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8279     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8280                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8281   }
8282   case ISD::MGATHER:
8283   case ISD::MSCATTER:
8284   case ISD::VP_GATHER:
8285   case ISD::VP_SCATTER: {
8286     if (!DCI.isBeforeLegalize())
8287       break;
8288     SDValue Index, ScaleOp;
8289     bool IsIndexScaled = false;
8290     bool IsIndexSigned = false;
8291     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8292       Index = VPGSN->getIndex();
8293       ScaleOp = VPGSN->getScale();
8294       IsIndexScaled = VPGSN->isIndexScaled();
8295       IsIndexSigned = VPGSN->isIndexSigned();
8296     } else {
8297       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8298       Index = MGSN->getIndex();
8299       ScaleOp = MGSN->getScale();
8300       IsIndexScaled = MGSN->isIndexScaled();
8301       IsIndexSigned = MGSN->isIndexSigned();
8302     }
8303     EVT IndexVT = Index.getValueType();
8304     MVT XLenVT = Subtarget.getXLenVT();
8305     // RISCV indexed loads only support the "unsigned unscaled" addressing
8306     // mode, so anything else must be manually legalized.
8307     bool NeedsIdxLegalization =
8308         IsIndexScaled ||
8309         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8310     if (!NeedsIdxLegalization)
8311       break;
8312 
8313     SDLoc DL(N);
8314 
8315     // Any index legalization should first promote to XLenVT, so we don't lose
8316     // bits when scaling. This may create an illegal index type so we let
8317     // LLVM's legalization take care of the splitting.
8318     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8319     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8320       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8321       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8322                           DL, IndexVT, Index);
8323     }
8324 
8325     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8326     if (IsIndexScaled && Scale != 1) {
8327       // Manually scale the indices by the element size.
8328       // TODO: Sanitize the scale operand here?
8329       // TODO: For VP nodes, should we use VP_SHL here?
8330       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8331       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8332       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8333     }
8334 
8335     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8336     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8337       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8338                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8339                               VPGN->getScale(), VPGN->getMask(),
8340                               VPGN->getVectorLength()},
8341                              VPGN->getMemOperand(), NewIndexTy);
8342     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8343       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8344                               {VPSN->getChain(), VPSN->getValue(),
8345                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8346                                VPSN->getMask(), VPSN->getVectorLength()},
8347                               VPSN->getMemOperand(), NewIndexTy);
8348     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8349       return DAG.getMaskedGather(
8350           N->getVTList(), MGN->getMemoryVT(), DL,
8351           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8352            MGN->getBasePtr(), Index, MGN->getScale()},
8353           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8354     const auto *MSN = cast<MaskedScatterSDNode>(N);
8355     return DAG.getMaskedScatter(
8356         N->getVTList(), MSN->getMemoryVT(), DL,
8357         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8358          Index, MSN->getScale()},
8359         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8360   }
8361   case RISCVISD::SRA_VL:
8362   case RISCVISD::SRL_VL:
8363   case RISCVISD::SHL_VL: {
8364     SDValue ShAmt = N->getOperand(1);
8365     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8366       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8367       SDLoc DL(N);
8368       SDValue VL = N->getOperand(3);
8369       EVT VT = N->getValueType(0);
8370       ShAmt =
8371           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
8372       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8373                          N->getOperand(2), N->getOperand(3));
8374     }
8375     break;
8376   }
8377   case ISD::SRA:
8378   case ISD::SRL:
8379   case ISD::SHL: {
8380     SDValue ShAmt = N->getOperand(1);
8381     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8382       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8383       SDLoc DL(N);
8384       EVT VT = N->getValueType(0);
8385       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0),
8386                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8387       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8388     }
8389     break;
8390   }
8391   case RISCVISD::ADD_VL:
8392     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8393       return V;
8394     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8395   case RISCVISD::SUB_VL:
8396     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8397   case RISCVISD::VWADD_W_VL:
8398   case RISCVISD::VWADDU_W_VL:
8399   case RISCVISD::VWSUB_W_VL:
8400   case RISCVISD::VWSUBU_W_VL:
8401     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8402   case RISCVISD::MUL_VL:
8403     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8404       return V;
8405     // Mul is commutative.
8406     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8407   case ISD::STORE: {
8408     auto *Store = cast<StoreSDNode>(N);
8409     SDValue Val = Store->getValue();
8410     // Combine store of vmv.x.s to vse with VL of 1.
8411     // FIXME: Support FP.
8412     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8413       SDValue Src = Val.getOperand(0);
8414       EVT VecVT = Src.getValueType();
8415       EVT MemVT = Store->getMemoryVT();
8416       // The memory VT and the element type must match.
8417       if (VecVT.getVectorElementType() == MemVT) {
8418         SDLoc DL(N);
8419         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8420         return DAG.getStoreVP(
8421             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8422             DAG.getConstant(1, DL, MaskVT),
8423             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8424             Store->getMemOperand(), Store->getAddressingMode(),
8425             Store->isTruncatingStore(), /*IsCompress*/ false);
8426       }
8427     }
8428 
8429     break;
8430   }
8431   case ISD::SPLAT_VECTOR: {
8432     EVT VT = N->getValueType(0);
8433     // Only perform this combine on legal MVT types.
8434     if (!isTypeLegal(VT))
8435       break;
8436     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8437                                          DAG, Subtarget))
8438       return Gather;
8439     break;
8440   }
8441   }
8442 
8443   return SDValue();
8444 }
8445 
8446 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8447     const SDNode *N, CombineLevel Level) const {
8448   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8449   // materialised in fewer instructions than `(OP _, c1)`:
8450   //
8451   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8452   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8453   SDValue N0 = N->getOperand(0);
8454   EVT Ty = N0.getValueType();
8455   if (Ty.isScalarInteger() &&
8456       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8457     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8458     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8459     if (C1 && C2) {
8460       const APInt &C1Int = C1->getAPIntValue();
8461       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8462 
8463       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8464       // and the combine should happen, to potentially allow further combines
8465       // later.
8466       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8467           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8468         return true;
8469 
8470       // We can materialise `c1` in an add immediate, so it's "free", and the
8471       // combine should be prevented.
8472       if (C1Int.getMinSignedBits() <= 64 &&
8473           isLegalAddImmediate(C1Int.getSExtValue()))
8474         return false;
8475 
8476       // Neither constant will fit into an immediate, so find materialisation
8477       // costs.
8478       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8479                                               Subtarget.getFeatureBits(),
8480                                               /*CompressionCost*/true);
8481       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8482           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8483           /*CompressionCost*/true);
8484 
8485       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8486       // combine should be prevented.
8487       if (C1Cost < ShiftedC1Cost)
8488         return false;
8489     }
8490   }
8491   return true;
8492 }
8493 
8494 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8495     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8496     TargetLoweringOpt &TLO) const {
8497   // Delay this optimization as late as possible.
8498   if (!TLO.LegalOps)
8499     return false;
8500 
8501   EVT VT = Op.getValueType();
8502   if (VT.isVector())
8503     return false;
8504 
8505   // Only handle AND for now.
8506   if (Op.getOpcode() != ISD::AND)
8507     return false;
8508 
8509   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8510   if (!C)
8511     return false;
8512 
8513   const APInt &Mask = C->getAPIntValue();
8514 
8515   // Clear all non-demanded bits initially.
8516   APInt ShrunkMask = Mask & DemandedBits;
8517 
8518   // Try to make a smaller immediate by setting undemanded bits.
8519 
8520   APInt ExpandedMask = Mask | ~DemandedBits;
8521 
8522   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8523     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8524   };
8525   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8526     if (NewMask == Mask)
8527       return true;
8528     SDLoc DL(Op);
8529     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8530     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8531     return TLO.CombineTo(Op, NewOp);
8532   };
8533 
8534   // If the shrunk mask fits in sign extended 12 bits, let the target
8535   // independent code apply it.
8536   if (ShrunkMask.isSignedIntN(12))
8537     return false;
8538 
8539   // Preserve (and X, 0xffff) when zext.h is supported.
8540   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8541     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8542     if (IsLegalMask(NewMask))
8543       return UseMask(NewMask);
8544   }
8545 
8546   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8547   if (VT == MVT::i64) {
8548     APInt NewMask = APInt(64, 0xffffffff);
8549     if (IsLegalMask(NewMask))
8550       return UseMask(NewMask);
8551   }
8552 
8553   // For the remaining optimizations, we need to be able to make a negative
8554   // number through a combination of mask and undemanded bits.
8555   if (!ExpandedMask.isNegative())
8556     return false;
8557 
8558   // What is the fewest number of bits we need to represent the negative number.
8559   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8560 
8561   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8562   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8563   APInt NewMask = ShrunkMask;
8564   if (MinSignedBits <= 12)
8565     NewMask.setBitsFrom(11);
8566   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8567     NewMask.setBitsFrom(31);
8568   else
8569     return false;
8570 
8571   // Check that our new mask is a subset of the demanded mask.
8572   assert(IsLegalMask(NewMask));
8573   return UseMask(NewMask);
8574 }
8575 
8576 static void computeGREV(APInt &Src, unsigned ShAmt) {
8577   ShAmt &= Src.getBitWidth() - 1;
8578   uint64_t x = Src.getZExtValue();
8579   if (ShAmt & 1)
8580     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8581   if (ShAmt & 2)
8582     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8583   if (ShAmt & 4)
8584     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8585   if (ShAmt & 8)
8586     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8587   if (ShAmt & 16)
8588     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8589   if (ShAmt & 32)
8590     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8591   Src = x;
8592 }
8593 
8594 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8595                                                         KnownBits &Known,
8596                                                         const APInt &DemandedElts,
8597                                                         const SelectionDAG &DAG,
8598                                                         unsigned Depth) const {
8599   unsigned BitWidth = Known.getBitWidth();
8600   unsigned Opc = Op.getOpcode();
8601   assert((Opc >= ISD::BUILTIN_OP_END ||
8602           Opc == ISD::INTRINSIC_WO_CHAIN ||
8603           Opc == ISD::INTRINSIC_W_CHAIN ||
8604           Opc == ISD::INTRINSIC_VOID) &&
8605          "Should use MaskedValueIsZero if you don't know whether Op"
8606          " is a target node!");
8607 
8608   Known.resetAll();
8609   switch (Opc) {
8610   default: break;
8611   case RISCVISD::SELECT_CC: {
8612     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8613     // If we don't know any bits, early out.
8614     if (Known.isUnknown())
8615       break;
8616     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8617 
8618     // Only known if known in both the LHS and RHS.
8619     Known = KnownBits::commonBits(Known, Known2);
8620     break;
8621   }
8622   case RISCVISD::REMUW: {
8623     KnownBits Known2;
8624     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8625     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8626     // We only care about the lower 32 bits.
8627     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8628     // Restore the original width by sign extending.
8629     Known = Known.sext(BitWidth);
8630     break;
8631   }
8632   case RISCVISD::DIVUW: {
8633     KnownBits Known2;
8634     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8635     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8636     // We only care about the lower 32 bits.
8637     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8638     // Restore the original width by sign extending.
8639     Known = Known.sext(BitWidth);
8640     break;
8641   }
8642   case RISCVISD::CTZW: {
8643     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8644     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8645     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8646     Known.Zero.setBitsFrom(LowBits);
8647     break;
8648   }
8649   case RISCVISD::CLZW: {
8650     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8651     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8652     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8653     Known.Zero.setBitsFrom(LowBits);
8654     break;
8655   }
8656   case RISCVISD::GREV:
8657   case RISCVISD::GREVW: {
8658     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8659       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8660       if (Opc == RISCVISD::GREVW)
8661         Known = Known.trunc(32);
8662       unsigned ShAmt = C->getZExtValue();
8663       computeGREV(Known.Zero, ShAmt);
8664       computeGREV(Known.One, ShAmt);
8665       if (Opc == RISCVISD::GREVW)
8666         Known = Known.sext(BitWidth);
8667     }
8668     break;
8669   }
8670   case RISCVISD::READ_VLENB: {
8671     // If we know the minimum VLen from Zvl extensions, we can use that to
8672     // determine the trailing zeros of VLENB.
8673     // FIXME: Limit to 128 bit vectors until we have more testing.
8674     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8675     if (MinVLenB > 0)
8676       Known.Zero.setLowBits(Log2_32(MinVLenB));
8677     // We assume VLENB is no more than 65536 / 8 bytes.
8678     Known.Zero.setBitsFrom(14);
8679     break;
8680   }
8681   case ISD::INTRINSIC_W_CHAIN:
8682   case ISD::INTRINSIC_WO_CHAIN: {
8683     unsigned IntNo =
8684         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8685     switch (IntNo) {
8686     default:
8687       // We can't do anything for most intrinsics.
8688       break;
8689     case Intrinsic::riscv_vsetvli:
8690     case Intrinsic::riscv_vsetvlimax:
8691     case Intrinsic::riscv_vsetvli_opt:
8692     case Intrinsic::riscv_vsetvlimax_opt:
8693       // Assume that VL output is positive and would fit in an int32_t.
8694       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8695       if (BitWidth >= 32)
8696         Known.Zero.setBitsFrom(31);
8697       break;
8698     }
8699     break;
8700   }
8701   }
8702 }
8703 
8704 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8705     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8706     unsigned Depth) const {
8707   switch (Op.getOpcode()) {
8708   default:
8709     break;
8710   case RISCVISD::SELECT_CC: {
8711     unsigned Tmp =
8712         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8713     if (Tmp == 1) return 1;  // Early out.
8714     unsigned Tmp2 =
8715         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8716     return std::min(Tmp, Tmp2);
8717   }
8718   case RISCVISD::SLLW:
8719   case RISCVISD::SRAW:
8720   case RISCVISD::SRLW:
8721   case RISCVISD::DIVW:
8722   case RISCVISD::DIVUW:
8723   case RISCVISD::REMUW:
8724   case RISCVISD::ROLW:
8725   case RISCVISD::RORW:
8726   case RISCVISD::GREVW:
8727   case RISCVISD::GORCW:
8728   case RISCVISD::FSLW:
8729   case RISCVISD::FSRW:
8730   case RISCVISD::SHFLW:
8731   case RISCVISD::UNSHFLW:
8732   case RISCVISD::BCOMPRESSW:
8733   case RISCVISD::BDECOMPRESSW:
8734   case RISCVISD::BFPW:
8735   case RISCVISD::FCVT_W_RV64:
8736   case RISCVISD::FCVT_WU_RV64:
8737   case RISCVISD::STRICT_FCVT_W_RV64:
8738   case RISCVISD::STRICT_FCVT_WU_RV64:
8739     // TODO: As the result is sign-extended, this is conservatively correct. A
8740     // more precise answer could be calculated for SRAW depending on known
8741     // bits in the shift amount.
8742     return 33;
8743   case RISCVISD::SHFL:
8744   case RISCVISD::UNSHFL: {
8745     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8746     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8747     // will stay within the upper 32 bits. If there were more than 32 sign bits
8748     // before there will be at least 33 sign bits after.
8749     if (Op.getValueType() == MVT::i64 &&
8750         isa<ConstantSDNode>(Op.getOperand(1)) &&
8751         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8752       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8753       if (Tmp > 32)
8754         return 33;
8755     }
8756     break;
8757   }
8758   case RISCVISD::VMV_X_S: {
8759     // The number of sign bits of the scalar result is computed by obtaining the
8760     // element type of the input vector operand, subtracting its width from the
8761     // XLEN, and then adding one (sign bit within the element type). If the
8762     // element type is wider than XLen, the least-significant XLEN bits are
8763     // taken.
8764     unsigned XLen = Subtarget.getXLen();
8765     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8766     if (EltBits <= XLen)
8767       return XLen - EltBits + 1;
8768     break;
8769   }
8770   }
8771 
8772   return 1;
8773 }
8774 
8775 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8776                                                   MachineBasicBlock *BB) {
8777   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8778 
8779   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8780   // Should the count have wrapped while it was being read, we need to try
8781   // again.
8782   // ...
8783   // read:
8784   // rdcycleh x3 # load high word of cycle
8785   // rdcycle  x2 # load low word of cycle
8786   // rdcycleh x4 # load high word of cycle
8787   // bne x3, x4, read # check if high word reads match, otherwise try again
8788   // ...
8789 
8790   MachineFunction &MF = *BB->getParent();
8791   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8792   MachineFunction::iterator It = ++BB->getIterator();
8793 
8794   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8795   MF.insert(It, LoopMBB);
8796 
8797   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8798   MF.insert(It, DoneMBB);
8799 
8800   // Transfer the remainder of BB and its successor edges to DoneMBB.
8801   DoneMBB->splice(DoneMBB->begin(), BB,
8802                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8803   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8804 
8805   BB->addSuccessor(LoopMBB);
8806 
8807   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8808   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8809   Register LoReg = MI.getOperand(0).getReg();
8810   Register HiReg = MI.getOperand(1).getReg();
8811   DebugLoc DL = MI.getDebugLoc();
8812 
8813   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8814   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8815       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8816       .addReg(RISCV::X0);
8817   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8818       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8819       .addReg(RISCV::X0);
8820   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8821       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8822       .addReg(RISCV::X0);
8823 
8824   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8825       .addReg(HiReg)
8826       .addReg(ReadAgainReg)
8827       .addMBB(LoopMBB);
8828 
8829   LoopMBB->addSuccessor(LoopMBB);
8830   LoopMBB->addSuccessor(DoneMBB);
8831 
8832   MI.eraseFromParent();
8833 
8834   return DoneMBB;
8835 }
8836 
8837 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8838                                              MachineBasicBlock *BB) {
8839   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8840 
8841   MachineFunction &MF = *BB->getParent();
8842   DebugLoc DL = MI.getDebugLoc();
8843   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8844   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8845   Register LoReg = MI.getOperand(0).getReg();
8846   Register HiReg = MI.getOperand(1).getReg();
8847   Register SrcReg = MI.getOperand(2).getReg();
8848   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8849   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8850 
8851   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8852                           RI);
8853   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8854   MachineMemOperand *MMOLo =
8855       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8856   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8857       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8858   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8859       .addFrameIndex(FI)
8860       .addImm(0)
8861       .addMemOperand(MMOLo);
8862   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8863       .addFrameIndex(FI)
8864       .addImm(4)
8865       .addMemOperand(MMOHi);
8866   MI.eraseFromParent(); // The pseudo instruction is gone now.
8867   return BB;
8868 }
8869 
8870 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8871                                                  MachineBasicBlock *BB) {
8872   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8873          "Unexpected instruction");
8874 
8875   MachineFunction &MF = *BB->getParent();
8876   DebugLoc DL = MI.getDebugLoc();
8877   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8878   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8879   Register DstReg = MI.getOperand(0).getReg();
8880   Register LoReg = MI.getOperand(1).getReg();
8881   Register HiReg = MI.getOperand(2).getReg();
8882   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8883   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8884 
8885   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8886   MachineMemOperand *MMOLo =
8887       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8888   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8889       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8890   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8891       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8892       .addFrameIndex(FI)
8893       .addImm(0)
8894       .addMemOperand(MMOLo);
8895   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8896       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8897       .addFrameIndex(FI)
8898       .addImm(4)
8899       .addMemOperand(MMOHi);
8900   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8901   MI.eraseFromParent(); // The pseudo instruction is gone now.
8902   return BB;
8903 }
8904 
8905 static bool isSelectPseudo(MachineInstr &MI) {
8906   switch (MI.getOpcode()) {
8907   default:
8908     return false;
8909   case RISCV::Select_GPR_Using_CC_GPR:
8910   case RISCV::Select_FPR16_Using_CC_GPR:
8911   case RISCV::Select_FPR32_Using_CC_GPR:
8912   case RISCV::Select_FPR64_Using_CC_GPR:
8913     return true;
8914   }
8915 }
8916 
8917 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8918                                         unsigned RelOpcode, unsigned EqOpcode,
8919                                         const RISCVSubtarget &Subtarget) {
8920   DebugLoc DL = MI.getDebugLoc();
8921   Register DstReg = MI.getOperand(0).getReg();
8922   Register Src1Reg = MI.getOperand(1).getReg();
8923   Register Src2Reg = MI.getOperand(2).getReg();
8924   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8925   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8926   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8927 
8928   // Save the current FFLAGS.
8929   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8930 
8931   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8932                  .addReg(Src1Reg)
8933                  .addReg(Src2Reg);
8934   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8935     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8936 
8937   // Restore the FFLAGS.
8938   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8939       .addReg(SavedFFlags, RegState::Kill);
8940 
8941   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8942   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8943                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8944                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8945   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8946     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8947 
8948   // Erase the pseudoinstruction.
8949   MI.eraseFromParent();
8950   return BB;
8951 }
8952 
8953 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8954                                            MachineBasicBlock *BB,
8955                                            const RISCVSubtarget &Subtarget) {
8956   // To "insert" Select_* instructions, we actually have to insert the triangle
8957   // control-flow pattern.  The incoming instructions know the destination vreg
8958   // to set, the condition code register to branch on, the true/false values to
8959   // select between, and the condcode to use to select the appropriate branch.
8960   //
8961   // We produce the following control flow:
8962   //     HeadMBB
8963   //     |  \
8964   //     |  IfFalseMBB
8965   //     | /
8966   //    TailMBB
8967   //
8968   // When we find a sequence of selects we attempt to optimize their emission
8969   // by sharing the control flow. Currently we only handle cases where we have
8970   // multiple selects with the exact same condition (same LHS, RHS and CC).
8971   // The selects may be interleaved with other instructions if the other
8972   // instructions meet some requirements we deem safe:
8973   // - They are debug instructions. Otherwise,
8974   // - They do not have side-effects, do not access memory and their inputs do
8975   //   not depend on the results of the select pseudo-instructions.
8976   // The TrueV/FalseV operands of the selects cannot depend on the result of
8977   // previous selects in the sequence.
8978   // These conditions could be further relaxed. See the X86 target for a
8979   // related approach and more information.
8980   Register LHS = MI.getOperand(1).getReg();
8981   Register RHS = MI.getOperand(2).getReg();
8982   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8983 
8984   SmallVector<MachineInstr *, 4> SelectDebugValues;
8985   SmallSet<Register, 4> SelectDests;
8986   SelectDests.insert(MI.getOperand(0).getReg());
8987 
8988   MachineInstr *LastSelectPseudo = &MI;
8989 
8990   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8991        SequenceMBBI != E; ++SequenceMBBI) {
8992     if (SequenceMBBI->isDebugInstr())
8993       continue;
8994     else if (isSelectPseudo(*SequenceMBBI)) {
8995       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8996           SequenceMBBI->getOperand(2).getReg() != RHS ||
8997           SequenceMBBI->getOperand(3).getImm() != CC ||
8998           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8999           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9000         break;
9001       LastSelectPseudo = &*SequenceMBBI;
9002       SequenceMBBI->collectDebugValues(SelectDebugValues);
9003       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9004     } else {
9005       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9006           SequenceMBBI->mayLoadOrStore())
9007         break;
9008       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9009             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9010           }))
9011         break;
9012     }
9013   }
9014 
9015   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9016   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9017   DebugLoc DL = MI.getDebugLoc();
9018   MachineFunction::iterator I = ++BB->getIterator();
9019 
9020   MachineBasicBlock *HeadMBB = BB;
9021   MachineFunction *F = BB->getParent();
9022   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9023   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9024 
9025   F->insert(I, IfFalseMBB);
9026   F->insert(I, TailMBB);
9027 
9028   // Transfer debug instructions associated with the selects to TailMBB.
9029   for (MachineInstr *DebugInstr : SelectDebugValues) {
9030     TailMBB->push_back(DebugInstr->removeFromParent());
9031   }
9032 
9033   // Move all instructions after the sequence to TailMBB.
9034   TailMBB->splice(TailMBB->end(), HeadMBB,
9035                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9036   // Update machine-CFG edges by transferring all successors of the current
9037   // block to the new block which will contain the Phi nodes for the selects.
9038   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9039   // Set the successors for HeadMBB.
9040   HeadMBB->addSuccessor(IfFalseMBB);
9041   HeadMBB->addSuccessor(TailMBB);
9042 
9043   // Insert appropriate branch.
9044   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9045     .addReg(LHS)
9046     .addReg(RHS)
9047     .addMBB(TailMBB);
9048 
9049   // IfFalseMBB just falls through to TailMBB.
9050   IfFalseMBB->addSuccessor(TailMBB);
9051 
9052   // Create PHIs for all of the select pseudo-instructions.
9053   auto SelectMBBI = MI.getIterator();
9054   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9055   auto InsertionPoint = TailMBB->begin();
9056   while (SelectMBBI != SelectEnd) {
9057     auto Next = std::next(SelectMBBI);
9058     if (isSelectPseudo(*SelectMBBI)) {
9059       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9060       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9061               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9062           .addReg(SelectMBBI->getOperand(4).getReg())
9063           .addMBB(HeadMBB)
9064           .addReg(SelectMBBI->getOperand(5).getReg())
9065           .addMBB(IfFalseMBB);
9066       SelectMBBI->eraseFromParent();
9067     }
9068     SelectMBBI = Next;
9069   }
9070 
9071   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9072   return TailMBB;
9073 }
9074 
9075 MachineBasicBlock *
9076 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9077                                                  MachineBasicBlock *BB) const {
9078   switch (MI.getOpcode()) {
9079   default:
9080     llvm_unreachable("Unexpected instr type to insert");
9081   case RISCV::ReadCycleWide:
9082     assert(!Subtarget.is64Bit() &&
9083            "ReadCycleWrite is only to be used on riscv32");
9084     return emitReadCycleWidePseudo(MI, BB);
9085   case RISCV::Select_GPR_Using_CC_GPR:
9086   case RISCV::Select_FPR16_Using_CC_GPR:
9087   case RISCV::Select_FPR32_Using_CC_GPR:
9088   case RISCV::Select_FPR64_Using_CC_GPR:
9089     return emitSelectPseudo(MI, BB, Subtarget);
9090   case RISCV::BuildPairF64Pseudo:
9091     return emitBuildPairF64Pseudo(MI, BB);
9092   case RISCV::SplitF64Pseudo:
9093     return emitSplitF64Pseudo(MI, BB);
9094   case RISCV::PseudoQuietFLE_H:
9095     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9096   case RISCV::PseudoQuietFLT_H:
9097     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9098   case RISCV::PseudoQuietFLE_S:
9099     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9100   case RISCV::PseudoQuietFLT_S:
9101     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9102   case RISCV::PseudoQuietFLE_D:
9103     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9104   case RISCV::PseudoQuietFLT_D:
9105     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9106   }
9107 }
9108 
9109 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9110                                                         SDNode *Node) const {
9111   // Add FRM dependency to any instructions with dynamic rounding mode.
9112   unsigned Opc = MI.getOpcode();
9113   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9114   if (Idx < 0)
9115     return;
9116   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9117     return;
9118   // If the instruction already reads FRM, don't add another read.
9119   if (MI.readsRegister(RISCV::FRM))
9120     return;
9121   MI.addOperand(
9122       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9123 }
9124 
9125 // Calling Convention Implementation.
9126 // The expectations for frontend ABI lowering vary from target to target.
9127 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9128 // details, but this is a longer term goal. For now, we simply try to keep the
9129 // role of the frontend as simple and well-defined as possible. The rules can
9130 // be summarised as:
9131 // * Never split up large scalar arguments. We handle them here.
9132 // * If a hardfloat calling convention is being used, and the struct may be
9133 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9134 // available, then pass as two separate arguments. If either the GPRs or FPRs
9135 // are exhausted, then pass according to the rule below.
9136 // * If a struct could never be passed in registers or directly in a stack
9137 // slot (as it is larger than 2*XLEN and the floating point rules don't
9138 // apply), then pass it using a pointer with the byval attribute.
9139 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9140 // word-sized array or a 2*XLEN scalar (depending on alignment).
9141 // * The frontend can determine whether a struct is returned by reference or
9142 // not based on its size and fields. If it will be returned by reference, the
9143 // frontend must modify the prototype so a pointer with the sret annotation is
9144 // passed as the first argument. This is not necessary for large scalar
9145 // returns.
9146 // * Struct return values and varargs should be coerced to structs containing
9147 // register-size fields in the same situations they would be for fixed
9148 // arguments.
9149 
9150 static const MCPhysReg ArgGPRs[] = {
9151   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9152   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9153 };
9154 static const MCPhysReg ArgFPR16s[] = {
9155   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9156   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9157 };
9158 static const MCPhysReg ArgFPR32s[] = {
9159   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9160   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9161 };
9162 static const MCPhysReg ArgFPR64s[] = {
9163   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9164   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9165 };
9166 // This is an interim calling convention and it may be changed in the future.
9167 static const MCPhysReg ArgVRs[] = {
9168     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9169     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9170     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9171 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9172                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9173                                      RISCV::V20M2, RISCV::V22M2};
9174 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9175                                      RISCV::V20M4};
9176 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9177 
9178 // Pass a 2*XLEN argument that has been split into two XLEN values through
9179 // registers or the stack as necessary.
9180 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9181                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9182                                 MVT ValVT2, MVT LocVT2,
9183                                 ISD::ArgFlagsTy ArgFlags2) {
9184   unsigned XLenInBytes = XLen / 8;
9185   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9186     // At least one half can be passed via register.
9187     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9188                                      VA1.getLocVT(), CCValAssign::Full));
9189   } else {
9190     // Both halves must be passed on the stack, with proper alignment.
9191     Align StackAlign =
9192         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9193     State.addLoc(
9194         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9195                             State.AllocateStack(XLenInBytes, StackAlign),
9196                             VA1.getLocVT(), CCValAssign::Full));
9197     State.addLoc(CCValAssign::getMem(
9198         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9199         LocVT2, CCValAssign::Full));
9200     return false;
9201   }
9202 
9203   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9204     // The second half can also be passed via register.
9205     State.addLoc(
9206         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9207   } else {
9208     // The second half is passed via the stack, without additional alignment.
9209     State.addLoc(CCValAssign::getMem(
9210         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9211         LocVT2, CCValAssign::Full));
9212   }
9213 
9214   return false;
9215 }
9216 
9217 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9218                                Optional<unsigned> FirstMaskArgument,
9219                                CCState &State, const RISCVTargetLowering &TLI) {
9220   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9221   if (RC == &RISCV::VRRegClass) {
9222     // Assign the first mask argument to V0.
9223     // This is an interim calling convention and it may be changed in the
9224     // future.
9225     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9226       return State.AllocateReg(RISCV::V0);
9227     return State.AllocateReg(ArgVRs);
9228   }
9229   if (RC == &RISCV::VRM2RegClass)
9230     return State.AllocateReg(ArgVRM2s);
9231   if (RC == &RISCV::VRM4RegClass)
9232     return State.AllocateReg(ArgVRM4s);
9233   if (RC == &RISCV::VRM8RegClass)
9234     return State.AllocateReg(ArgVRM8s);
9235   llvm_unreachable("Unhandled register class for ValueType");
9236 }
9237 
9238 // Implements the RISC-V calling convention. Returns true upon failure.
9239 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9240                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9241                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9242                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9243                      Optional<unsigned> FirstMaskArgument) {
9244   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9245   assert(XLen == 32 || XLen == 64);
9246   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9247 
9248   // Any return value split in to more than two values can't be returned
9249   // directly. Vectors are returned via the available vector registers.
9250   if (!LocVT.isVector() && IsRet && ValNo > 1)
9251     return true;
9252 
9253   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9254   // variadic argument, or if no F16/F32 argument registers are available.
9255   bool UseGPRForF16_F32 = true;
9256   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9257   // variadic argument, or if no F64 argument registers are available.
9258   bool UseGPRForF64 = true;
9259 
9260   switch (ABI) {
9261   default:
9262     llvm_unreachable("Unexpected ABI");
9263   case RISCVABI::ABI_ILP32:
9264   case RISCVABI::ABI_LP64:
9265     break;
9266   case RISCVABI::ABI_ILP32F:
9267   case RISCVABI::ABI_LP64F:
9268     UseGPRForF16_F32 = !IsFixed;
9269     break;
9270   case RISCVABI::ABI_ILP32D:
9271   case RISCVABI::ABI_LP64D:
9272     UseGPRForF16_F32 = !IsFixed;
9273     UseGPRForF64 = !IsFixed;
9274     break;
9275   }
9276 
9277   // FPR16, FPR32, and FPR64 alias each other.
9278   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9279     UseGPRForF16_F32 = true;
9280     UseGPRForF64 = true;
9281   }
9282 
9283   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9284   // similar local variables rather than directly checking against the target
9285   // ABI.
9286 
9287   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9288     LocVT = XLenVT;
9289     LocInfo = CCValAssign::BCvt;
9290   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9291     LocVT = MVT::i64;
9292     LocInfo = CCValAssign::BCvt;
9293   }
9294 
9295   // If this is a variadic argument, the RISC-V calling convention requires
9296   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9297   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9298   // be used regardless of whether the original argument was split during
9299   // legalisation or not. The argument will not be passed by registers if the
9300   // original type is larger than 2*XLEN, so the register alignment rule does
9301   // not apply.
9302   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9303   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9304       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9305     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9306     // Skip 'odd' register if necessary.
9307     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9308       State.AllocateReg(ArgGPRs);
9309   }
9310 
9311   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9312   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9313       State.getPendingArgFlags();
9314 
9315   assert(PendingLocs.size() == PendingArgFlags.size() &&
9316          "PendingLocs and PendingArgFlags out of sync");
9317 
9318   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9319   // registers are exhausted.
9320   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9321     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9322            "Can't lower f64 if it is split");
9323     // Depending on available argument GPRS, f64 may be passed in a pair of
9324     // GPRs, split between a GPR and the stack, or passed completely on the
9325     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9326     // cases.
9327     Register Reg = State.AllocateReg(ArgGPRs);
9328     LocVT = MVT::i32;
9329     if (!Reg) {
9330       unsigned StackOffset = State.AllocateStack(8, Align(8));
9331       State.addLoc(
9332           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9333       return false;
9334     }
9335     if (!State.AllocateReg(ArgGPRs))
9336       State.AllocateStack(4, Align(4));
9337     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9338     return false;
9339   }
9340 
9341   // Fixed-length vectors are located in the corresponding scalable-vector
9342   // container types.
9343   if (ValVT.isFixedLengthVector())
9344     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9345 
9346   // Split arguments might be passed indirectly, so keep track of the pending
9347   // values. Split vectors are passed via a mix of registers and indirectly, so
9348   // treat them as we would any other argument.
9349   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9350     LocVT = XLenVT;
9351     LocInfo = CCValAssign::Indirect;
9352     PendingLocs.push_back(
9353         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9354     PendingArgFlags.push_back(ArgFlags);
9355     if (!ArgFlags.isSplitEnd()) {
9356       return false;
9357     }
9358   }
9359 
9360   // If the split argument only had two elements, it should be passed directly
9361   // in registers or on the stack.
9362   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9363       PendingLocs.size() <= 2) {
9364     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9365     // Apply the normal calling convention rules to the first half of the
9366     // split argument.
9367     CCValAssign VA = PendingLocs[0];
9368     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9369     PendingLocs.clear();
9370     PendingArgFlags.clear();
9371     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9372                                ArgFlags);
9373   }
9374 
9375   // Allocate to a register if possible, or else a stack slot.
9376   Register Reg;
9377   unsigned StoreSizeBytes = XLen / 8;
9378   Align StackAlign = Align(XLen / 8);
9379 
9380   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9381     Reg = State.AllocateReg(ArgFPR16s);
9382   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9383     Reg = State.AllocateReg(ArgFPR32s);
9384   else if (ValVT == MVT::f64 && !UseGPRForF64)
9385     Reg = State.AllocateReg(ArgFPR64s);
9386   else if (ValVT.isVector()) {
9387     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9388     if (!Reg) {
9389       // For return values, the vector must be passed fully via registers or
9390       // via the stack.
9391       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9392       // but we're using all of them.
9393       if (IsRet)
9394         return true;
9395       // Try using a GPR to pass the address
9396       if ((Reg = State.AllocateReg(ArgGPRs))) {
9397         LocVT = XLenVT;
9398         LocInfo = CCValAssign::Indirect;
9399       } else if (ValVT.isScalableVector()) {
9400         LocVT = XLenVT;
9401         LocInfo = CCValAssign::Indirect;
9402       } else {
9403         // Pass fixed-length vectors on the stack.
9404         LocVT = ValVT;
9405         StoreSizeBytes = ValVT.getStoreSize();
9406         // Align vectors to their element sizes, being careful for vXi1
9407         // vectors.
9408         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9409       }
9410     }
9411   } else {
9412     Reg = State.AllocateReg(ArgGPRs);
9413   }
9414 
9415   unsigned StackOffset =
9416       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9417 
9418   // If we reach this point and PendingLocs is non-empty, we must be at the
9419   // end of a split argument that must be passed indirectly.
9420   if (!PendingLocs.empty()) {
9421     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9422     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9423 
9424     for (auto &It : PendingLocs) {
9425       if (Reg)
9426         It.convertToReg(Reg);
9427       else
9428         It.convertToMem(StackOffset);
9429       State.addLoc(It);
9430     }
9431     PendingLocs.clear();
9432     PendingArgFlags.clear();
9433     return false;
9434   }
9435 
9436   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9437           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9438          "Expected an XLenVT or vector types at this stage");
9439 
9440   if (Reg) {
9441     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9442     return false;
9443   }
9444 
9445   // When a floating-point value is passed on the stack, no bit-conversion is
9446   // needed.
9447   if (ValVT.isFloatingPoint()) {
9448     LocVT = ValVT;
9449     LocInfo = CCValAssign::Full;
9450   }
9451   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9452   return false;
9453 }
9454 
9455 template <typename ArgTy>
9456 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9457   for (const auto &ArgIdx : enumerate(Args)) {
9458     MVT ArgVT = ArgIdx.value().VT;
9459     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9460       return ArgIdx.index();
9461   }
9462   return None;
9463 }
9464 
9465 void RISCVTargetLowering::analyzeInputArgs(
9466     MachineFunction &MF, CCState &CCInfo,
9467     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9468     RISCVCCAssignFn Fn) const {
9469   unsigned NumArgs = Ins.size();
9470   FunctionType *FType = MF.getFunction().getFunctionType();
9471 
9472   Optional<unsigned> FirstMaskArgument;
9473   if (Subtarget.hasVInstructions())
9474     FirstMaskArgument = preAssignMask(Ins);
9475 
9476   for (unsigned i = 0; i != NumArgs; ++i) {
9477     MVT ArgVT = Ins[i].VT;
9478     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9479 
9480     Type *ArgTy = nullptr;
9481     if (IsRet)
9482       ArgTy = FType->getReturnType();
9483     else if (Ins[i].isOrigArg())
9484       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9485 
9486     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9487     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9488            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9489            FirstMaskArgument)) {
9490       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9491                         << EVT(ArgVT).getEVTString() << '\n');
9492       llvm_unreachable(nullptr);
9493     }
9494   }
9495 }
9496 
9497 void RISCVTargetLowering::analyzeOutputArgs(
9498     MachineFunction &MF, CCState &CCInfo,
9499     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9500     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9501   unsigned NumArgs = Outs.size();
9502 
9503   Optional<unsigned> FirstMaskArgument;
9504   if (Subtarget.hasVInstructions())
9505     FirstMaskArgument = preAssignMask(Outs);
9506 
9507   for (unsigned i = 0; i != NumArgs; i++) {
9508     MVT ArgVT = Outs[i].VT;
9509     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9510     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9511 
9512     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9513     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9514            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9515            FirstMaskArgument)) {
9516       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9517                         << EVT(ArgVT).getEVTString() << "\n");
9518       llvm_unreachable(nullptr);
9519     }
9520   }
9521 }
9522 
9523 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9524 // values.
9525 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9526                                    const CCValAssign &VA, const SDLoc &DL,
9527                                    const RISCVSubtarget &Subtarget) {
9528   switch (VA.getLocInfo()) {
9529   default:
9530     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9531   case CCValAssign::Full:
9532     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9533       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9534     break;
9535   case CCValAssign::BCvt:
9536     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9537       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9538     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9539       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9540     else
9541       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9542     break;
9543   }
9544   return Val;
9545 }
9546 
9547 // The caller is responsible for loading the full value if the argument is
9548 // passed with CCValAssign::Indirect.
9549 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9550                                 const CCValAssign &VA, const SDLoc &DL,
9551                                 const RISCVTargetLowering &TLI) {
9552   MachineFunction &MF = DAG.getMachineFunction();
9553   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9554   EVT LocVT = VA.getLocVT();
9555   SDValue Val;
9556   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9557   Register VReg = RegInfo.createVirtualRegister(RC);
9558   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9559   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9560 
9561   if (VA.getLocInfo() == CCValAssign::Indirect)
9562     return Val;
9563 
9564   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9565 }
9566 
9567 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9568                                    const CCValAssign &VA, const SDLoc &DL,
9569                                    const RISCVSubtarget &Subtarget) {
9570   EVT LocVT = VA.getLocVT();
9571 
9572   switch (VA.getLocInfo()) {
9573   default:
9574     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9575   case CCValAssign::Full:
9576     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9577       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9578     break;
9579   case CCValAssign::BCvt:
9580     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9581       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9582     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9583       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9584     else
9585       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9586     break;
9587   }
9588   return Val;
9589 }
9590 
9591 // The caller is responsible for loading the full value if the argument is
9592 // passed with CCValAssign::Indirect.
9593 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9594                                 const CCValAssign &VA, const SDLoc &DL) {
9595   MachineFunction &MF = DAG.getMachineFunction();
9596   MachineFrameInfo &MFI = MF.getFrameInfo();
9597   EVT LocVT = VA.getLocVT();
9598   EVT ValVT = VA.getValVT();
9599   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9600   if (ValVT.isScalableVector()) {
9601     // When the value is a scalable vector, we save the pointer which points to
9602     // the scalable vector value in the stack. The ValVT will be the pointer
9603     // type, instead of the scalable vector type.
9604     ValVT = LocVT;
9605   }
9606   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9607                                  /*IsImmutable=*/true);
9608   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9609   SDValue Val;
9610 
9611   ISD::LoadExtType ExtType;
9612   switch (VA.getLocInfo()) {
9613   default:
9614     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9615   case CCValAssign::Full:
9616   case CCValAssign::Indirect:
9617   case CCValAssign::BCvt:
9618     ExtType = ISD::NON_EXTLOAD;
9619     break;
9620   }
9621   Val = DAG.getExtLoad(
9622       ExtType, DL, LocVT, Chain, FIN,
9623       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9624   return Val;
9625 }
9626 
9627 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9628                                        const CCValAssign &VA, const SDLoc &DL) {
9629   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9630          "Unexpected VA");
9631   MachineFunction &MF = DAG.getMachineFunction();
9632   MachineFrameInfo &MFI = MF.getFrameInfo();
9633   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9634 
9635   if (VA.isMemLoc()) {
9636     // f64 is passed on the stack.
9637     int FI =
9638         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9639     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9640     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9641                        MachinePointerInfo::getFixedStack(MF, FI));
9642   }
9643 
9644   assert(VA.isRegLoc() && "Expected register VA assignment");
9645 
9646   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9647   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9648   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9649   SDValue Hi;
9650   if (VA.getLocReg() == RISCV::X17) {
9651     // Second half of f64 is passed on the stack.
9652     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9653     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9654     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9655                      MachinePointerInfo::getFixedStack(MF, FI));
9656   } else {
9657     // Second half of f64 is passed in another GPR.
9658     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9659     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9660     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9661   }
9662   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9663 }
9664 
9665 // FastCC has less than 1% performance improvement for some particular
9666 // benchmark. But theoretically, it may has benenfit for some cases.
9667 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9668                             unsigned ValNo, MVT ValVT, MVT LocVT,
9669                             CCValAssign::LocInfo LocInfo,
9670                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9671                             bool IsFixed, bool IsRet, Type *OrigTy,
9672                             const RISCVTargetLowering &TLI,
9673                             Optional<unsigned> FirstMaskArgument) {
9674 
9675   // X5 and X6 might be used for save-restore libcall.
9676   static const MCPhysReg GPRList[] = {
9677       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9678       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9679       RISCV::X29, RISCV::X30, RISCV::X31};
9680 
9681   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9682     if (unsigned Reg = State.AllocateReg(GPRList)) {
9683       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9684       return false;
9685     }
9686   }
9687 
9688   if (LocVT == MVT::f16) {
9689     static const MCPhysReg FPR16List[] = {
9690         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9691         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9692         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9693         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9694     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9695       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9696       return false;
9697     }
9698   }
9699 
9700   if (LocVT == MVT::f32) {
9701     static const MCPhysReg FPR32List[] = {
9702         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9703         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9704         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9705         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9706     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9707       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9708       return false;
9709     }
9710   }
9711 
9712   if (LocVT == MVT::f64) {
9713     static const MCPhysReg FPR64List[] = {
9714         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9715         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9716         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9717         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9718     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9719       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9720       return false;
9721     }
9722   }
9723 
9724   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9725     unsigned Offset4 = State.AllocateStack(4, Align(4));
9726     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9727     return false;
9728   }
9729 
9730   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9731     unsigned Offset5 = State.AllocateStack(8, Align(8));
9732     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9733     return false;
9734   }
9735 
9736   if (LocVT.isVector()) {
9737     if (unsigned Reg =
9738             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9739       // Fixed-length vectors are located in the corresponding scalable-vector
9740       // container types.
9741       if (ValVT.isFixedLengthVector())
9742         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9743       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9744     } else {
9745       // Try and pass the address via a "fast" GPR.
9746       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9747         LocInfo = CCValAssign::Indirect;
9748         LocVT = TLI.getSubtarget().getXLenVT();
9749         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9750       } else if (ValVT.isFixedLengthVector()) {
9751         auto StackAlign =
9752             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9753         unsigned StackOffset =
9754             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9755         State.addLoc(
9756             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9757       } else {
9758         // Can't pass scalable vectors on the stack.
9759         return true;
9760       }
9761     }
9762 
9763     return false;
9764   }
9765 
9766   return true; // CC didn't match.
9767 }
9768 
9769 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9770                          CCValAssign::LocInfo LocInfo,
9771                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9772 
9773   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9774     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9775     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9776     static const MCPhysReg GPRList[] = {
9777         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9778         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9779     if (unsigned Reg = State.AllocateReg(GPRList)) {
9780       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9781       return false;
9782     }
9783   }
9784 
9785   if (LocVT == MVT::f32) {
9786     // Pass in STG registers: F1, ..., F6
9787     //                        fs0 ... fs5
9788     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9789                                           RISCV::F18_F, RISCV::F19_F,
9790                                           RISCV::F20_F, RISCV::F21_F};
9791     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9792       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9793       return false;
9794     }
9795   }
9796 
9797   if (LocVT == MVT::f64) {
9798     // Pass in STG registers: D1, ..., D6
9799     //                        fs6 ... fs11
9800     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9801                                           RISCV::F24_D, RISCV::F25_D,
9802                                           RISCV::F26_D, RISCV::F27_D};
9803     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9804       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9805       return false;
9806     }
9807   }
9808 
9809   report_fatal_error("No registers left in GHC calling convention");
9810   return true;
9811 }
9812 
9813 // Transform physical registers into virtual registers.
9814 SDValue RISCVTargetLowering::LowerFormalArguments(
9815     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9816     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9817     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9818 
9819   MachineFunction &MF = DAG.getMachineFunction();
9820 
9821   switch (CallConv) {
9822   default:
9823     report_fatal_error("Unsupported calling convention");
9824   case CallingConv::C:
9825   case CallingConv::Fast:
9826     break;
9827   case CallingConv::GHC:
9828     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9829         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9830       report_fatal_error(
9831         "GHC calling convention requires the F and D instruction set extensions");
9832   }
9833 
9834   const Function &Func = MF.getFunction();
9835   if (Func.hasFnAttribute("interrupt")) {
9836     if (!Func.arg_empty())
9837       report_fatal_error(
9838         "Functions with the interrupt attribute cannot have arguments!");
9839 
9840     StringRef Kind =
9841       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9842 
9843     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9844       report_fatal_error(
9845         "Function interrupt attribute argument not supported!");
9846   }
9847 
9848   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9849   MVT XLenVT = Subtarget.getXLenVT();
9850   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9851   // Used with vargs to acumulate store chains.
9852   std::vector<SDValue> OutChains;
9853 
9854   // Assign locations to all of the incoming arguments.
9855   SmallVector<CCValAssign, 16> ArgLocs;
9856   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9857 
9858   if (CallConv == CallingConv::GHC)
9859     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9860   else
9861     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9862                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9863                                                    : CC_RISCV);
9864 
9865   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9866     CCValAssign &VA = ArgLocs[i];
9867     SDValue ArgValue;
9868     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9869     // case.
9870     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9871       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9872     else if (VA.isRegLoc())
9873       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9874     else
9875       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9876 
9877     if (VA.getLocInfo() == CCValAssign::Indirect) {
9878       // If the original argument was split and passed by reference (e.g. i128
9879       // on RV32), we need to load all parts of it here (using the same
9880       // address). Vectors may be partly split to registers and partly to the
9881       // stack, in which case the base address is partly offset and subsequent
9882       // stores are relative to that.
9883       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9884                                    MachinePointerInfo()));
9885       unsigned ArgIndex = Ins[i].OrigArgIndex;
9886       unsigned ArgPartOffset = Ins[i].PartOffset;
9887       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9888       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9889         CCValAssign &PartVA = ArgLocs[i + 1];
9890         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9891         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9892         if (PartVA.getValVT().isScalableVector())
9893           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9894         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9895         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9896                                      MachinePointerInfo()));
9897         ++i;
9898       }
9899       continue;
9900     }
9901     InVals.push_back(ArgValue);
9902   }
9903 
9904   if (IsVarArg) {
9905     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9906     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9907     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9908     MachineFrameInfo &MFI = MF.getFrameInfo();
9909     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9910     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9911 
9912     // Offset of the first variable argument from stack pointer, and size of
9913     // the vararg save area. For now, the varargs save area is either zero or
9914     // large enough to hold a0-a7.
9915     int VaArgOffset, VarArgsSaveSize;
9916 
9917     // If all registers are allocated, then all varargs must be passed on the
9918     // stack and we don't need to save any argregs.
9919     if (ArgRegs.size() == Idx) {
9920       VaArgOffset = CCInfo.getNextStackOffset();
9921       VarArgsSaveSize = 0;
9922     } else {
9923       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9924       VaArgOffset = -VarArgsSaveSize;
9925     }
9926 
9927     // Record the frame index of the first variable argument
9928     // which is a value necessary to VASTART.
9929     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9930     RVFI->setVarArgsFrameIndex(FI);
9931 
9932     // If saving an odd number of registers then create an extra stack slot to
9933     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9934     // offsets to even-numbered registered remain 2*XLEN-aligned.
9935     if (Idx % 2) {
9936       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9937       VarArgsSaveSize += XLenInBytes;
9938     }
9939 
9940     // Copy the integer registers that may have been used for passing varargs
9941     // to the vararg save area.
9942     for (unsigned I = Idx; I < ArgRegs.size();
9943          ++I, VaArgOffset += XLenInBytes) {
9944       const Register Reg = RegInfo.createVirtualRegister(RC);
9945       RegInfo.addLiveIn(ArgRegs[I], Reg);
9946       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9947       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9948       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9949       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9950                                    MachinePointerInfo::getFixedStack(MF, FI));
9951       cast<StoreSDNode>(Store.getNode())
9952           ->getMemOperand()
9953           ->setValue((Value *)nullptr);
9954       OutChains.push_back(Store);
9955     }
9956     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9957   }
9958 
9959   // All stores are grouped in one node to allow the matching between
9960   // the size of Ins and InVals. This only happens for vararg functions.
9961   if (!OutChains.empty()) {
9962     OutChains.push_back(Chain);
9963     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9964   }
9965 
9966   return Chain;
9967 }
9968 
9969 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9970 /// for tail call optimization.
9971 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9972 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9973     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9974     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9975 
9976   auto &Callee = CLI.Callee;
9977   auto CalleeCC = CLI.CallConv;
9978   auto &Outs = CLI.Outs;
9979   auto &Caller = MF.getFunction();
9980   auto CallerCC = Caller.getCallingConv();
9981 
9982   // Exception-handling functions need a special set of instructions to
9983   // indicate a return to the hardware. Tail-calling another function would
9984   // probably break this.
9985   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9986   // should be expanded as new function attributes are introduced.
9987   if (Caller.hasFnAttribute("interrupt"))
9988     return false;
9989 
9990   // Do not tail call opt if the stack is used to pass parameters.
9991   if (CCInfo.getNextStackOffset() != 0)
9992     return false;
9993 
9994   // Do not tail call opt if any parameters need to be passed indirectly.
9995   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9996   // passed indirectly. So the address of the value will be passed in a
9997   // register, or if not available, then the address is put on the stack. In
9998   // order to pass indirectly, space on the stack often needs to be allocated
9999   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10000   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10001   // are passed CCValAssign::Indirect.
10002   for (auto &VA : ArgLocs)
10003     if (VA.getLocInfo() == CCValAssign::Indirect)
10004       return false;
10005 
10006   // Do not tail call opt if either caller or callee uses struct return
10007   // semantics.
10008   auto IsCallerStructRet = Caller.hasStructRetAttr();
10009   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10010   if (IsCallerStructRet || IsCalleeStructRet)
10011     return false;
10012 
10013   // Externally-defined functions with weak linkage should not be
10014   // tail-called. The behaviour of branch instructions in this situation (as
10015   // used for tail calls) is implementation-defined, so we cannot rely on the
10016   // linker replacing the tail call with a return.
10017   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10018     const GlobalValue *GV = G->getGlobal();
10019     if (GV->hasExternalWeakLinkage())
10020       return false;
10021   }
10022 
10023   // The callee has to preserve all registers the caller needs to preserve.
10024   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10025   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10026   if (CalleeCC != CallerCC) {
10027     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10028     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10029       return false;
10030   }
10031 
10032   // Byval parameters hand the function a pointer directly into the stack area
10033   // we want to reuse during a tail call. Working around this *is* possible
10034   // but less efficient and uglier in LowerCall.
10035   for (auto &Arg : Outs)
10036     if (Arg.Flags.isByVal())
10037       return false;
10038 
10039   return true;
10040 }
10041 
10042 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10043   return DAG.getDataLayout().getPrefTypeAlign(
10044       VT.getTypeForEVT(*DAG.getContext()));
10045 }
10046 
10047 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10048 // and output parameter nodes.
10049 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10050                                        SmallVectorImpl<SDValue> &InVals) const {
10051   SelectionDAG &DAG = CLI.DAG;
10052   SDLoc &DL = CLI.DL;
10053   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10054   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10055   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10056   SDValue Chain = CLI.Chain;
10057   SDValue Callee = CLI.Callee;
10058   bool &IsTailCall = CLI.IsTailCall;
10059   CallingConv::ID CallConv = CLI.CallConv;
10060   bool IsVarArg = CLI.IsVarArg;
10061   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10062   MVT XLenVT = Subtarget.getXLenVT();
10063 
10064   MachineFunction &MF = DAG.getMachineFunction();
10065 
10066   // Analyze the operands of the call, assigning locations to each operand.
10067   SmallVector<CCValAssign, 16> ArgLocs;
10068   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10069 
10070   if (CallConv == CallingConv::GHC)
10071     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10072   else
10073     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10074                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10075                                                     : CC_RISCV);
10076 
10077   // Check if it's really possible to do a tail call.
10078   if (IsTailCall)
10079     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10080 
10081   if (IsTailCall)
10082     ++NumTailCalls;
10083   else if (CLI.CB && CLI.CB->isMustTailCall())
10084     report_fatal_error("failed to perform tail call elimination on a call "
10085                        "site marked musttail");
10086 
10087   // Get a count of how many bytes are to be pushed on the stack.
10088   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10089 
10090   // Create local copies for byval args
10091   SmallVector<SDValue, 8> ByValArgs;
10092   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10093     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10094     if (!Flags.isByVal())
10095       continue;
10096 
10097     SDValue Arg = OutVals[i];
10098     unsigned Size = Flags.getByValSize();
10099     Align Alignment = Flags.getNonZeroByValAlign();
10100 
10101     int FI =
10102         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10103     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10104     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10105 
10106     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10107                           /*IsVolatile=*/false,
10108                           /*AlwaysInline=*/false, IsTailCall,
10109                           MachinePointerInfo(), MachinePointerInfo());
10110     ByValArgs.push_back(FIPtr);
10111   }
10112 
10113   if (!IsTailCall)
10114     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10115 
10116   // Copy argument values to their designated locations.
10117   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10118   SmallVector<SDValue, 8> MemOpChains;
10119   SDValue StackPtr;
10120   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10121     CCValAssign &VA = ArgLocs[i];
10122     SDValue ArgValue = OutVals[i];
10123     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10124 
10125     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10126     bool IsF64OnRV32DSoftABI =
10127         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10128     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10129       SDValue SplitF64 = DAG.getNode(
10130           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10131       SDValue Lo = SplitF64.getValue(0);
10132       SDValue Hi = SplitF64.getValue(1);
10133 
10134       Register RegLo = VA.getLocReg();
10135       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10136 
10137       if (RegLo == RISCV::X17) {
10138         // Second half of f64 is passed on the stack.
10139         // Work out the address of the stack slot.
10140         if (!StackPtr.getNode())
10141           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10142         // Emit the store.
10143         MemOpChains.push_back(
10144             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10145       } else {
10146         // Second half of f64 is passed in another GPR.
10147         assert(RegLo < RISCV::X31 && "Invalid register pair");
10148         Register RegHigh = RegLo + 1;
10149         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10150       }
10151       continue;
10152     }
10153 
10154     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10155     // as any other MemLoc.
10156 
10157     // Promote the value if needed.
10158     // For now, only handle fully promoted and indirect arguments.
10159     if (VA.getLocInfo() == CCValAssign::Indirect) {
10160       // Store the argument in a stack slot and pass its address.
10161       Align StackAlign =
10162           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10163                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10164       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10165       // If the original argument was split (e.g. i128), we need
10166       // to store the required parts of it here (and pass just one address).
10167       // Vectors may be partly split to registers and partly to the stack, in
10168       // which case the base address is partly offset and subsequent stores are
10169       // relative to that.
10170       unsigned ArgIndex = Outs[i].OrigArgIndex;
10171       unsigned ArgPartOffset = Outs[i].PartOffset;
10172       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10173       // Calculate the total size to store. We don't have access to what we're
10174       // actually storing other than performing the loop and collecting the
10175       // info.
10176       SmallVector<std::pair<SDValue, SDValue>> Parts;
10177       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10178         SDValue PartValue = OutVals[i + 1];
10179         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10180         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10181         EVT PartVT = PartValue.getValueType();
10182         if (PartVT.isScalableVector())
10183           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10184         StoredSize += PartVT.getStoreSize();
10185         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10186         Parts.push_back(std::make_pair(PartValue, Offset));
10187         ++i;
10188       }
10189       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10190       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10191       MemOpChains.push_back(
10192           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10193                        MachinePointerInfo::getFixedStack(MF, FI)));
10194       for (const auto &Part : Parts) {
10195         SDValue PartValue = Part.first;
10196         SDValue PartOffset = Part.second;
10197         SDValue Address =
10198             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10199         MemOpChains.push_back(
10200             DAG.getStore(Chain, DL, PartValue, Address,
10201                          MachinePointerInfo::getFixedStack(MF, FI)));
10202       }
10203       ArgValue = SpillSlot;
10204     } else {
10205       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10206     }
10207 
10208     // Use local copy if it is a byval arg.
10209     if (Flags.isByVal())
10210       ArgValue = ByValArgs[j++];
10211 
10212     if (VA.isRegLoc()) {
10213       // Queue up the argument copies and emit them at the end.
10214       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10215     } else {
10216       assert(VA.isMemLoc() && "Argument not register or memory");
10217       assert(!IsTailCall && "Tail call not allowed if stack is used "
10218                             "for passing parameters");
10219 
10220       // Work out the address of the stack slot.
10221       if (!StackPtr.getNode())
10222         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10223       SDValue Address =
10224           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10225                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10226 
10227       // Emit the store.
10228       MemOpChains.push_back(
10229           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10230     }
10231   }
10232 
10233   // Join the stores, which are independent of one another.
10234   if (!MemOpChains.empty())
10235     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10236 
10237   SDValue Glue;
10238 
10239   // Build a sequence of copy-to-reg nodes, chained and glued together.
10240   for (auto &Reg : RegsToPass) {
10241     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10242     Glue = Chain.getValue(1);
10243   }
10244 
10245   // Validate that none of the argument registers have been marked as
10246   // reserved, if so report an error. Do the same for the return address if this
10247   // is not a tailcall.
10248   validateCCReservedRegs(RegsToPass, MF);
10249   if (!IsTailCall &&
10250       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10251     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10252         MF.getFunction(),
10253         "Return address register required, but has been reserved."});
10254 
10255   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10256   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10257   // split it and then direct call can be matched by PseudoCALL.
10258   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10259     const GlobalValue *GV = S->getGlobal();
10260 
10261     unsigned OpFlags = RISCVII::MO_CALL;
10262     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10263       OpFlags = RISCVII::MO_PLT;
10264 
10265     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10266   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10267     unsigned OpFlags = RISCVII::MO_CALL;
10268 
10269     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10270                                                  nullptr))
10271       OpFlags = RISCVII::MO_PLT;
10272 
10273     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10274   }
10275 
10276   // The first call operand is the chain and the second is the target address.
10277   SmallVector<SDValue, 8> Ops;
10278   Ops.push_back(Chain);
10279   Ops.push_back(Callee);
10280 
10281   // Add argument registers to the end of the list so that they are
10282   // known live into the call.
10283   for (auto &Reg : RegsToPass)
10284     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10285 
10286   if (!IsTailCall) {
10287     // Add a register mask operand representing the call-preserved registers.
10288     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10289     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10290     assert(Mask && "Missing call preserved mask for calling convention");
10291     Ops.push_back(DAG.getRegisterMask(Mask));
10292   }
10293 
10294   // Glue the call to the argument copies, if any.
10295   if (Glue.getNode())
10296     Ops.push_back(Glue);
10297 
10298   // Emit the call.
10299   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10300 
10301   if (IsTailCall) {
10302     MF.getFrameInfo().setHasTailCall();
10303     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10304   }
10305 
10306   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10307   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10308   Glue = Chain.getValue(1);
10309 
10310   // Mark the end of the call, which is glued to the call itself.
10311   Chain = DAG.getCALLSEQ_END(Chain,
10312                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10313                              DAG.getConstant(0, DL, PtrVT, true),
10314                              Glue, DL);
10315   Glue = Chain.getValue(1);
10316 
10317   // Assign locations to each value returned by this call.
10318   SmallVector<CCValAssign, 16> RVLocs;
10319   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10320   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10321 
10322   // Copy all of the result registers out of their specified physreg.
10323   for (auto &VA : RVLocs) {
10324     // Copy the value out
10325     SDValue RetValue =
10326         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10327     // Glue the RetValue to the end of the call sequence
10328     Chain = RetValue.getValue(1);
10329     Glue = RetValue.getValue(2);
10330 
10331     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10332       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10333       SDValue RetValue2 =
10334           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10335       Chain = RetValue2.getValue(1);
10336       Glue = RetValue2.getValue(2);
10337       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10338                              RetValue2);
10339     }
10340 
10341     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10342 
10343     InVals.push_back(RetValue);
10344   }
10345 
10346   return Chain;
10347 }
10348 
10349 bool RISCVTargetLowering::CanLowerReturn(
10350     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10351     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10352   SmallVector<CCValAssign, 16> RVLocs;
10353   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10354 
10355   Optional<unsigned> FirstMaskArgument;
10356   if (Subtarget.hasVInstructions())
10357     FirstMaskArgument = preAssignMask(Outs);
10358 
10359   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10360     MVT VT = Outs[i].VT;
10361     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10362     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10363     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10364                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10365                  *this, FirstMaskArgument))
10366       return false;
10367   }
10368   return true;
10369 }
10370 
10371 SDValue
10372 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10373                                  bool IsVarArg,
10374                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10375                                  const SmallVectorImpl<SDValue> &OutVals,
10376                                  const SDLoc &DL, SelectionDAG &DAG) const {
10377   const MachineFunction &MF = DAG.getMachineFunction();
10378   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10379 
10380   // Stores the assignment of the return value to a location.
10381   SmallVector<CCValAssign, 16> RVLocs;
10382 
10383   // Info about the registers and stack slot.
10384   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10385                  *DAG.getContext());
10386 
10387   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10388                     nullptr, CC_RISCV);
10389 
10390   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10391     report_fatal_error("GHC functions return void only");
10392 
10393   SDValue Glue;
10394   SmallVector<SDValue, 4> RetOps(1, Chain);
10395 
10396   // Copy the result values into the output registers.
10397   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10398     SDValue Val = OutVals[i];
10399     CCValAssign &VA = RVLocs[i];
10400     assert(VA.isRegLoc() && "Can only return in registers!");
10401 
10402     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10403       // Handle returning f64 on RV32D with a soft float ABI.
10404       assert(VA.isRegLoc() && "Expected return via registers");
10405       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10406                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10407       SDValue Lo = SplitF64.getValue(0);
10408       SDValue Hi = SplitF64.getValue(1);
10409       Register RegLo = VA.getLocReg();
10410       assert(RegLo < RISCV::X31 && "Invalid register pair");
10411       Register RegHi = RegLo + 1;
10412 
10413       if (STI.isRegisterReservedByUser(RegLo) ||
10414           STI.isRegisterReservedByUser(RegHi))
10415         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10416             MF.getFunction(),
10417             "Return value register required, but has been reserved."});
10418 
10419       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10420       Glue = Chain.getValue(1);
10421       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10422       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10423       Glue = Chain.getValue(1);
10424       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10425     } else {
10426       // Handle a 'normal' return.
10427       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10428       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10429 
10430       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10431         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10432             MF.getFunction(),
10433             "Return value register required, but has been reserved."});
10434 
10435       // Guarantee that all emitted copies are stuck together.
10436       Glue = Chain.getValue(1);
10437       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10438     }
10439   }
10440 
10441   RetOps[0] = Chain; // Update chain.
10442 
10443   // Add the glue node if we have it.
10444   if (Glue.getNode()) {
10445     RetOps.push_back(Glue);
10446   }
10447 
10448   unsigned RetOpc = RISCVISD::RET_FLAG;
10449   // Interrupt service routines use different return instructions.
10450   const Function &Func = DAG.getMachineFunction().getFunction();
10451   if (Func.hasFnAttribute("interrupt")) {
10452     if (!Func.getReturnType()->isVoidTy())
10453       report_fatal_error(
10454           "Functions with the interrupt attribute must have void return type!");
10455 
10456     MachineFunction &MF = DAG.getMachineFunction();
10457     StringRef Kind =
10458       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10459 
10460     if (Kind == "user")
10461       RetOpc = RISCVISD::URET_FLAG;
10462     else if (Kind == "supervisor")
10463       RetOpc = RISCVISD::SRET_FLAG;
10464     else
10465       RetOpc = RISCVISD::MRET_FLAG;
10466   }
10467 
10468   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10469 }
10470 
10471 void RISCVTargetLowering::validateCCReservedRegs(
10472     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10473     MachineFunction &MF) const {
10474   const Function &F = MF.getFunction();
10475   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10476 
10477   if (llvm::any_of(Regs, [&STI](auto Reg) {
10478         return STI.isRegisterReservedByUser(Reg.first);
10479       }))
10480     F.getContext().diagnose(DiagnosticInfoUnsupported{
10481         F, "Argument register required, but has been reserved."});
10482 }
10483 
10484 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10485   return CI->isTailCall();
10486 }
10487 
10488 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10489 #define NODE_NAME_CASE(NODE)                                                   \
10490   case RISCVISD::NODE:                                                         \
10491     return "RISCVISD::" #NODE;
10492   // clang-format off
10493   switch ((RISCVISD::NodeType)Opcode) {
10494   case RISCVISD::FIRST_NUMBER:
10495     break;
10496   NODE_NAME_CASE(RET_FLAG)
10497   NODE_NAME_CASE(URET_FLAG)
10498   NODE_NAME_CASE(SRET_FLAG)
10499   NODE_NAME_CASE(MRET_FLAG)
10500   NODE_NAME_CASE(CALL)
10501   NODE_NAME_CASE(SELECT_CC)
10502   NODE_NAME_CASE(BR_CC)
10503   NODE_NAME_CASE(BuildPairF64)
10504   NODE_NAME_CASE(SplitF64)
10505   NODE_NAME_CASE(TAIL)
10506   NODE_NAME_CASE(MULHSU)
10507   NODE_NAME_CASE(SLLW)
10508   NODE_NAME_CASE(SRAW)
10509   NODE_NAME_CASE(SRLW)
10510   NODE_NAME_CASE(DIVW)
10511   NODE_NAME_CASE(DIVUW)
10512   NODE_NAME_CASE(REMUW)
10513   NODE_NAME_CASE(ROLW)
10514   NODE_NAME_CASE(RORW)
10515   NODE_NAME_CASE(CLZW)
10516   NODE_NAME_CASE(CTZW)
10517   NODE_NAME_CASE(FSLW)
10518   NODE_NAME_CASE(FSRW)
10519   NODE_NAME_CASE(FSL)
10520   NODE_NAME_CASE(FSR)
10521   NODE_NAME_CASE(FMV_H_X)
10522   NODE_NAME_CASE(FMV_X_ANYEXTH)
10523   NODE_NAME_CASE(FMV_W_X_RV64)
10524   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10525   NODE_NAME_CASE(FCVT_X)
10526   NODE_NAME_CASE(FCVT_XU)
10527   NODE_NAME_CASE(FCVT_W_RV64)
10528   NODE_NAME_CASE(FCVT_WU_RV64)
10529   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10530   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10531   NODE_NAME_CASE(READ_CYCLE_WIDE)
10532   NODE_NAME_CASE(GREV)
10533   NODE_NAME_CASE(GREVW)
10534   NODE_NAME_CASE(GORC)
10535   NODE_NAME_CASE(GORCW)
10536   NODE_NAME_CASE(SHFL)
10537   NODE_NAME_CASE(SHFLW)
10538   NODE_NAME_CASE(UNSHFL)
10539   NODE_NAME_CASE(UNSHFLW)
10540   NODE_NAME_CASE(BFP)
10541   NODE_NAME_CASE(BFPW)
10542   NODE_NAME_CASE(BCOMPRESS)
10543   NODE_NAME_CASE(BCOMPRESSW)
10544   NODE_NAME_CASE(BDECOMPRESS)
10545   NODE_NAME_CASE(BDECOMPRESSW)
10546   NODE_NAME_CASE(VMV_V_X_VL)
10547   NODE_NAME_CASE(VFMV_V_F_VL)
10548   NODE_NAME_CASE(VMV_X_S)
10549   NODE_NAME_CASE(VMV_S_X_VL)
10550   NODE_NAME_CASE(VFMV_S_F_VL)
10551   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10552   NODE_NAME_CASE(READ_VLENB)
10553   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10554   NODE_NAME_CASE(VSLIDEUP_VL)
10555   NODE_NAME_CASE(VSLIDE1UP_VL)
10556   NODE_NAME_CASE(VSLIDEDOWN_VL)
10557   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10558   NODE_NAME_CASE(VID_VL)
10559   NODE_NAME_CASE(VFNCVT_ROD_VL)
10560   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10561   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10562   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10563   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10564   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10565   NODE_NAME_CASE(VECREDUCE_AND_VL)
10566   NODE_NAME_CASE(VECREDUCE_OR_VL)
10567   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10568   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10569   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10570   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10571   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10572   NODE_NAME_CASE(ADD_VL)
10573   NODE_NAME_CASE(AND_VL)
10574   NODE_NAME_CASE(MUL_VL)
10575   NODE_NAME_CASE(OR_VL)
10576   NODE_NAME_CASE(SDIV_VL)
10577   NODE_NAME_CASE(SHL_VL)
10578   NODE_NAME_CASE(SREM_VL)
10579   NODE_NAME_CASE(SRA_VL)
10580   NODE_NAME_CASE(SRL_VL)
10581   NODE_NAME_CASE(SUB_VL)
10582   NODE_NAME_CASE(UDIV_VL)
10583   NODE_NAME_CASE(UREM_VL)
10584   NODE_NAME_CASE(XOR_VL)
10585   NODE_NAME_CASE(SADDSAT_VL)
10586   NODE_NAME_CASE(UADDSAT_VL)
10587   NODE_NAME_CASE(SSUBSAT_VL)
10588   NODE_NAME_CASE(USUBSAT_VL)
10589   NODE_NAME_CASE(FADD_VL)
10590   NODE_NAME_CASE(FSUB_VL)
10591   NODE_NAME_CASE(FMUL_VL)
10592   NODE_NAME_CASE(FDIV_VL)
10593   NODE_NAME_CASE(FNEG_VL)
10594   NODE_NAME_CASE(FABS_VL)
10595   NODE_NAME_CASE(FSQRT_VL)
10596   NODE_NAME_CASE(FMA_VL)
10597   NODE_NAME_CASE(FCOPYSIGN_VL)
10598   NODE_NAME_CASE(SMIN_VL)
10599   NODE_NAME_CASE(SMAX_VL)
10600   NODE_NAME_CASE(UMIN_VL)
10601   NODE_NAME_CASE(UMAX_VL)
10602   NODE_NAME_CASE(FMINNUM_VL)
10603   NODE_NAME_CASE(FMAXNUM_VL)
10604   NODE_NAME_CASE(MULHS_VL)
10605   NODE_NAME_CASE(MULHU_VL)
10606   NODE_NAME_CASE(FP_TO_SINT_VL)
10607   NODE_NAME_CASE(FP_TO_UINT_VL)
10608   NODE_NAME_CASE(SINT_TO_FP_VL)
10609   NODE_NAME_CASE(UINT_TO_FP_VL)
10610   NODE_NAME_CASE(FP_EXTEND_VL)
10611   NODE_NAME_CASE(FP_ROUND_VL)
10612   NODE_NAME_CASE(VWMUL_VL)
10613   NODE_NAME_CASE(VWMULU_VL)
10614   NODE_NAME_CASE(VWMULSU_VL)
10615   NODE_NAME_CASE(VWADD_VL)
10616   NODE_NAME_CASE(VWADDU_VL)
10617   NODE_NAME_CASE(VWSUB_VL)
10618   NODE_NAME_CASE(VWSUBU_VL)
10619   NODE_NAME_CASE(VWADD_W_VL)
10620   NODE_NAME_CASE(VWADDU_W_VL)
10621   NODE_NAME_CASE(VWSUB_W_VL)
10622   NODE_NAME_CASE(VWSUBU_W_VL)
10623   NODE_NAME_CASE(SETCC_VL)
10624   NODE_NAME_CASE(VSELECT_VL)
10625   NODE_NAME_CASE(VP_MERGE_VL)
10626   NODE_NAME_CASE(VMAND_VL)
10627   NODE_NAME_CASE(VMOR_VL)
10628   NODE_NAME_CASE(VMXOR_VL)
10629   NODE_NAME_CASE(VMCLR_VL)
10630   NODE_NAME_CASE(VMSET_VL)
10631   NODE_NAME_CASE(VRGATHER_VX_VL)
10632   NODE_NAME_CASE(VRGATHER_VV_VL)
10633   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10634   NODE_NAME_CASE(VSEXT_VL)
10635   NODE_NAME_CASE(VZEXT_VL)
10636   NODE_NAME_CASE(VCPOP_VL)
10637   NODE_NAME_CASE(VLE_VL)
10638   NODE_NAME_CASE(VSE_VL)
10639   NODE_NAME_CASE(READ_CSR)
10640   NODE_NAME_CASE(WRITE_CSR)
10641   NODE_NAME_CASE(SWAP_CSR)
10642   }
10643   // clang-format on
10644   return nullptr;
10645 #undef NODE_NAME_CASE
10646 }
10647 
10648 /// getConstraintType - Given a constraint letter, return the type of
10649 /// constraint it is for this target.
10650 RISCVTargetLowering::ConstraintType
10651 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10652   if (Constraint.size() == 1) {
10653     switch (Constraint[0]) {
10654     default:
10655       break;
10656     case 'f':
10657       return C_RegisterClass;
10658     case 'I':
10659     case 'J':
10660     case 'K':
10661       return C_Immediate;
10662     case 'A':
10663       return C_Memory;
10664     case 'S': // A symbolic address
10665       return C_Other;
10666     }
10667   } else {
10668     if (Constraint == "vr" || Constraint == "vm")
10669       return C_RegisterClass;
10670   }
10671   return TargetLowering::getConstraintType(Constraint);
10672 }
10673 
10674 std::pair<unsigned, const TargetRegisterClass *>
10675 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10676                                                   StringRef Constraint,
10677                                                   MVT VT) const {
10678   // First, see if this is a constraint that directly corresponds to a
10679   // RISCV register class.
10680   if (Constraint.size() == 1) {
10681     switch (Constraint[0]) {
10682     case 'r':
10683       // TODO: Support fixed vectors up to XLen for P extension?
10684       if (VT.isVector())
10685         break;
10686       return std::make_pair(0U, &RISCV::GPRRegClass);
10687     case 'f':
10688       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10689         return std::make_pair(0U, &RISCV::FPR16RegClass);
10690       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10691         return std::make_pair(0U, &RISCV::FPR32RegClass);
10692       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10693         return std::make_pair(0U, &RISCV::FPR64RegClass);
10694       break;
10695     default:
10696       break;
10697     }
10698   } else if (Constraint == "vr") {
10699     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10700                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10701       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10702         return std::make_pair(0U, RC);
10703     }
10704   } else if (Constraint == "vm") {
10705     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10706       return std::make_pair(0U, &RISCV::VMV0RegClass);
10707   }
10708 
10709   // Clang will correctly decode the usage of register name aliases into their
10710   // official names. However, other frontends like `rustc` do not. This allows
10711   // users of these frontends to use the ABI names for registers in LLVM-style
10712   // register constraints.
10713   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10714                                .Case("{zero}", RISCV::X0)
10715                                .Case("{ra}", RISCV::X1)
10716                                .Case("{sp}", RISCV::X2)
10717                                .Case("{gp}", RISCV::X3)
10718                                .Case("{tp}", RISCV::X4)
10719                                .Case("{t0}", RISCV::X5)
10720                                .Case("{t1}", RISCV::X6)
10721                                .Case("{t2}", RISCV::X7)
10722                                .Cases("{s0}", "{fp}", RISCV::X8)
10723                                .Case("{s1}", RISCV::X9)
10724                                .Case("{a0}", RISCV::X10)
10725                                .Case("{a1}", RISCV::X11)
10726                                .Case("{a2}", RISCV::X12)
10727                                .Case("{a3}", RISCV::X13)
10728                                .Case("{a4}", RISCV::X14)
10729                                .Case("{a5}", RISCV::X15)
10730                                .Case("{a6}", RISCV::X16)
10731                                .Case("{a7}", RISCV::X17)
10732                                .Case("{s2}", RISCV::X18)
10733                                .Case("{s3}", RISCV::X19)
10734                                .Case("{s4}", RISCV::X20)
10735                                .Case("{s5}", RISCV::X21)
10736                                .Case("{s6}", RISCV::X22)
10737                                .Case("{s7}", RISCV::X23)
10738                                .Case("{s8}", RISCV::X24)
10739                                .Case("{s9}", RISCV::X25)
10740                                .Case("{s10}", RISCV::X26)
10741                                .Case("{s11}", RISCV::X27)
10742                                .Case("{t3}", RISCV::X28)
10743                                .Case("{t4}", RISCV::X29)
10744                                .Case("{t5}", RISCV::X30)
10745                                .Case("{t6}", RISCV::X31)
10746                                .Default(RISCV::NoRegister);
10747   if (XRegFromAlias != RISCV::NoRegister)
10748     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10749 
10750   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10751   // TableGen record rather than the AsmName to choose registers for InlineAsm
10752   // constraints, plus we want to match those names to the widest floating point
10753   // register type available, manually select floating point registers here.
10754   //
10755   // The second case is the ABI name of the register, so that frontends can also
10756   // use the ABI names in register constraint lists.
10757   if (Subtarget.hasStdExtF()) {
10758     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10759                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10760                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10761                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10762                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10763                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10764                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10765                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10766                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10767                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10768                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10769                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10770                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10771                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10772                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10773                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10774                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10775                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10776                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10777                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10778                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10779                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10780                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10781                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10782                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10783                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10784                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10785                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10786                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10787                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10788                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10789                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10790                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10791                         .Default(RISCV::NoRegister);
10792     if (FReg != RISCV::NoRegister) {
10793       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10794       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10795         unsigned RegNo = FReg - RISCV::F0_F;
10796         unsigned DReg = RISCV::F0_D + RegNo;
10797         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10798       }
10799       if (VT == MVT::f32 || VT == MVT::Other)
10800         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10801       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10802         unsigned RegNo = FReg - RISCV::F0_F;
10803         unsigned HReg = RISCV::F0_H + RegNo;
10804         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10805       }
10806     }
10807   }
10808 
10809   if (Subtarget.hasVInstructions()) {
10810     Register VReg = StringSwitch<Register>(Constraint.lower())
10811                         .Case("{v0}", RISCV::V0)
10812                         .Case("{v1}", RISCV::V1)
10813                         .Case("{v2}", RISCV::V2)
10814                         .Case("{v3}", RISCV::V3)
10815                         .Case("{v4}", RISCV::V4)
10816                         .Case("{v5}", RISCV::V5)
10817                         .Case("{v6}", RISCV::V6)
10818                         .Case("{v7}", RISCV::V7)
10819                         .Case("{v8}", RISCV::V8)
10820                         .Case("{v9}", RISCV::V9)
10821                         .Case("{v10}", RISCV::V10)
10822                         .Case("{v11}", RISCV::V11)
10823                         .Case("{v12}", RISCV::V12)
10824                         .Case("{v13}", RISCV::V13)
10825                         .Case("{v14}", RISCV::V14)
10826                         .Case("{v15}", RISCV::V15)
10827                         .Case("{v16}", RISCV::V16)
10828                         .Case("{v17}", RISCV::V17)
10829                         .Case("{v18}", RISCV::V18)
10830                         .Case("{v19}", RISCV::V19)
10831                         .Case("{v20}", RISCV::V20)
10832                         .Case("{v21}", RISCV::V21)
10833                         .Case("{v22}", RISCV::V22)
10834                         .Case("{v23}", RISCV::V23)
10835                         .Case("{v24}", RISCV::V24)
10836                         .Case("{v25}", RISCV::V25)
10837                         .Case("{v26}", RISCV::V26)
10838                         .Case("{v27}", RISCV::V27)
10839                         .Case("{v28}", RISCV::V28)
10840                         .Case("{v29}", RISCV::V29)
10841                         .Case("{v30}", RISCV::V30)
10842                         .Case("{v31}", RISCV::V31)
10843                         .Default(RISCV::NoRegister);
10844     if (VReg != RISCV::NoRegister) {
10845       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10846         return std::make_pair(VReg, &RISCV::VMRegClass);
10847       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10848         return std::make_pair(VReg, &RISCV::VRRegClass);
10849       for (const auto *RC :
10850            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10851         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10852           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10853           return std::make_pair(VReg, RC);
10854         }
10855       }
10856     }
10857   }
10858 
10859   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10860 }
10861 
10862 unsigned
10863 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10864   // Currently only support length 1 constraints.
10865   if (ConstraintCode.size() == 1) {
10866     switch (ConstraintCode[0]) {
10867     case 'A':
10868       return InlineAsm::Constraint_A;
10869     default:
10870       break;
10871     }
10872   }
10873 
10874   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10875 }
10876 
10877 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10878     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10879     SelectionDAG &DAG) const {
10880   // Currently only support length 1 constraints.
10881   if (Constraint.length() == 1) {
10882     switch (Constraint[0]) {
10883     case 'I':
10884       // Validate & create a 12-bit signed immediate operand.
10885       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10886         uint64_t CVal = C->getSExtValue();
10887         if (isInt<12>(CVal))
10888           Ops.push_back(
10889               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10890       }
10891       return;
10892     case 'J':
10893       // Validate & create an integer zero operand.
10894       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10895         if (C->getZExtValue() == 0)
10896           Ops.push_back(
10897               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10898       return;
10899     case 'K':
10900       // Validate & create a 5-bit unsigned immediate operand.
10901       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10902         uint64_t CVal = C->getZExtValue();
10903         if (isUInt<5>(CVal))
10904           Ops.push_back(
10905               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10906       }
10907       return;
10908     case 'S':
10909       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10910         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10911                                                  GA->getValueType(0)));
10912       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10913         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10914                                                 BA->getValueType(0)));
10915       }
10916       return;
10917     default:
10918       break;
10919     }
10920   }
10921   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10922 }
10923 
10924 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10925                                                    Instruction *Inst,
10926                                                    AtomicOrdering Ord) const {
10927   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10928     return Builder.CreateFence(Ord);
10929   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10930     return Builder.CreateFence(AtomicOrdering::Release);
10931   return nullptr;
10932 }
10933 
10934 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10935                                                     Instruction *Inst,
10936                                                     AtomicOrdering Ord) const {
10937   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10938     return Builder.CreateFence(AtomicOrdering::Acquire);
10939   return nullptr;
10940 }
10941 
10942 TargetLowering::AtomicExpansionKind
10943 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10944   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10945   // point operations can't be used in an lr/sc sequence without breaking the
10946   // forward-progress guarantee.
10947   if (AI->isFloatingPointOperation())
10948     return AtomicExpansionKind::CmpXChg;
10949 
10950   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10951   if (Size == 8 || Size == 16)
10952     return AtomicExpansionKind::MaskedIntrinsic;
10953   return AtomicExpansionKind::None;
10954 }
10955 
10956 static Intrinsic::ID
10957 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10958   if (XLen == 32) {
10959     switch (BinOp) {
10960     default:
10961       llvm_unreachable("Unexpected AtomicRMW BinOp");
10962     case AtomicRMWInst::Xchg:
10963       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10964     case AtomicRMWInst::Add:
10965       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10966     case AtomicRMWInst::Sub:
10967       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10968     case AtomicRMWInst::Nand:
10969       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10970     case AtomicRMWInst::Max:
10971       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10972     case AtomicRMWInst::Min:
10973       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10974     case AtomicRMWInst::UMax:
10975       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10976     case AtomicRMWInst::UMin:
10977       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10978     }
10979   }
10980 
10981   if (XLen == 64) {
10982     switch (BinOp) {
10983     default:
10984       llvm_unreachable("Unexpected AtomicRMW BinOp");
10985     case AtomicRMWInst::Xchg:
10986       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10987     case AtomicRMWInst::Add:
10988       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10989     case AtomicRMWInst::Sub:
10990       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10991     case AtomicRMWInst::Nand:
10992       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10993     case AtomicRMWInst::Max:
10994       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10995     case AtomicRMWInst::Min:
10996       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10997     case AtomicRMWInst::UMax:
10998       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10999     case AtomicRMWInst::UMin:
11000       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11001     }
11002   }
11003 
11004   llvm_unreachable("Unexpected XLen\n");
11005 }
11006 
11007 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11008     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11009     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11010   unsigned XLen = Subtarget.getXLen();
11011   Value *Ordering =
11012       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11013   Type *Tys[] = {AlignedAddr->getType()};
11014   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11015       AI->getModule(),
11016       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11017 
11018   if (XLen == 64) {
11019     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11020     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11021     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11022   }
11023 
11024   Value *Result;
11025 
11026   // Must pass the shift amount needed to sign extend the loaded value prior
11027   // to performing a signed comparison for min/max. ShiftAmt is the number of
11028   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11029   // is the number of bits to left+right shift the value in order to
11030   // sign-extend.
11031   if (AI->getOperation() == AtomicRMWInst::Min ||
11032       AI->getOperation() == AtomicRMWInst::Max) {
11033     const DataLayout &DL = AI->getModule()->getDataLayout();
11034     unsigned ValWidth =
11035         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11036     Value *SextShamt =
11037         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11038     Result = Builder.CreateCall(LrwOpScwLoop,
11039                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11040   } else {
11041     Result =
11042         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11043   }
11044 
11045   if (XLen == 64)
11046     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11047   return Result;
11048 }
11049 
11050 TargetLowering::AtomicExpansionKind
11051 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11052     AtomicCmpXchgInst *CI) const {
11053   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11054   if (Size == 8 || Size == 16)
11055     return AtomicExpansionKind::MaskedIntrinsic;
11056   return AtomicExpansionKind::None;
11057 }
11058 
11059 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11060     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11061     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11062   unsigned XLen = Subtarget.getXLen();
11063   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11064   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11065   if (XLen == 64) {
11066     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11067     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11068     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11069     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11070   }
11071   Type *Tys[] = {AlignedAddr->getType()};
11072   Function *MaskedCmpXchg =
11073       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11074   Value *Result = Builder.CreateCall(
11075       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11076   if (XLen == 64)
11077     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11078   return Result;
11079 }
11080 
11081 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11082   return false;
11083 }
11084 
11085 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11086                                                EVT VT) const {
11087   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11088     return false;
11089 
11090   switch (FPVT.getSimpleVT().SimpleTy) {
11091   case MVT::f16:
11092     return Subtarget.hasStdExtZfh();
11093   case MVT::f32:
11094     return Subtarget.hasStdExtF();
11095   case MVT::f64:
11096     return Subtarget.hasStdExtD();
11097   default:
11098     return false;
11099   }
11100 }
11101 
11102 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11103   // If we are using the small code model, we can reduce size of jump table
11104   // entry to 4 bytes.
11105   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11106       getTargetMachine().getCodeModel() == CodeModel::Small) {
11107     return MachineJumpTableInfo::EK_Custom32;
11108   }
11109   return TargetLowering::getJumpTableEncoding();
11110 }
11111 
11112 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11113     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11114     unsigned uid, MCContext &Ctx) const {
11115   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11116          getTargetMachine().getCodeModel() == CodeModel::Small);
11117   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11118 }
11119 
11120 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11121                                                      EVT VT) const {
11122   VT = VT.getScalarType();
11123 
11124   if (!VT.isSimple())
11125     return false;
11126 
11127   switch (VT.getSimpleVT().SimpleTy) {
11128   case MVT::f16:
11129     return Subtarget.hasStdExtZfh();
11130   case MVT::f32:
11131     return Subtarget.hasStdExtF();
11132   case MVT::f64:
11133     return Subtarget.hasStdExtD();
11134   default:
11135     break;
11136   }
11137 
11138   return false;
11139 }
11140 
11141 Register RISCVTargetLowering::getExceptionPointerRegister(
11142     const Constant *PersonalityFn) const {
11143   return RISCV::X10;
11144 }
11145 
11146 Register RISCVTargetLowering::getExceptionSelectorRegister(
11147     const Constant *PersonalityFn) const {
11148   return RISCV::X11;
11149 }
11150 
11151 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11152   // Return false to suppress the unnecessary extensions if the LibCall
11153   // arguments or return value is f32 type for LP64 ABI.
11154   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11155   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11156     return false;
11157 
11158   return true;
11159 }
11160 
11161 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11162   if (Subtarget.is64Bit() && Type == MVT::i32)
11163     return true;
11164 
11165   return IsSigned;
11166 }
11167 
11168 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11169                                                  SDValue C) const {
11170   // Check integral scalar types.
11171   if (VT.isScalarInteger()) {
11172     // Omit the optimization if the sub target has the M extension and the data
11173     // size exceeds XLen.
11174     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11175       return false;
11176     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11177       // Break the MUL to a SLLI and an ADD/SUB.
11178       const APInt &Imm = ConstNode->getAPIntValue();
11179       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11180           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11181         return true;
11182       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11183       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11184           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11185            (Imm - 8).isPowerOf2()))
11186         return true;
11187       // Omit the following optimization if the sub target has the M extension
11188       // and the data size >= XLen.
11189       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11190         return false;
11191       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11192       // a pair of LUI/ADDI.
11193       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11194         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11195         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11196             (1 - ImmS).isPowerOf2())
11197         return true;
11198       }
11199     }
11200   }
11201 
11202   return false;
11203 }
11204 
11205 bool RISCVTargetLowering::isMulAddWithConstProfitable(
11206     const SDValue &AddNode, const SDValue &ConstNode) const {
11207   // Let the DAGCombiner decide for vectors.
11208   EVT VT = AddNode.getValueType();
11209   if (VT.isVector())
11210     return true;
11211 
11212   // Let the DAGCombiner decide for larger types.
11213   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11214     return true;
11215 
11216   // It is worse if c1 is simm12 while c1*c2 is not.
11217   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11218   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11219   const APInt &C1 = C1Node->getAPIntValue();
11220   const APInt &C2 = C2Node->getAPIntValue();
11221   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11222     return false;
11223 
11224   // Default to true and let the DAGCombiner decide.
11225   return true;
11226 }
11227 
11228 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11229     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11230     bool *Fast) const {
11231   if (!VT.isVector())
11232     return false;
11233 
11234   EVT ElemVT = VT.getVectorElementType();
11235   if (Alignment >= ElemVT.getStoreSize()) {
11236     if (Fast)
11237       *Fast = true;
11238     return true;
11239   }
11240 
11241   return false;
11242 }
11243 
11244 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11245     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11246     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11247   bool IsABIRegCopy = CC.hasValue();
11248   EVT ValueVT = Val.getValueType();
11249   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11250     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11251     // and cast to f32.
11252     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11253     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11254     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11255                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11256     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11257     Parts[0] = Val;
11258     return true;
11259   }
11260 
11261   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11262     LLVMContext &Context = *DAG.getContext();
11263     EVT ValueEltVT = ValueVT.getVectorElementType();
11264     EVT PartEltVT = PartVT.getVectorElementType();
11265     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11266     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11267     if (PartVTBitSize % ValueVTBitSize == 0) {
11268       assert(PartVTBitSize >= ValueVTBitSize);
11269       // If the element types are different, bitcast to the same element type of
11270       // PartVT first.
11271       // Give an example here, we want copy a <vscale x 1 x i8> value to
11272       // <vscale x 4 x i16>.
11273       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11274       // subvector, then we can bitcast to <vscale x 4 x i16>.
11275       if (ValueEltVT != PartEltVT) {
11276         if (PartVTBitSize > ValueVTBitSize) {
11277           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11278           assert(Count != 0 && "The number of element should not be zero.");
11279           EVT SameEltTypeVT =
11280               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11281           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11282                             DAG.getUNDEF(SameEltTypeVT), Val,
11283                             DAG.getVectorIdxConstant(0, DL));
11284         }
11285         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11286       } else {
11287         Val =
11288             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11289                         Val, DAG.getVectorIdxConstant(0, DL));
11290       }
11291       Parts[0] = Val;
11292       return true;
11293     }
11294   }
11295   return false;
11296 }
11297 
11298 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11299     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11300     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11301   bool IsABIRegCopy = CC.hasValue();
11302   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11303     SDValue Val = Parts[0];
11304 
11305     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11306     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11307     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11308     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11309     return Val;
11310   }
11311 
11312   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11313     LLVMContext &Context = *DAG.getContext();
11314     SDValue Val = Parts[0];
11315     EVT ValueEltVT = ValueVT.getVectorElementType();
11316     EVT PartEltVT = PartVT.getVectorElementType();
11317     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11318     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11319     if (PartVTBitSize % ValueVTBitSize == 0) {
11320       assert(PartVTBitSize >= ValueVTBitSize);
11321       EVT SameEltTypeVT = ValueVT;
11322       // If the element types are different, convert it to the same element type
11323       // of PartVT.
11324       // Give an example here, we want copy a <vscale x 1 x i8> value from
11325       // <vscale x 4 x i16>.
11326       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11327       // then we can extract <vscale x 1 x i8>.
11328       if (ValueEltVT != PartEltVT) {
11329         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11330         assert(Count != 0 && "The number of element should not be zero.");
11331         SameEltTypeVT =
11332             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11333         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11334       }
11335       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11336                         DAG.getVectorIdxConstant(0, DL));
11337       return Val;
11338     }
11339   }
11340   return SDValue();
11341 }
11342 
11343 SDValue
11344 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11345                                    SelectionDAG &DAG,
11346                                    SmallVectorImpl<SDNode *> &Created) const {
11347   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11348   if (isIntDivCheap(N->getValueType(0), Attr))
11349     return SDValue(N, 0); // Lower SDIV as SDIV
11350 
11351   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11352          "Unexpected divisor!");
11353 
11354   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11355   if (!Subtarget.hasStdExtZbt())
11356     return SDValue();
11357 
11358   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11359   // Besides, more critical path instructions will be generated when dividing
11360   // by 2. So we keep using the original DAGs for these cases.
11361   unsigned Lg2 = Divisor.countTrailingZeros();
11362   if (Lg2 == 1 || Lg2 >= 12)
11363     return SDValue();
11364 
11365   // fold (sdiv X, pow2)
11366   EVT VT = N->getValueType(0);
11367   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11368     return SDValue();
11369 
11370   SDLoc DL(N);
11371   SDValue N0 = N->getOperand(0);
11372   SDValue Zero = DAG.getConstant(0, DL, VT);
11373   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11374 
11375   // Add (N0 < 0) ? Pow2 - 1 : 0;
11376   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11377   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11378   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11379 
11380   Created.push_back(Cmp.getNode());
11381   Created.push_back(Add.getNode());
11382   Created.push_back(Sel.getNode());
11383 
11384   // Divide by pow2.
11385   SDValue SRA =
11386       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11387 
11388   // If we're dividing by a positive value, we're done.  Otherwise, we must
11389   // negate the result.
11390   if (Divisor.isNonNegative())
11391     return SRA;
11392 
11393   Created.push_back(SRA.getNode());
11394   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11395 }
11396 
11397 #define GET_REGISTER_MATCHER
11398 #include "RISCVGenAsmMatcher.inc"
11399 
11400 Register
11401 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11402                                        const MachineFunction &MF) const {
11403   Register Reg = MatchRegisterAltName(RegName);
11404   if (Reg == RISCV::NoRegister)
11405     Reg = MatchRegisterName(RegName);
11406   if (Reg == RISCV::NoRegister)
11407     report_fatal_error(
11408         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11409   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11410   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11411     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11412                              StringRef(RegName) + "\"."));
11413   return Reg;
11414 }
11415 
11416 namespace llvm {
11417 namespace RISCVVIntrinsicsTable {
11418 
11419 #define GET_RISCVVIntrinsicsTable_IMPL
11420 #include "RISCVGenSearchableTables.inc"
11421 
11422 } // namespace RISCVVIntrinsicsTable
11423 
11424 } // namespace llvm
11425