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, DAG.getUNDEF(ContainerVT),
1910                               Op.getOperand(0), VL);
1911   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1912 }
1913 
1914 struct VIDSequence {
1915   int64_t StepNumerator;
1916   unsigned StepDenominator;
1917   int64_t Addend;
1918 };
1919 
1920 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1921 // to the (non-zero) step S and start value X. This can be then lowered as the
1922 // RVV sequence (VID * S) + X, for example.
1923 // The step S is represented as an integer numerator divided by a positive
1924 // denominator. Note that the implementation currently only identifies
1925 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1926 // cannot detect 2/3, for example.
1927 // Note that this method will also match potentially unappealing index
1928 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1929 // determine whether this is worth generating code for.
1930 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1931   unsigned NumElts = Op.getNumOperands();
1932   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1933   if (!Op.getValueType().isInteger())
1934     return None;
1935 
1936   Optional<unsigned> SeqStepDenom;
1937   Optional<int64_t> SeqStepNum, SeqAddend;
1938   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1939   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1940   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1941     // Assume undef elements match the sequence; we just have to be careful
1942     // when interpolating across them.
1943     if (Op.getOperand(Idx).isUndef())
1944       continue;
1945     // The BUILD_VECTOR must be all constants.
1946     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1947       return None;
1948 
1949     uint64_t Val = Op.getConstantOperandVal(Idx) &
1950                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1951 
1952     if (PrevElt) {
1953       // Calculate the step since the last non-undef element, and ensure
1954       // it's consistent across the entire sequence.
1955       unsigned IdxDiff = Idx - PrevElt->second;
1956       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1957 
1958       // A zero-value value difference means that we're somewhere in the middle
1959       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1960       // step change before evaluating the sequence.
1961       if (ValDiff != 0) {
1962         int64_t Remainder = ValDiff % IdxDiff;
1963         // Normalize the step if it's greater than 1.
1964         if (Remainder != ValDiff) {
1965           // The difference must cleanly divide the element span.
1966           if (Remainder != 0)
1967             return None;
1968           ValDiff /= IdxDiff;
1969           IdxDiff = 1;
1970         }
1971 
1972         if (!SeqStepNum)
1973           SeqStepNum = ValDiff;
1974         else if (ValDiff != SeqStepNum)
1975           return None;
1976 
1977         if (!SeqStepDenom)
1978           SeqStepDenom = IdxDiff;
1979         else if (IdxDiff != *SeqStepDenom)
1980           return None;
1981       }
1982     }
1983 
1984     // Record and/or check any addend.
1985     if (SeqStepNum && SeqStepDenom) {
1986       uint64_t ExpectedVal =
1987           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1988       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1989       if (!SeqAddend)
1990         SeqAddend = Addend;
1991       else if (SeqAddend != Addend)
1992         return None;
1993     }
1994 
1995     // Record this non-undef element for later.
1996     if (!PrevElt || PrevElt->first != Val)
1997       PrevElt = std::make_pair(Val, Idx);
1998   }
1999   // We need to have logged both a step and an addend for this to count as
2000   // a legal index sequence.
2001   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
2002     return None;
2003 
2004   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
2005 }
2006 
2007 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
2008 // and lower it as a VRGATHER_VX_VL from the source vector.
2009 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
2010                                   SelectionDAG &DAG,
2011                                   const RISCVSubtarget &Subtarget) {
2012   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2013     return SDValue();
2014   SDValue Vec = SplatVal.getOperand(0);
2015   // Only perform this optimization on vectors of the same size for simplicity.
2016   if (Vec.getValueType() != VT)
2017     return SDValue();
2018   SDValue Idx = SplatVal.getOperand(1);
2019   // The index must be a legal type.
2020   if (Idx.getValueType() != Subtarget.getXLenVT())
2021     return SDValue();
2022 
2023   MVT ContainerVT = VT;
2024   if (VT.isFixedLengthVector()) {
2025     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2026     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2027   }
2028 
2029   SDValue Mask, VL;
2030   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2031 
2032   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2033                                Idx, Mask, VL);
2034 
2035   if (!VT.isFixedLengthVector())
2036     return Gather;
2037 
2038   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2039 }
2040 
2041 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2042                                  const RISCVSubtarget &Subtarget) {
2043   MVT VT = Op.getSimpleValueType();
2044   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2045 
2046   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2047 
2048   SDLoc DL(Op);
2049   SDValue Mask, VL;
2050   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2051 
2052   MVT XLenVT = Subtarget.getXLenVT();
2053   unsigned NumElts = Op.getNumOperands();
2054 
2055   if (VT.getVectorElementType() == MVT::i1) {
2056     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2057       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2058       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2059     }
2060 
2061     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2062       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2063       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2064     }
2065 
2066     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2067     // scalar integer chunks whose bit-width depends on the number of mask
2068     // bits and XLEN.
2069     // First, determine the most appropriate scalar integer type to use. This
2070     // is at most XLenVT, but may be shrunk to a smaller vector element type
2071     // according to the size of the final vector - use i8 chunks rather than
2072     // XLenVT if we're producing a v8i1. This results in more consistent
2073     // codegen across RV32 and RV64.
2074     unsigned NumViaIntegerBits =
2075         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2076     NumViaIntegerBits = std::min(NumViaIntegerBits,
2077                                  Subtarget.getMaxELENForFixedLengthVectors());
2078     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2079       // If we have to use more than one INSERT_VECTOR_ELT then this
2080       // optimization is likely to increase code size; avoid peforming it in
2081       // such a case. We can use a load from a constant pool in this case.
2082       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2083         return SDValue();
2084       // Now we can create our integer vector type. Note that it may be larger
2085       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2086       MVT IntegerViaVecVT =
2087           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2088                            divideCeil(NumElts, NumViaIntegerBits));
2089 
2090       uint64_t Bits = 0;
2091       unsigned BitPos = 0, IntegerEltIdx = 0;
2092       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2093 
2094       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2095         // Once we accumulate enough bits to fill our scalar type, insert into
2096         // our vector and clear our accumulated data.
2097         if (I != 0 && I % NumViaIntegerBits == 0) {
2098           if (NumViaIntegerBits <= 32)
2099             Bits = SignExtend64(Bits, 32);
2100           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2101           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2102                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2103           Bits = 0;
2104           BitPos = 0;
2105           IntegerEltIdx++;
2106         }
2107         SDValue V = Op.getOperand(I);
2108         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2109         Bits |= ((uint64_t)BitValue << BitPos);
2110       }
2111 
2112       // Insert the (remaining) scalar value into position in our integer
2113       // vector type.
2114       if (NumViaIntegerBits <= 32)
2115         Bits = SignExtend64(Bits, 32);
2116       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2117       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2118                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2119 
2120       if (NumElts < NumViaIntegerBits) {
2121         // If we're producing a smaller vector than our minimum legal integer
2122         // type, bitcast to the equivalent (known-legal) mask type, and extract
2123         // our final mask.
2124         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2125         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2126         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2127                           DAG.getConstant(0, DL, XLenVT));
2128       } else {
2129         // Else we must have produced an integer type with the same size as the
2130         // mask type; bitcast for the final result.
2131         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2132         Vec = DAG.getBitcast(VT, Vec);
2133       }
2134 
2135       return Vec;
2136     }
2137 
2138     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2139     // vector type, we have a legal equivalently-sized i8 type, so we can use
2140     // that.
2141     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2142     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2143 
2144     SDValue WideVec;
2145     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2146       // For a splat, perform a scalar truncate before creating the wider
2147       // vector.
2148       assert(Splat.getValueType() == XLenVT &&
2149              "Unexpected type for i1 splat value");
2150       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2151                           DAG.getConstant(1, DL, XLenVT));
2152       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2153     } else {
2154       SmallVector<SDValue, 8> Ops(Op->op_values());
2155       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2156       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2157       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2158     }
2159 
2160     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2161   }
2162 
2163   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2164     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2165       return Gather;
2166     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2167                                         : RISCVISD::VMV_V_X_VL;
2168     Splat =
2169         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2170     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2171   }
2172 
2173   // Try and match index sequences, which we can lower to the vid instruction
2174   // with optional modifications. An all-undef vector is matched by
2175   // getSplatValue, above.
2176   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2177     int64_t StepNumerator = SimpleVID->StepNumerator;
2178     unsigned StepDenominator = SimpleVID->StepDenominator;
2179     int64_t Addend = SimpleVID->Addend;
2180 
2181     assert(StepNumerator != 0 && "Invalid step");
2182     bool Negate = false;
2183     int64_t SplatStepVal = StepNumerator;
2184     unsigned StepOpcode = ISD::MUL;
2185     if (StepNumerator != 1) {
2186       if (isPowerOf2_64(std::abs(StepNumerator))) {
2187         Negate = StepNumerator < 0;
2188         StepOpcode = ISD::SHL;
2189         SplatStepVal = Log2_64(std::abs(StepNumerator));
2190       }
2191     }
2192 
2193     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2194     // threshold since it's the immediate value many RVV instructions accept.
2195     // There is no vmul.vi instruction so ensure multiply constant can fit in
2196     // a single addi instruction.
2197     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2198          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2199         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2200       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2201       // Convert right out of the scalable type so we can use standard ISD
2202       // nodes for the rest of the computation. If we used scalable types with
2203       // these, we'd lose the fixed-length vector info and generate worse
2204       // vsetvli code.
2205       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2206       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2207           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2208         SDValue SplatStep = DAG.getSplatVector(
2209             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2210         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2211       }
2212       if (StepDenominator != 1) {
2213         SDValue SplatStep = DAG.getSplatVector(
2214             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2215         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2216       }
2217       if (Addend != 0 || Negate) {
2218         SDValue SplatAddend =
2219             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2220         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2221       }
2222       return VID;
2223     }
2224   }
2225 
2226   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2227   // when re-interpreted as a vector with a larger element type. For example,
2228   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2229   // could be instead splat as
2230   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2231   // TODO: This optimization could also work on non-constant splats, but it
2232   // would require bit-manipulation instructions to construct the splat value.
2233   SmallVector<SDValue> Sequence;
2234   unsigned EltBitSize = VT.getScalarSizeInBits();
2235   const auto *BV = cast<BuildVectorSDNode>(Op);
2236   if (VT.isInteger() && EltBitSize < 64 &&
2237       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2238       BV->getRepeatedSequence(Sequence) &&
2239       (Sequence.size() * EltBitSize) <= 64) {
2240     unsigned SeqLen = Sequence.size();
2241     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2242     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2243     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2244             ViaIntVT == MVT::i64) &&
2245            "Unexpected sequence type");
2246 
2247     unsigned EltIdx = 0;
2248     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2249     uint64_t SplatValue = 0;
2250     // Construct the amalgamated value which can be splatted as this larger
2251     // vector type.
2252     for (const auto &SeqV : Sequence) {
2253       if (!SeqV.isUndef())
2254         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2255                        << (EltIdx * EltBitSize));
2256       EltIdx++;
2257     }
2258 
2259     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2260     // achieve better constant materializion.
2261     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2262       SplatValue = SignExtend64(SplatValue, 32);
2263 
2264     // Since we can't introduce illegal i64 types at this stage, we can only
2265     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2266     // way we can use RVV instructions to splat.
2267     assert((ViaIntVT.bitsLE(XLenVT) ||
2268             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2269            "Unexpected bitcast sequence");
2270     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2271       SDValue ViaVL =
2272           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2273       MVT ViaContainerVT =
2274           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2275       SDValue Splat =
2276           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2277                       DAG.getUNDEF(ViaContainerVT),
2278                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2279       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2280       return DAG.getBitcast(VT, Splat);
2281     }
2282   }
2283 
2284   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2285   // which constitute a large proportion of the elements. In such cases we can
2286   // splat a vector with the dominant element and make up the shortfall with
2287   // INSERT_VECTOR_ELTs.
2288   // Note that this includes vectors of 2 elements by association. The
2289   // upper-most element is the "dominant" one, allowing us to use a splat to
2290   // "insert" the upper element, and an insert of the lower element at position
2291   // 0, which improves codegen.
2292   SDValue DominantValue;
2293   unsigned MostCommonCount = 0;
2294   DenseMap<SDValue, unsigned> ValueCounts;
2295   unsigned NumUndefElts =
2296       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2297 
2298   // Track the number of scalar loads we know we'd be inserting, estimated as
2299   // any non-zero floating-point constant. Other kinds of element are either
2300   // already in registers or are materialized on demand. The threshold at which
2301   // a vector load is more desirable than several scalar materializion and
2302   // vector-insertion instructions is not known.
2303   unsigned NumScalarLoads = 0;
2304 
2305   for (SDValue V : Op->op_values()) {
2306     if (V.isUndef())
2307       continue;
2308 
2309     ValueCounts.insert(std::make_pair(V, 0));
2310     unsigned &Count = ValueCounts[V];
2311 
2312     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2313       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2314 
2315     // Is this value dominant? In case of a tie, prefer the highest element as
2316     // it's cheaper to insert near the beginning of a vector than it is at the
2317     // end.
2318     if (++Count >= MostCommonCount) {
2319       DominantValue = V;
2320       MostCommonCount = Count;
2321     }
2322   }
2323 
2324   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2325   unsigned NumDefElts = NumElts - NumUndefElts;
2326   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2327 
2328   // Don't perform this optimization when optimizing for size, since
2329   // materializing elements and inserting them tends to cause code bloat.
2330   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2331       ((MostCommonCount > DominantValueCountThreshold) ||
2332        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2333     // Start by splatting the most common element.
2334     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2335 
2336     DenseSet<SDValue> Processed{DominantValue};
2337     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2338     for (const auto &OpIdx : enumerate(Op->ops())) {
2339       const SDValue &V = OpIdx.value();
2340       if (V.isUndef() || !Processed.insert(V).second)
2341         continue;
2342       if (ValueCounts[V] == 1) {
2343         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2344                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2345       } else {
2346         // Blend in all instances of this value using a VSELECT, using a
2347         // mask where each bit signals whether that element is the one
2348         // we're after.
2349         SmallVector<SDValue> Ops;
2350         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2351           return DAG.getConstant(V == V1, DL, XLenVT);
2352         });
2353         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2354                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2355                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2356       }
2357     }
2358 
2359     return Vec;
2360   }
2361 
2362   return SDValue();
2363 }
2364 
2365 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2366                                    SDValue Lo, SDValue Hi, SDValue VL,
2367                                    SelectionDAG &DAG) {
2368   bool HasPassthru = Passthru && !Passthru.isUndef();
2369   if (!HasPassthru && !Passthru)
2370     Passthru = DAG.getUNDEF(VT);
2371   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2372     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2373     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2374     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2375     // node in order to try and match RVV vector/scalar instructions.
2376     if ((LoC >> 31) == HiC)
2377       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2378 
2379     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2380     // vmv.v.x whose EEW = 32 to lower it.
2381     auto *Const = dyn_cast<ConstantSDNode>(VL);
2382     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2383       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2384       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2385       // access the subtarget here now.
2386       auto InterVec = DAG.getNode(
2387           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2388                                   DAG.getRegister(RISCV::X0, MVT::i32));
2389       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2390     }
2391   }
2392 
2393   // Fall back to a stack store and stride x0 vector load.
2394   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2395                      Hi, VL);
2396 }
2397 
2398 // Called by type legalization to handle splat of i64 on RV32.
2399 // FIXME: We can optimize this when the type has sign or zero bits in one
2400 // of the halves.
2401 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2402                                    SDValue Scalar, SDValue VL,
2403                                    SelectionDAG &DAG) {
2404   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2405   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2406                            DAG.getConstant(0, DL, MVT::i32));
2407   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2408                            DAG.getConstant(1, DL, MVT::i32));
2409   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2410 }
2411 
2412 // This function lowers a splat of a scalar operand Splat with the vector
2413 // length VL. It ensures the final sequence is type legal, which is useful when
2414 // lowering a splat after type legalization.
2415 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2416                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2417                                 const RISCVSubtarget &Subtarget) {
2418   bool HasPassthru = Passthru && !Passthru.isUndef();
2419   if (!HasPassthru && !Passthru)
2420     Passthru = DAG.getUNDEF(VT);
2421   if (VT.isFloatingPoint()) {
2422     // If VL is 1, we could use vfmv.s.f.
2423     if (isOneConstant(VL))
2424       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2425     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2426   }
2427 
2428   MVT XLenVT = Subtarget.getXLenVT();
2429 
2430   // Simplest case is that the operand needs to be promoted to XLenVT.
2431   if (Scalar.getValueType().bitsLE(XLenVT)) {
2432     // If the operand is a constant, sign extend to increase our chances
2433     // of being able to use a .vi instruction. ANY_EXTEND would become a
2434     // a zero extend and the simm5 check in isel would fail.
2435     // FIXME: Should we ignore the upper bits in isel instead?
2436     unsigned ExtOpc =
2437         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2438     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2439     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2440     // If VL is 1 and the scalar value won't benefit from immediate, we could
2441     // use vmv.s.x.
2442     if (isOneConstant(VL) &&
2443         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2444       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2445     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2446   }
2447 
2448   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2449          "Unexpected scalar for splat lowering!");
2450 
2451   if (isOneConstant(VL) && isNullConstant(Scalar))
2452     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2453                        DAG.getConstant(0, DL, XLenVT), VL);
2454 
2455   // Otherwise use the more complicated splatting algorithm.
2456   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2457 }
2458 
2459 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2460                                 const RISCVSubtarget &Subtarget) {
2461   // We need to be able to widen elements to the next larger integer type.
2462   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2463     return false;
2464 
2465   int Size = Mask.size();
2466   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2467 
2468   int Srcs[] = {-1, -1};
2469   for (int i = 0; i != Size; ++i) {
2470     // Ignore undef elements.
2471     if (Mask[i] < 0)
2472       continue;
2473 
2474     // Is this an even or odd element.
2475     int Pol = i % 2;
2476 
2477     // Ensure we consistently use the same source for this element polarity.
2478     int Src = Mask[i] / Size;
2479     if (Srcs[Pol] < 0)
2480       Srcs[Pol] = Src;
2481     if (Srcs[Pol] != Src)
2482       return false;
2483 
2484     // Make sure the element within the source is appropriate for this element
2485     // in the destination.
2486     int Elt = Mask[i] % Size;
2487     if (Elt != i / 2)
2488       return false;
2489   }
2490 
2491   // We need to find a source for each polarity and they can't be the same.
2492   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2493     return false;
2494 
2495   // Swap the sources if the second source was in the even polarity.
2496   SwapSources = Srcs[0] > Srcs[1];
2497 
2498   return true;
2499 }
2500 
2501 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2502 /// and then extract the original number of elements from the rotated result.
2503 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2504 /// returned rotation amount is for a rotate right, where elements move from
2505 /// higher elements to lower elements. \p LoSrc indicates the first source
2506 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2507 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2508 /// 0 or 1 if a rotation is found.
2509 ///
2510 /// NOTE: We talk about rotate to the right which matches how bit shift and
2511 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2512 /// and the table below write vectors with the lowest elements on the left.
2513 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2514   int Size = Mask.size();
2515 
2516   // We need to detect various ways of spelling a rotation:
2517   //   [11, 12, 13, 14, 15,  0,  1,  2]
2518   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2519   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2520   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2521   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2522   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2523   int Rotation = 0;
2524   LoSrc = -1;
2525   HiSrc = -1;
2526   for (int i = 0; i != Size; ++i) {
2527     int M = Mask[i];
2528     if (M < 0)
2529       continue;
2530 
2531     // Determine where a rotate vector would have started.
2532     int StartIdx = i - (M % Size);
2533     // The identity rotation isn't interesting, stop.
2534     if (StartIdx == 0)
2535       return -1;
2536 
2537     // If we found the tail of a vector the rotation must be the missing
2538     // front. If we found the head of a vector, it must be how much of the
2539     // head.
2540     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2541 
2542     if (Rotation == 0)
2543       Rotation = CandidateRotation;
2544     else if (Rotation != CandidateRotation)
2545       // The rotations don't match, so we can't match this mask.
2546       return -1;
2547 
2548     // Compute which value this mask is pointing at.
2549     int MaskSrc = M < Size ? 0 : 1;
2550 
2551     // Compute which of the two target values this index should be assigned to.
2552     // This reflects whether the high elements are remaining or the low elemnts
2553     // are remaining.
2554     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2555 
2556     // Either set up this value if we've not encountered it before, or check
2557     // that it remains consistent.
2558     if (TargetSrc < 0)
2559       TargetSrc = MaskSrc;
2560     else if (TargetSrc != MaskSrc)
2561       // This may be a rotation, but it pulls from the inputs in some
2562       // unsupported interleaving.
2563       return -1;
2564   }
2565 
2566   // Check that we successfully analyzed the mask, and normalize the results.
2567   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2568   assert((LoSrc >= 0 || HiSrc >= 0) &&
2569          "Failed to find a rotated input vector!");
2570 
2571   return Rotation;
2572 }
2573 
2574 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2575                                    const RISCVSubtarget &Subtarget) {
2576   SDValue V1 = Op.getOperand(0);
2577   SDValue V2 = Op.getOperand(1);
2578   SDLoc DL(Op);
2579   MVT XLenVT = Subtarget.getXLenVT();
2580   MVT VT = Op.getSimpleValueType();
2581   unsigned NumElts = VT.getVectorNumElements();
2582   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2583 
2584   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2585 
2586   SDValue TrueMask, VL;
2587   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2588 
2589   if (SVN->isSplat()) {
2590     const int Lane = SVN->getSplatIndex();
2591     if (Lane >= 0) {
2592       MVT SVT = VT.getVectorElementType();
2593 
2594       // Turn splatted vector load into a strided load with an X0 stride.
2595       SDValue V = V1;
2596       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2597       // with undef.
2598       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2599       int Offset = Lane;
2600       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2601         int OpElements =
2602             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2603         V = V.getOperand(Offset / OpElements);
2604         Offset %= OpElements;
2605       }
2606 
2607       // We need to ensure the load isn't atomic or volatile.
2608       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2609         auto *Ld = cast<LoadSDNode>(V);
2610         Offset *= SVT.getStoreSize();
2611         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2612                                                    TypeSize::Fixed(Offset), DL);
2613 
2614         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2615         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2616           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2617           SDValue IntID =
2618               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2619           SDValue Ops[] = {Ld->getChain(),
2620                            IntID,
2621                            DAG.getUNDEF(ContainerVT),
2622                            NewAddr,
2623                            DAG.getRegister(RISCV::X0, XLenVT),
2624                            VL};
2625           SDValue NewLoad = DAG.getMemIntrinsicNode(
2626               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2627               DAG.getMachineFunction().getMachineMemOperand(
2628                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2629           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2630           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2631         }
2632 
2633         // Otherwise use a scalar load and splat. This will give the best
2634         // opportunity to fold a splat into the operation. ISel can turn it into
2635         // the x0 strided load if we aren't able to fold away the select.
2636         if (SVT.isFloatingPoint())
2637           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2638                           Ld->getPointerInfo().getWithOffset(Offset),
2639                           Ld->getOriginalAlign(),
2640                           Ld->getMemOperand()->getFlags());
2641         else
2642           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2643                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2644                              Ld->getOriginalAlign(),
2645                              Ld->getMemOperand()->getFlags());
2646         DAG.makeEquivalentMemoryOrdering(Ld, V);
2647 
2648         unsigned Opc =
2649             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2650         SDValue Splat =
2651             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2652         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2653       }
2654 
2655       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2656       assert(Lane < (int)NumElts && "Unexpected lane!");
2657       SDValue Gather =
2658           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2659                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2660       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2661     }
2662   }
2663 
2664   ArrayRef<int> Mask = SVN->getMask();
2665 
2666   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2667   // be undef which can be handled with a single SLIDEDOWN/UP.
2668   int LoSrc, HiSrc;
2669   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2670   if (Rotation > 0) {
2671     SDValue LoV, HiV;
2672     if (LoSrc >= 0) {
2673       LoV = LoSrc == 0 ? V1 : V2;
2674       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2675     }
2676     if (HiSrc >= 0) {
2677       HiV = HiSrc == 0 ? V1 : V2;
2678       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2679     }
2680 
2681     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2682     // to slide LoV up by (NumElts - Rotation).
2683     unsigned InvRotate = NumElts - Rotation;
2684 
2685     SDValue Res = DAG.getUNDEF(ContainerVT);
2686     if (HiV) {
2687       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2688       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2689       // causes multiple vsetvlis in some test cases such as lowering
2690       // reduce.mul
2691       SDValue DownVL = VL;
2692       if (LoV)
2693         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2694       Res =
2695           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2696                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2697     }
2698     if (LoV)
2699       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2700                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2701 
2702     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2703   }
2704 
2705   // Detect an interleave shuffle and lower to
2706   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2707   bool SwapSources;
2708   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2709     // Swap sources if needed.
2710     if (SwapSources)
2711       std::swap(V1, V2);
2712 
2713     // Extract the lower half of the vectors.
2714     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2715     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2716                      DAG.getConstant(0, DL, XLenVT));
2717     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2718                      DAG.getConstant(0, DL, XLenVT));
2719 
2720     // Double the element width and halve the number of elements in an int type.
2721     unsigned EltBits = VT.getScalarSizeInBits();
2722     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2723     MVT WideIntVT =
2724         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2725     // Convert this to a scalable vector. We need to base this on the
2726     // destination size to ensure there's always a type with a smaller LMUL.
2727     MVT WideIntContainerVT =
2728         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2729 
2730     // Convert sources to scalable vectors with the same element count as the
2731     // larger type.
2732     MVT HalfContainerVT = MVT::getVectorVT(
2733         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2734     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2735     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2736 
2737     // Cast sources to integer.
2738     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2739     MVT IntHalfVT =
2740         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2741     V1 = DAG.getBitcast(IntHalfVT, V1);
2742     V2 = DAG.getBitcast(IntHalfVT, V2);
2743 
2744     // Freeze V2 since we use it twice and we need to be sure that the add and
2745     // multiply see the same value.
2746     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2747 
2748     // Recreate TrueMask using the widened type's element count.
2749     MVT MaskVT =
2750         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2751     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2752 
2753     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2754     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2755                               V2, TrueMask, VL);
2756     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2757     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2758                                      DAG.getUNDEF(IntHalfVT),
2759                                      DAG.getAllOnesConstant(DL, XLenVT));
2760     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2761                                    V2, Multiplier, TrueMask, VL);
2762     // Add the new copies to our previous addition giving us 2^eltbits copies of
2763     // V2. This is equivalent to shifting V2 left by eltbits. This should
2764     // combine with the vwmulu.vv above to form vwmaccu.vv.
2765     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2766                       TrueMask, VL);
2767     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2768     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2769     // vector VT.
2770     ContainerVT =
2771         MVT::getVectorVT(VT.getVectorElementType(),
2772                          WideIntContainerVT.getVectorElementCount() * 2);
2773     Add = DAG.getBitcast(ContainerVT, Add);
2774     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2775   }
2776 
2777   // Detect shuffles which can be re-expressed as vector selects; these are
2778   // shuffles in which each element in the destination is taken from an element
2779   // at the corresponding index in either source vectors.
2780   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2781     int MaskIndex = MaskIdx.value();
2782     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2783   });
2784 
2785   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2786 
2787   SmallVector<SDValue> MaskVals;
2788   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2789   // merged with a second vrgather.
2790   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2791 
2792   // By default we preserve the original operand order, and use a mask to
2793   // select LHS as true and RHS as false. However, since RVV vector selects may
2794   // feature splats but only on the LHS, we may choose to invert our mask and
2795   // instead select between RHS and LHS.
2796   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2797   bool InvertMask = IsSelect == SwapOps;
2798 
2799   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2800   // half.
2801   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2802 
2803   // Now construct the mask that will be used by the vselect or blended
2804   // vrgather operation. For vrgathers, construct the appropriate indices into
2805   // each vector.
2806   for (int MaskIndex : Mask) {
2807     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2808     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2809     if (!IsSelect) {
2810       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2811       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2812                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2813                                      : DAG.getUNDEF(XLenVT));
2814       GatherIndicesRHS.push_back(
2815           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2816                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2817       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2818         ++LHSIndexCounts[MaskIndex];
2819       if (!IsLHSOrUndefIndex)
2820         ++RHSIndexCounts[MaskIndex - NumElts];
2821     }
2822   }
2823 
2824   if (SwapOps) {
2825     std::swap(V1, V2);
2826     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2827   }
2828 
2829   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2830   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2831   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2832 
2833   if (IsSelect)
2834     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2835 
2836   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2837     // On such a large vector we're unable to use i8 as the index type.
2838     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2839     // may involve vector splitting if we're already at LMUL=8, or our
2840     // user-supplied maximum fixed-length LMUL.
2841     return SDValue();
2842   }
2843 
2844   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2845   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2846   MVT IndexVT = VT.changeTypeToInteger();
2847   // Since we can't introduce illegal index types at this stage, use i16 and
2848   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2849   // than XLenVT.
2850   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2851     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2852     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2853   }
2854 
2855   MVT IndexContainerVT =
2856       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2857 
2858   SDValue Gather;
2859   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2860   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2861   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2862     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2863                               Subtarget);
2864   } else {
2865     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2866     // If only one index is used, we can use a "splat" vrgather.
2867     // TODO: We can splat the most-common index and fix-up any stragglers, if
2868     // that's beneficial.
2869     if (LHSIndexCounts.size() == 1) {
2870       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2871       Gather =
2872           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2873                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2874     } else {
2875       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2876       LHSIndices =
2877           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2878 
2879       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2880                            TrueMask, VL);
2881     }
2882   }
2883 
2884   // If a second vector operand is used by this shuffle, blend it in with an
2885   // additional vrgather.
2886   if (!V2.isUndef()) {
2887     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2888     // If only one index is used, we can use a "splat" vrgather.
2889     // TODO: We can splat the most-common index and fix-up any stragglers, if
2890     // that's beneficial.
2891     if (RHSIndexCounts.size() == 1) {
2892       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2893       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2894                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2895     } else {
2896       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2897       RHSIndices =
2898           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2899       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2900                        VL);
2901     }
2902 
2903     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2904     SelectMask =
2905         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2906 
2907     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2908                          Gather, VL);
2909   }
2910 
2911   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2912 }
2913 
2914 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2915   // Support splats for any type. These should type legalize well.
2916   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2917     return true;
2918 
2919   // Only support legal VTs for other shuffles for now.
2920   if (!isTypeLegal(VT))
2921     return false;
2922 
2923   MVT SVT = VT.getSimpleVT();
2924 
2925   bool SwapSources;
2926   int LoSrc, HiSrc;
2927   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2928          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2929 }
2930 
2931 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2932                                      SDLoc DL, SelectionDAG &DAG,
2933                                      const RISCVSubtarget &Subtarget) {
2934   if (VT.isScalableVector())
2935     return DAG.getFPExtendOrRound(Op, DL, VT);
2936   assert(VT.isFixedLengthVector() &&
2937          "Unexpected value type for RVV FP extend/round lowering");
2938   SDValue Mask, VL;
2939   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2940   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2941                         ? RISCVISD::FP_EXTEND_VL
2942                         : RISCVISD::FP_ROUND_VL;
2943   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2944 }
2945 
2946 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2947 // the exponent.
2948 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2949   MVT VT = Op.getSimpleValueType();
2950   unsigned EltSize = VT.getScalarSizeInBits();
2951   SDValue Src = Op.getOperand(0);
2952   SDLoc DL(Op);
2953 
2954   // We need a FP type that can represent the value.
2955   // TODO: Use f16 for i8 when possible?
2956   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2957   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2958 
2959   // Legal types should have been checked in the RISCVTargetLowering
2960   // constructor.
2961   // TODO: Splitting may make sense in some cases.
2962   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2963          "Expected legal float type!");
2964 
2965   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2966   // The trailing zero count is equal to log2 of this single bit value.
2967   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2968     SDValue Neg =
2969         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2970     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2971   }
2972 
2973   // We have a legal FP type, convert to it.
2974   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2975   // Bitcast to integer and shift the exponent to the LSB.
2976   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2977   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2978   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2979   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2980                               DAG.getConstant(ShiftAmt, DL, IntVT));
2981   // Truncate back to original type to allow vnsrl.
2982   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2983   // The exponent contains log2 of the value in biased form.
2984   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2985 
2986   // For trailing zeros, we just need to subtract the bias.
2987   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2988     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2989                        DAG.getConstant(ExponentBias, DL, VT));
2990 
2991   // For leading zeros, we need to remove the bias and convert from log2 to
2992   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2993   unsigned Adjust = ExponentBias + (EltSize - 1);
2994   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2995 }
2996 
2997 // While RVV has alignment restrictions, we should always be able to load as a
2998 // legal equivalently-sized byte-typed vector instead. This method is
2999 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
3000 // the load is already correctly-aligned, it returns SDValue().
3001 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
3002                                                     SelectionDAG &DAG) const {
3003   auto *Load = cast<LoadSDNode>(Op);
3004   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
3005 
3006   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3007                                      Load->getMemoryVT(),
3008                                      *Load->getMemOperand()))
3009     return SDValue();
3010 
3011   SDLoc DL(Op);
3012   MVT VT = Op.getSimpleValueType();
3013   unsigned EltSizeBits = VT.getScalarSizeInBits();
3014   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3015          "Unexpected unaligned RVV load type");
3016   MVT NewVT =
3017       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3018   assert(NewVT.isValid() &&
3019          "Expecting equally-sized RVV vector types to be legal");
3020   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3021                           Load->getPointerInfo(), Load->getOriginalAlign(),
3022                           Load->getMemOperand()->getFlags());
3023   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3024 }
3025 
3026 // While RVV has alignment restrictions, we should always be able to store as a
3027 // legal equivalently-sized byte-typed vector instead. This method is
3028 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3029 // returns SDValue() if the store is already correctly aligned.
3030 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3031                                                      SelectionDAG &DAG) const {
3032   auto *Store = cast<StoreSDNode>(Op);
3033   assert(Store && Store->getValue().getValueType().isVector() &&
3034          "Expected vector store");
3035 
3036   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3037                                      Store->getMemoryVT(),
3038                                      *Store->getMemOperand()))
3039     return SDValue();
3040 
3041   SDLoc DL(Op);
3042   SDValue StoredVal = Store->getValue();
3043   MVT VT = StoredVal.getSimpleValueType();
3044   unsigned EltSizeBits = VT.getScalarSizeInBits();
3045   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3046          "Unexpected unaligned RVV store type");
3047   MVT NewVT =
3048       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3049   assert(NewVT.isValid() &&
3050          "Expecting equally-sized RVV vector types to be legal");
3051   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3052   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3053                       Store->getPointerInfo(), Store->getOriginalAlign(),
3054                       Store->getMemOperand()->getFlags());
3055 }
3056 
3057 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3058                                             SelectionDAG &DAG) const {
3059   switch (Op.getOpcode()) {
3060   default:
3061     report_fatal_error("unimplemented operand");
3062   case ISD::GlobalAddress:
3063     return lowerGlobalAddress(Op, DAG);
3064   case ISD::BlockAddress:
3065     return lowerBlockAddress(Op, DAG);
3066   case ISD::ConstantPool:
3067     return lowerConstantPool(Op, DAG);
3068   case ISD::JumpTable:
3069     return lowerJumpTable(Op, DAG);
3070   case ISD::GlobalTLSAddress:
3071     return lowerGlobalTLSAddress(Op, DAG);
3072   case ISD::SELECT:
3073     return lowerSELECT(Op, DAG);
3074   case ISD::BRCOND:
3075     return lowerBRCOND(Op, DAG);
3076   case ISD::VASTART:
3077     return lowerVASTART(Op, DAG);
3078   case ISD::FRAMEADDR:
3079     return lowerFRAMEADDR(Op, DAG);
3080   case ISD::RETURNADDR:
3081     return lowerRETURNADDR(Op, DAG);
3082   case ISD::SHL_PARTS:
3083     return lowerShiftLeftParts(Op, DAG);
3084   case ISD::SRA_PARTS:
3085     return lowerShiftRightParts(Op, DAG, true);
3086   case ISD::SRL_PARTS:
3087     return lowerShiftRightParts(Op, DAG, false);
3088   case ISD::BITCAST: {
3089     SDLoc DL(Op);
3090     EVT VT = Op.getValueType();
3091     SDValue Op0 = Op.getOperand(0);
3092     EVT Op0VT = Op0.getValueType();
3093     MVT XLenVT = Subtarget.getXLenVT();
3094     if (VT.isFixedLengthVector()) {
3095       // We can handle fixed length vector bitcasts with a simple replacement
3096       // in isel.
3097       if (Op0VT.isFixedLengthVector())
3098         return Op;
3099       // When bitcasting from scalar to fixed-length vector, insert the scalar
3100       // into a one-element vector of the result type, and perform a vector
3101       // bitcast.
3102       if (!Op0VT.isVector()) {
3103         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3104         if (!isTypeLegal(BVT))
3105           return SDValue();
3106         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3107                                               DAG.getUNDEF(BVT), Op0,
3108                                               DAG.getConstant(0, DL, XLenVT)));
3109       }
3110       return SDValue();
3111     }
3112     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3113     // thus: bitcast the vector to a one-element vector type whose element type
3114     // is the same as the result type, and extract the first element.
3115     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3116       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3117       if (!isTypeLegal(BVT))
3118         return SDValue();
3119       SDValue BVec = DAG.getBitcast(BVT, Op0);
3120       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3121                          DAG.getConstant(0, DL, XLenVT));
3122     }
3123     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3124       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3125       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3126       return FPConv;
3127     }
3128     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3129         Subtarget.hasStdExtF()) {
3130       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3131       SDValue FPConv =
3132           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3133       return FPConv;
3134     }
3135     return SDValue();
3136   }
3137   case ISD::INTRINSIC_WO_CHAIN:
3138     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3139   case ISD::INTRINSIC_W_CHAIN:
3140     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3141   case ISD::INTRINSIC_VOID:
3142     return LowerINTRINSIC_VOID(Op, DAG);
3143   case ISD::BSWAP:
3144   case ISD::BITREVERSE: {
3145     MVT VT = Op.getSimpleValueType();
3146     SDLoc DL(Op);
3147     if (Subtarget.hasStdExtZbp()) {
3148       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3149       // Start with the maximum immediate value which is the bitwidth - 1.
3150       unsigned Imm = VT.getSizeInBits() - 1;
3151       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3152       if (Op.getOpcode() == ISD::BSWAP)
3153         Imm &= ~0x7U;
3154       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3155                          DAG.getConstant(Imm, DL, VT));
3156     }
3157     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3158     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3159     // Expand bitreverse to a bswap(rev8) followed by brev8.
3160     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3161     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3162     // as brev8 by an isel pattern.
3163     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3164                        DAG.getConstant(7, DL, VT));
3165   }
3166   case ISD::FSHL:
3167   case ISD::FSHR: {
3168     MVT VT = Op.getSimpleValueType();
3169     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3170     SDLoc DL(Op);
3171     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3172     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3173     // accidentally setting the extra bit.
3174     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3175     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3176                                 DAG.getConstant(ShAmtWidth, DL, VT));
3177     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3178     // instruction use different orders. fshl will return its first operand for
3179     // shift of zero, fshr will return its second operand. fsl and fsr both
3180     // return rs1 so the ISD nodes need to have different operand orders.
3181     // Shift amount is in rs2.
3182     SDValue Op0 = Op.getOperand(0);
3183     SDValue Op1 = Op.getOperand(1);
3184     unsigned Opc = RISCVISD::FSL;
3185     if (Op.getOpcode() == ISD::FSHR) {
3186       std::swap(Op0, Op1);
3187       Opc = RISCVISD::FSR;
3188     }
3189     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3190   }
3191   case ISD::TRUNCATE: {
3192     SDLoc DL(Op);
3193     MVT VT = Op.getSimpleValueType();
3194     // Only custom-lower vector truncates
3195     if (!VT.isVector())
3196       return Op;
3197 
3198     // Truncates to mask types are handled differently
3199     if (VT.getVectorElementType() == MVT::i1)
3200       return lowerVectorMaskTrunc(Op, DAG);
3201 
3202     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3203     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3204     // truncate by one power of two at a time.
3205     MVT DstEltVT = VT.getVectorElementType();
3206 
3207     SDValue Src = Op.getOperand(0);
3208     MVT SrcVT = Src.getSimpleValueType();
3209     MVT SrcEltVT = SrcVT.getVectorElementType();
3210 
3211     assert(DstEltVT.bitsLT(SrcEltVT) &&
3212            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3213            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3214            "Unexpected vector truncate lowering");
3215 
3216     MVT ContainerVT = SrcVT;
3217     if (SrcVT.isFixedLengthVector()) {
3218       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3219       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3220     }
3221 
3222     SDValue Result = Src;
3223     SDValue Mask, VL;
3224     std::tie(Mask, VL) =
3225         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3226     LLVMContext &Context = *DAG.getContext();
3227     const ElementCount Count = ContainerVT.getVectorElementCount();
3228     do {
3229       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3230       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3231       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3232                            Mask, VL);
3233     } while (SrcEltVT != DstEltVT);
3234 
3235     if (SrcVT.isFixedLengthVector())
3236       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3237 
3238     return Result;
3239   }
3240   case ISD::ANY_EXTEND:
3241   case ISD::ZERO_EXTEND:
3242     if (Op.getOperand(0).getValueType().isVector() &&
3243         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3244       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3245     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3246   case ISD::SIGN_EXTEND:
3247     if (Op.getOperand(0).getValueType().isVector() &&
3248         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3249       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3250     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3251   case ISD::SPLAT_VECTOR_PARTS:
3252     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3253   case ISD::INSERT_VECTOR_ELT:
3254     return lowerINSERT_VECTOR_ELT(Op, DAG);
3255   case ISD::EXTRACT_VECTOR_ELT:
3256     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3257   case ISD::VSCALE: {
3258     MVT VT = Op.getSimpleValueType();
3259     SDLoc DL(Op);
3260     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3261     // We define our scalable vector types for lmul=1 to use a 64 bit known
3262     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3263     // vscale as VLENB / 8.
3264     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3265     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3266       report_fatal_error("Support for VLEN==32 is incomplete.");
3267     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3268       // We assume VLENB is a multiple of 8. We manually choose the best shift
3269       // here because SimplifyDemandedBits isn't always able to simplify it.
3270       uint64_t Val = Op.getConstantOperandVal(0);
3271       if (isPowerOf2_64(Val)) {
3272         uint64_t Log2 = Log2_64(Val);
3273         if (Log2 < 3)
3274           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3275                              DAG.getConstant(3 - Log2, DL, VT));
3276         if (Log2 > 3)
3277           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3278                              DAG.getConstant(Log2 - 3, DL, VT));
3279         return VLENB;
3280       }
3281       // If the multiplier is a multiple of 8, scale it down to avoid needing
3282       // to shift the VLENB value.
3283       if ((Val % 8) == 0)
3284         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3285                            DAG.getConstant(Val / 8, DL, VT));
3286     }
3287 
3288     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3289                                  DAG.getConstant(3, DL, VT));
3290     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3291   }
3292   case ISD::FPOWI: {
3293     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3294     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3295     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3296         Op.getOperand(1).getValueType() == MVT::i32) {
3297       SDLoc DL(Op);
3298       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3299       SDValue Powi =
3300           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3301       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3302                          DAG.getIntPtrConstant(0, DL));
3303     }
3304     return SDValue();
3305   }
3306   case ISD::FP_EXTEND: {
3307     // RVV can only do fp_extend to types double the size as the source. We
3308     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3309     // via f32.
3310     SDLoc DL(Op);
3311     MVT VT = Op.getSimpleValueType();
3312     SDValue Src = Op.getOperand(0);
3313     MVT SrcVT = Src.getSimpleValueType();
3314 
3315     // Prepare any fixed-length vector operands.
3316     MVT ContainerVT = VT;
3317     if (SrcVT.isFixedLengthVector()) {
3318       ContainerVT = getContainerForFixedLengthVector(VT);
3319       MVT SrcContainerVT =
3320           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3321       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3322     }
3323 
3324     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3325         SrcVT.getVectorElementType() != MVT::f16) {
3326       // For scalable vectors, we only need to close the gap between
3327       // vXf16->vXf64.
3328       if (!VT.isFixedLengthVector())
3329         return Op;
3330       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3331       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3332       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3333     }
3334 
3335     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3336     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3337     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3338         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3339 
3340     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3341                                            DL, DAG, Subtarget);
3342     if (VT.isFixedLengthVector())
3343       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3344     return Extend;
3345   }
3346   case ISD::FP_ROUND: {
3347     // RVV can only do fp_round to types half the size as the source. We
3348     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3349     // conversion instruction.
3350     SDLoc DL(Op);
3351     MVT VT = Op.getSimpleValueType();
3352     SDValue Src = Op.getOperand(0);
3353     MVT SrcVT = Src.getSimpleValueType();
3354 
3355     // Prepare any fixed-length vector operands.
3356     MVT ContainerVT = VT;
3357     if (VT.isFixedLengthVector()) {
3358       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3359       ContainerVT =
3360           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3361       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3362     }
3363 
3364     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3365         SrcVT.getVectorElementType() != MVT::f64) {
3366       // For scalable vectors, we only need to close the gap between
3367       // vXf64<->vXf16.
3368       if (!VT.isFixedLengthVector())
3369         return Op;
3370       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3371       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3372       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3373     }
3374 
3375     SDValue Mask, VL;
3376     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3377 
3378     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3379     SDValue IntermediateRound =
3380         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3381     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3382                                           DL, DAG, Subtarget);
3383 
3384     if (VT.isFixedLengthVector())
3385       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3386     return Round;
3387   }
3388   case ISD::FP_TO_SINT:
3389   case ISD::FP_TO_UINT:
3390   case ISD::SINT_TO_FP:
3391   case ISD::UINT_TO_FP: {
3392     // RVV can only do fp<->int conversions to types half/double the size as
3393     // the source. We custom-lower any conversions that do two hops into
3394     // sequences.
3395     MVT VT = Op.getSimpleValueType();
3396     if (!VT.isVector())
3397       return Op;
3398     SDLoc DL(Op);
3399     SDValue Src = Op.getOperand(0);
3400     MVT EltVT = VT.getVectorElementType();
3401     MVT SrcVT = Src.getSimpleValueType();
3402     MVT SrcEltVT = SrcVT.getVectorElementType();
3403     unsigned EltSize = EltVT.getSizeInBits();
3404     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3405     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3406            "Unexpected vector element types");
3407 
3408     bool IsInt2FP = SrcEltVT.isInteger();
3409     // Widening conversions
3410     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3411       if (IsInt2FP) {
3412         // Do a regular integer sign/zero extension then convert to float.
3413         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3414                                       VT.getVectorElementCount());
3415         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3416                                  ? ISD::ZERO_EXTEND
3417                                  : ISD::SIGN_EXTEND;
3418         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3419         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3420       }
3421       // FP2Int
3422       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3423       // Do one doubling fp_extend then complete the operation by converting
3424       // to int.
3425       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3426       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3427       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3428     }
3429 
3430     // Narrowing conversions
3431     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3432       if (IsInt2FP) {
3433         // One narrowing int_to_fp, then an fp_round.
3434         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3435         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3436         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3437         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3438       }
3439       // FP2Int
3440       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3441       // representable by the integer, the result is poison.
3442       MVT IVecVT =
3443           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3444                            VT.getVectorElementCount());
3445       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3446       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3447     }
3448 
3449     // Scalable vectors can exit here. Patterns will handle equally-sized
3450     // conversions halving/doubling ones.
3451     if (!VT.isFixedLengthVector())
3452       return Op;
3453 
3454     // For fixed-length vectors we lower to a custom "VL" node.
3455     unsigned RVVOpc = 0;
3456     switch (Op.getOpcode()) {
3457     default:
3458       llvm_unreachable("Impossible opcode");
3459     case ISD::FP_TO_SINT:
3460       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3461       break;
3462     case ISD::FP_TO_UINT:
3463       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3464       break;
3465     case ISD::SINT_TO_FP:
3466       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3467       break;
3468     case ISD::UINT_TO_FP:
3469       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3470       break;
3471     }
3472 
3473     MVT ContainerVT, SrcContainerVT;
3474     // Derive the reference container type from the larger vector type.
3475     if (SrcEltSize > EltSize) {
3476       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3477       ContainerVT =
3478           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3479     } else {
3480       ContainerVT = getContainerForFixedLengthVector(VT);
3481       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3482     }
3483 
3484     SDValue Mask, VL;
3485     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3486 
3487     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3488     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3489     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3490   }
3491   case ISD::FP_TO_SINT_SAT:
3492   case ISD::FP_TO_UINT_SAT:
3493     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3494   case ISD::FTRUNC:
3495   case ISD::FCEIL:
3496   case ISD::FFLOOR:
3497     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3498   case ISD::FROUND:
3499     return lowerFROUND(Op, DAG);
3500   case ISD::VECREDUCE_ADD:
3501   case ISD::VECREDUCE_UMAX:
3502   case ISD::VECREDUCE_SMAX:
3503   case ISD::VECREDUCE_UMIN:
3504   case ISD::VECREDUCE_SMIN:
3505     return lowerVECREDUCE(Op, DAG);
3506   case ISD::VECREDUCE_AND:
3507   case ISD::VECREDUCE_OR:
3508   case ISD::VECREDUCE_XOR:
3509     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3510       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3511     return lowerVECREDUCE(Op, DAG);
3512   case ISD::VECREDUCE_FADD:
3513   case ISD::VECREDUCE_SEQ_FADD:
3514   case ISD::VECREDUCE_FMIN:
3515   case ISD::VECREDUCE_FMAX:
3516     return lowerFPVECREDUCE(Op, DAG);
3517   case ISD::VP_REDUCE_ADD:
3518   case ISD::VP_REDUCE_UMAX:
3519   case ISD::VP_REDUCE_SMAX:
3520   case ISD::VP_REDUCE_UMIN:
3521   case ISD::VP_REDUCE_SMIN:
3522   case ISD::VP_REDUCE_FADD:
3523   case ISD::VP_REDUCE_SEQ_FADD:
3524   case ISD::VP_REDUCE_FMIN:
3525   case ISD::VP_REDUCE_FMAX:
3526     return lowerVPREDUCE(Op, DAG);
3527   case ISD::VP_REDUCE_AND:
3528   case ISD::VP_REDUCE_OR:
3529   case ISD::VP_REDUCE_XOR:
3530     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3531       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3532     return lowerVPREDUCE(Op, DAG);
3533   case ISD::INSERT_SUBVECTOR:
3534     return lowerINSERT_SUBVECTOR(Op, DAG);
3535   case ISD::EXTRACT_SUBVECTOR:
3536     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3537   case ISD::STEP_VECTOR:
3538     return lowerSTEP_VECTOR(Op, DAG);
3539   case ISD::VECTOR_REVERSE:
3540     return lowerVECTOR_REVERSE(Op, DAG);
3541   case ISD::BUILD_VECTOR:
3542     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3543   case ISD::SPLAT_VECTOR:
3544     if (Op.getValueType().getVectorElementType() == MVT::i1)
3545       return lowerVectorMaskSplat(Op, DAG);
3546     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3547   case ISD::VECTOR_SHUFFLE:
3548     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3549   case ISD::CONCAT_VECTORS: {
3550     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3551     // better than going through the stack, as the default expansion does.
3552     SDLoc DL(Op);
3553     MVT VT = Op.getSimpleValueType();
3554     unsigned NumOpElts =
3555         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3556     SDValue Vec = DAG.getUNDEF(VT);
3557     for (const auto &OpIdx : enumerate(Op->ops())) {
3558       SDValue SubVec = OpIdx.value();
3559       // Don't insert undef subvectors.
3560       if (SubVec.isUndef())
3561         continue;
3562       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3563                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3564     }
3565     return Vec;
3566   }
3567   case ISD::LOAD:
3568     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3569       return V;
3570     if (Op.getValueType().isFixedLengthVector())
3571       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3572     return Op;
3573   case ISD::STORE:
3574     if (auto V = expandUnalignedRVVStore(Op, DAG))
3575       return V;
3576     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3577       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3578     return Op;
3579   case ISD::MLOAD:
3580   case ISD::VP_LOAD:
3581     return lowerMaskedLoad(Op, DAG);
3582   case ISD::MSTORE:
3583   case ISD::VP_STORE:
3584     return lowerMaskedStore(Op, DAG);
3585   case ISD::SETCC:
3586     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3587   case ISD::ADD:
3588     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3589   case ISD::SUB:
3590     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3591   case ISD::MUL:
3592     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3593   case ISD::MULHS:
3594     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3595   case ISD::MULHU:
3596     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3597   case ISD::AND:
3598     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3599                                               RISCVISD::AND_VL);
3600   case ISD::OR:
3601     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3602                                               RISCVISD::OR_VL);
3603   case ISD::XOR:
3604     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3605                                               RISCVISD::XOR_VL);
3606   case ISD::SDIV:
3607     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3608   case ISD::SREM:
3609     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3610   case ISD::UDIV:
3611     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3612   case ISD::UREM:
3613     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3614   case ISD::SHL:
3615   case ISD::SRA:
3616   case ISD::SRL:
3617     if (Op.getSimpleValueType().isFixedLengthVector())
3618       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3619     // This can be called for an i32 shift amount that needs to be promoted.
3620     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3621            "Unexpected custom legalisation");
3622     return SDValue();
3623   case ISD::SADDSAT:
3624     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3625   case ISD::UADDSAT:
3626     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3627   case ISD::SSUBSAT:
3628     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3629   case ISD::USUBSAT:
3630     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3631   case ISD::FADD:
3632     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3633   case ISD::FSUB:
3634     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3635   case ISD::FMUL:
3636     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3637   case ISD::FDIV:
3638     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3639   case ISD::FNEG:
3640     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3641   case ISD::FABS:
3642     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3643   case ISD::FSQRT:
3644     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3645   case ISD::FMA:
3646     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3647   case ISD::SMIN:
3648     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3649   case ISD::SMAX:
3650     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3651   case ISD::UMIN:
3652     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3653   case ISD::UMAX:
3654     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3655   case ISD::FMINNUM:
3656     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3657   case ISD::FMAXNUM:
3658     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3659   case ISD::ABS:
3660     return lowerABS(Op, DAG);
3661   case ISD::CTLZ_ZERO_UNDEF:
3662   case ISD::CTTZ_ZERO_UNDEF:
3663     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3664   case ISD::VSELECT:
3665     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3666   case ISD::FCOPYSIGN:
3667     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3668   case ISD::MGATHER:
3669   case ISD::VP_GATHER:
3670     return lowerMaskedGather(Op, DAG);
3671   case ISD::MSCATTER:
3672   case ISD::VP_SCATTER:
3673     return lowerMaskedScatter(Op, DAG);
3674   case ISD::FLT_ROUNDS_:
3675     return lowerGET_ROUNDING(Op, DAG);
3676   case ISD::SET_ROUNDING:
3677     return lowerSET_ROUNDING(Op, DAG);
3678   case ISD::VP_SELECT:
3679     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3680   case ISD::VP_MERGE:
3681     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3682   case ISD::VP_ADD:
3683     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3684   case ISD::VP_SUB:
3685     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3686   case ISD::VP_MUL:
3687     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3688   case ISD::VP_SDIV:
3689     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3690   case ISD::VP_UDIV:
3691     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3692   case ISD::VP_SREM:
3693     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3694   case ISD::VP_UREM:
3695     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3696   case ISD::VP_AND:
3697     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3698   case ISD::VP_OR:
3699     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3700   case ISD::VP_XOR:
3701     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3702   case ISD::VP_ASHR:
3703     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3704   case ISD::VP_LSHR:
3705     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3706   case ISD::VP_SHL:
3707     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3708   case ISD::VP_FADD:
3709     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3710   case ISD::VP_FSUB:
3711     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3712   case ISD::VP_FMUL:
3713     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3714   case ISD::VP_FDIV:
3715     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3716   case ISD::VP_FNEG:
3717     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3718   case ISD::VP_FMA:
3719     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3720   }
3721 }
3722 
3723 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3724                              SelectionDAG &DAG, unsigned Flags) {
3725   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3726 }
3727 
3728 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3729                              SelectionDAG &DAG, unsigned Flags) {
3730   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3731                                    Flags);
3732 }
3733 
3734 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3735                              SelectionDAG &DAG, unsigned Flags) {
3736   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3737                                    N->getOffset(), Flags);
3738 }
3739 
3740 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3741                              SelectionDAG &DAG, unsigned Flags) {
3742   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3743 }
3744 
3745 template <class NodeTy>
3746 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3747                                      bool IsLocal) const {
3748   SDLoc DL(N);
3749   EVT Ty = getPointerTy(DAG.getDataLayout());
3750 
3751   if (isPositionIndependent()) {
3752     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3753     if (IsLocal)
3754       // Use PC-relative addressing to access the symbol. This generates the
3755       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3756       // %pcrel_lo(auipc)).
3757       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3758 
3759     // Use PC-relative addressing to access the GOT for this symbol, then load
3760     // the address from the GOT. This generates the pattern (PseudoLA sym),
3761     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3762     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3763   }
3764 
3765   switch (getTargetMachine().getCodeModel()) {
3766   default:
3767     report_fatal_error("Unsupported code model for lowering");
3768   case CodeModel::Small: {
3769     // Generate a sequence for accessing addresses within the first 2 GiB of
3770     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3771     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3772     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3773     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3774     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3775   }
3776   case CodeModel::Medium: {
3777     // Generate a sequence for accessing addresses within any 2GiB range within
3778     // the address space. This generates the pattern (PseudoLLA sym), which
3779     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3780     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3781     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3782   }
3783   }
3784 }
3785 
3786 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3787                                                 SelectionDAG &DAG) const {
3788   SDLoc DL(Op);
3789   EVT Ty = Op.getValueType();
3790   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3791   int64_t Offset = N->getOffset();
3792   MVT XLenVT = Subtarget.getXLenVT();
3793 
3794   const GlobalValue *GV = N->getGlobal();
3795   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3796   SDValue Addr = getAddr(N, DAG, IsLocal);
3797 
3798   // In order to maximise the opportunity for common subexpression elimination,
3799   // emit a separate ADD node for the global address offset instead of folding
3800   // it in the global address node. Later peephole optimisations may choose to
3801   // fold it back in when profitable.
3802   if (Offset != 0)
3803     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3804                        DAG.getConstant(Offset, DL, XLenVT));
3805   return Addr;
3806 }
3807 
3808 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3809                                                SelectionDAG &DAG) const {
3810   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3811 
3812   return getAddr(N, DAG);
3813 }
3814 
3815 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3816                                                SelectionDAG &DAG) const {
3817   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3818 
3819   return getAddr(N, DAG);
3820 }
3821 
3822 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3823                                             SelectionDAG &DAG) const {
3824   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3825 
3826   return getAddr(N, DAG);
3827 }
3828 
3829 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3830                                               SelectionDAG &DAG,
3831                                               bool UseGOT) const {
3832   SDLoc DL(N);
3833   EVT Ty = getPointerTy(DAG.getDataLayout());
3834   const GlobalValue *GV = N->getGlobal();
3835   MVT XLenVT = Subtarget.getXLenVT();
3836 
3837   if (UseGOT) {
3838     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3839     // load the address from the GOT and add the thread pointer. This generates
3840     // the pattern (PseudoLA_TLS_IE sym), which expands to
3841     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3842     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3843     SDValue Load =
3844         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3845 
3846     // Add the thread pointer.
3847     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3848     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3849   }
3850 
3851   // Generate a sequence for accessing the address relative to the thread
3852   // pointer, with the appropriate adjustment for the thread pointer offset.
3853   // This generates the pattern
3854   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3855   SDValue AddrHi =
3856       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3857   SDValue AddrAdd =
3858       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3859   SDValue AddrLo =
3860       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3861 
3862   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3863   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3864   SDValue MNAdd = SDValue(
3865       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3866       0);
3867   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3868 }
3869 
3870 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3871                                                SelectionDAG &DAG) const {
3872   SDLoc DL(N);
3873   EVT Ty = getPointerTy(DAG.getDataLayout());
3874   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3875   const GlobalValue *GV = N->getGlobal();
3876 
3877   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3878   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3879   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3880   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3881   SDValue Load =
3882       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3883 
3884   // Prepare argument list to generate call.
3885   ArgListTy Args;
3886   ArgListEntry Entry;
3887   Entry.Node = Load;
3888   Entry.Ty = CallTy;
3889   Args.push_back(Entry);
3890 
3891   // Setup call to __tls_get_addr.
3892   TargetLowering::CallLoweringInfo CLI(DAG);
3893   CLI.setDebugLoc(DL)
3894       .setChain(DAG.getEntryNode())
3895       .setLibCallee(CallingConv::C, CallTy,
3896                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3897                     std::move(Args));
3898 
3899   return LowerCallTo(CLI).first;
3900 }
3901 
3902 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3903                                                    SelectionDAG &DAG) const {
3904   SDLoc DL(Op);
3905   EVT Ty = Op.getValueType();
3906   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3907   int64_t Offset = N->getOffset();
3908   MVT XLenVT = Subtarget.getXLenVT();
3909 
3910   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3911 
3912   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3913       CallingConv::GHC)
3914     report_fatal_error("In GHC calling convention TLS is not supported");
3915 
3916   SDValue Addr;
3917   switch (Model) {
3918   case TLSModel::LocalExec:
3919     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3920     break;
3921   case TLSModel::InitialExec:
3922     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3923     break;
3924   case TLSModel::LocalDynamic:
3925   case TLSModel::GeneralDynamic:
3926     Addr = getDynamicTLSAddr(N, DAG);
3927     break;
3928   }
3929 
3930   // In order to maximise the opportunity for common subexpression elimination,
3931   // emit a separate ADD node for the global address offset instead of folding
3932   // it in the global address node. Later peephole optimisations may choose to
3933   // fold it back in when profitable.
3934   if (Offset != 0)
3935     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3936                        DAG.getConstant(Offset, DL, XLenVT));
3937   return Addr;
3938 }
3939 
3940 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3941   SDValue CondV = Op.getOperand(0);
3942   SDValue TrueV = Op.getOperand(1);
3943   SDValue FalseV = Op.getOperand(2);
3944   SDLoc DL(Op);
3945   MVT VT = Op.getSimpleValueType();
3946   MVT XLenVT = Subtarget.getXLenVT();
3947 
3948   // Lower vector SELECTs to VSELECTs by splatting the condition.
3949   if (VT.isVector()) {
3950     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3951     SDValue CondSplat = VT.isScalableVector()
3952                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3953                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3954     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3955   }
3956 
3957   // If the result type is XLenVT and CondV is the output of a SETCC node
3958   // which also operated on XLenVT inputs, then merge the SETCC node into the
3959   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3960   // compare+branch instructions. i.e.:
3961   // (select (setcc lhs, rhs, cc), truev, falsev)
3962   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3963   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3964       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3965     SDValue LHS = CondV.getOperand(0);
3966     SDValue RHS = CondV.getOperand(1);
3967     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3968     ISD::CondCode CCVal = CC->get();
3969 
3970     // Special case for a select of 2 constants that have a diffence of 1.
3971     // Normally this is done by DAGCombine, but if the select is introduced by
3972     // type legalization or op legalization, we miss it. Restricting to SETLT
3973     // case for now because that is what signed saturating add/sub need.
3974     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3975     // but we would probably want to swap the true/false values if the condition
3976     // is SETGE/SETLE to avoid an XORI.
3977     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3978         CCVal == ISD::SETLT) {
3979       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3980       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3981       if (TrueVal - 1 == FalseVal)
3982         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3983       if (TrueVal + 1 == FalseVal)
3984         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3985     }
3986 
3987     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3988 
3989     SDValue TargetCC = DAG.getCondCode(CCVal);
3990     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3991     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3992   }
3993 
3994   // Otherwise:
3995   // (select condv, truev, falsev)
3996   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3997   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3998   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3999 
4000   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
4001 
4002   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4003 }
4004 
4005 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4006   SDValue CondV = Op.getOperand(1);
4007   SDLoc DL(Op);
4008   MVT XLenVT = Subtarget.getXLenVT();
4009 
4010   if (CondV.getOpcode() == ISD::SETCC &&
4011       CondV.getOperand(0).getValueType() == XLenVT) {
4012     SDValue LHS = CondV.getOperand(0);
4013     SDValue RHS = CondV.getOperand(1);
4014     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
4015 
4016     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4017 
4018     SDValue TargetCC = DAG.getCondCode(CCVal);
4019     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4020                        LHS, RHS, TargetCC, Op.getOperand(2));
4021   }
4022 
4023   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4024                      CondV, DAG.getConstant(0, DL, XLenVT),
4025                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4026 }
4027 
4028 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4029   MachineFunction &MF = DAG.getMachineFunction();
4030   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4031 
4032   SDLoc DL(Op);
4033   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4034                                  getPointerTy(MF.getDataLayout()));
4035 
4036   // vastart just stores the address of the VarArgsFrameIndex slot into the
4037   // memory location argument.
4038   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4039   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4040                       MachinePointerInfo(SV));
4041 }
4042 
4043 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4044                                             SelectionDAG &DAG) const {
4045   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4046   MachineFunction &MF = DAG.getMachineFunction();
4047   MachineFrameInfo &MFI = MF.getFrameInfo();
4048   MFI.setFrameAddressIsTaken(true);
4049   Register FrameReg = RI.getFrameRegister(MF);
4050   int XLenInBytes = Subtarget.getXLen() / 8;
4051 
4052   EVT VT = Op.getValueType();
4053   SDLoc DL(Op);
4054   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4055   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4056   while (Depth--) {
4057     int Offset = -(XLenInBytes * 2);
4058     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4059                               DAG.getIntPtrConstant(Offset, DL));
4060     FrameAddr =
4061         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4062   }
4063   return FrameAddr;
4064 }
4065 
4066 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4067                                              SelectionDAG &DAG) const {
4068   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4069   MachineFunction &MF = DAG.getMachineFunction();
4070   MachineFrameInfo &MFI = MF.getFrameInfo();
4071   MFI.setReturnAddressIsTaken(true);
4072   MVT XLenVT = Subtarget.getXLenVT();
4073   int XLenInBytes = Subtarget.getXLen() / 8;
4074 
4075   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4076     return SDValue();
4077 
4078   EVT VT = Op.getValueType();
4079   SDLoc DL(Op);
4080   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4081   if (Depth) {
4082     int Off = -XLenInBytes;
4083     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4084     SDValue Offset = DAG.getConstant(Off, DL, VT);
4085     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4086                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4087                        MachinePointerInfo());
4088   }
4089 
4090   // Return the value of the return address register, marking it an implicit
4091   // live-in.
4092   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4093   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4094 }
4095 
4096 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4097                                                  SelectionDAG &DAG) const {
4098   SDLoc DL(Op);
4099   SDValue Lo = Op.getOperand(0);
4100   SDValue Hi = Op.getOperand(1);
4101   SDValue Shamt = Op.getOperand(2);
4102   EVT VT = Lo.getValueType();
4103 
4104   // if Shamt-XLEN < 0: // Shamt < XLEN
4105   //   Lo = Lo << Shamt
4106   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4107   // else:
4108   //   Lo = 0
4109   //   Hi = Lo << (Shamt-XLEN)
4110 
4111   SDValue Zero = DAG.getConstant(0, DL, VT);
4112   SDValue One = DAG.getConstant(1, DL, VT);
4113   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4114   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4115   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4116   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4117 
4118   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4119   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4120   SDValue ShiftRightLo =
4121       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4122   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4123   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4124   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4125 
4126   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4127 
4128   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4129   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4130 
4131   SDValue Parts[2] = {Lo, Hi};
4132   return DAG.getMergeValues(Parts, DL);
4133 }
4134 
4135 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4136                                                   bool IsSRA) const {
4137   SDLoc DL(Op);
4138   SDValue Lo = Op.getOperand(0);
4139   SDValue Hi = Op.getOperand(1);
4140   SDValue Shamt = Op.getOperand(2);
4141   EVT VT = Lo.getValueType();
4142 
4143   // SRA expansion:
4144   //   if Shamt-XLEN < 0: // Shamt < XLEN
4145   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4146   //     Hi = Hi >>s Shamt
4147   //   else:
4148   //     Lo = Hi >>s (Shamt-XLEN);
4149   //     Hi = Hi >>s (XLEN-1)
4150   //
4151   // SRL expansion:
4152   //   if Shamt-XLEN < 0: // Shamt < XLEN
4153   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4154   //     Hi = Hi >>u Shamt
4155   //   else:
4156   //     Lo = Hi >>u (Shamt-XLEN);
4157   //     Hi = 0;
4158 
4159   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4160 
4161   SDValue Zero = DAG.getConstant(0, DL, VT);
4162   SDValue One = DAG.getConstant(1, DL, VT);
4163   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4164   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4165   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4166   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4167 
4168   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4169   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4170   SDValue ShiftLeftHi =
4171       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4172   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4173   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4174   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4175   SDValue HiFalse =
4176       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4177 
4178   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4179 
4180   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4181   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4182 
4183   SDValue Parts[2] = {Lo, Hi};
4184   return DAG.getMergeValues(Parts, DL);
4185 }
4186 
4187 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4188 // legal equivalently-sized i8 type, so we can use that as a go-between.
4189 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4190                                                   SelectionDAG &DAG) const {
4191   SDLoc DL(Op);
4192   MVT VT = Op.getSimpleValueType();
4193   SDValue SplatVal = Op.getOperand(0);
4194   // All-zeros or all-ones splats are handled specially.
4195   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4196     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4197     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4198   }
4199   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4200     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4201     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4202   }
4203   MVT XLenVT = Subtarget.getXLenVT();
4204   assert(SplatVal.getValueType() == XLenVT &&
4205          "Unexpected type for i1 splat value");
4206   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4207   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4208                          DAG.getConstant(1, DL, XLenVT));
4209   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4210   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4211   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4212 }
4213 
4214 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4215 // illegal (currently only vXi64 RV32).
4216 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4217 // them to VMV_V_X_VL.
4218 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4219                                                      SelectionDAG &DAG) const {
4220   SDLoc DL(Op);
4221   MVT VecVT = Op.getSimpleValueType();
4222   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4223          "Unexpected SPLAT_VECTOR_PARTS lowering");
4224 
4225   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4226   SDValue Lo = Op.getOperand(0);
4227   SDValue Hi = Op.getOperand(1);
4228 
4229   if (VecVT.isFixedLengthVector()) {
4230     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4231     SDLoc DL(Op);
4232     SDValue Mask, VL;
4233     std::tie(Mask, VL) =
4234         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4235 
4236     SDValue Res =
4237         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4238     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4239   }
4240 
4241   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4242     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4243     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4244     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4245     // node in order to try and match RVV vector/scalar instructions.
4246     if ((LoC >> 31) == HiC)
4247       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4248                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4249   }
4250 
4251   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4252   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4253       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4254       Hi.getConstantOperandVal(1) == 31)
4255     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4256                        DAG.getRegister(RISCV::X0, MVT::i32));
4257 
4258   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4259   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4260                      DAG.getUNDEF(VecVT), Lo, Hi,
4261                      DAG.getRegister(RISCV::X0, MVT::i32));
4262 }
4263 
4264 // Custom-lower extensions from mask vectors by using a vselect either with 1
4265 // for zero/any-extension or -1 for sign-extension:
4266 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4267 // Note that any-extension is lowered identically to zero-extension.
4268 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4269                                                 int64_t ExtTrueVal) const {
4270   SDLoc DL(Op);
4271   MVT VecVT = Op.getSimpleValueType();
4272   SDValue Src = Op.getOperand(0);
4273   // Only custom-lower extensions from mask types
4274   assert(Src.getValueType().isVector() &&
4275          Src.getValueType().getVectorElementType() == MVT::i1);
4276 
4277   MVT XLenVT = Subtarget.getXLenVT();
4278   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4279   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4280 
4281   if (VecVT.isScalableVector()) {
4282     // Be careful not to introduce illegal scalar types at this stage, and be
4283     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4284     // illegal and must be expanded. Since we know that the constants are
4285     // sign-extended 32-bit values, we use VMV_V_X_VL directly.
4286     bool IsRV32E64 =
4287         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4288 
4289     if (!IsRV32E64) {
4290       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4291       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4292     } else {
4293       SplatZero =
4294           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4295                       SplatZero, DAG.getRegister(RISCV::X0, XLenVT));
4296       SplatTrueVal =
4297           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4298                       SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT));
4299     }
4300 
4301     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4302   }
4303 
4304   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4305   MVT I1ContainerVT =
4306       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4307 
4308   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4309 
4310   SDValue Mask, VL;
4311   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4312 
4313   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4314                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4315   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4316                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4317   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4318                                SplatTrueVal, SplatZero, VL);
4319 
4320   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4321 }
4322 
4323 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4324     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4325   MVT ExtVT = Op.getSimpleValueType();
4326   // Only custom-lower extensions from fixed-length vector types.
4327   if (!ExtVT.isFixedLengthVector())
4328     return Op;
4329   MVT VT = Op.getOperand(0).getSimpleValueType();
4330   // Grab the canonical container type for the extended type. Infer the smaller
4331   // type from that to ensure the same number of vector elements, as we know
4332   // the LMUL will be sufficient to hold the smaller type.
4333   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4334   // Get the extended container type manually to ensure the same number of
4335   // vector elements between source and dest.
4336   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4337                                      ContainerExtVT.getVectorElementCount());
4338 
4339   SDValue Op1 =
4340       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4341 
4342   SDLoc DL(Op);
4343   SDValue Mask, VL;
4344   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4345 
4346   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4347 
4348   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4349 }
4350 
4351 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4352 // setcc operation:
4353 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4354 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4355                                                   SelectionDAG &DAG) const {
4356   SDLoc DL(Op);
4357   EVT MaskVT = Op.getValueType();
4358   // Only expect to custom-lower truncations to mask types
4359   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4360          "Unexpected type for vector mask lowering");
4361   SDValue Src = Op.getOperand(0);
4362   MVT VecVT = Src.getSimpleValueType();
4363 
4364   // If this is a fixed vector, we need to convert it to a scalable vector.
4365   MVT ContainerVT = VecVT;
4366   if (VecVT.isFixedLengthVector()) {
4367     ContainerVT = getContainerForFixedLengthVector(VecVT);
4368     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4369   }
4370 
4371   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4372   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4373 
4374   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4375                          DAG.getUNDEF(ContainerVT), SplatOne);
4376   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4377                           DAG.getUNDEF(ContainerVT), SplatZero);
4378 
4379   if (VecVT.isScalableVector()) {
4380     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4381     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4382   }
4383 
4384   SDValue Mask, VL;
4385   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4386 
4387   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4388   SDValue Trunc =
4389       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4390   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4391                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4392   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4393 }
4394 
4395 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4396 // first position of a vector, and that vector is slid up to the insert index.
4397 // By limiting the active vector length to index+1 and merging with the
4398 // original vector (with an undisturbed tail policy for elements >= VL), we
4399 // achieve the desired result of leaving all elements untouched except the one
4400 // at VL-1, which is replaced with the desired value.
4401 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4402                                                     SelectionDAG &DAG) const {
4403   SDLoc DL(Op);
4404   MVT VecVT = Op.getSimpleValueType();
4405   SDValue Vec = Op.getOperand(0);
4406   SDValue Val = Op.getOperand(1);
4407   SDValue Idx = Op.getOperand(2);
4408 
4409   if (VecVT.getVectorElementType() == MVT::i1) {
4410     // FIXME: For now we just promote to an i8 vector and insert into that,
4411     // but this is probably not optimal.
4412     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4413     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4414     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4415     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4416   }
4417 
4418   MVT ContainerVT = VecVT;
4419   // If the operand is a fixed-length vector, convert to a scalable one.
4420   if (VecVT.isFixedLengthVector()) {
4421     ContainerVT = getContainerForFixedLengthVector(VecVT);
4422     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4423   }
4424 
4425   MVT XLenVT = Subtarget.getXLenVT();
4426 
4427   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4428   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4429   // Even i64-element vectors on RV32 can be lowered without scalar
4430   // legalization if the most-significant 32 bits of the value are not affected
4431   // by the sign-extension of the lower 32 bits.
4432   // TODO: We could also catch sign extensions of a 32-bit value.
4433   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4434     const auto *CVal = cast<ConstantSDNode>(Val);
4435     if (isInt<32>(CVal->getSExtValue())) {
4436       IsLegalInsert = true;
4437       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4438     }
4439   }
4440 
4441   SDValue Mask, VL;
4442   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4443 
4444   SDValue ValInVec;
4445 
4446   if (IsLegalInsert) {
4447     unsigned Opc =
4448         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4449     if (isNullConstant(Idx)) {
4450       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4451       if (!VecVT.isFixedLengthVector())
4452         return Vec;
4453       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4454     }
4455     ValInVec =
4456         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4457   } else {
4458     // On RV32, i64-element vectors must be specially handled to place the
4459     // value at element 0, by using two vslide1up instructions in sequence on
4460     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4461     // this.
4462     SDValue One = DAG.getConstant(1, DL, XLenVT);
4463     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4464     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4465     MVT I32ContainerVT =
4466         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4467     SDValue I32Mask =
4468         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4469     // Limit the active VL to two.
4470     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4471     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4472     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4473     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4474                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4475     // First slide in the hi value, then the lo in underneath it.
4476     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4477                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4478                            I32Mask, InsertI64VL);
4479     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4480                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4481                            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, SDValue(), 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.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4724                             Subtarget);
4725   case Intrinsic::riscv_vfmv_v_f:
4726     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4727                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4728   case Intrinsic::riscv_vmv_s_x: {
4729     SDValue Scalar = Op.getOperand(2);
4730 
4731     if (Scalar.getValueType().bitsLE(XLenVT)) {
4732       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4733       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4734                          Op.getOperand(1), Scalar, Op.getOperand(3));
4735     }
4736 
4737     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4738 
4739     // This is an i64 value that lives in two scalar registers. We have to
4740     // insert this in a convoluted way. First we build vXi64 splat containing
4741     // the/ two values that we assemble using some bit math. Next we'll use
4742     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4743     // to merge element 0 from our splat into the source vector.
4744     // FIXME: This is probably not the best way to do this, but it is
4745     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4746     // point.
4747     //   sw lo, (a0)
4748     //   sw hi, 4(a0)
4749     //   vlse vX, (a0)
4750     //
4751     //   vid.v      vVid
4752     //   vmseq.vx   mMask, vVid, 0
4753     //   vmerge.vvm vDest, vSrc, vVal, mMask
4754     MVT VT = Op.getSimpleValueType();
4755     SDValue Vec = Op.getOperand(1);
4756     SDValue VL = getVLOperand(Op);
4757 
4758     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4759     SDValue SplattedIdx =
4760         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4761                     DAG.getConstant(0, DL, MVT::i32), VL);
4762 
4763     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4764     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4765     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4766     SDValue SelectCond =
4767         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4768                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4769     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4770                        Vec, VL);
4771   }
4772   case Intrinsic::riscv_vslide1up:
4773   case Intrinsic::riscv_vslide1down:
4774   case Intrinsic::riscv_vslide1up_mask:
4775   case Intrinsic::riscv_vslide1down_mask: {
4776     // We need to special case these when the scalar is larger than XLen.
4777     unsigned NumOps = Op.getNumOperands();
4778     bool IsMasked = NumOps == 7;
4779     SDValue Scalar = Op.getOperand(3);
4780     if (Scalar.getValueType().bitsLE(XLenVT))
4781       break;
4782 
4783     // Splatting a sign extended constant is fine.
4784     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4785       if (isInt<32>(CVal->getSExtValue()))
4786         break;
4787 
4788     MVT VT = Op.getSimpleValueType();
4789     assert(VT.getVectorElementType() == MVT::i64 &&
4790            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4791 
4792     // Convert the vector source to the equivalent nxvXi32 vector.
4793     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4794     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(2));
4795 
4796     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4797                                    DAG.getConstant(0, DL, XLenVT));
4798     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4799                                    DAG.getConstant(1, DL, XLenVT));
4800 
4801     // Double the VL since we halved SEW.
4802     SDValue VL = getVLOperand(Op);
4803     SDValue I32VL =
4804         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4805 
4806     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4807     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4808 
4809     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4810     // instructions.
4811     SDValue Passthru = DAG.getBitcast(I32VT, Op.getOperand(1));
4812     if (!IsMasked) {
4813       if (IntNo == Intrinsic::riscv_vslide1up) {
4814         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4815                           ScalarHi, I32Mask, I32VL);
4816         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4817                           ScalarLo, I32Mask, I32VL);
4818       } else {
4819         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4820                           ScalarLo, I32Mask, I32VL);
4821         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4822                           ScalarHi, I32Mask, I32VL);
4823       }
4824     } else {
4825       // TODO Those VSLIDE1 could be TAMA because we use vmerge to select
4826       // maskedoff
4827       SDValue Undef = DAG.getUNDEF(I32VT);
4828       if (IntNo == Intrinsic::riscv_vslide1up_mask) {
4829         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec,
4830                           ScalarHi, I32Mask, I32VL);
4831         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec,
4832                           ScalarLo, I32Mask, I32VL);
4833       } else {
4834         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec,
4835                           ScalarLo, I32Mask, I32VL);
4836         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec,
4837                           ScalarHi, I32Mask, I32VL);
4838       }
4839     }
4840 
4841     // Convert back to nxvXi64.
4842     Vec = DAG.getBitcast(VT, Vec);
4843 
4844     if (!IsMasked)
4845       return Vec;
4846     // Apply mask after the operation.
4847     SDValue Mask = Op.getOperand(NumOps - 3);
4848     SDValue MaskedOff = Op.getOperand(1);
4849     // Assume Policy operand is the last operand.
4850     uint64_t Policy = Op.getConstantOperandVal(NumOps - 1);
4851     // We don't need to select maskedoff if it's undef.
4852     if (MaskedOff.isUndef())
4853       return Vec;
4854     // TAMU
4855     if (Policy == RISCVII::TAIL_AGNOSTIC)
4856       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4857                          VL);
4858     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4859     // It's fine because vmerge does not care mask policy.
4860     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4861   }
4862   }
4863 
4864   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4865 }
4866 
4867 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4868                                                     SelectionDAG &DAG) const {
4869   unsigned IntNo = Op.getConstantOperandVal(1);
4870   switch (IntNo) {
4871   default:
4872     break;
4873   case Intrinsic::riscv_masked_strided_load: {
4874     SDLoc DL(Op);
4875     MVT XLenVT = Subtarget.getXLenVT();
4876 
4877     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4878     // the selection of the masked intrinsics doesn't do this for us.
4879     SDValue Mask = Op.getOperand(5);
4880     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4881 
4882     MVT VT = Op->getSimpleValueType(0);
4883     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4884 
4885     SDValue PassThru = Op.getOperand(2);
4886     if (!IsUnmasked) {
4887       MVT MaskVT =
4888           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4889       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4890       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4891     }
4892 
4893     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4894 
4895     SDValue IntID = DAG.getTargetConstant(
4896         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4897         XLenVT);
4898 
4899     auto *Load = cast<MemIntrinsicSDNode>(Op);
4900     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4901     if (IsUnmasked)
4902       Ops.push_back(DAG.getUNDEF(ContainerVT));
4903     else
4904       Ops.push_back(PassThru);
4905     Ops.push_back(Op.getOperand(3)); // Ptr
4906     Ops.push_back(Op.getOperand(4)); // Stride
4907     if (!IsUnmasked)
4908       Ops.push_back(Mask);
4909     Ops.push_back(VL);
4910     if (!IsUnmasked) {
4911       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4912       Ops.push_back(Policy);
4913     }
4914 
4915     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4916     SDValue Result =
4917         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4918                                 Load->getMemoryVT(), Load->getMemOperand());
4919     SDValue Chain = Result.getValue(1);
4920     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4921     return DAG.getMergeValues({Result, Chain}, DL);
4922   }
4923   }
4924 
4925   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4926 }
4927 
4928 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4929                                                  SelectionDAG &DAG) const {
4930   unsigned IntNo = Op.getConstantOperandVal(1);
4931   switch (IntNo) {
4932   default:
4933     break;
4934   case Intrinsic::riscv_masked_strided_store: {
4935     SDLoc DL(Op);
4936     MVT XLenVT = Subtarget.getXLenVT();
4937 
4938     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4939     // the selection of the masked intrinsics doesn't do this for us.
4940     SDValue Mask = Op.getOperand(5);
4941     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4942 
4943     SDValue Val = Op.getOperand(2);
4944     MVT VT = Val.getSimpleValueType();
4945     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4946 
4947     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4948     if (!IsUnmasked) {
4949       MVT MaskVT =
4950           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4951       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4952     }
4953 
4954     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4955 
4956     SDValue IntID = DAG.getTargetConstant(
4957         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4958         XLenVT);
4959 
4960     auto *Store = cast<MemIntrinsicSDNode>(Op);
4961     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4962     Ops.push_back(Val);
4963     Ops.push_back(Op.getOperand(3)); // Ptr
4964     Ops.push_back(Op.getOperand(4)); // Stride
4965     if (!IsUnmasked)
4966       Ops.push_back(Mask);
4967     Ops.push_back(VL);
4968 
4969     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4970                                    Ops, Store->getMemoryVT(),
4971                                    Store->getMemOperand());
4972   }
4973   }
4974 
4975   return SDValue();
4976 }
4977 
4978 static MVT getLMUL1VT(MVT VT) {
4979   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4980          "Unexpected vector MVT");
4981   return MVT::getScalableVectorVT(
4982       VT.getVectorElementType(),
4983       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4984 }
4985 
4986 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4987   switch (ISDOpcode) {
4988   default:
4989     llvm_unreachable("Unhandled reduction");
4990   case ISD::VECREDUCE_ADD:
4991     return RISCVISD::VECREDUCE_ADD_VL;
4992   case ISD::VECREDUCE_UMAX:
4993     return RISCVISD::VECREDUCE_UMAX_VL;
4994   case ISD::VECREDUCE_SMAX:
4995     return RISCVISD::VECREDUCE_SMAX_VL;
4996   case ISD::VECREDUCE_UMIN:
4997     return RISCVISD::VECREDUCE_UMIN_VL;
4998   case ISD::VECREDUCE_SMIN:
4999     return RISCVISD::VECREDUCE_SMIN_VL;
5000   case ISD::VECREDUCE_AND:
5001     return RISCVISD::VECREDUCE_AND_VL;
5002   case ISD::VECREDUCE_OR:
5003     return RISCVISD::VECREDUCE_OR_VL;
5004   case ISD::VECREDUCE_XOR:
5005     return RISCVISD::VECREDUCE_XOR_VL;
5006   }
5007 }
5008 
5009 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5010                                                          SelectionDAG &DAG,
5011                                                          bool IsVP) const {
5012   SDLoc DL(Op);
5013   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5014   MVT VecVT = Vec.getSimpleValueType();
5015   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5016           Op.getOpcode() == ISD::VECREDUCE_OR ||
5017           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5018           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5019           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5020           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5021          "Unexpected reduction lowering");
5022 
5023   MVT XLenVT = Subtarget.getXLenVT();
5024   assert(Op.getValueType() == XLenVT &&
5025          "Expected reduction output to be legalized to XLenVT");
5026 
5027   MVT ContainerVT = VecVT;
5028   if (VecVT.isFixedLengthVector()) {
5029     ContainerVT = getContainerForFixedLengthVector(VecVT);
5030     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5031   }
5032 
5033   SDValue Mask, VL;
5034   if (IsVP) {
5035     Mask = Op.getOperand(2);
5036     VL = Op.getOperand(3);
5037   } else {
5038     std::tie(Mask, VL) =
5039         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5040   }
5041 
5042   unsigned BaseOpc;
5043   ISD::CondCode CC;
5044   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5045 
5046   switch (Op.getOpcode()) {
5047   default:
5048     llvm_unreachable("Unhandled reduction");
5049   case ISD::VECREDUCE_AND:
5050   case ISD::VP_REDUCE_AND: {
5051     // vcpop ~x == 0
5052     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5053     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5054     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5055     CC = ISD::SETEQ;
5056     BaseOpc = ISD::AND;
5057     break;
5058   }
5059   case ISD::VECREDUCE_OR:
5060   case ISD::VP_REDUCE_OR:
5061     // vcpop x != 0
5062     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5063     CC = ISD::SETNE;
5064     BaseOpc = ISD::OR;
5065     break;
5066   case ISD::VECREDUCE_XOR:
5067   case ISD::VP_REDUCE_XOR: {
5068     // ((vcpop x) & 1) != 0
5069     SDValue One = DAG.getConstant(1, DL, XLenVT);
5070     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5071     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5072     CC = ISD::SETNE;
5073     BaseOpc = ISD::XOR;
5074     break;
5075   }
5076   }
5077 
5078   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5079 
5080   if (!IsVP)
5081     return SetCC;
5082 
5083   // Now include the start value in the operation.
5084   // Note that we must return the start value when no elements are operated
5085   // upon. The vcpop instructions we've emitted in each case above will return
5086   // 0 for an inactive vector, and so we've already received the neutral value:
5087   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5088   // can simply include the start value.
5089   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5090 }
5091 
5092 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5093                                             SelectionDAG &DAG) const {
5094   SDLoc DL(Op);
5095   SDValue Vec = Op.getOperand(0);
5096   EVT VecEVT = Vec.getValueType();
5097 
5098   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5099 
5100   // Due to ordering in legalize types we may have a vector type that needs to
5101   // be split. Do that manually so we can get down to a legal type.
5102   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5103          TargetLowering::TypeSplitVector) {
5104     SDValue Lo, Hi;
5105     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5106     VecEVT = Lo.getValueType();
5107     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5108   }
5109 
5110   // TODO: The type may need to be widened rather than split. Or widened before
5111   // it can be split.
5112   if (!isTypeLegal(VecEVT))
5113     return SDValue();
5114 
5115   MVT VecVT = VecEVT.getSimpleVT();
5116   MVT VecEltVT = VecVT.getVectorElementType();
5117   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5118 
5119   MVT ContainerVT = VecVT;
5120   if (VecVT.isFixedLengthVector()) {
5121     ContainerVT = getContainerForFixedLengthVector(VecVT);
5122     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5123   }
5124 
5125   MVT M1VT = getLMUL1VT(ContainerVT);
5126   MVT XLenVT = Subtarget.getXLenVT();
5127 
5128   SDValue Mask, VL;
5129   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5130 
5131   SDValue NeutralElem =
5132       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5133   SDValue IdentitySplat =
5134       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5135                        M1VT, DL, DAG, Subtarget);
5136   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5137                                   IdentitySplat, Mask, VL);
5138   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5139                              DAG.getConstant(0, DL, XLenVT));
5140   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5141 }
5142 
5143 // Given a reduction op, this function returns the matching reduction opcode,
5144 // the vector SDValue and the scalar SDValue required to lower this to a
5145 // RISCVISD node.
5146 static std::tuple<unsigned, SDValue, SDValue>
5147 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5148   SDLoc DL(Op);
5149   auto Flags = Op->getFlags();
5150   unsigned Opcode = Op.getOpcode();
5151   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5152   switch (Opcode) {
5153   default:
5154     llvm_unreachable("Unhandled reduction");
5155   case ISD::VECREDUCE_FADD: {
5156     // Use positive zero if we can. It is cheaper to materialize.
5157     SDValue Zero =
5158         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5159     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5160   }
5161   case ISD::VECREDUCE_SEQ_FADD:
5162     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5163                            Op.getOperand(0));
5164   case ISD::VECREDUCE_FMIN:
5165     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5166                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5167   case ISD::VECREDUCE_FMAX:
5168     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5169                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5170   }
5171 }
5172 
5173 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5174                                               SelectionDAG &DAG) const {
5175   SDLoc DL(Op);
5176   MVT VecEltVT = Op.getSimpleValueType();
5177 
5178   unsigned RVVOpcode;
5179   SDValue VectorVal, ScalarVal;
5180   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5181       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5182   MVT VecVT = VectorVal.getSimpleValueType();
5183 
5184   MVT ContainerVT = VecVT;
5185   if (VecVT.isFixedLengthVector()) {
5186     ContainerVT = getContainerForFixedLengthVector(VecVT);
5187     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5188   }
5189 
5190   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5191   MVT XLenVT = Subtarget.getXLenVT();
5192 
5193   SDValue Mask, VL;
5194   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5195 
5196   SDValue ScalarSplat =
5197       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5198                        M1VT, DL, DAG, Subtarget);
5199   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5200                                   VectorVal, ScalarSplat, Mask, VL);
5201   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5202                      DAG.getConstant(0, DL, XLenVT));
5203 }
5204 
5205 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5206   switch (ISDOpcode) {
5207   default:
5208     llvm_unreachable("Unhandled reduction");
5209   case ISD::VP_REDUCE_ADD:
5210     return RISCVISD::VECREDUCE_ADD_VL;
5211   case ISD::VP_REDUCE_UMAX:
5212     return RISCVISD::VECREDUCE_UMAX_VL;
5213   case ISD::VP_REDUCE_SMAX:
5214     return RISCVISD::VECREDUCE_SMAX_VL;
5215   case ISD::VP_REDUCE_UMIN:
5216     return RISCVISD::VECREDUCE_UMIN_VL;
5217   case ISD::VP_REDUCE_SMIN:
5218     return RISCVISD::VECREDUCE_SMIN_VL;
5219   case ISD::VP_REDUCE_AND:
5220     return RISCVISD::VECREDUCE_AND_VL;
5221   case ISD::VP_REDUCE_OR:
5222     return RISCVISD::VECREDUCE_OR_VL;
5223   case ISD::VP_REDUCE_XOR:
5224     return RISCVISD::VECREDUCE_XOR_VL;
5225   case ISD::VP_REDUCE_FADD:
5226     return RISCVISD::VECREDUCE_FADD_VL;
5227   case ISD::VP_REDUCE_SEQ_FADD:
5228     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5229   case ISD::VP_REDUCE_FMAX:
5230     return RISCVISD::VECREDUCE_FMAX_VL;
5231   case ISD::VP_REDUCE_FMIN:
5232     return RISCVISD::VECREDUCE_FMIN_VL;
5233   }
5234 }
5235 
5236 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5237                                            SelectionDAG &DAG) const {
5238   SDLoc DL(Op);
5239   SDValue Vec = Op.getOperand(1);
5240   EVT VecEVT = Vec.getValueType();
5241 
5242   // TODO: The type may need to be widened rather than split. Or widened before
5243   // it can be split.
5244   if (!isTypeLegal(VecEVT))
5245     return SDValue();
5246 
5247   MVT VecVT = VecEVT.getSimpleVT();
5248   MVT VecEltVT = VecVT.getVectorElementType();
5249   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5250 
5251   MVT ContainerVT = VecVT;
5252   if (VecVT.isFixedLengthVector()) {
5253     ContainerVT = getContainerForFixedLengthVector(VecVT);
5254     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5255   }
5256 
5257   SDValue VL = Op.getOperand(3);
5258   SDValue Mask = Op.getOperand(2);
5259 
5260   MVT M1VT = getLMUL1VT(ContainerVT);
5261   MVT XLenVT = Subtarget.getXLenVT();
5262   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5263 
5264   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5265                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5266                                         DL, DAG, Subtarget);
5267   SDValue Reduction =
5268       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5269   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5270                              DAG.getConstant(0, DL, XLenVT));
5271   if (!VecVT.isInteger())
5272     return Elt0;
5273   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5274 }
5275 
5276 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5277                                                    SelectionDAG &DAG) const {
5278   SDValue Vec = Op.getOperand(0);
5279   SDValue SubVec = Op.getOperand(1);
5280   MVT VecVT = Vec.getSimpleValueType();
5281   MVT SubVecVT = SubVec.getSimpleValueType();
5282 
5283   SDLoc DL(Op);
5284   MVT XLenVT = Subtarget.getXLenVT();
5285   unsigned OrigIdx = Op.getConstantOperandVal(2);
5286   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5287 
5288   // We don't have the ability to slide mask vectors up indexed by their i1
5289   // elements; the smallest we can do is i8. Often we are able to bitcast to
5290   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5291   // into a scalable one, we might not necessarily have enough scalable
5292   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5293   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5294       (OrigIdx != 0 || !Vec.isUndef())) {
5295     if (VecVT.getVectorMinNumElements() >= 8 &&
5296         SubVecVT.getVectorMinNumElements() >= 8) {
5297       assert(OrigIdx % 8 == 0 && "Invalid index");
5298       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5299              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5300              "Unexpected mask vector lowering");
5301       OrigIdx /= 8;
5302       SubVecVT =
5303           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5304                            SubVecVT.isScalableVector());
5305       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5306                                VecVT.isScalableVector());
5307       Vec = DAG.getBitcast(VecVT, Vec);
5308       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5309     } else {
5310       // We can't slide this mask vector up indexed by its i1 elements.
5311       // This poses a problem when we wish to insert a scalable vector which
5312       // can't be re-expressed as a larger type. Just choose the slow path and
5313       // extend to a larger type, then truncate back down.
5314       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5315       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5316       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5317       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5318       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5319                         Op.getOperand(2));
5320       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5321       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5322     }
5323   }
5324 
5325   // If the subvector vector is a fixed-length type, we cannot use subregister
5326   // manipulation to simplify the codegen; we don't know which register of a
5327   // LMUL group contains the specific subvector as we only know the minimum
5328   // register size. Therefore we must slide the vector group up the full
5329   // amount.
5330   if (SubVecVT.isFixedLengthVector()) {
5331     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5332       return Op;
5333     MVT ContainerVT = VecVT;
5334     if (VecVT.isFixedLengthVector()) {
5335       ContainerVT = getContainerForFixedLengthVector(VecVT);
5336       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5337     }
5338     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5339                          DAG.getUNDEF(ContainerVT), SubVec,
5340                          DAG.getConstant(0, DL, XLenVT));
5341     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5342       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5343       return DAG.getBitcast(Op.getValueType(), SubVec);
5344     }
5345     SDValue Mask =
5346         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5347     // Set the vector length to only the number of elements we care about. Note
5348     // that for slideup this includes the offset.
5349     SDValue VL =
5350         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5351     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5352     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5353                                   SubVec, SlideupAmt, Mask, VL);
5354     if (VecVT.isFixedLengthVector())
5355       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5356     return DAG.getBitcast(Op.getValueType(), Slideup);
5357   }
5358 
5359   unsigned SubRegIdx, RemIdx;
5360   std::tie(SubRegIdx, RemIdx) =
5361       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5362           VecVT, SubVecVT, OrigIdx, TRI);
5363 
5364   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5365   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5366                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5367                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5368 
5369   // 1. If the Idx has been completely eliminated and this subvector's size is
5370   // a vector register or a multiple thereof, or the surrounding elements are
5371   // undef, then this is a subvector insert which naturally aligns to a vector
5372   // register. These can easily be handled using subregister manipulation.
5373   // 2. If the subvector is smaller than a vector register, then the insertion
5374   // must preserve the undisturbed elements of the register. We do this by
5375   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5376   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5377   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5378   // LMUL=1 type back into the larger vector (resolving to another subregister
5379   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5380   // to avoid allocating a large register group to hold our subvector.
5381   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5382     return Op;
5383 
5384   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5385   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5386   // (in our case undisturbed). This means we can set up a subvector insertion
5387   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5388   // size of the subvector.
5389   MVT InterSubVT = VecVT;
5390   SDValue AlignedExtract = Vec;
5391   unsigned AlignedIdx = OrigIdx - RemIdx;
5392   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5393     InterSubVT = getLMUL1VT(VecVT);
5394     // Extract a subvector equal to the nearest full vector register type. This
5395     // should resolve to a EXTRACT_SUBREG instruction.
5396     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5397                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5398   }
5399 
5400   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5401   // For scalable vectors this must be further multiplied by vscale.
5402   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5403 
5404   SDValue Mask, VL;
5405   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5406 
5407   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5408   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5409   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5410   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5411 
5412   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5413                        DAG.getUNDEF(InterSubVT), SubVec,
5414                        DAG.getConstant(0, DL, XLenVT));
5415 
5416   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5417                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5418 
5419   // If required, insert this subvector back into the correct vector register.
5420   // This should resolve to an INSERT_SUBREG instruction.
5421   if (VecVT.bitsGT(InterSubVT))
5422     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5423                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5424 
5425   // We might have bitcast from a mask type: cast back to the original type if
5426   // required.
5427   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5428 }
5429 
5430 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5431                                                     SelectionDAG &DAG) const {
5432   SDValue Vec = Op.getOperand(0);
5433   MVT SubVecVT = Op.getSimpleValueType();
5434   MVT VecVT = Vec.getSimpleValueType();
5435 
5436   SDLoc DL(Op);
5437   MVT XLenVT = Subtarget.getXLenVT();
5438   unsigned OrigIdx = Op.getConstantOperandVal(1);
5439   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5440 
5441   // We don't have the ability to slide mask vectors down indexed by their i1
5442   // elements; the smallest we can do is i8. Often we are able to bitcast to
5443   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5444   // from a scalable one, we might not necessarily have enough scalable
5445   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5446   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5447     if (VecVT.getVectorMinNumElements() >= 8 &&
5448         SubVecVT.getVectorMinNumElements() >= 8) {
5449       assert(OrigIdx % 8 == 0 && "Invalid index");
5450       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5451              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5452              "Unexpected mask vector lowering");
5453       OrigIdx /= 8;
5454       SubVecVT =
5455           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5456                            SubVecVT.isScalableVector());
5457       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5458                                VecVT.isScalableVector());
5459       Vec = DAG.getBitcast(VecVT, Vec);
5460     } else {
5461       // We can't slide this mask vector down, indexed by its i1 elements.
5462       // This poses a problem when we wish to extract a scalable vector which
5463       // can't be re-expressed as a larger type. Just choose the slow path and
5464       // extend to a larger type, then truncate back down.
5465       // TODO: We could probably improve this when extracting certain fixed
5466       // from fixed, where we can extract as i8 and shift the correct element
5467       // right to reach the desired subvector?
5468       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5469       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5470       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5471       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5472                         Op.getOperand(1));
5473       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5474       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5475     }
5476   }
5477 
5478   // If the subvector vector is a fixed-length type, we cannot use subregister
5479   // manipulation to simplify the codegen; we don't know which register of a
5480   // LMUL group contains the specific subvector as we only know the minimum
5481   // register size. Therefore we must slide the vector group down the full
5482   // amount.
5483   if (SubVecVT.isFixedLengthVector()) {
5484     // With an index of 0 this is a cast-like subvector, which can be performed
5485     // with subregister operations.
5486     if (OrigIdx == 0)
5487       return Op;
5488     MVT ContainerVT = VecVT;
5489     if (VecVT.isFixedLengthVector()) {
5490       ContainerVT = getContainerForFixedLengthVector(VecVT);
5491       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5492     }
5493     SDValue Mask =
5494         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5495     // Set the vector length to only the number of elements we care about. This
5496     // avoids sliding down elements we're going to discard straight away.
5497     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5498     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5499     SDValue Slidedown =
5500         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5501                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5502     // Now we can use a cast-like subvector extract to get the result.
5503     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5504                             DAG.getConstant(0, DL, XLenVT));
5505     return DAG.getBitcast(Op.getValueType(), Slidedown);
5506   }
5507 
5508   unsigned SubRegIdx, RemIdx;
5509   std::tie(SubRegIdx, RemIdx) =
5510       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5511           VecVT, SubVecVT, OrigIdx, TRI);
5512 
5513   // If the Idx has been completely eliminated then this is a subvector extract
5514   // which naturally aligns to a vector register. These can easily be handled
5515   // using subregister manipulation.
5516   if (RemIdx == 0)
5517     return Op;
5518 
5519   // Else we must shift our vector register directly to extract the subvector.
5520   // Do this using VSLIDEDOWN.
5521 
5522   // If the vector type is an LMUL-group type, extract a subvector equal to the
5523   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5524   // instruction.
5525   MVT InterSubVT = VecVT;
5526   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5527     InterSubVT = getLMUL1VT(VecVT);
5528     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5529                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5530   }
5531 
5532   // Slide this vector register down by the desired number of elements in order
5533   // to place the desired subvector starting at element 0.
5534   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5535   // For scalable vectors this must be further multiplied by vscale.
5536   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5537 
5538   SDValue Mask, VL;
5539   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5540   SDValue Slidedown =
5541       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5542                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5543 
5544   // Now the vector is in the right position, extract our final subvector. This
5545   // should resolve to a COPY.
5546   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5547                           DAG.getConstant(0, DL, XLenVT));
5548 
5549   // We might have bitcast from a mask type: cast back to the original type if
5550   // required.
5551   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5552 }
5553 
5554 // Lower step_vector to the vid instruction. Any non-identity step value must
5555 // be accounted for my manual expansion.
5556 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5557                                               SelectionDAG &DAG) const {
5558   SDLoc DL(Op);
5559   MVT VT = Op.getSimpleValueType();
5560   MVT XLenVT = Subtarget.getXLenVT();
5561   SDValue Mask, VL;
5562   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5563   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5564   uint64_t StepValImm = Op.getConstantOperandVal(0);
5565   if (StepValImm != 1) {
5566     if (isPowerOf2_64(StepValImm)) {
5567       SDValue StepVal =
5568           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5569                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5570       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5571     } else {
5572       SDValue StepVal = lowerScalarSplat(
5573           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5574           VL, VT, DL, DAG, Subtarget);
5575       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5576     }
5577   }
5578   return StepVec;
5579 }
5580 
5581 // Implement vector_reverse using vrgather.vv with indices determined by
5582 // subtracting the id of each element from (VLMAX-1). This will convert
5583 // the indices like so:
5584 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5585 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5586 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5587                                                  SelectionDAG &DAG) const {
5588   SDLoc DL(Op);
5589   MVT VecVT = Op.getSimpleValueType();
5590   unsigned EltSize = VecVT.getScalarSizeInBits();
5591   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5592 
5593   unsigned MaxVLMAX = 0;
5594   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5595   if (VectorBitsMax != 0)
5596     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5597 
5598   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5599   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5600 
5601   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5602   // to use vrgatherei16.vv.
5603   // TODO: It's also possible to use vrgatherei16.vv for other types to
5604   // decrease register width for the index calculation.
5605   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5606     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5607     // Reverse each half, then reassemble them in reverse order.
5608     // NOTE: It's also possible that after splitting that VLMAX no longer
5609     // requires vrgatherei16.vv.
5610     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5611       SDValue Lo, Hi;
5612       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5613       EVT LoVT, HiVT;
5614       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5615       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5616       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5617       // Reassemble the low and high pieces reversed.
5618       // FIXME: This is a CONCAT_VECTORS.
5619       SDValue Res =
5620           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5621                       DAG.getIntPtrConstant(0, DL));
5622       return DAG.getNode(
5623           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5624           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5625     }
5626 
5627     // Just promote the int type to i16 which will double the LMUL.
5628     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5629     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5630   }
5631 
5632   MVT XLenVT = Subtarget.getXLenVT();
5633   SDValue Mask, VL;
5634   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5635 
5636   // Calculate VLMAX-1 for the desired SEW.
5637   unsigned MinElts = VecVT.getVectorMinNumElements();
5638   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5639                               DAG.getConstant(MinElts, DL, XLenVT));
5640   SDValue VLMinus1 =
5641       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5642 
5643   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5644   bool IsRV32E64 =
5645       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5646   SDValue SplatVL;
5647   if (!IsRV32E64)
5648     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5649   else
5650     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5651                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5652 
5653   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5654   SDValue Indices =
5655       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5656 
5657   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5658 }
5659 
5660 SDValue
5661 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5662                                                      SelectionDAG &DAG) const {
5663   SDLoc DL(Op);
5664   auto *Load = cast<LoadSDNode>(Op);
5665 
5666   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5667                                         Load->getMemoryVT(),
5668                                         *Load->getMemOperand()) &&
5669          "Expecting a correctly-aligned load");
5670 
5671   MVT VT = Op.getSimpleValueType();
5672   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5673 
5674   SDValue VL =
5675       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5676 
5677   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5678   SDValue NewLoad = DAG.getMemIntrinsicNode(
5679       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5680       Load->getMemoryVT(), Load->getMemOperand());
5681 
5682   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5683   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5684 }
5685 
5686 SDValue
5687 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5688                                                       SelectionDAG &DAG) const {
5689   SDLoc DL(Op);
5690   auto *Store = cast<StoreSDNode>(Op);
5691 
5692   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5693                                         Store->getMemoryVT(),
5694                                         *Store->getMemOperand()) &&
5695          "Expecting a correctly-aligned store");
5696 
5697   SDValue StoreVal = Store->getValue();
5698   MVT VT = StoreVal.getSimpleValueType();
5699 
5700   // If the size less than a byte, we need to pad with zeros to make a byte.
5701   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5702     VT = MVT::v8i1;
5703     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5704                            DAG.getConstant(0, DL, VT), StoreVal,
5705                            DAG.getIntPtrConstant(0, DL));
5706   }
5707 
5708   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5709 
5710   SDValue VL =
5711       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5712 
5713   SDValue NewValue =
5714       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5715   return DAG.getMemIntrinsicNode(
5716       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5717       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5718       Store->getMemoryVT(), Store->getMemOperand());
5719 }
5720 
5721 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5722                                              SelectionDAG &DAG) const {
5723   SDLoc DL(Op);
5724   MVT VT = Op.getSimpleValueType();
5725 
5726   const auto *MemSD = cast<MemSDNode>(Op);
5727   EVT MemVT = MemSD->getMemoryVT();
5728   MachineMemOperand *MMO = MemSD->getMemOperand();
5729   SDValue Chain = MemSD->getChain();
5730   SDValue BasePtr = MemSD->getBasePtr();
5731 
5732   SDValue Mask, PassThru, VL;
5733   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5734     Mask = VPLoad->getMask();
5735     PassThru = DAG.getUNDEF(VT);
5736     VL = VPLoad->getVectorLength();
5737   } else {
5738     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5739     Mask = MLoad->getMask();
5740     PassThru = MLoad->getPassThru();
5741   }
5742 
5743   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5744 
5745   MVT XLenVT = Subtarget.getXLenVT();
5746 
5747   MVT ContainerVT = VT;
5748   if (VT.isFixedLengthVector()) {
5749     ContainerVT = getContainerForFixedLengthVector(VT);
5750     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5751     if (!IsUnmasked) {
5752       MVT MaskVT =
5753           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5754       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5755     }
5756   }
5757 
5758   if (!VL)
5759     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5760 
5761   unsigned IntID =
5762       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5763   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5764   if (IsUnmasked)
5765     Ops.push_back(DAG.getUNDEF(ContainerVT));
5766   else
5767     Ops.push_back(PassThru);
5768   Ops.push_back(BasePtr);
5769   if (!IsUnmasked)
5770     Ops.push_back(Mask);
5771   Ops.push_back(VL);
5772   if (!IsUnmasked)
5773     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5774 
5775   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5776 
5777   SDValue Result =
5778       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5779   Chain = Result.getValue(1);
5780 
5781   if (VT.isFixedLengthVector())
5782     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5783 
5784   return DAG.getMergeValues({Result, Chain}, DL);
5785 }
5786 
5787 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5788                                               SelectionDAG &DAG) const {
5789   SDLoc DL(Op);
5790 
5791   const auto *MemSD = cast<MemSDNode>(Op);
5792   EVT MemVT = MemSD->getMemoryVT();
5793   MachineMemOperand *MMO = MemSD->getMemOperand();
5794   SDValue Chain = MemSD->getChain();
5795   SDValue BasePtr = MemSD->getBasePtr();
5796   SDValue Val, Mask, VL;
5797 
5798   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5799     Val = VPStore->getValue();
5800     Mask = VPStore->getMask();
5801     VL = VPStore->getVectorLength();
5802   } else {
5803     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5804     Val = MStore->getValue();
5805     Mask = MStore->getMask();
5806   }
5807 
5808   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5809 
5810   MVT VT = Val.getSimpleValueType();
5811   MVT XLenVT = Subtarget.getXLenVT();
5812 
5813   MVT ContainerVT = VT;
5814   if (VT.isFixedLengthVector()) {
5815     ContainerVT = getContainerForFixedLengthVector(VT);
5816 
5817     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5818     if (!IsUnmasked) {
5819       MVT MaskVT =
5820           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5821       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5822     }
5823   }
5824 
5825   if (!VL)
5826     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5827 
5828   unsigned IntID =
5829       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5830   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5831   Ops.push_back(Val);
5832   Ops.push_back(BasePtr);
5833   if (!IsUnmasked)
5834     Ops.push_back(Mask);
5835   Ops.push_back(VL);
5836 
5837   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5838                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5839 }
5840 
5841 SDValue
5842 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5843                                                       SelectionDAG &DAG) const {
5844   MVT InVT = Op.getOperand(0).getSimpleValueType();
5845   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5846 
5847   MVT VT = Op.getSimpleValueType();
5848 
5849   SDValue Op1 =
5850       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5851   SDValue Op2 =
5852       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5853 
5854   SDLoc DL(Op);
5855   SDValue VL =
5856       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5857 
5858   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5859   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5860 
5861   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5862                             Op.getOperand(2), Mask, VL);
5863 
5864   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5865 }
5866 
5867 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5868     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5869   MVT VT = Op.getSimpleValueType();
5870 
5871   if (VT.getVectorElementType() == MVT::i1)
5872     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5873 
5874   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5875 }
5876 
5877 SDValue
5878 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5879                                                       SelectionDAG &DAG) const {
5880   unsigned Opc;
5881   switch (Op.getOpcode()) {
5882   default: llvm_unreachable("Unexpected opcode!");
5883   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5884   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5885   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5886   }
5887 
5888   return lowerToScalableOp(Op, DAG, Opc);
5889 }
5890 
5891 // Lower vector ABS to smax(X, sub(0, X)).
5892 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5893   SDLoc DL(Op);
5894   MVT VT = Op.getSimpleValueType();
5895   SDValue X = Op.getOperand(0);
5896 
5897   assert(VT.isFixedLengthVector() && "Unexpected type");
5898 
5899   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5900   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5901 
5902   SDValue Mask, VL;
5903   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5904 
5905   SDValue SplatZero = DAG.getNode(
5906       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5907       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5908   SDValue NegX =
5909       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5910   SDValue Max =
5911       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5912 
5913   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5914 }
5915 
5916 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5917     SDValue Op, SelectionDAG &DAG) const {
5918   SDLoc DL(Op);
5919   MVT VT = Op.getSimpleValueType();
5920   SDValue Mag = Op.getOperand(0);
5921   SDValue Sign = Op.getOperand(1);
5922   assert(Mag.getValueType() == Sign.getValueType() &&
5923          "Can only handle COPYSIGN with matching types.");
5924 
5925   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5926   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5927   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5928 
5929   SDValue Mask, VL;
5930   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5931 
5932   SDValue CopySign =
5933       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5934 
5935   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5936 }
5937 
5938 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5939     SDValue Op, SelectionDAG &DAG) const {
5940   MVT VT = Op.getSimpleValueType();
5941   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5942 
5943   MVT I1ContainerVT =
5944       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5945 
5946   SDValue CC =
5947       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5948   SDValue Op1 =
5949       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5950   SDValue Op2 =
5951       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5952 
5953   SDLoc DL(Op);
5954   SDValue Mask, VL;
5955   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5956 
5957   SDValue Select =
5958       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5959 
5960   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5961 }
5962 
5963 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5964                                                unsigned NewOpc,
5965                                                bool HasMask) const {
5966   MVT VT = Op.getSimpleValueType();
5967   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5968 
5969   // Create list of operands by converting existing ones to scalable types.
5970   SmallVector<SDValue, 6> Ops;
5971   for (const SDValue &V : Op->op_values()) {
5972     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5973 
5974     // Pass through non-vector operands.
5975     if (!V.getValueType().isVector()) {
5976       Ops.push_back(V);
5977       continue;
5978     }
5979 
5980     // "cast" fixed length vector to a scalable vector.
5981     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5982            "Only fixed length vectors are supported!");
5983     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5984   }
5985 
5986   SDLoc DL(Op);
5987   SDValue Mask, VL;
5988   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5989   if (HasMask)
5990     Ops.push_back(Mask);
5991   Ops.push_back(VL);
5992 
5993   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5994   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5995 }
5996 
5997 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5998 // * Operands of each node are assumed to be in the same order.
5999 // * The EVL operand is promoted from i32 to i64 on RV64.
6000 // * Fixed-length vectors are converted to their scalable-vector container
6001 //   types.
6002 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6003                                        unsigned RISCVISDOpc) const {
6004   SDLoc DL(Op);
6005   MVT VT = Op.getSimpleValueType();
6006   SmallVector<SDValue, 4> Ops;
6007 
6008   for (const auto &OpIdx : enumerate(Op->ops())) {
6009     SDValue V = OpIdx.value();
6010     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6011     // Pass through operands which aren't fixed-length vectors.
6012     if (!V.getValueType().isFixedLengthVector()) {
6013       Ops.push_back(V);
6014       continue;
6015     }
6016     // "cast" fixed length vector to a scalable vector.
6017     MVT OpVT = V.getSimpleValueType();
6018     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6019     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6020            "Only fixed length vectors are supported!");
6021     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6022   }
6023 
6024   if (!VT.isFixedLengthVector())
6025     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6026 
6027   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6028 
6029   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6030 
6031   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6032 }
6033 
6034 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6035                                             unsigned MaskOpc,
6036                                             unsigned VecOpc) const {
6037   MVT VT = Op.getSimpleValueType();
6038   if (VT.getVectorElementType() != MVT::i1)
6039     return lowerVPOp(Op, DAG, VecOpc);
6040 
6041   // It is safe to drop mask parameter as masked-off elements are undef.
6042   SDValue Op1 = Op->getOperand(0);
6043   SDValue Op2 = Op->getOperand(1);
6044   SDValue VL = Op->getOperand(3);
6045 
6046   MVT ContainerVT = VT;
6047   const bool IsFixed = VT.isFixedLengthVector();
6048   if (IsFixed) {
6049     ContainerVT = getContainerForFixedLengthVector(VT);
6050     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6051     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6052   }
6053 
6054   SDLoc DL(Op);
6055   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6056   if (!IsFixed)
6057     return Val;
6058   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6059 }
6060 
6061 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6062 // matched to a RVV indexed load. The RVV indexed load instructions only
6063 // support the "unsigned unscaled" addressing mode; indices are implicitly
6064 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6065 // signed or scaled indexing is extended to the XLEN value type and scaled
6066 // accordingly.
6067 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6068                                                SelectionDAG &DAG) const {
6069   SDLoc DL(Op);
6070   MVT VT = Op.getSimpleValueType();
6071 
6072   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6073   EVT MemVT = MemSD->getMemoryVT();
6074   MachineMemOperand *MMO = MemSD->getMemOperand();
6075   SDValue Chain = MemSD->getChain();
6076   SDValue BasePtr = MemSD->getBasePtr();
6077 
6078   ISD::LoadExtType LoadExtType;
6079   SDValue Index, Mask, PassThru, VL;
6080 
6081   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6082     Index = VPGN->getIndex();
6083     Mask = VPGN->getMask();
6084     PassThru = DAG.getUNDEF(VT);
6085     VL = VPGN->getVectorLength();
6086     // VP doesn't support extending loads.
6087     LoadExtType = ISD::NON_EXTLOAD;
6088   } else {
6089     // Else it must be a MGATHER.
6090     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6091     Index = MGN->getIndex();
6092     Mask = MGN->getMask();
6093     PassThru = MGN->getPassThru();
6094     LoadExtType = MGN->getExtensionType();
6095   }
6096 
6097   MVT IndexVT = Index.getSimpleValueType();
6098   MVT XLenVT = Subtarget.getXLenVT();
6099 
6100   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6101          "Unexpected VTs!");
6102   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6103   // Targets have to explicitly opt-in for extending vector loads.
6104   assert(LoadExtType == ISD::NON_EXTLOAD &&
6105          "Unexpected extending MGATHER/VP_GATHER");
6106   (void)LoadExtType;
6107 
6108   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6109   // the selection of the masked intrinsics doesn't do this for us.
6110   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6111 
6112   MVT ContainerVT = VT;
6113   if (VT.isFixedLengthVector()) {
6114     // We need to use the larger of the result and index type to determine the
6115     // scalable type to use so we don't increase LMUL for any operand/result.
6116     if (VT.bitsGE(IndexVT)) {
6117       ContainerVT = getContainerForFixedLengthVector(VT);
6118       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6119                                  ContainerVT.getVectorElementCount());
6120     } else {
6121       IndexVT = getContainerForFixedLengthVector(IndexVT);
6122       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6123                                      IndexVT.getVectorElementCount());
6124     }
6125 
6126     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6127 
6128     if (!IsUnmasked) {
6129       MVT MaskVT =
6130           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6131       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6132       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6133     }
6134   }
6135 
6136   if (!VL)
6137     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6138 
6139   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6140     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6141     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6142                                    VL);
6143     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6144                         TrueMask, VL);
6145   }
6146 
6147   unsigned IntID =
6148       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6149   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6150   if (IsUnmasked)
6151     Ops.push_back(DAG.getUNDEF(ContainerVT));
6152   else
6153     Ops.push_back(PassThru);
6154   Ops.push_back(BasePtr);
6155   Ops.push_back(Index);
6156   if (!IsUnmasked)
6157     Ops.push_back(Mask);
6158   Ops.push_back(VL);
6159   if (!IsUnmasked)
6160     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6161 
6162   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6163   SDValue Result =
6164       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6165   Chain = Result.getValue(1);
6166 
6167   if (VT.isFixedLengthVector())
6168     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6169 
6170   return DAG.getMergeValues({Result, Chain}, DL);
6171 }
6172 
6173 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6174 // matched to a RVV indexed store. The RVV indexed store instructions only
6175 // support the "unsigned unscaled" addressing mode; indices are implicitly
6176 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6177 // signed or scaled indexing is extended to the XLEN value type and scaled
6178 // accordingly.
6179 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6180                                                 SelectionDAG &DAG) const {
6181   SDLoc DL(Op);
6182   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6183   EVT MemVT = MemSD->getMemoryVT();
6184   MachineMemOperand *MMO = MemSD->getMemOperand();
6185   SDValue Chain = MemSD->getChain();
6186   SDValue BasePtr = MemSD->getBasePtr();
6187 
6188   bool IsTruncatingStore = false;
6189   SDValue Index, Mask, Val, VL;
6190 
6191   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6192     Index = VPSN->getIndex();
6193     Mask = VPSN->getMask();
6194     Val = VPSN->getValue();
6195     VL = VPSN->getVectorLength();
6196     // VP doesn't support truncating stores.
6197     IsTruncatingStore = false;
6198   } else {
6199     // Else it must be a MSCATTER.
6200     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6201     Index = MSN->getIndex();
6202     Mask = MSN->getMask();
6203     Val = MSN->getValue();
6204     IsTruncatingStore = MSN->isTruncatingStore();
6205   }
6206 
6207   MVT VT = Val.getSimpleValueType();
6208   MVT IndexVT = Index.getSimpleValueType();
6209   MVT XLenVT = Subtarget.getXLenVT();
6210 
6211   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6212          "Unexpected VTs!");
6213   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6214   // Targets have to explicitly opt-in for extending vector loads and
6215   // truncating vector stores.
6216   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6217   (void)IsTruncatingStore;
6218 
6219   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6220   // the selection of the masked intrinsics doesn't do this for us.
6221   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6222 
6223   MVT ContainerVT = VT;
6224   if (VT.isFixedLengthVector()) {
6225     // We need to use the larger of the value and index type to determine the
6226     // scalable type to use so we don't increase LMUL for any operand/result.
6227     if (VT.bitsGE(IndexVT)) {
6228       ContainerVT = getContainerForFixedLengthVector(VT);
6229       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6230                                  ContainerVT.getVectorElementCount());
6231     } else {
6232       IndexVT = getContainerForFixedLengthVector(IndexVT);
6233       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6234                                      IndexVT.getVectorElementCount());
6235     }
6236 
6237     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6238     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6239 
6240     if (!IsUnmasked) {
6241       MVT MaskVT =
6242           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6243       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6244     }
6245   }
6246 
6247   if (!VL)
6248     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6249 
6250   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6251     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6252     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6253                                    VL);
6254     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6255                         TrueMask, VL);
6256   }
6257 
6258   unsigned IntID =
6259       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6260   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6261   Ops.push_back(Val);
6262   Ops.push_back(BasePtr);
6263   Ops.push_back(Index);
6264   if (!IsUnmasked)
6265     Ops.push_back(Mask);
6266   Ops.push_back(VL);
6267 
6268   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6269                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6270 }
6271 
6272 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6273                                                SelectionDAG &DAG) const {
6274   const MVT XLenVT = Subtarget.getXLenVT();
6275   SDLoc DL(Op);
6276   SDValue Chain = Op->getOperand(0);
6277   SDValue SysRegNo = DAG.getTargetConstant(
6278       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6279   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6280   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6281 
6282   // Encoding used for rounding mode in RISCV differs from that used in
6283   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6284   // table, which consists of a sequence of 4-bit fields, each representing
6285   // corresponding FLT_ROUNDS mode.
6286   static const int Table =
6287       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6288       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6289       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6290       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6291       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6292 
6293   SDValue Shift =
6294       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6295   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6296                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6297   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6298                                DAG.getConstant(7, DL, XLenVT));
6299 
6300   return DAG.getMergeValues({Masked, Chain}, DL);
6301 }
6302 
6303 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6304                                                SelectionDAG &DAG) const {
6305   const MVT XLenVT = Subtarget.getXLenVT();
6306   SDLoc DL(Op);
6307   SDValue Chain = Op->getOperand(0);
6308   SDValue RMValue = Op->getOperand(1);
6309   SDValue SysRegNo = DAG.getTargetConstant(
6310       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6311 
6312   // Encoding used for rounding mode in RISCV differs from that used in
6313   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6314   // a table, which consists of a sequence of 4-bit fields, each representing
6315   // corresponding RISCV mode.
6316   static const unsigned Table =
6317       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6318       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6319       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6320       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6321       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6322 
6323   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6324                               DAG.getConstant(2, DL, XLenVT));
6325   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6326                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6327   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6328                         DAG.getConstant(0x7, DL, XLenVT));
6329   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6330                      RMValue);
6331 }
6332 
6333 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6334   switch (IntNo) {
6335   default:
6336     llvm_unreachable("Unexpected Intrinsic");
6337   case Intrinsic::riscv_grev:
6338     return RISCVISD::GREVW;
6339   case Intrinsic::riscv_gorc:
6340     return RISCVISD::GORCW;
6341   case Intrinsic::riscv_bcompress:
6342     return RISCVISD::BCOMPRESSW;
6343   case Intrinsic::riscv_bdecompress:
6344     return RISCVISD::BDECOMPRESSW;
6345   case Intrinsic::riscv_bfp:
6346     return RISCVISD::BFPW;
6347   case Intrinsic::riscv_fsl:
6348     return RISCVISD::FSLW;
6349   case Intrinsic::riscv_fsr:
6350     return RISCVISD::FSRW;
6351   }
6352 }
6353 
6354 // Converts the given intrinsic to a i64 operation with any extension.
6355 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6356                                          unsigned IntNo) {
6357   SDLoc DL(N);
6358   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6359   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6360   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6361   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6362   // ReplaceNodeResults requires we maintain the same type for the return value.
6363   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6364 }
6365 
6366 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6367 // form of the given Opcode.
6368 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6369   switch (Opcode) {
6370   default:
6371     llvm_unreachable("Unexpected opcode");
6372   case ISD::SHL:
6373     return RISCVISD::SLLW;
6374   case ISD::SRA:
6375     return RISCVISD::SRAW;
6376   case ISD::SRL:
6377     return RISCVISD::SRLW;
6378   case ISD::SDIV:
6379     return RISCVISD::DIVW;
6380   case ISD::UDIV:
6381     return RISCVISD::DIVUW;
6382   case ISD::UREM:
6383     return RISCVISD::REMUW;
6384   case ISD::ROTL:
6385     return RISCVISD::ROLW;
6386   case ISD::ROTR:
6387     return RISCVISD::RORW;
6388   case RISCVISD::GREV:
6389     return RISCVISD::GREVW;
6390   case RISCVISD::GORC:
6391     return RISCVISD::GORCW;
6392   }
6393 }
6394 
6395 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6396 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6397 // otherwise be promoted to i64, making it difficult to select the
6398 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6399 // type i8/i16/i32 is lost.
6400 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6401                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6402   SDLoc DL(N);
6403   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6404   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6405   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6406   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6407   // ReplaceNodeResults requires we maintain the same type for the return value.
6408   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6409 }
6410 
6411 // Converts the given 32-bit operation to a i64 operation with signed extension
6412 // semantic to reduce the signed extension instructions.
6413 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6414   SDLoc DL(N);
6415   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6416   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6417   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6418   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6419                                DAG.getValueType(MVT::i32));
6420   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6421 }
6422 
6423 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6424                                              SmallVectorImpl<SDValue> &Results,
6425                                              SelectionDAG &DAG) const {
6426   SDLoc DL(N);
6427   switch (N->getOpcode()) {
6428   default:
6429     llvm_unreachable("Don't know how to custom type legalize this operation!");
6430   case ISD::STRICT_FP_TO_SINT:
6431   case ISD::STRICT_FP_TO_UINT:
6432   case ISD::FP_TO_SINT:
6433   case ISD::FP_TO_UINT: {
6434     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6435            "Unexpected custom legalisation");
6436     bool IsStrict = N->isStrictFPOpcode();
6437     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6438                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6439     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6440     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6441         TargetLowering::TypeSoftenFloat) {
6442       if (!isTypeLegal(Op0.getValueType()))
6443         return;
6444       if (IsStrict) {
6445         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6446                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6447         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6448         SDValue Res = DAG.getNode(
6449             Opc, DL, VTs, N->getOperand(0), Op0,
6450             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6451         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6452         Results.push_back(Res.getValue(1));
6453         return;
6454       }
6455       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6456       SDValue Res =
6457           DAG.getNode(Opc, DL, MVT::i64, Op0,
6458                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6459       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6460       return;
6461     }
6462     // If the FP type needs to be softened, emit a library call using the 'si'
6463     // version. If we left it to default legalization we'd end up with 'di'. If
6464     // the FP type doesn't need to be softened just let generic type
6465     // legalization promote the result type.
6466     RTLIB::Libcall LC;
6467     if (IsSigned)
6468       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6469     else
6470       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6471     MakeLibCallOptions CallOptions;
6472     EVT OpVT = Op0.getValueType();
6473     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6474     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6475     SDValue Result;
6476     std::tie(Result, Chain) =
6477         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6478     Results.push_back(Result);
6479     if (IsStrict)
6480       Results.push_back(Chain);
6481     break;
6482   }
6483   case ISD::READCYCLECOUNTER: {
6484     assert(!Subtarget.is64Bit() &&
6485            "READCYCLECOUNTER only has custom type legalization on riscv32");
6486 
6487     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6488     SDValue RCW =
6489         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6490 
6491     Results.push_back(
6492         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6493     Results.push_back(RCW.getValue(2));
6494     break;
6495   }
6496   case ISD::MUL: {
6497     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6498     unsigned XLen = Subtarget.getXLen();
6499     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6500     if (Size > XLen) {
6501       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6502       SDValue LHS = N->getOperand(0);
6503       SDValue RHS = N->getOperand(1);
6504       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6505 
6506       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6507       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6508       // We need exactly one side to be unsigned.
6509       if (LHSIsU == RHSIsU)
6510         return;
6511 
6512       auto MakeMULPair = [&](SDValue S, SDValue U) {
6513         MVT XLenVT = Subtarget.getXLenVT();
6514         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6515         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6516         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6517         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6518         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6519       };
6520 
6521       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6522       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6523 
6524       // The other operand should be signed, but still prefer MULH when
6525       // possible.
6526       if (RHSIsU && LHSIsS && !RHSIsS)
6527         Results.push_back(MakeMULPair(LHS, RHS));
6528       else if (LHSIsU && RHSIsS && !LHSIsS)
6529         Results.push_back(MakeMULPair(RHS, LHS));
6530 
6531       return;
6532     }
6533     LLVM_FALLTHROUGH;
6534   }
6535   case ISD::ADD:
6536   case ISD::SUB:
6537     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6538            "Unexpected custom legalisation");
6539     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6540     break;
6541   case ISD::SHL:
6542   case ISD::SRA:
6543   case ISD::SRL:
6544     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6545            "Unexpected custom legalisation");
6546     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6547       Results.push_back(customLegalizeToWOp(N, DAG));
6548       break;
6549     }
6550 
6551     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6552     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6553     // shift amount.
6554     if (N->getOpcode() == ISD::SHL) {
6555       SDLoc DL(N);
6556       SDValue NewOp0 =
6557           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6558       SDValue NewOp1 =
6559           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6560       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6561       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6562                                    DAG.getValueType(MVT::i32));
6563       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6564     }
6565 
6566     break;
6567   case ISD::ROTL:
6568   case ISD::ROTR:
6569     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6570            "Unexpected custom legalisation");
6571     Results.push_back(customLegalizeToWOp(N, DAG));
6572     break;
6573   case ISD::CTTZ:
6574   case ISD::CTTZ_ZERO_UNDEF:
6575   case ISD::CTLZ:
6576   case ISD::CTLZ_ZERO_UNDEF: {
6577     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6578            "Unexpected custom legalisation");
6579 
6580     SDValue NewOp0 =
6581         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6582     bool IsCTZ =
6583         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6584     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6585     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6586     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6587     return;
6588   }
6589   case ISD::SDIV:
6590   case ISD::UDIV:
6591   case ISD::UREM: {
6592     MVT VT = N->getSimpleValueType(0);
6593     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6594            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6595            "Unexpected custom legalisation");
6596     // Don't promote division/remainder by constant since we should expand those
6597     // to multiply by magic constant.
6598     // FIXME: What if the expansion is disabled for minsize.
6599     if (N->getOperand(1).getOpcode() == ISD::Constant)
6600       return;
6601 
6602     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6603     // the upper 32 bits. For other types we need to sign or zero extend
6604     // based on the opcode.
6605     unsigned ExtOpc = ISD::ANY_EXTEND;
6606     if (VT != MVT::i32)
6607       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6608                                            : ISD::ZERO_EXTEND;
6609 
6610     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6611     break;
6612   }
6613   case ISD::UADDO:
6614   case ISD::USUBO: {
6615     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6616            "Unexpected custom legalisation");
6617     bool IsAdd = N->getOpcode() == ISD::UADDO;
6618     // Create an ADDW or SUBW.
6619     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6620     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6621     SDValue Res =
6622         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6623     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6624                       DAG.getValueType(MVT::i32));
6625 
6626     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6627     // Since the inputs are sign extended from i32, this is equivalent to
6628     // comparing the lower 32 bits.
6629     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6630     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6631                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6632 
6633     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6634     Results.push_back(Overflow);
6635     return;
6636   }
6637   case ISD::UADDSAT:
6638   case ISD::USUBSAT: {
6639     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6640            "Unexpected custom legalisation");
6641     if (Subtarget.hasStdExtZbb()) {
6642       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6643       // sign extend allows overflow of the lower 32 bits to be detected on
6644       // the promoted size.
6645       SDValue LHS =
6646           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6647       SDValue RHS =
6648           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6649       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6650       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6651       return;
6652     }
6653 
6654     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6655     // promotion for UADDO/USUBO.
6656     Results.push_back(expandAddSubSat(N, DAG));
6657     return;
6658   }
6659   case ISD::BITCAST: {
6660     EVT VT = N->getValueType(0);
6661     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6662     SDValue Op0 = N->getOperand(0);
6663     EVT Op0VT = Op0.getValueType();
6664     MVT XLenVT = Subtarget.getXLenVT();
6665     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6666       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6667       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6668     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6669                Subtarget.hasStdExtF()) {
6670       SDValue FPConv =
6671           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6672       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6673     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6674                isTypeLegal(Op0VT)) {
6675       // Custom-legalize bitcasts from fixed-length vector types to illegal
6676       // scalar types in order to improve codegen. Bitcast the vector to a
6677       // one-element vector type whose element type is the same as the result
6678       // type, and extract the first element.
6679       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6680       if (isTypeLegal(BVT)) {
6681         SDValue BVec = DAG.getBitcast(BVT, Op0);
6682         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6683                                       DAG.getConstant(0, DL, XLenVT)));
6684       }
6685     }
6686     break;
6687   }
6688   case RISCVISD::GREV:
6689   case RISCVISD::GORC: {
6690     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6691            "Unexpected custom legalisation");
6692     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6693     // This is similar to customLegalizeToWOp, except that we pass the second
6694     // operand (a TargetConstant) straight through: it is already of type
6695     // XLenVT.
6696     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6697     SDValue NewOp0 =
6698         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6699     SDValue NewOp1 =
6700         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6701     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6702     // ReplaceNodeResults requires we maintain the same type for the return
6703     // value.
6704     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6705     break;
6706   }
6707   case RISCVISD::SHFL: {
6708     // There is no SHFLIW instruction, but we can just promote the operation.
6709     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6710            "Unexpected custom legalisation");
6711     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6712     SDValue NewOp0 =
6713         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6714     SDValue NewOp1 =
6715         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6716     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6717     // ReplaceNodeResults requires we maintain the same type for the return
6718     // value.
6719     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6720     break;
6721   }
6722   case ISD::BSWAP:
6723   case ISD::BITREVERSE: {
6724     MVT VT = N->getSimpleValueType(0);
6725     MVT XLenVT = Subtarget.getXLenVT();
6726     assert((VT == MVT::i8 || VT == MVT::i16 ||
6727             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6728            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6729     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6730     unsigned Imm = VT.getSizeInBits() - 1;
6731     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6732     if (N->getOpcode() == ISD::BSWAP)
6733       Imm &= ~0x7U;
6734     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6735     SDValue GREVI =
6736         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6737     // ReplaceNodeResults requires we maintain the same type for the return
6738     // value.
6739     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6740     break;
6741   }
6742   case ISD::FSHL:
6743   case ISD::FSHR: {
6744     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6745            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6746     SDValue NewOp0 =
6747         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6748     SDValue NewOp1 =
6749         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6750     SDValue NewShAmt =
6751         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6752     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6753     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6754     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6755                            DAG.getConstant(0x1f, DL, MVT::i64));
6756     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6757     // instruction use different orders. fshl will return its first operand for
6758     // shift of zero, fshr will return its second operand. fsl and fsr both
6759     // return rs1 so the ISD nodes need to have different operand orders.
6760     // Shift amount is in rs2.
6761     unsigned Opc = RISCVISD::FSLW;
6762     if (N->getOpcode() == ISD::FSHR) {
6763       std::swap(NewOp0, NewOp1);
6764       Opc = RISCVISD::FSRW;
6765     }
6766     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6767     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6768     break;
6769   }
6770   case ISD::EXTRACT_VECTOR_ELT: {
6771     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6772     // type is illegal (currently only vXi64 RV32).
6773     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6774     // transferred to the destination register. We issue two of these from the
6775     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6776     // first element.
6777     SDValue Vec = N->getOperand(0);
6778     SDValue Idx = N->getOperand(1);
6779 
6780     // The vector type hasn't been legalized yet so we can't issue target
6781     // specific nodes if it needs legalization.
6782     // FIXME: We would manually legalize if it's important.
6783     if (!isTypeLegal(Vec.getValueType()))
6784       return;
6785 
6786     MVT VecVT = Vec.getSimpleValueType();
6787 
6788     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6789            VecVT.getVectorElementType() == MVT::i64 &&
6790            "Unexpected EXTRACT_VECTOR_ELT legalization");
6791 
6792     // If this is a fixed vector, we need to convert it to a scalable vector.
6793     MVT ContainerVT = VecVT;
6794     if (VecVT.isFixedLengthVector()) {
6795       ContainerVT = getContainerForFixedLengthVector(VecVT);
6796       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6797     }
6798 
6799     MVT XLenVT = Subtarget.getXLenVT();
6800 
6801     // Use a VL of 1 to avoid processing more elements than we need.
6802     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6803     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6804     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6805 
6806     // Unless the index is known to be 0, we must slide the vector down to get
6807     // the desired element into index 0.
6808     if (!isNullConstant(Idx)) {
6809       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6810                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6811     }
6812 
6813     // Extract the lower XLEN bits of the correct vector element.
6814     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6815 
6816     // To extract the upper XLEN bits of the vector element, shift the first
6817     // element right by 32 bits and re-extract the lower XLEN bits.
6818     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6819                                      DAG.getUNDEF(ContainerVT),
6820                                      DAG.getConstant(32, DL, XLenVT), VL);
6821     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6822                                  ThirtyTwoV, Mask, VL);
6823 
6824     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6825 
6826     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6827     break;
6828   }
6829   case ISD::INTRINSIC_WO_CHAIN: {
6830     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6831     switch (IntNo) {
6832     default:
6833       llvm_unreachable(
6834           "Don't know how to custom type legalize this intrinsic!");
6835     case Intrinsic::riscv_grev:
6836     case Intrinsic::riscv_gorc:
6837     case Intrinsic::riscv_bcompress:
6838     case Intrinsic::riscv_bdecompress:
6839     case Intrinsic::riscv_bfp: {
6840       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6841              "Unexpected custom legalisation");
6842       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6843       break;
6844     }
6845     case Intrinsic::riscv_fsl:
6846     case Intrinsic::riscv_fsr: {
6847       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6848              "Unexpected custom legalisation");
6849       SDValue NewOp1 =
6850           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6851       SDValue NewOp2 =
6852           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6853       SDValue NewOp3 =
6854           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6855       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6856       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6857       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6858       break;
6859     }
6860     case Intrinsic::riscv_orc_b: {
6861       // Lower to the GORCI encoding for orc.b with the operand extended.
6862       SDValue NewOp =
6863           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6864       // If Zbp is enabled, use GORCIW which will sign extend the result.
6865       unsigned Opc =
6866           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6867       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6868                                 DAG.getConstant(7, DL, MVT::i64));
6869       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6870       return;
6871     }
6872     case Intrinsic::riscv_shfl:
6873     case Intrinsic::riscv_unshfl: {
6874       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6875              "Unexpected custom legalisation");
6876       SDValue NewOp1 =
6877           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6878       SDValue NewOp2 =
6879           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6880       unsigned Opc =
6881           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6882       // There is no (UN)SHFLIW. If the control word is a constant, we can use
6883       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
6884       // will be shuffled the same way as the lower 32 bit half, but the two
6885       // halves won't cross.
6886       if (isa<ConstantSDNode>(NewOp2)) {
6887         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6888                              DAG.getConstant(0xf, DL, MVT::i64));
6889         Opc =
6890             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6891       }
6892       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6893       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6894       break;
6895     }
6896     case Intrinsic::riscv_vmv_x_s: {
6897       EVT VT = N->getValueType(0);
6898       MVT XLenVT = Subtarget.getXLenVT();
6899       if (VT.bitsLT(XLenVT)) {
6900         // Simple case just extract using vmv.x.s and truncate.
6901         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6902                                       Subtarget.getXLenVT(), N->getOperand(1));
6903         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6904         return;
6905       }
6906 
6907       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6908              "Unexpected custom legalization");
6909 
6910       // We need to do the move in two steps.
6911       SDValue Vec = N->getOperand(1);
6912       MVT VecVT = Vec.getSimpleValueType();
6913 
6914       // First extract the lower XLEN bits of the element.
6915       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6916 
6917       // To extract the upper XLEN bits of the vector element, shift the first
6918       // element right by 32 bits and re-extract the lower XLEN bits.
6919       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6920       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6921       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6922       SDValue ThirtyTwoV =
6923           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
6924                       DAG.getConstant(32, DL, XLenVT), VL);
6925       SDValue LShr32 =
6926           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6927       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6928 
6929       Results.push_back(
6930           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6931       break;
6932     }
6933     }
6934     break;
6935   }
6936   case ISD::VECREDUCE_ADD:
6937   case ISD::VECREDUCE_AND:
6938   case ISD::VECREDUCE_OR:
6939   case ISD::VECREDUCE_XOR:
6940   case ISD::VECREDUCE_SMAX:
6941   case ISD::VECREDUCE_UMAX:
6942   case ISD::VECREDUCE_SMIN:
6943   case ISD::VECREDUCE_UMIN:
6944     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6945       Results.push_back(V);
6946     break;
6947   case ISD::VP_REDUCE_ADD:
6948   case ISD::VP_REDUCE_AND:
6949   case ISD::VP_REDUCE_OR:
6950   case ISD::VP_REDUCE_XOR:
6951   case ISD::VP_REDUCE_SMAX:
6952   case ISD::VP_REDUCE_UMAX:
6953   case ISD::VP_REDUCE_SMIN:
6954   case ISD::VP_REDUCE_UMIN:
6955     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6956       Results.push_back(V);
6957     break;
6958   case ISD::FLT_ROUNDS_: {
6959     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6960     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6961     Results.push_back(Res.getValue(0));
6962     Results.push_back(Res.getValue(1));
6963     break;
6964   }
6965   }
6966 }
6967 
6968 // A structure to hold one of the bit-manipulation patterns below. Together, a
6969 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6970 //   (or (and (shl x, 1), 0xAAAAAAAA),
6971 //       (and (srl x, 1), 0x55555555))
6972 struct RISCVBitmanipPat {
6973   SDValue Op;
6974   unsigned ShAmt;
6975   bool IsSHL;
6976 
6977   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6978     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6979   }
6980 };
6981 
6982 // Matches patterns of the form
6983 //   (and (shl x, C2), (C1 << C2))
6984 //   (and (srl x, C2), C1)
6985 //   (shl (and x, C1), C2)
6986 //   (srl (and x, (C1 << C2)), C2)
6987 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6988 // The expected masks for each shift amount are specified in BitmanipMasks where
6989 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6990 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6991 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6992 // XLen is 64.
6993 static Optional<RISCVBitmanipPat>
6994 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6995   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6996          "Unexpected number of masks");
6997   Optional<uint64_t> Mask;
6998   // Optionally consume a mask around the shift operation.
6999   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7000     Mask = Op.getConstantOperandVal(1);
7001     Op = Op.getOperand(0);
7002   }
7003   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7004     return None;
7005   bool IsSHL = Op.getOpcode() == ISD::SHL;
7006 
7007   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7008     return None;
7009   uint64_t ShAmt = Op.getConstantOperandVal(1);
7010 
7011   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7012   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7013     return None;
7014   // If we don't have enough masks for 64 bit, then we must be trying to
7015   // match SHFL so we're only allowed to shift 1/4 of the width.
7016   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7017     return None;
7018 
7019   SDValue Src = Op.getOperand(0);
7020 
7021   // The expected mask is shifted left when the AND is found around SHL
7022   // patterns.
7023   //   ((x >> 1) & 0x55555555)
7024   //   ((x << 1) & 0xAAAAAAAA)
7025   bool SHLExpMask = IsSHL;
7026 
7027   if (!Mask) {
7028     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7029     // the mask is all ones: consume that now.
7030     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7031       Mask = Src.getConstantOperandVal(1);
7032       Src = Src.getOperand(0);
7033       // The expected mask is now in fact shifted left for SRL, so reverse the
7034       // decision.
7035       //   ((x & 0xAAAAAAAA) >> 1)
7036       //   ((x & 0x55555555) << 1)
7037       SHLExpMask = !SHLExpMask;
7038     } else {
7039       // Use a default shifted mask of all-ones if there's no AND, truncated
7040       // down to the expected width. This simplifies the logic later on.
7041       Mask = maskTrailingOnes<uint64_t>(Width);
7042       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7043     }
7044   }
7045 
7046   unsigned MaskIdx = Log2_32(ShAmt);
7047   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7048 
7049   if (SHLExpMask)
7050     ExpMask <<= ShAmt;
7051 
7052   if (Mask != ExpMask)
7053     return None;
7054 
7055   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7056 }
7057 
7058 // Matches any of the following bit-manipulation patterns:
7059 //   (and (shl x, 1), (0x55555555 << 1))
7060 //   (and (srl x, 1), 0x55555555)
7061 //   (shl (and x, 0x55555555), 1)
7062 //   (srl (and x, (0x55555555 << 1)), 1)
7063 // where the shift amount and mask may vary thus:
7064 //   [1]  = 0x55555555 / 0xAAAAAAAA
7065 //   [2]  = 0x33333333 / 0xCCCCCCCC
7066 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7067 //   [8]  = 0x00FF00FF / 0xFF00FF00
7068 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7069 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7070 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7071   // These are the unshifted masks which we use to match bit-manipulation
7072   // patterns. They may be shifted left in certain circumstances.
7073   static const uint64_t BitmanipMasks[] = {
7074       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7075       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7076 
7077   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7078 }
7079 
7080 // Match the following pattern as a GREVI(W) operation
7081 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7082 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7083                                const RISCVSubtarget &Subtarget) {
7084   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7085   EVT VT = Op.getValueType();
7086 
7087   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7088     auto LHS = matchGREVIPat(Op.getOperand(0));
7089     auto RHS = matchGREVIPat(Op.getOperand(1));
7090     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7091       SDLoc DL(Op);
7092       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7093                          DAG.getConstant(LHS->ShAmt, DL, VT));
7094     }
7095   }
7096   return SDValue();
7097 }
7098 
7099 // Matches any the following pattern as a GORCI(W) operation
7100 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7101 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7102 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7103 // Note that with the variant of 3.,
7104 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7105 // the inner pattern will first be matched as GREVI and then the outer
7106 // pattern will be matched to GORC via the first rule above.
7107 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7108 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7109                                const RISCVSubtarget &Subtarget) {
7110   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7111   EVT VT = Op.getValueType();
7112 
7113   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7114     SDLoc DL(Op);
7115     SDValue Op0 = Op.getOperand(0);
7116     SDValue Op1 = Op.getOperand(1);
7117 
7118     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7119       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7120           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7121           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7122         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7123       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7124       if ((Reverse.getOpcode() == ISD::ROTL ||
7125            Reverse.getOpcode() == ISD::ROTR) &&
7126           Reverse.getOperand(0) == X &&
7127           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7128         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7129         if (RotAmt == (VT.getSizeInBits() / 2))
7130           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7131                              DAG.getConstant(RotAmt, DL, VT));
7132       }
7133       return SDValue();
7134     };
7135 
7136     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7137     if (SDValue V = MatchOROfReverse(Op0, Op1))
7138       return V;
7139     if (SDValue V = MatchOROfReverse(Op1, Op0))
7140       return V;
7141 
7142     // OR is commutable so canonicalize its OR operand to the left
7143     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7144       std::swap(Op0, Op1);
7145     if (Op0.getOpcode() != ISD::OR)
7146       return SDValue();
7147     SDValue OrOp0 = Op0.getOperand(0);
7148     SDValue OrOp1 = Op0.getOperand(1);
7149     auto LHS = matchGREVIPat(OrOp0);
7150     // OR is commutable so swap the operands and try again: x might have been
7151     // on the left
7152     if (!LHS) {
7153       std::swap(OrOp0, OrOp1);
7154       LHS = matchGREVIPat(OrOp0);
7155     }
7156     auto RHS = matchGREVIPat(Op1);
7157     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7158       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7159                          DAG.getConstant(LHS->ShAmt, DL, VT));
7160     }
7161   }
7162   return SDValue();
7163 }
7164 
7165 // Matches any of the following bit-manipulation patterns:
7166 //   (and (shl x, 1), (0x22222222 << 1))
7167 //   (and (srl x, 1), 0x22222222)
7168 //   (shl (and x, 0x22222222), 1)
7169 //   (srl (and x, (0x22222222 << 1)), 1)
7170 // where the shift amount and mask may vary thus:
7171 //   [1]  = 0x22222222 / 0x44444444
7172 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7173 //   [4]  = 0x00F000F0 / 0x0F000F00
7174 //   [8]  = 0x0000FF00 / 0x00FF0000
7175 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7176 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7177   // These are the unshifted masks which we use to match bit-manipulation
7178   // patterns. They may be shifted left in certain circumstances.
7179   static const uint64_t BitmanipMasks[] = {
7180       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7181       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7182 
7183   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7184 }
7185 
7186 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7187 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7188                                const RISCVSubtarget &Subtarget) {
7189   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7190   EVT VT = Op.getValueType();
7191 
7192   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7193     return SDValue();
7194 
7195   SDValue Op0 = Op.getOperand(0);
7196   SDValue Op1 = Op.getOperand(1);
7197 
7198   // Or is commutable so canonicalize the second OR to the LHS.
7199   if (Op0.getOpcode() != ISD::OR)
7200     std::swap(Op0, Op1);
7201   if (Op0.getOpcode() != ISD::OR)
7202     return SDValue();
7203 
7204   // We found an inner OR, so our operands are the operands of the inner OR
7205   // and the other operand of the outer OR.
7206   SDValue A = Op0.getOperand(0);
7207   SDValue B = Op0.getOperand(1);
7208   SDValue C = Op1;
7209 
7210   auto Match1 = matchSHFLPat(A);
7211   auto Match2 = matchSHFLPat(B);
7212 
7213   // If neither matched, we failed.
7214   if (!Match1 && !Match2)
7215     return SDValue();
7216 
7217   // We had at least one match. if one failed, try the remaining C operand.
7218   if (!Match1) {
7219     std::swap(A, C);
7220     Match1 = matchSHFLPat(A);
7221     if (!Match1)
7222       return SDValue();
7223   } else if (!Match2) {
7224     std::swap(B, C);
7225     Match2 = matchSHFLPat(B);
7226     if (!Match2)
7227       return SDValue();
7228   }
7229   assert(Match1 && Match2);
7230 
7231   // Make sure our matches pair up.
7232   if (!Match1->formsPairWith(*Match2))
7233     return SDValue();
7234 
7235   // All the remains is to make sure C is an AND with the same input, that masks
7236   // out the bits that are being shuffled.
7237   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7238       C.getOperand(0) != Match1->Op)
7239     return SDValue();
7240 
7241   uint64_t Mask = C.getConstantOperandVal(1);
7242 
7243   static const uint64_t BitmanipMasks[] = {
7244       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7245       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7246   };
7247 
7248   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7249   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7250   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7251 
7252   if (Mask != ExpMask)
7253     return SDValue();
7254 
7255   SDLoc DL(Op);
7256   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7257                      DAG.getConstant(Match1->ShAmt, DL, VT));
7258 }
7259 
7260 // Optimize (add (shl x, c0), (shl y, c1)) ->
7261 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7262 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7263                                   const RISCVSubtarget &Subtarget) {
7264   // Perform this optimization only in the zba extension.
7265   if (!Subtarget.hasStdExtZba())
7266     return SDValue();
7267 
7268   // Skip for vector types and larger types.
7269   EVT VT = N->getValueType(0);
7270   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7271     return SDValue();
7272 
7273   // The two operand nodes must be SHL and have no other use.
7274   SDValue N0 = N->getOperand(0);
7275   SDValue N1 = N->getOperand(1);
7276   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7277       !N0->hasOneUse() || !N1->hasOneUse())
7278     return SDValue();
7279 
7280   // Check c0 and c1.
7281   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7282   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7283   if (!N0C || !N1C)
7284     return SDValue();
7285   int64_t C0 = N0C->getSExtValue();
7286   int64_t C1 = N1C->getSExtValue();
7287   if (C0 <= 0 || C1 <= 0)
7288     return SDValue();
7289 
7290   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7291   int64_t Bits = std::min(C0, C1);
7292   int64_t Diff = std::abs(C0 - C1);
7293   if (Diff != 1 && Diff != 2 && Diff != 3)
7294     return SDValue();
7295 
7296   // Build nodes.
7297   SDLoc DL(N);
7298   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7299   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7300   SDValue NA0 =
7301       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7302   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7303   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7304 }
7305 
7306 // Combine
7307 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8)
7308 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8)
7309 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8)
7310 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8)
7311 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG) {
7312   SDValue Src = N->getOperand(0);
7313   SDLoc DL(N);
7314   unsigned Opc;
7315 
7316   if ((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL) &&
7317       Src.getOpcode() == RISCVISD::GREV)
7318     Opc = RISCVISD::GREV;
7319   else if ((N->getOpcode() == RISCVISD::RORW ||
7320             N->getOpcode() == RISCVISD::ROLW) &&
7321            Src.getOpcode() == RISCVISD::GREVW)
7322     Opc = RISCVISD::GREVW;
7323   else
7324     return SDValue();
7325 
7326   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7327       !isa<ConstantSDNode>(Src.getOperand(1)))
7328     return SDValue();
7329 
7330   unsigned ShAmt1 = N->getConstantOperandVal(1);
7331   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7332   if (ShAmt1 != 16 && ShAmt2 != 24)
7333     return SDValue();
7334 
7335   Src = Src.getOperand(0);
7336   return DAG.getNode(Opc, DL, N->getValueType(0), Src,
7337                      DAG.getConstant(8, DL, N->getOperand(1).getValueType()));
7338 }
7339 
7340 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7341 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7342 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7343 // not undo itself, but they are redundant.
7344 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7345   SDValue Src = N->getOperand(0);
7346 
7347   if (Src.getOpcode() != N->getOpcode())
7348     return SDValue();
7349 
7350   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7351       !isa<ConstantSDNode>(Src.getOperand(1)))
7352     return SDValue();
7353 
7354   unsigned ShAmt1 = N->getConstantOperandVal(1);
7355   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7356   Src = Src.getOperand(0);
7357 
7358   unsigned CombinedShAmt;
7359   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7360     CombinedShAmt = ShAmt1 | ShAmt2;
7361   else
7362     CombinedShAmt = ShAmt1 ^ ShAmt2;
7363 
7364   if (CombinedShAmt == 0)
7365     return Src;
7366 
7367   SDLoc DL(N);
7368   return DAG.getNode(
7369       N->getOpcode(), DL, N->getValueType(0), Src,
7370       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7371 }
7372 
7373 // Combine a constant select operand into its use:
7374 //
7375 // (and (select cond, -1, c), x)
7376 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7377 // (or  (select cond, 0, c), x)
7378 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7379 // (xor (select cond, 0, c), x)
7380 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7381 // (add (select cond, 0, c), x)
7382 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7383 // (sub x, (select cond, 0, c))
7384 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7385 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7386                                    SelectionDAG &DAG, bool AllOnes) {
7387   EVT VT = N->getValueType(0);
7388 
7389   // Skip vectors.
7390   if (VT.isVector())
7391     return SDValue();
7392 
7393   if ((Slct.getOpcode() != ISD::SELECT &&
7394        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7395       !Slct.hasOneUse())
7396     return SDValue();
7397 
7398   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7399     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7400   };
7401 
7402   bool SwapSelectOps;
7403   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7404   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7405   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7406   SDValue NonConstantVal;
7407   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7408     SwapSelectOps = false;
7409     NonConstantVal = FalseVal;
7410   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7411     SwapSelectOps = true;
7412     NonConstantVal = TrueVal;
7413   } else
7414     return SDValue();
7415 
7416   // Slct is now know to be the desired identity constant when CC is true.
7417   TrueVal = OtherOp;
7418   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7419   // Unless SwapSelectOps says the condition should be false.
7420   if (SwapSelectOps)
7421     std::swap(TrueVal, FalseVal);
7422 
7423   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7424     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7425                        {Slct.getOperand(0), Slct.getOperand(1),
7426                         Slct.getOperand(2), TrueVal, FalseVal});
7427 
7428   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7429                      {Slct.getOperand(0), TrueVal, FalseVal});
7430 }
7431 
7432 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7433 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7434                                               bool AllOnes) {
7435   SDValue N0 = N->getOperand(0);
7436   SDValue N1 = N->getOperand(1);
7437   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7438     return Result;
7439   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7440     return Result;
7441   return SDValue();
7442 }
7443 
7444 // Transform (add (mul x, c0), c1) ->
7445 //           (add (mul (add x, c1/c0), c0), c1%c0).
7446 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7447 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7448 // to an infinite loop in DAGCombine if transformed.
7449 // Or transform (add (mul x, c0), c1) ->
7450 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7451 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7452 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7453 // lead to an infinite loop in DAGCombine if transformed.
7454 // Or transform (add (mul x, c0), c1) ->
7455 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7456 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7457 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7458 // lead to an infinite loop in DAGCombine if transformed.
7459 // Or transform (add (mul x, c0), c1) ->
7460 //              (mul (add x, c1/c0), c0).
7461 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7462 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7463                                      const RISCVSubtarget &Subtarget) {
7464   // Skip for vector types and larger types.
7465   EVT VT = N->getValueType(0);
7466   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7467     return SDValue();
7468   // The first operand node must be a MUL and has no other use.
7469   SDValue N0 = N->getOperand(0);
7470   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7471     return SDValue();
7472   // Check if c0 and c1 match above conditions.
7473   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7474   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7475   if (!N0C || !N1C)
7476     return SDValue();
7477   int64_t C0 = N0C->getSExtValue();
7478   int64_t C1 = N1C->getSExtValue();
7479   int64_t CA, CB;
7480   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7481     return SDValue();
7482   // Search for proper CA (non-zero) and CB that both are simm12.
7483   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7484       !isInt<12>(C0 * (C1 / C0))) {
7485     CA = C1 / C0;
7486     CB = C1 % C0;
7487   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7488              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7489     CA = C1 / C0 + 1;
7490     CB = C1 % C0 - C0;
7491   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7492              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7493     CA = C1 / C0 - 1;
7494     CB = C1 % C0 + C0;
7495   } else
7496     return SDValue();
7497   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7498   SDLoc DL(N);
7499   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7500                              DAG.getConstant(CA, DL, VT));
7501   SDValue New1 =
7502       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7503   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7504 }
7505 
7506 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7507                                  const RISCVSubtarget &Subtarget) {
7508   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7509     return V;
7510   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7511     return V;
7512   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7513   //      (select lhs, rhs, cc, x, (add x, y))
7514   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7515 }
7516 
7517 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7518   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7519   //      (select lhs, rhs, cc, x, (sub x, y))
7520   SDValue N0 = N->getOperand(0);
7521   SDValue N1 = N->getOperand(1);
7522   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7523 }
7524 
7525 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7526   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7527   //      (select lhs, rhs, cc, x, (and x, y))
7528   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7529 }
7530 
7531 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7532                                 const RISCVSubtarget &Subtarget) {
7533   if (Subtarget.hasStdExtZbp()) {
7534     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7535       return GREV;
7536     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7537       return GORC;
7538     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7539       return SHFL;
7540   }
7541 
7542   // fold (or (select cond, 0, y), x) ->
7543   //      (select cond, x, (or x, y))
7544   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7545 }
7546 
7547 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7548   // fold (xor (select cond, 0, y), x) ->
7549   //      (select cond, x, (xor x, y))
7550   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7551 }
7552 
7553 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7554 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7555 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7556 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7557 // ADDW/SUBW/MULW.
7558 static SDValue performANY_EXTENDCombine(SDNode *N,
7559                                         TargetLowering::DAGCombinerInfo &DCI,
7560                                         const RISCVSubtarget &Subtarget) {
7561   if (!Subtarget.is64Bit())
7562     return SDValue();
7563 
7564   SelectionDAG &DAG = DCI.DAG;
7565 
7566   SDValue Src = N->getOperand(0);
7567   EVT VT = N->getValueType(0);
7568   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7569     return SDValue();
7570 
7571   // The opcode must be one that can implicitly sign_extend.
7572   // FIXME: Additional opcodes.
7573   switch (Src.getOpcode()) {
7574   default:
7575     return SDValue();
7576   case ISD::MUL:
7577     if (!Subtarget.hasStdExtM())
7578       return SDValue();
7579     LLVM_FALLTHROUGH;
7580   case ISD::ADD:
7581   case ISD::SUB:
7582     break;
7583   }
7584 
7585   // Only handle cases where the result is used by a CopyToReg. That likely
7586   // means the value is a liveout of the basic block. This helps prevent
7587   // infinite combine loops like PR51206.
7588   if (none_of(N->uses(),
7589               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7590     return SDValue();
7591 
7592   SmallVector<SDNode *, 4> SetCCs;
7593   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7594                             UE = Src.getNode()->use_end();
7595        UI != UE; ++UI) {
7596     SDNode *User = *UI;
7597     if (User == N)
7598       continue;
7599     if (UI.getUse().getResNo() != Src.getResNo())
7600       continue;
7601     // All i32 setccs are legalized by sign extending operands.
7602     if (User->getOpcode() == ISD::SETCC) {
7603       SetCCs.push_back(User);
7604       continue;
7605     }
7606     // We don't know if we can extend this user.
7607     break;
7608   }
7609 
7610   // If we don't have any SetCCs, this isn't worthwhile.
7611   if (SetCCs.empty())
7612     return SDValue();
7613 
7614   SDLoc DL(N);
7615   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7616   DCI.CombineTo(N, SExt);
7617 
7618   // Promote all the setccs.
7619   for (SDNode *SetCC : SetCCs) {
7620     SmallVector<SDValue, 4> Ops;
7621 
7622     for (unsigned j = 0; j != 2; ++j) {
7623       SDValue SOp = SetCC->getOperand(j);
7624       if (SOp == Src)
7625         Ops.push_back(SExt);
7626       else
7627         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7628     }
7629 
7630     Ops.push_back(SetCC->getOperand(2));
7631     DCI.CombineTo(SetCC,
7632                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7633   }
7634   return SDValue(N, 0);
7635 }
7636 
7637 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7638 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7639 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7640                                              bool Commute = false) {
7641   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7642           N->getOpcode() == RISCVISD::SUB_VL) &&
7643          "Unexpected opcode");
7644   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7645   SDValue Op0 = N->getOperand(0);
7646   SDValue Op1 = N->getOperand(1);
7647   if (Commute)
7648     std::swap(Op0, Op1);
7649 
7650   MVT VT = N->getSimpleValueType(0);
7651 
7652   // Determine the narrow size for a widening add/sub.
7653   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7654   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7655                                   VT.getVectorElementCount());
7656 
7657   SDValue Mask = N->getOperand(2);
7658   SDValue VL = N->getOperand(3);
7659 
7660   SDLoc DL(N);
7661 
7662   // If the RHS is a sext or zext, we can form a widening op.
7663   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7664        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7665       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7666     unsigned ExtOpc = Op1.getOpcode();
7667     Op1 = Op1.getOperand(0);
7668     // Re-introduce narrower extends if needed.
7669     if (Op1.getValueType() != NarrowVT)
7670       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7671 
7672     unsigned WOpc;
7673     if (ExtOpc == RISCVISD::VSEXT_VL)
7674       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7675     else
7676       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7677 
7678     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7679   }
7680 
7681   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7682   // sext/zext?
7683 
7684   return SDValue();
7685 }
7686 
7687 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7688 // vwsub(u).vv/vx.
7689 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7690   SDValue Op0 = N->getOperand(0);
7691   SDValue Op1 = N->getOperand(1);
7692   SDValue Mask = N->getOperand(2);
7693   SDValue VL = N->getOperand(3);
7694 
7695   MVT VT = N->getSimpleValueType(0);
7696   MVT NarrowVT = Op1.getSimpleValueType();
7697   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7698 
7699   unsigned VOpc;
7700   switch (N->getOpcode()) {
7701   default: llvm_unreachable("Unexpected opcode");
7702   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7703   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7704   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7705   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7706   }
7707 
7708   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7709                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7710 
7711   SDLoc DL(N);
7712 
7713   // If the LHS is a sext or zext, we can narrow this op to the same size as
7714   // the RHS.
7715   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7716        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7717       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7718     unsigned ExtOpc = Op0.getOpcode();
7719     Op0 = Op0.getOperand(0);
7720     // Re-introduce narrower extends if needed.
7721     if (Op0.getValueType() != NarrowVT)
7722       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7723     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7724   }
7725 
7726   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7727                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7728 
7729   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7730   // to commute and use a vwadd(u).vx instead.
7731   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7732       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
7733     Op0 = Op0.getOperand(1);
7734 
7735     // See if have enough sign bits or zero bits in the scalar to use a
7736     // widening add/sub by splatting to smaller element size.
7737     unsigned EltBits = VT.getScalarSizeInBits();
7738     unsigned ScalarBits = Op0.getValueSizeInBits();
7739     // Make sure we're getting all element bits from the scalar register.
7740     // FIXME: Support implicit sign extension of vmv.v.x?
7741     if (ScalarBits < EltBits)
7742       return SDValue();
7743 
7744     if (IsSigned) {
7745       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7746         return SDValue();
7747     } else {
7748       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7749       if (!DAG.MaskedValueIsZero(Op0, Mask))
7750         return SDValue();
7751     }
7752 
7753     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7754                       DAG.getUNDEF(NarrowVT), Op0, VL);
7755     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7756   }
7757 
7758   return SDValue();
7759 }
7760 
7761 // Try to form VWMUL, VWMULU or VWMULSU.
7762 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7763 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7764                                        bool Commute) {
7765   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7766   SDValue Op0 = N->getOperand(0);
7767   SDValue Op1 = N->getOperand(1);
7768   if (Commute)
7769     std::swap(Op0, Op1);
7770 
7771   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7772   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7773   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7774   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7775     return SDValue();
7776 
7777   SDValue Mask = N->getOperand(2);
7778   SDValue VL = N->getOperand(3);
7779 
7780   // Make sure the mask and VL match.
7781   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7782     return SDValue();
7783 
7784   MVT VT = N->getSimpleValueType(0);
7785 
7786   // Determine the narrow size for a widening multiply.
7787   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7788   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7789                                   VT.getVectorElementCount());
7790 
7791   SDLoc DL(N);
7792 
7793   // See if the other operand is the same opcode.
7794   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7795     if (!Op1.hasOneUse())
7796       return SDValue();
7797 
7798     // Make sure the mask and VL match.
7799     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7800       return SDValue();
7801 
7802     Op1 = Op1.getOperand(0);
7803   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7804     // The operand is a splat of a scalar.
7805 
7806     // The pasthru must be undef for tail agnostic
7807     if (!Op1.getOperand(0).isUndef())
7808       return SDValue();
7809     // The VL must be the same.
7810     if (Op1.getOperand(2) != VL)
7811       return SDValue();
7812 
7813     // Get the scalar value.
7814     Op1 = Op1.getOperand(1);
7815 
7816     // See if have enough sign bits or zero bits in the scalar to use a
7817     // widening multiply by splatting to smaller element size.
7818     unsigned EltBits = VT.getScalarSizeInBits();
7819     unsigned ScalarBits = Op1.getValueSizeInBits();
7820     // Make sure we're getting all element bits from the scalar register.
7821     // FIXME: Support implicit sign extension of vmv.v.x?
7822     if (ScalarBits < EltBits)
7823       return SDValue();
7824 
7825     // If the LHS is a sign extend, try to use vwmul.
7826     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
7827       // Can use vwmul.
7828     } else {
7829       // Otherwise try to use vwmulu or vwmulsu.
7830       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7831       if (DAG.MaskedValueIsZero(Op1, Mask))
7832         IsVWMULSU = IsSignExt;
7833       else
7834         return SDValue();
7835     }
7836 
7837     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7838                       DAG.getUNDEF(NarrowVT), Op1, VL);
7839   } else
7840     return SDValue();
7841 
7842   Op0 = Op0.getOperand(0);
7843 
7844   // Re-introduce narrower extends if needed.
7845   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7846   if (Op0.getValueType() != NarrowVT)
7847     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7848   // vwmulsu requires second operand to be zero extended.
7849   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
7850   if (Op1.getValueType() != NarrowVT)
7851     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7852 
7853   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7854   if (!IsVWMULSU)
7855     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7856   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7857 }
7858 
7859 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7860   switch (Op.getOpcode()) {
7861   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7862   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7863   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7864   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7865   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7866   }
7867 
7868   return RISCVFPRndMode::Invalid;
7869 }
7870 
7871 // Fold
7872 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7873 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7874 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7875 //   (fp_to_int (fceil X))      -> fcvt X, rup
7876 //   (fp_to_int (fround X))     -> fcvt X, rmm
7877 static SDValue performFP_TO_INTCombine(SDNode *N,
7878                                        TargetLowering::DAGCombinerInfo &DCI,
7879                                        const RISCVSubtarget &Subtarget) {
7880   SelectionDAG &DAG = DCI.DAG;
7881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7882   MVT XLenVT = Subtarget.getXLenVT();
7883 
7884   // Only handle XLen or i32 types. Other types narrower than XLen will
7885   // eventually be legalized to XLenVT.
7886   EVT VT = N->getValueType(0);
7887   if (VT != MVT::i32 && VT != XLenVT)
7888     return SDValue();
7889 
7890   SDValue Src = N->getOperand(0);
7891 
7892   // Ensure the FP type is also legal.
7893   if (!TLI.isTypeLegal(Src.getValueType()))
7894     return SDValue();
7895 
7896   // Don't do this for f16 with Zfhmin and not Zfh.
7897   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7898     return SDValue();
7899 
7900   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7901   if (FRM == RISCVFPRndMode::Invalid)
7902     return SDValue();
7903 
7904   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7905 
7906   unsigned Opc;
7907   if (VT == XLenVT)
7908     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7909   else
7910     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7911 
7912   SDLoc DL(N);
7913   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7914                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7915   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7916 }
7917 
7918 // Fold
7919 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7920 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7921 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7922 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7923 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7924 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7925                                        TargetLowering::DAGCombinerInfo &DCI,
7926                                        const RISCVSubtarget &Subtarget) {
7927   SelectionDAG &DAG = DCI.DAG;
7928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7929   MVT XLenVT = Subtarget.getXLenVT();
7930 
7931   // Only handle XLen types. Other types narrower than XLen will eventually be
7932   // legalized to XLenVT.
7933   EVT DstVT = N->getValueType(0);
7934   if (DstVT != XLenVT)
7935     return SDValue();
7936 
7937   SDValue Src = N->getOperand(0);
7938 
7939   // Ensure the FP type is also legal.
7940   if (!TLI.isTypeLegal(Src.getValueType()))
7941     return SDValue();
7942 
7943   // Don't do this for f16 with Zfhmin and not Zfh.
7944   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7945     return SDValue();
7946 
7947   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7948 
7949   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7950   if (FRM == RISCVFPRndMode::Invalid)
7951     return SDValue();
7952 
7953   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7954 
7955   unsigned Opc;
7956   if (SatVT == DstVT)
7957     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7958   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7959     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7960   else
7961     return SDValue();
7962   // FIXME: Support other SatVTs by clamping before or after the conversion.
7963 
7964   Src = Src.getOperand(0);
7965 
7966   SDLoc DL(N);
7967   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7968                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7969 
7970   // RISCV FP-to-int conversions saturate to the destination register size, but
7971   // don't produce 0 for nan.
7972   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7973   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7974 }
7975 
7976 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7977                                                DAGCombinerInfo &DCI) const {
7978   SelectionDAG &DAG = DCI.DAG;
7979 
7980   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7981   // bits are demanded. N will be added to the Worklist if it was not deleted.
7982   // Caller should return SDValue(N, 0) if this returns true.
7983   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7984     SDValue Op = N->getOperand(OpNo);
7985     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7986     if (!SimplifyDemandedBits(Op, Mask, DCI))
7987       return false;
7988 
7989     if (N->getOpcode() != ISD::DELETED_NODE)
7990       DCI.AddToWorklist(N);
7991     return true;
7992   };
7993 
7994   switch (N->getOpcode()) {
7995   default:
7996     break;
7997   case RISCVISD::SplitF64: {
7998     SDValue Op0 = N->getOperand(0);
7999     // If the input to SplitF64 is just BuildPairF64 then the operation is
8000     // redundant. Instead, use BuildPairF64's operands directly.
8001     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8002       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8003 
8004     if (Op0->isUndef()) {
8005       SDValue Lo = DAG.getUNDEF(MVT::i32);
8006       SDValue Hi = DAG.getUNDEF(MVT::i32);
8007       return DCI.CombineTo(N, Lo, Hi);
8008     }
8009 
8010     SDLoc DL(N);
8011 
8012     // It's cheaper to materialise two 32-bit integers than to load a double
8013     // from the constant pool and transfer it to integer registers through the
8014     // stack.
8015     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8016       APInt V = C->getValueAPF().bitcastToAPInt();
8017       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8018       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8019       return DCI.CombineTo(N, Lo, Hi);
8020     }
8021 
8022     // This is a target-specific version of a DAGCombine performed in
8023     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8024     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8025     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8026     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8027         !Op0.getNode()->hasOneUse())
8028       break;
8029     SDValue NewSplitF64 =
8030         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8031                     Op0.getOperand(0));
8032     SDValue Lo = NewSplitF64.getValue(0);
8033     SDValue Hi = NewSplitF64.getValue(1);
8034     APInt SignBit = APInt::getSignMask(32);
8035     if (Op0.getOpcode() == ISD::FNEG) {
8036       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8037                                   DAG.getConstant(SignBit, DL, MVT::i32));
8038       return DCI.CombineTo(N, Lo, NewHi);
8039     }
8040     assert(Op0.getOpcode() == ISD::FABS);
8041     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8042                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8043     return DCI.CombineTo(N, Lo, NewHi);
8044   }
8045   case RISCVISD::SLLW:
8046   case RISCVISD::SRAW:
8047   case RISCVISD::SRLW:
8048   case RISCVISD::ROLW:
8049   case RISCVISD::RORW: {
8050     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8051     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8052         SimplifyDemandedLowBitsHelper(1, 5))
8053       return SDValue(N, 0);
8054 
8055     return combineROTR_ROTL_RORW_ROLW(N, DAG);
8056   }
8057   case ISD::ROTR:
8058   case ISD::ROTL:
8059     return combineROTR_ROTL_RORW_ROLW(N, DAG);
8060   case RISCVISD::CLZW:
8061   case RISCVISD::CTZW: {
8062     // Only the lower 32 bits of the first operand are read
8063     if (SimplifyDemandedLowBitsHelper(0, 32))
8064       return SDValue(N, 0);
8065     break;
8066   }
8067   case RISCVISD::GREV:
8068   case RISCVISD::GORC: {
8069     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8070     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8071     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8072     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8073       return SDValue(N, 0);
8074 
8075     return combineGREVI_GORCI(N, DAG);
8076   }
8077   case RISCVISD::GREVW:
8078   case RISCVISD::GORCW: {
8079     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8080     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8081         SimplifyDemandedLowBitsHelper(1, 5))
8082       return SDValue(N, 0);
8083 
8084     return combineGREVI_GORCI(N, DAG);
8085   }
8086   case RISCVISD::SHFL:
8087   case RISCVISD::UNSHFL: {
8088     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8089     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8090     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8091     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8092       return SDValue(N, 0);
8093 
8094     break;
8095   }
8096   case RISCVISD::SHFLW:
8097   case RISCVISD::UNSHFLW: {
8098     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8099     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8100         SimplifyDemandedLowBitsHelper(1, 4))
8101       return SDValue(N, 0);
8102 
8103     break;
8104   }
8105   case RISCVISD::BCOMPRESSW:
8106   case RISCVISD::BDECOMPRESSW: {
8107     // Only the lower 32 bits of LHS and RHS are read.
8108     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8109         SimplifyDemandedLowBitsHelper(1, 32))
8110       return SDValue(N, 0);
8111 
8112     break;
8113   }
8114   case RISCVISD::FMV_X_ANYEXTH:
8115   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8116     SDLoc DL(N);
8117     SDValue Op0 = N->getOperand(0);
8118     MVT VT = N->getSimpleValueType(0);
8119     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8120     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8121     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8122     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8123          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8124         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8125          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8126       assert(Op0.getOperand(0).getValueType() == VT &&
8127              "Unexpected value type!");
8128       return Op0.getOperand(0);
8129     }
8130 
8131     // This is a target-specific version of a DAGCombine performed in
8132     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8133     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8134     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8135     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8136         !Op0.getNode()->hasOneUse())
8137       break;
8138     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8139     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8140     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8141     if (Op0.getOpcode() == ISD::FNEG)
8142       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8143                          DAG.getConstant(SignBit, DL, VT));
8144 
8145     assert(Op0.getOpcode() == ISD::FABS);
8146     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8147                        DAG.getConstant(~SignBit, DL, VT));
8148   }
8149   case ISD::ADD:
8150     return performADDCombine(N, DAG, Subtarget);
8151   case ISD::SUB:
8152     return performSUBCombine(N, DAG);
8153   case ISD::AND:
8154     return performANDCombine(N, DAG);
8155   case ISD::OR:
8156     return performORCombine(N, DAG, Subtarget);
8157   case ISD::XOR:
8158     return performXORCombine(N, DAG);
8159   case ISD::ANY_EXTEND:
8160     return performANY_EXTENDCombine(N, DCI, Subtarget);
8161   case ISD::ZERO_EXTEND:
8162     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8163     // type legalization. This is safe because fp_to_uint produces poison if
8164     // it overflows.
8165     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8166       SDValue Src = N->getOperand(0);
8167       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8168           isTypeLegal(Src.getOperand(0).getValueType()))
8169         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8170                            Src.getOperand(0));
8171       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8172           isTypeLegal(Src.getOperand(1).getValueType())) {
8173         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8174         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8175                                   Src.getOperand(0), Src.getOperand(1));
8176         DCI.CombineTo(N, Res);
8177         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8178         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8179         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8180       }
8181     }
8182     return SDValue();
8183   case RISCVISD::SELECT_CC: {
8184     // Transform
8185     SDValue LHS = N->getOperand(0);
8186     SDValue RHS = N->getOperand(1);
8187     SDValue TrueV = N->getOperand(3);
8188     SDValue FalseV = N->getOperand(4);
8189 
8190     // If the True and False values are the same, we don't need a select_cc.
8191     if (TrueV == FalseV)
8192       return TrueV;
8193 
8194     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8195     if (!ISD::isIntEqualitySetCC(CCVal))
8196       break;
8197 
8198     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8199     //      (select_cc X, Y, lt, trueV, falseV)
8200     // Sometimes the setcc is introduced after select_cc has been formed.
8201     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8202         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8203       // If we're looking for eq 0 instead of ne 0, we need to invert the
8204       // condition.
8205       bool Invert = CCVal == ISD::SETEQ;
8206       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8207       if (Invert)
8208         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8209 
8210       SDLoc DL(N);
8211       RHS = LHS.getOperand(1);
8212       LHS = LHS.getOperand(0);
8213       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8214 
8215       SDValue TargetCC = DAG.getCondCode(CCVal);
8216       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8217                          {LHS, RHS, TargetCC, TrueV, FalseV});
8218     }
8219 
8220     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8221     //      (select_cc X, Y, eq/ne, trueV, falseV)
8222     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8223       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8224                          {LHS.getOperand(0), LHS.getOperand(1),
8225                           N->getOperand(2), TrueV, FalseV});
8226     // (select_cc X, 1, setne, trueV, falseV) ->
8227     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8228     // This can occur when legalizing some floating point comparisons.
8229     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8230     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8231       SDLoc DL(N);
8232       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8233       SDValue TargetCC = DAG.getCondCode(CCVal);
8234       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8235       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8236                          {LHS, RHS, TargetCC, TrueV, FalseV});
8237     }
8238 
8239     break;
8240   }
8241   case RISCVISD::BR_CC: {
8242     SDValue LHS = N->getOperand(1);
8243     SDValue RHS = N->getOperand(2);
8244     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8245     if (!ISD::isIntEqualitySetCC(CCVal))
8246       break;
8247 
8248     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8249     //      (br_cc X, Y, lt, dest)
8250     // Sometimes the setcc is introduced after br_cc has been formed.
8251     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8252         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8253       // If we're looking for eq 0 instead of ne 0, we need to invert the
8254       // condition.
8255       bool Invert = CCVal == ISD::SETEQ;
8256       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8257       if (Invert)
8258         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8259 
8260       SDLoc DL(N);
8261       RHS = LHS.getOperand(1);
8262       LHS = LHS.getOperand(0);
8263       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8264 
8265       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8266                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8267                          N->getOperand(4));
8268     }
8269 
8270     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8271     //      (br_cc X, Y, eq/ne, trueV, falseV)
8272     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8273       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8274                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8275                          N->getOperand(3), N->getOperand(4));
8276 
8277     // (br_cc X, 1, setne, br_cc) ->
8278     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8279     // This can occur when legalizing some floating point comparisons.
8280     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8281     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8282       SDLoc DL(N);
8283       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8284       SDValue TargetCC = DAG.getCondCode(CCVal);
8285       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8286       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8287                          N->getOperand(0), LHS, RHS, TargetCC,
8288                          N->getOperand(4));
8289     }
8290     break;
8291   }
8292   case ISD::FP_TO_SINT:
8293   case ISD::FP_TO_UINT:
8294     return performFP_TO_INTCombine(N, DCI, Subtarget);
8295   case ISD::FP_TO_SINT_SAT:
8296   case ISD::FP_TO_UINT_SAT:
8297     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8298   case ISD::FCOPYSIGN: {
8299     EVT VT = N->getValueType(0);
8300     if (!VT.isVector())
8301       break;
8302     // There is a form of VFSGNJ which injects the negated sign of its second
8303     // operand. Try and bubble any FNEG up after the extend/round to produce
8304     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8305     // TRUNC=1.
8306     SDValue In2 = N->getOperand(1);
8307     // Avoid cases where the extend/round has multiple uses, as duplicating
8308     // those is typically more expensive than removing a fneg.
8309     if (!In2.hasOneUse())
8310       break;
8311     if (In2.getOpcode() != ISD::FP_EXTEND &&
8312         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8313       break;
8314     In2 = In2.getOperand(0);
8315     if (In2.getOpcode() != ISD::FNEG)
8316       break;
8317     SDLoc DL(N);
8318     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8319     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8320                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8321   }
8322   case ISD::MGATHER:
8323   case ISD::MSCATTER:
8324   case ISD::VP_GATHER:
8325   case ISD::VP_SCATTER: {
8326     if (!DCI.isBeforeLegalize())
8327       break;
8328     SDValue Index, ScaleOp;
8329     bool IsIndexScaled = false;
8330     bool IsIndexSigned = false;
8331     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8332       Index = VPGSN->getIndex();
8333       ScaleOp = VPGSN->getScale();
8334       IsIndexScaled = VPGSN->isIndexScaled();
8335       IsIndexSigned = VPGSN->isIndexSigned();
8336     } else {
8337       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8338       Index = MGSN->getIndex();
8339       ScaleOp = MGSN->getScale();
8340       IsIndexScaled = MGSN->isIndexScaled();
8341       IsIndexSigned = MGSN->isIndexSigned();
8342     }
8343     EVT IndexVT = Index.getValueType();
8344     MVT XLenVT = Subtarget.getXLenVT();
8345     // RISCV indexed loads only support the "unsigned unscaled" addressing
8346     // mode, so anything else must be manually legalized.
8347     bool NeedsIdxLegalization =
8348         IsIndexScaled ||
8349         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8350     if (!NeedsIdxLegalization)
8351       break;
8352 
8353     SDLoc DL(N);
8354 
8355     // Any index legalization should first promote to XLenVT, so we don't lose
8356     // bits when scaling. This may create an illegal index type so we let
8357     // LLVM's legalization take care of the splitting.
8358     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8359     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8360       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8361       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8362                           DL, IndexVT, Index);
8363     }
8364 
8365     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8366     if (IsIndexScaled && Scale != 1) {
8367       // Manually scale the indices by the element size.
8368       // TODO: Sanitize the scale operand here?
8369       // TODO: For VP nodes, should we use VP_SHL here?
8370       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8371       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8372       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8373     }
8374 
8375     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8376     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8377       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8378                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8379                               VPGN->getScale(), VPGN->getMask(),
8380                               VPGN->getVectorLength()},
8381                              VPGN->getMemOperand(), NewIndexTy);
8382     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8383       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8384                               {VPSN->getChain(), VPSN->getValue(),
8385                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8386                                VPSN->getMask(), VPSN->getVectorLength()},
8387                               VPSN->getMemOperand(), NewIndexTy);
8388     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8389       return DAG.getMaskedGather(
8390           N->getVTList(), MGN->getMemoryVT(), DL,
8391           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8392            MGN->getBasePtr(), Index, MGN->getScale()},
8393           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8394     const auto *MSN = cast<MaskedScatterSDNode>(N);
8395     return DAG.getMaskedScatter(
8396         N->getVTList(), MSN->getMemoryVT(), DL,
8397         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8398          Index, MSN->getScale()},
8399         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8400   }
8401   case RISCVISD::SRA_VL:
8402   case RISCVISD::SRL_VL:
8403   case RISCVISD::SHL_VL: {
8404     SDValue ShAmt = N->getOperand(1);
8405     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8406       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8407       SDLoc DL(N);
8408       SDValue VL = N->getOperand(3);
8409       EVT VT = N->getValueType(0);
8410       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8411                           ShAmt.getOperand(1), VL);
8412       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8413                          N->getOperand(2), N->getOperand(3));
8414     }
8415     break;
8416   }
8417   case ISD::SRA:
8418   case ISD::SRL:
8419   case ISD::SHL: {
8420     SDValue ShAmt = N->getOperand(1);
8421     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8422       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8423       SDLoc DL(N);
8424       EVT VT = N->getValueType(0);
8425       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8426                           ShAmt.getOperand(1),
8427                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8428       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8429     }
8430     break;
8431   }
8432   case RISCVISD::ADD_VL:
8433     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8434       return V;
8435     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8436   case RISCVISD::SUB_VL:
8437     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8438   case RISCVISD::VWADD_W_VL:
8439   case RISCVISD::VWADDU_W_VL:
8440   case RISCVISD::VWSUB_W_VL:
8441   case RISCVISD::VWSUBU_W_VL:
8442     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8443   case RISCVISD::MUL_VL:
8444     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8445       return V;
8446     // Mul is commutative.
8447     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8448   case ISD::STORE: {
8449     auto *Store = cast<StoreSDNode>(N);
8450     SDValue Val = Store->getValue();
8451     // Combine store of vmv.x.s to vse with VL of 1.
8452     // FIXME: Support FP.
8453     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8454       SDValue Src = Val.getOperand(0);
8455       EVT VecVT = Src.getValueType();
8456       EVT MemVT = Store->getMemoryVT();
8457       // The memory VT and the element type must match.
8458       if (VecVT.getVectorElementType() == MemVT) {
8459         SDLoc DL(N);
8460         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8461         return DAG.getStoreVP(
8462             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8463             DAG.getConstant(1, DL, MaskVT),
8464             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8465             Store->getMemOperand(), Store->getAddressingMode(),
8466             Store->isTruncatingStore(), /*IsCompress*/ false);
8467       }
8468     }
8469 
8470     break;
8471   }
8472   case ISD::SPLAT_VECTOR: {
8473     EVT VT = N->getValueType(0);
8474     // Only perform this combine on legal MVT types.
8475     if (!isTypeLegal(VT))
8476       break;
8477     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8478                                          DAG, Subtarget))
8479       return Gather;
8480     break;
8481   }
8482   case RISCVISD::VMV_V_X_VL: {
8483     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8484     // scalar input.
8485     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8486     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8487     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8488       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8489         return SDValue(N, 0);
8490 
8491     break;
8492   }
8493   }
8494 
8495   return SDValue();
8496 }
8497 
8498 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8499     const SDNode *N, CombineLevel Level) const {
8500   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8501   // materialised in fewer instructions than `(OP _, c1)`:
8502   //
8503   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8504   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8505   SDValue N0 = N->getOperand(0);
8506   EVT Ty = N0.getValueType();
8507   if (Ty.isScalarInteger() &&
8508       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8509     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8510     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8511     if (C1 && C2) {
8512       const APInt &C1Int = C1->getAPIntValue();
8513       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8514 
8515       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8516       // and the combine should happen, to potentially allow further combines
8517       // later.
8518       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8519           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8520         return true;
8521 
8522       // We can materialise `c1` in an add immediate, so it's "free", and the
8523       // combine should be prevented.
8524       if (C1Int.getMinSignedBits() <= 64 &&
8525           isLegalAddImmediate(C1Int.getSExtValue()))
8526         return false;
8527 
8528       // Neither constant will fit into an immediate, so find materialisation
8529       // costs.
8530       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8531                                               Subtarget.getFeatureBits(),
8532                                               /*CompressionCost*/true);
8533       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8534           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8535           /*CompressionCost*/true);
8536 
8537       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8538       // combine should be prevented.
8539       if (C1Cost < ShiftedC1Cost)
8540         return false;
8541     }
8542   }
8543   return true;
8544 }
8545 
8546 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8547     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8548     TargetLoweringOpt &TLO) const {
8549   // Delay this optimization as late as possible.
8550   if (!TLO.LegalOps)
8551     return false;
8552 
8553   EVT VT = Op.getValueType();
8554   if (VT.isVector())
8555     return false;
8556 
8557   // Only handle AND for now.
8558   if (Op.getOpcode() != ISD::AND)
8559     return false;
8560 
8561   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8562   if (!C)
8563     return false;
8564 
8565   const APInt &Mask = C->getAPIntValue();
8566 
8567   // Clear all non-demanded bits initially.
8568   APInt ShrunkMask = Mask & DemandedBits;
8569 
8570   // Try to make a smaller immediate by setting undemanded bits.
8571 
8572   APInt ExpandedMask = Mask | ~DemandedBits;
8573 
8574   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8575     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8576   };
8577   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8578     if (NewMask == Mask)
8579       return true;
8580     SDLoc DL(Op);
8581     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8582     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8583     return TLO.CombineTo(Op, NewOp);
8584   };
8585 
8586   // If the shrunk mask fits in sign extended 12 bits, let the target
8587   // independent code apply it.
8588   if (ShrunkMask.isSignedIntN(12))
8589     return false;
8590 
8591   // Preserve (and X, 0xffff) when zext.h is supported.
8592   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8593     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8594     if (IsLegalMask(NewMask))
8595       return UseMask(NewMask);
8596   }
8597 
8598   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8599   if (VT == MVT::i64) {
8600     APInt NewMask = APInt(64, 0xffffffff);
8601     if (IsLegalMask(NewMask))
8602       return UseMask(NewMask);
8603   }
8604 
8605   // For the remaining optimizations, we need to be able to make a negative
8606   // number through a combination of mask and undemanded bits.
8607   if (!ExpandedMask.isNegative())
8608     return false;
8609 
8610   // What is the fewest number of bits we need to represent the negative number.
8611   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8612 
8613   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8614   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8615   APInt NewMask = ShrunkMask;
8616   if (MinSignedBits <= 12)
8617     NewMask.setBitsFrom(11);
8618   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8619     NewMask.setBitsFrom(31);
8620   else
8621     return false;
8622 
8623   // Check that our new mask is a subset of the demanded mask.
8624   assert(IsLegalMask(NewMask));
8625   return UseMask(NewMask);
8626 }
8627 
8628 static void computeGREV(APInt &Src, unsigned ShAmt) {
8629   ShAmt &= Src.getBitWidth() - 1;
8630   uint64_t x = Src.getZExtValue();
8631   if (ShAmt & 1)
8632     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8633   if (ShAmt & 2)
8634     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8635   if (ShAmt & 4)
8636     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8637   if (ShAmt & 8)
8638     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8639   if (ShAmt & 16)
8640     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8641   if (ShAmt & 32)
8642     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8643   Src = x;
8644 }
8645 
8646 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8647                                                         KnownBits &Known,
8648                                                         const APInt &DemandedElts,
8649                                                         const SelectionDAG &DAG,
8650                                                         unsigned Depth) const {
8651   unsigned BitWidth = Known.getBitWidth();
8652   unsigned Opc = Op.getOpcode();
8653   assert((Opc >= ISD::BUILTIN_OP_END ||
8654           Opc == ISD::INTRINSIC_WO_CHAIN ||
8655           Opc == ISD::INTRINSIC_W_CHAIN ||
8656           Opc == ISD::INTRINSIC_VOID) &&
8657          "Should use MaskedValueIsZero if you don't know whether Op"
8658          " is a target node!");
8659 
8660   Known.resetAll();
8661   switch (Opc) {
8662   default: break;
8663   case RISCVISD::SELECT_CC: {
8664     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8665     // If we don't know any bits, early out.
8666     if (Known.isUnknown())
8667       break;
8668     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8669 
8670     // Only known if known in both the LHS and RHS.
8671     Known = KnownBits::commonBits(Known, Known2);
8672     break;
8673   }
8674   case RISCVISD::REMUW: {
8675     KnownBits Known2;
8676     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8677     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8678     // We only care about the lower 32 bits.
8679     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8680     // Restore the original width by sign extending.
8681     Known = Known.sext(BitWidth);
8682     break;
8683   }
8684   case RISCVISD::DIVUW: {
8685     KnownBits Known2;
8686     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8687     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8688     // We only care about the lower 32 bits.
8689     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8690     // Restore the original width by sign extending.
8691     Known = Known.sext(BitWidth);
8692     break;
8693   }
8694   case RISCVISD::CTZW: {
8695     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8696     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8697     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8698     Known.Zero.setBitsFrom(LowBits);
8699     break;
8700   }
8701   case RISCVISD::CLZW: {
8702     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8703     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8704     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8705     Known.Zero.setBitsFrom(LowBits);
8706     break;
8707   }
8708   case RISCVISD::GREV:
8709   case RISCVISD::GREVW: {
8710     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8711       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8712       if (Opc == RISCVISD::GREVW)
8713         Known = Known.trunc(32);
8714       unsigned ShAmt = C->getZExtValue();
8715       computeGREV(Known.Zero, ShAmt);
8716       computeGREV(Known.One, ShAmt);
8717       if (Opc == RISCVISD::GREVW)
8718         Known = Known.sext(BitWidth);
8719     }
8720     break;
8721   }
8722   case RISCVISD::READ_VLENB: {
8723     // If we know the minimum VLen from Zvl extensions, we can use that to
8724     // determine the trailing zeros of VLENB.
8725     // FIXME: Limit to 128 bit vectors until we have more testing.
8726     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8727     if (MinVLenB > 0)
8728       Known.Zero.setLowBits(Log2_32(MinVLenB));
8729     // We assume VLENB is no more than 65536 / 8 bytes.
8730     Known.Zero.setBitsFrom(14);
8731     break;
8732   }
8733   case ISD::INTRINSIC_W_CHAIN:
8734   case ISD::INTRINSIC_WO_CHAIN: {
8735     unsigned IntNo =
8736         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8737     switch (IntNo) {
8738     default:
8739       // We can't do anything for most intrinsics.
8740       break;
8741     case Intrinsic::riscv_vsetvli:
8742     case Intrinsic::riscv_vsetvlimax:
8743     case Intrinsic::riscv_vsetvli_opt:
8744     case Intrinsic::riscv_vsetvlimax_opt:
8745       // Assume that VL output is positive and would fit in an int32_t.
8746       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8747       if (BitWidth >= 32)
8748         Known.Zero.setBitsFrom(31);
8749       break;
8750     }
8751     break;
8752   }
8753   }
8754 }
8755 
8756 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8757     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8758     unsigned Depth) const {
8759   switch (Op.getOpcode()) {
8760   default:
8761     break;
8762   case RISCVISD::SELECT_CC: {
8763     unsigned Tmp =
8764         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8765     if (Tmp == 1) return 1;  // Early out.
8766     unsigned Tmp2 =
8767         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8768     return std::min(Tmp, Tmp2);
8769   }
8770   case RISCVISD::SLLW:
8771   case RISCVISD::SRAW:
8772   case RISCVISD::SRLW:
8773   case RISCVISD::DIVW:
8774   case RISCVISD::DIVUW:
8775   case RISCVISD::REMUW:
8776   case RISCVISD::ROLW:
8777   case RISCVISD::RORW:
8778   case RISCVISD::GREVW:
8779   case RISCVISD::GORCW:
8780   case RISCVISD::FSLW:
8781   case RISCVISD::FSRW:
8782   case RISCVISD::SHFLW:
8783   case RISCVISD::UNSHFLW:
8784   case RISCVISD::BCOMPRESSW:
8785   case RISCVISD::BDECOMPRESSW:
8786   case RISCVISD::BFPW:
8787   case RISCVISD::FCVT_W_RV64:
8788   case RISCVISD::FCVT_WU_RV64:
8789   case RISCVISD::STRICT_FCVT_W_RV64:
8790   case RISCVISD::STRICT_FCVT_WU_RV64:
8791     // TODO: As the result is sign-extended, this is conservatively correct. A
8792     // more precise answer could be calculated for SRAW depending on known
8793     // bits in the shift amount.
8794     return 33;
8795   case RISCVISD::SHFL:
8796   case RISCVISD::UNSHFL: {
8797     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8798     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8799     // will stay within the upper 32 bits. If there were more than 32 sign bits
8800     // before there will be at least 33 sign bits after.
8801     if (Op.getValueType() == MVT::i64 &&
8802         isa<ConstantSDNode>(Op.getOperand(1)) &&
8803         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8804       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8805       if (Tmp > 32)
8806         return 33;
8807     }
8808     break;
8809   }
8810   case RISCVISD::VMV_X_S: {
8811     // The number of sign bits of the scalar result is computed by obtaining the
8812     // element type of the input vector operand, subtracting its width from the
8813     // XLEN, and then adding one (sign bit within the element type). If the
8814     // element type is wider than XLen, the least-significant XLEN bits are
8815     // taken.
8816     unsigned XLen = Subtarget.getXLen();
8817     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8818     if (EltBits <= XLen)
8819       return XLen - EltBits + 1;
8820     break;
8821   }
8822   }
8823 
8824   return 1;
8825 }
8826 
8827 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8828                                                   MachineBasicBlock *BB) {
8829   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8830 
8831   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8832   // Should the count have wrapped while it was being read, we need to try
8833   // again.
8834   // ...
8835   // read:
8836   // rdcycleh x3 # load high word of cycle
8837   // rdcycle  x2 # load low word of cycle
8838   // rdcycleh x4 # load high word of cycle
8839   // bne x3, x4, read # check if high word reads match, otherwise try again
8840   // ...
8841 
8842   MachineFunction &MF = *BB->getParent();
8843   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8844   MachineFunction::iterator It = ++BB->getIterator();
8845 
8846   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8847   MF.insert(It, LoopMBB);
8848 
8849   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8850   MF.insert(It, DoneMBB);
8851 
8852   // Transfer the remainder of BB and its successor edges to DoneMBB.
8853   DoneMBB->splice(DoneMBB->begin(), BB,
8854                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8855   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8856 
8857   BB->addSuccessor(LoopMBB);
8858 
8859   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8860   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8861   Register LoReg = MI.getOperand(0).getReg();
8862   Register HiReg = MI.getOperand(1).getReg();
8863   DebugLoc DL = MI.getDebugLoc();
8864 
8865   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8866   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8867       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8868       .addReg(RISCV::X0);
8869   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8870       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8871       .addReg(RISCV::X0);
8872   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8873       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8874       .addReg(RISCV::X0);
8875 
8876   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8877       .addReg(HiReg)
8878       .addReg(ReadAgainReg)
8879       .addMBB(LoopMBB);
8880 
8881   LoopMBB->addSuccessor(LoopMBB);
8882   LoopMBB->addSuccessor(DoneMBB);
8883 
8884   MI.eraseFromParent();
8885 
8886   return DoneMBB;
8887 }
8888 
8889 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8890                                              MachineBasicBlock *BB) {
8891   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8892 
8893   MachineFunction &MF = *BB->getParent();
8894   DebugLoc DL = MI.getDebugLoc();
8895   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8896   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8897   Register LoReg = MI.getOperand(0).getReg();
8898   Register HiReg = MI.getOperand(1).getReg();
8899   Register SrcReg = MI.getOperand(2).getReg();
8900   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8901   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8902 
8903   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8904                           RI);
8905   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8906   MachineMemOperand *MMOLo =
8907       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8908   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8909       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8910   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8911       .addFrameIndex(FI)
8912       .addImm(0)
8913       .addMemOperand(MMOLo);
8914   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8915       .addFrameIndex(FI)
8916       .addImm(4)
8917       .addMemOperand(MMOHi);
8918   MI.eraseFromParent(); // The pseudo instruction is gone now.
8919   return BB;
8920 }
8921 
8922 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8923                                                  MachineBasicBlock *BB) {
8924   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8925          "Unexpected instruction");
8926 
8927   MachineFunction &MF = *BB->getParent();
8928   DebugLoc DL = MI.getDebugLoc();
8929   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8930   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8931   Register DstReg = MI.getOperand(0).getReg();
8932   Register LoReg = MI.getOperand(1).getReg();
8933   Register HiReg = MI.getOperand(2).getReg();
8934   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8935   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8936 
8937   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8938   MachineMemOperand *MMOLo =
8939       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8940   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8941       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8942   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8943       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8944       .addFrameIndex(FI)
8945       .addImm(0)
8946       .addMemOperand(MMOLo);
8947   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8948       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8949       .addFrameIndex(FI)
8950       .addImm(4)
8951       .addMemOperand(MMOHi);
8952   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8953   MI.eraseFromParent(); // The pseudo instruction is gone now.
8954   return BB;
8955 }
8956 
8957 static bool isSelectPseudo(MachineInstr &MI) {
8958   switch (MI.getOpcode()) {
8959   default:
8960     return false;
8961   case RISCV::Select_GPR_Using_CC_GPR:
8962   case RISCV::Select_FPR16_Using_CC_GPR:
8963   case RISCV::Select_FPR32_Using_CC_GPR:
8964   case RISCV::Select_FPR64_Using_CC_GPR:
8965     return true;
8966   }
8967 }
8968 
8969 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8970                                         unsigned RelOpcode, unsigned EqOpcode,
8971                                         const RISCVSubtarget &Subtarget) {
8972   DebugLoc DL = MI.getDebugLoc();
8973   Register DstReg = MI.getOperand(0).getReg();
8974   Register Src1Reg = MI.getOperand(1).getReg();
8975   Register Src2Reg = MI.getOperand(2).getReg();
8976   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8977   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8978   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8979 
8980   // Save the current FFLAGS.
8981   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8982 
8983   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8984                  .addReg(Src1Reg)
8985                  .addReg(Src2Reg);
8986   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8987     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8988 
8989   // Restore the FFLAGS.
8990   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8991       .addReg(SavedFFlags, RegState::Kill);
8992 
8993   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8994   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8995                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8996                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8997   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8998     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8999 
9000   // Erase the pseudoinstruction.
9001   MI.eraseFromParent();
9002   return BB;
9003 }
9004 
9005 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9006                                            MachineBasicBlock *BB,
9007                                            const RISCVSubtarget &Subtarget) {
9008   // To "insert" Select_* instructions, we actually have to insert the triangle
9009   // control-flow pattern.  The incoming instructions know the destination vreg
9010   // to set, the condition code register to branch on, the true/false values to
9011   // select between, and the condcode to use to select the appropriate branch.
9012   //
9013   // We produce the following control flow:
9014   //     HeadMBB
9015   //     |  \
9016   //     |  IfFalseMBB
9017   //     | /
9018   //    TailMBB
9019   //
9020   // When we find a sequence of selects we attempt to optimize their emission
9021   // by sharing the control flow. Currently we only handle cases where we have
9022   // multiple selects with the exact same condition (same LHS, RHS and CC).
9023   // The selects may be interleaved with other instructions if the other
9024   // instructions meet some requirements we deem safe:
9025   // - They are debug instructions. Otherwise,
9026   // - They do not have side-effects, do not access memory and their inputs do
9027   //   not depend on the results of the select pseudo-instructions.
9028   // The TrueV/FalseV operands of the selects cannot depend on the result of
9029   // previous selects in the sequence.
9030   // These conditions could be further relaxed. See the X86 target for a
9031   // related approach and more information.
9032   Register LHS = MI.getOperand(1).getReg();
9033   Register RHS = MI.getOperand(2).getReg();
9034   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9035 
9036   SmallVector<MachineInstr *, 4> SelectDebugValues;
9037   SmallSet<Register, 4> SelectDests;
9038   SelectDests.insert(MI.getOperand(0).getReg());
9039 
9040   MachineInstr *LastSelectPseudo = &MI;
9041 
9042   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9043        SequenceMBBI != E; ++SequenceMBBI) {
9044     if (SequenceMBBI->isDebugInstr())
9045       continue;
9046     else if (isSelectPseudo(*SequenceMBBI)) {
9047       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9048           SequenceMBBI->getOperand(2).getReg() != RHS ||
9049           SequenceMBBI->getOperand(3).getImm() != CC ||
9050           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9051           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9052         break;
9053       LastSelectPseudo = &*SequenceMBBI;
9054       SequenceMBBI->collectDebugValues(SelectDebugValues);
9055       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9056     } else {
9057       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9058           SequenceMBBI->mayLoadOrStore())
9059         break;
9060       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9061             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9062           }))
9063         break;
9064     }
9065   }
9066 
9067   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9068   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9069   DebugLoc DL = MI.getDebugLoc();
9070   MachineFunction::iterator I = ++BB->getIterator();
9071 
9072   MachineBasicBlock *HeadMBB = BB;
9073   MachineFunction *F = BB->getParent();
9074   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9075   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9076 
9077   F->insert(I, IfFalseMBB);
9078   F->insert(I, TailMBB);
9079 
9080   // Transfer debug instructions associated with the selects to TailMBB.
9081   for (MachineInstr *DebugInstr : SelectDebugValues) {
9082     TailMBB->push_back(DebugInstr->removeFromParent());
9083   }
9084 
9085   // Move all instructions after the sequence to TailMBB.
9086   TailMBB->splice(TailMBB->end(), HeadMBB,
9087                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9088   // Update machine-CFG edges by transferring all successors of the current
9089   // block to the new block which will contain the Phi nodes for the selects.
9090   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9091   // Set the successors for HeadMBB.
9092   HeadMBB->addSuccessor(IfFalseMBB);
9093   HeadMBB->addSuccessor(TailMBB);
9094 
9095   // Insert appropriate branch.
9096   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9097     .addReg(LHS)
9098     .addReg(RHS)
9099     .addMBB(TailMBB);
9100 
9101   // IfFalseMBB just falls through to TailMBB.
9102   IfFalseMBB->addSuccessor(TailMBB);
9103 
9104   // Create PHIs for all of the select pseudo-instructions.
9105   auto SelectMBBI = MI.getIterator();
9106   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9107   auto InsertionPoint = TailMBB->begin();
9108   while (SelectMBBI != SelectEnd) {
9109     auto Next = std::next(SelectMBBI);
9110     if (isSelectPseudo(*SelectMBBI)) {
9111       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9112       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9113               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9114           .addReg(SelectMBBI->getOperand(4).getReg())
9115           .addMBB(HeadMBB)
9116           .addReg(SelectMBBI->getOperand(5).getReg())
9117           .addMBB(IfFalseMBB);
9118       SelectMBBI->eraseFromParent();
9119     }
9120     SelectMBBI = Next;
9121   }
9122 
9123   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9124   return TailMBB;
9125 }
9126 
9127 MachineBasicBlock *
9128 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9129                                                  MachineBasicBlock *BB) const {
9130   switch (MI.getOpcode()) {
9131   default:
9132     llvm_unreachable("Unexpected instr type to insert");
9133   case RISCV::ReadCycleWide:
9134     assert(!Subtarget.is64Bit() &&
9135            "ReadCycleWrite is only to be used on riscv32");
9136     return emitReadCycleWidePseudo(MI, BB);
9137   case RISCV::Select_GPR_Using_CC_GPR:
9138   case RISCV::Select_FPR16_Using_CC_GPR:
9139   case RISCV::Select_FPR32_Using_CC_GPR:
9140   case RISCV::Select_FPR64_Using_CC_GPR:
9141     return emitSelectPseudo(MI, BB, Subtarget);
9142   case RISCV::BuildPairF64Pseudo:
9143     return emitBuildPairF64Pseudo(MI, BB);
9144   case RISCV::SplitF64Pseudo:
9145     return emitSplitF64Pseudo(MI, BB);
9146   case RISCV::PseudoQuietFLE_H:
9147     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9148   case RISCV::PseudoQuietFLT_H:
9149     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9150   case RISCV::PseudoQuietFLE_S:
9151     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9152   case RISCV::PseudoQuietFLT_S:
9153     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9154   case RISCV::PseudoQuietFLE_D:
9155     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9156   case RISCV::PseudoQuietFLT_D:
9157     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9158   }
9159 }
9160 
9161 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9162                                                         SDNode *Node) const {
9163   // Add FRM dependency to any instructions with dynamic rounding mode.
9164   unsigned Opc = MI.getOpcode();
9165   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9166   if (Idx < 0)
9167     return;
9168   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9169     return;
9170   // If the instruction already reads FRM, don't add another read.
9171   if (MI.readsRegister(RISCV::FRM))
9172     return;
9173   MI.addOperand(
9174       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9175 }
9176 
9177 // Calling Convention Implementation.
9178 // The expectations for frontend ABI lowering vary from target to target.
9179 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9180 // details, but this is a longer term goal. For now, we simply try to keep the
9181 // role of the frontend as simple and well-defined as possible. The rules can
9182 // be summarised as:
9183 // * Never split up large scalar arguments. We handle them here.
9184 // * If a hardfloat calling convention is being used, and the struct may be
9185 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9186 // available, then pass as two separate arguments. If either the GPRs or FPRs
9187 // are exhausted, then pass according to the rule below.
9188 // * If a struct could never be passed in registers or directly in a stack
9189 // slot (as it is larger than 2*XLEN and the floating point rules don't
9190 // apply), then pass it using a pointer with the byval attribute.
9191 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9192 // word-sized array or a 2*XLEN scalar (depending on alignment).
9193 // * The frontend can determine whether a struct is returned by reference or
9194 // not based on its size and fields. If it will be returned by reference, the
9195 // frontend must modify the prototype so a pointer with the sret annotation is
9196 // passed as the first argument. This is not necessary for large scalar
9197 // returns.
9198 // * Struct return values and varargs should be coerced to structs containing
9199 // register-size fields in the same situations they would be for fixed
9200 // arguments.
9201 
9202 static const MCPhysReg ArgGPRs[] = {
9203   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9204   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9205 };
9206 static const MCPhysReg ArgFPR16s[] = {
9207   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9208   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9209 };
9210 static const MCPhysReg ArgFPR32s[] = {
9211   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9212   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9213 };
9214 static const MCPhysReg ArgFPR64s[] = {
9215   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9216   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9217 };
9218 // This is an interim calling convention and it may be changed in the future.
9219 static const MCPhysReg ArgVRs[] = {
9220     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9221     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9222     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9223 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9224                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9225                                      RISCV::V20M2, RISCV::V22M2};
9226 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9227                                      RISCV::V20M4};
9228 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9229 
9230 // Pass a 2*XLEN argument that has been split into two XLEN values through
9231 // registers or the stack as necessary.
9232 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9233                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9234                                 MVT ValVT2, MVT LocVT2,
9235                                 ISD::ArgFlagsTy ArgFlags2) {
9236   unsigned XLenInBytes = XLen / 8;
9237   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9238     // At least one half can be passed via register.
9239     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9240                                      VA1.getLocVT(), CCValAssign::Full));
9241   } else {
9242     // Both halves must be passed on the stack, with proper alignment.
9243     Align StackAlign =
9244         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9245     State.addLoc(
9246         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9247                             State.AllocateStack(XLenInBytes, StackAlign),
9248                             VA1.getLocVT(), CCValAssign::Full));
9249     State.addLoc(CCValAssign::getMem(
9250         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9251         LocVT2, CCValAssign::Full));
9252     return false;
9253   }
9254 
9255   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9256     // The second half can also be passed via register.
9257     State.addLoc(
9258         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9259   } else {
9260     // The second half is passed via the stack, without additional alignment.
9261     State.addLoc(CCValAssign::getMem(
9262         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9263         LocVT2, CCValAssign::Full));
9264   }
9265 
9266   return false;
9267 }
9268 
9269 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9270                                Optional<unsigned> FirstMaskArgument,
9271                                CCState &State, const RISCVTargetLowering &TLI) {
9272   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9273   if (RC == &RISCV::VRRegClass) {
9274     // Assign the first mask argument to V0.
9275     // This is an interim calling convention and it may be changed in the
9276     // future.
9277     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9278       return State.AllocateReg(RISCV::V0);
9279     return State.AllocateReg(ArgVRs);
9280   }
9281   if (RC == &RISCV::VRM2RegClass)
9282     return State.AllocateReg(ArgVRM2s);
9283   if (RC == &RISCV::VRM4RegClass)
9284     return State.AllocateReg(ArgVRM4s);
9285   if (RC == &RISCV::VRM8RegClass)
9286     return State.AllocateReg(ArgVRM8s);
9287   llvm_unreachable("Unhandled register class for ValueType");
9288 }
9289 
9290 // Implements the RISC-V calling convention. Returns true upon failure.
9291 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9292                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9293                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9294                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9295                      Optional<unsigned> FirstMaskArgument) {
9296   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9297   assert(XLen == 32 || XLen == 64);
9298   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9299 
9300   // Any return value split in to more than two values can't be returned
9301   // directly. Vectors are returned via the available vector registers.
9302   if (!LocVT.isVector() && IsRet && ValNo > 1)
9303     return true;
9304 
9305   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9306   // variadic argument, or if no F16/F32 argument registers are available.
9307   bool UseGPRForF16_F32 = true;
9308   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9309   // variadic argument, or if no F64 argument registers are available.
9310   bool UseGPRForF64 = true;
9311 
9312   switch (ABI) {
9313   default:
9314     llvm_unreachable("Unexpected ABI");
9315   case RISCVABI::ABI_ILP32:
9316   case RISCVABI::ABI_LP64:
9317     break;
9318   case RISCVABI::ABI_ILP32F:
9319   case RISCVABI::ABI_LP64F:
9320     UseGPRForF16_F32 = !IsFixed;
9321     break;
9322   case RISCVABI::ABI_ILP32D:
9323   case RISCVABI::ABI_LP64D:
9324     UseGPRForF16_F32 = !IsFixed;
9325     UseGPRForF64 = !IsFixed;
9326     break;
9327   }
9328 
9329   // FPR16, FPR32, and FPR64 alias each other.
9330   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9331     UseGPRForF16_F32 = true;
9332     UseGPRForF64 = true;
9333   }
9334 
9335   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9336   // similar local variables rather than directly checking against the target
9337   // ABI.
9338 
9339   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9340     LocVT = XLenVT;
9341     LocInfo = CCValAssign::BCvt;
9342   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9343     LocVT = MVT::i64;
9344     LocInfo = CCValAssign::BCvt;
9345   }
9346 
9347   // If this is a variadic argument, the RISC-V calling convention requires
9348   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9349   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9350   // be used regardless of whether the original argument was split during
9351   // legalisation or not. The argument will not be passed by registers if the
9352   // original type is larger than 2*XLEN, so the register alignment rule does
9353   // not apply.
9354   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9355   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9356       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9357     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9358     // Skip 'odd' register if necessary.
9359     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9360       State.AllocateReg(ArgGPRs);
9361   }
9362 
9363   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9364   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9365       State.getPendingArgFlags();
9366 
9367   assert(PendingLocs.size() == PendingArgFlags.size() &&
9368          "PendingLocs and PendingArgFlags out of sync");
9369 
9370   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9371   // registers are exhausted.
9372   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9373     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9374            "Can't lower f64 if it is split");
9375     // Depending on available argument GPRS, f64 may be passed in a pair of
9376     // GPRs, split between a GPR and the stack, or passed completely on the
9377     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9378     // cases.
9379     Register Reg = State.AllocateReg(ArgGPRs);
9380     LocVT = MVT::i32;
9381     if (!Reg) {
9382       unsigned StackOffset = State.AllocateStack(8, Align(8));
9383       State.addLoc(
9384           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9385       return false;
9386     }
9387     if (!State.AllocateReg(ArgGPRs))
9388       State.AllocateStack(4, Align(4));
9389     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9390     return false;
9391   }
9392 
9393   // Fixed-length vectors are located in the corresponding scalable-vector
9394   // container types.
9395   if (ValVT.isFixedLengthVector())
9396     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9397 
9398   // Split arguments might be passed indirectly, so keep track of the pending
9399   // values. Split vectors are passed via a mix of registers and indirectly, so
9400   // treat them as we would any other argument.
9401   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9402     LocVT = XLenVT;
9403     LocInfo = CCValAssign::Indirect;
9404     PendingLocs.push_back(
9405         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9406     PendingArgFlags.push_back(ArgFlags);
9407     if (!ArgFlags.isSplitEnd()) {
9408       return false;
9409     }
9410   }
9411 
9412   // If the split argument only had two elements, it should be passed directly
9413   // in registers or on the stack.
9414   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9415       PendingLocs.size() <= 2) {
9416     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9417     // Apply the normal calling convention rules to the first half of the
9418     // split argument.
9419     CCValAssign VA = PendingLocs[0];
9420     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9421     PendingLocs.clear();
9422     PendingArgFlags.clear();
9423     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9424                                ArgFlags);
9425   }
9426 
9427   // Allocate to a register if possible, or else a stack slot.
9428   Register Reg;
9429   unsigned StoreSizeBytes = XLen / 8;
9430   Align StackAlign = Align(XLen / 8);
9431 
9432   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9433     Reg = State.AllocateReg(ArgFPR16s);
9434   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9435     Reg = State.AllocateReg(ArgFPR32s);
9436   else if (ValVT == MVT::f64 && !UseGPRForF64)
9437     Reg = State.AllocateReg(ArgFPR64s);
9438   else if (ValVT.isVector()) {
9439     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9440     if (!Reg) {
9441       // For return values, the vector must be passed fully via registers or
9442       // via the stack.
9443       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9444       // but we're using all of them.
9445       if (IsRet)
9446         return true;
9447       // Try using a GPR to pass the address
9448       if ((Reg = State.AllocateReg(ArgGPRs))) {
9449         LocVT = XLenVT;
9450         LocInfo = CCValAssign::Indirect;
9451       } else if (ValVT.isScalableVector()) {
9452         LocVT = XLenVT;
9453         LocInfo = CCValAssign::Indirect;
9454       } else {
9455         // Pass fixed-length vectors on the stack.
9456         LocVT = ValVT;
9457         StoreSizeBytes = ValVT.getStoreSize();
9458         // Align vectors to their element sizes, being careful for vXi1
9459         // vectors.
9460         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9461       }
9462     }
9463   } else {
9464     Reg = State.AllocateReg(ArgGPRs);
9465   }
9466 
9467   unsigned StackOffset =
9468       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9469 
9470   // If we reach this point and PendingLocs is non-empty, we must be at the
9471   // end of a split argument that must be passed indirectly.
9472   if (!PendingLocs.empty()) {
9473     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9474     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9475 
9476     for (auto &It : PendingLocs) {
9477       if (Reg)
9478         It.convertToReg(Reg);
9479       else
9480         It.convertToMem(StackOffset);
9481       State.addLoc(It);
9482     }
9483     PendingLocs.clear();
9484     PendingArgFlags.clear();
9485     return false;
9486   }
9487 
9488   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9489           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9490          "Expected an XLenVT or vector types at this stage");
9491 
9492   if (Reg) {
9493     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9494     return false;
9495   }
9496 
9497   // When a floating-point value is passed on the stack, no bit-conversion is
9498   // needed.
9499   if (ValVT.isFloatingPoint()) {
9500     LocVT = ValVT;
9501     LocInfo = CCValAssign::Full;
9502   }
9503   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9504   return false;
9505 }
9506 
9507 template <typename ArgTy>
9508 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9509   for (const auto &ArgIdx : enumerate(Args)) {
9510     MVT ArgVT = ArgIdx.value().VT;
9511     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9512       return ArgIdx.index();
9513   }
9514   return None;
9515 }
9516 
9517 void RISCVTargetLowering::analyzeInputArgs(
9518     MachineFunction &MF, CCState &CCInfo,
9519     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9520     RISCVCCAssignFn Fn) const {
9521   unsigned NumArgs = Ins.size();
9522   FunctionType *FType = MF.getFunction().getFunctionType();
9523 
9524   Optional<unsigned> FirstMaskArgument;
9525   if (Subtarget.hasVInstructions())
9526     FirstMaskArgument = preAssignMask(Ins);
9527 
9528   for (unsigned i = 0; i != NumArgs; ++i) {
9529     MVT ArgVT = Ins[i].VT;
9530     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9531 
9532     Type *ArgTy = nullptr;
9533     if (IsRet)
9534       ArgTy = FType->getReturnType();
9535     else if (Ins[i].isOrigArg())
9536       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9537 
9538     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9539     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9540            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9541            FirstMaskArgument)) {
9542       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9543                         << EVT(ArgVT).getEVTString() << '\n');
9544       llvm_unreachable(nullptr);
9545     }
9546   }
9547 }
9548 
9549 void RISCVTargetLowering::analyzeOutputArgs(
9550     MachineFunction &MF, CCState &CCInfo,
9551     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9552     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9553   unsigned NumArgs = Outs.size();
9554 
9555   Optional<unsigned> FirstMaskArgument;
9556   if (Subtarget.hasVInstructions())
9557     FirstMaskArgument = preAssignMask(Outs);
9558 
9559   for (unsigned i = 0; i != NumArgs; i++) {
9560     MVT ArgVT = Outs[i].VT;
9561     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9562     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9563 
9564     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9565     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9566            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9567            FirstMaskArgument)) {
9568       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9569                         << EVT(ArgVT).getEVTString() << "\n");
9570       llvm_unreachable(nullptr);
9571     }
9572   }
9573 }
9574 
9575 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9576 // values.
9577 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9578                                    const CCValAssign &VA, const SDLoc &DL,
9579                                    const RISCVSubtarget &Subtarget) {
9580   switch (VA.getLocInfo()) {
9581   default:
9582     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9583   case CCValAssign::Full:
9584     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9585       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9586     break;
9587   case CCValAssign::BCvt:
9588     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9589       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9590     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9591       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9592     else
9593       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9594     break;
9595   }
9596   return Val;
9597 }
9598 
9599 // The caller is responsible for loading the full value if the argument is
9600 // passed with CCValAssign::Indirect.
9601 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9602                                 const CCValAssign &VA, const SDLoc &DL,
9603                                 const RISCVTargetLowering &TLI) {
9604   MachineFunction &MF = DAG.getMachineFunction();
9605   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9606   EVT LocVT = VA.getLocVT();
9607   SDValue Val;
9608   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9609   Register VReg = RegInfo.createVirtualRegister(RC);
9610   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9611   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9612 
9613   if (VA.getLocInfo() == CCValAssign::Indirect)
9614     return Val;
9615 
9616   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9617 }
9618 
9619 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9620                                    const CCValAssign &VA, const SDLoc &DL,
9621                                    const RISCVSubtarget &Subtarget) {
9622   EVT LocVT = VA.getLocVT();
9623 
9624   switch (VA.getLocInfo()) {
9625   default:
9626     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9627   case CCValAssign::Full:
9628     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9629       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9630     break;
9631   case CCValAssign::BCvt:
9632     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9633       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9634     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9635       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9636     else
9637       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9638     break;
9639   }
9640   return Val;
9641 }
9642 
9643 // The caller is responsible for loading the full value if the argument is
9644 // passed with CCValAssign::Indirect.
9645 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9646                                 const CCValAssign &VA, const SDLoc &DL) {
9647   MachineFunction &MF = DAG.getMachineFunction();
9648   MachineFrameInfo &MFI = MF.getFrameInfo();
9649   EVT LocVT = VA.getLocVT();
9650   EVT ValVT = VA.getValVT();
9651   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9652   if (ValVT.isScalableVector()) {
9653     // When the value is a scalable vector, we save the pointer which points to
9654     // the scalable vector value in the stack. The ValVT will be the pointer
9655     // type, instead of the scalable vector type.
9656     ValVT = LocVT;
9657   }
9658   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9659                                  /*IsImmutable=*/true);
9660   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9661   SDValue Val;
9662 
9663   ISD::LoadExtType ExtType;
9664   switch (VA.getLocInfo()) {
9665   default:
9666     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9667   case CCValAssign::Full:
9668   case CCValAssign::Indirect:
9669   case CCValAssign::BCvt:
9670     ExtType = ISD::NON_EXTLOAD;
9671     break;
9672   }
9673   Val = DAG.getExtLoad(
9674       ExtType, DL, LocVT, Chain, FIN,
9675       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9676   return Val;
9677 }
9678 
9679 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9680                                        const CCValAssign &VA, const SDLoc &DL) {
9681   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9682          "Unexpected VA");
9683   MachineFunction &MF = DAG.getMachineFunction();
9684   MachineFrameInfo &MFI = MF.getFrameInfo();
9685   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9686 
9687   if (VA.isMemLoc()) {
9688     // f64 is passed on the stack.
9689     int FI =
9690         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9691     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9692     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9693                        MachinePointerInfo::getFixedStack(MF, FI));
9694   }
9695 
9696   assert(VA.isRegLoc() && "Expected register VA assignment");
9697 
9698   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9699   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9700   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9701   SDValue Hi;
9702   if (VA.getLocReg() == RISCV::X17) {
9703     // Second half of f64 is passed on the stack.
9704     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9705     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9706     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9707                      MachinePointerInfo::getFixedStack(MF, FI));
9708   } else {
9709     // Second half of f64 is passed in another GPR.
9710     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9711     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9712     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9713   }
9714   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9715 }
9716 
9717 // FastCC has less than 1% performance improvement for some particular
9718 // benchmark. But theoretically, it may has benenfit for some cases.
9719 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9720                             unsigned ValNo, MVT ValVT, MVT LocVT,
9721                             CCValAssign::LocInfo LocInfo,
9722                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9723                             bool IsFixed, bool IsRet, Type *OrigTy,
9724                             const RISCVTargetLowering &TLI,
9725                             Optional<unsigned> FirstMaskArgument) {
9726 
9727   // X5 and X6 might be used for save-restore libcall.
9728   static const MCPhysReg GPRList[] = {
9729       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9730       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9731       RISCV::X29, RISCV::X30, RISCV::X31};
9732 
9733   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9734     if (unsigned Reg = State.AllocateReg(GPRList)) {
9735       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9736       return false;
9737     }
9738   }
9739 
9740   if (LocVT == MVT::f16) {
9741     static const MCPhysReg FPR16List[] = {
9742         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9743         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9744         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9745         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9746     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9747       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9748       return false;
9749     }
9750   }
9751 
9752   if (LocVT == MVT::f32) {
9753     static const MCPhysReg FPR32List[] = {
9754         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9755         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9756         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9757         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9758     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9759       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9760       return false;
9761     }
9762   }
9763 
9764   if (LocVT == MVT::f64) {
9765     static const MCPhysReg FPR64List[] = {
9766         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9767         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9768         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9769         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9770     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9771       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9772       return false;
9773     }
9774   }
9775 
9776   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9777     unsigned Offset4 = State.AllocateStack(4, Align(4));
9778     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9779     return false;
9780   }
9781 
9782   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9783     unsigned Offset5 = State.AllocateStack(8, Align(8));
9784     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9785     return false;
9786   }
9787 
9788   if (LocVT.isVector()) {
9789     if (unsigned Reg =
9790             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9791       // Fixed-length vectors are located in the corresponding scalable-vector
9792       // container types.
9793       if (ValVT.isFixedLengthVector())
9794         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9795       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9796     } else {
9797       // Try and pass the address via a "fast" GPR.
9798       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9799         LocInfo = CCValAssign::Indirect;
9800         LocVT = TLI.getSubtarget().getXLenVT();
9801         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9802       } else if (ValVT.isFixedLengthVector()) {
9803         auto StackAlign =
9804             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9805         unsigned StackOffset =
9806             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9807         State.addLoc(
9808             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9809       } else {
9810         // Can't pass scalable vectors on the stack.
9811         return true;
9812       }
9813     }
9814 
9815     return false;
9816   }
9817 
9818   return true; // CC didn't match.
9819 }
9820 
9821 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9822                          CCValAssign::LocInfo LocInfo,
9823                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9824 
9825   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9826     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9827     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9828     static const MCPhysReg GPRList[] = {
9829         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9830         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9831     if (unsigned Reg = State.AllocateReg(GPRList)) {
9832       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9833       return false;
9834     }
9835   }
9836 
9837   if (LocVT == MVT::f32) {
9838     // Pass in STG registers: F1, ..., F6
9839     //                        fs0 ... fs5
9840     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9841                                           RISCV::F18_F, RISCV::F19_F,
9842                                           RISCV::F20_F, RISCV::F21_F};
9843     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9844       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9845       return false;
9846     }
9847   }
9848 
9849   if (LocVT == MVT::f64) {
9850     // Pass in STG registers: D1, ..., D6
9851     //                        fs6 ... fs11
9852     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9853                                           RISCV::F24_D, RISCV::F25_D,
9854                                           RISCV::F26_D, RISCV::F27_D};
9855     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9856       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9857       return false;
9858     }
9859   }
9860 
9861   report_fatal_error("No registers left in GHC calling convention");
9862   return true;
9863 }
9864 
9865 // Transform physical registers into virtual registers.
9866 SDValue RISCVTargetLowering::LowerFormalArguments(
9867     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9868     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9869     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9870 
9871   MachineFunction &MF = DAG.getMachineFunction();
9872 
9873   switch (CallConv) {
9874   default:
9875     report_fatal_error("Unsupported calling convention");
9876   case CallingConv::C:
9877   case CallingConv::Fast:
9878     break;
9879   case CallingConv::GHC:
9880     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9881         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9882       report_fatal_error(
9883         "GHC calling convention requires the F and D instruction set extensions");
9884   }
9885 
9886   const Function &Func = MF.getFunction();
9887   if (Func.hasFnAttribute("interrupt")) {
9888     if (!Func.arg_empty())
9889       report_fatal_error(
9890         "Functions with the interrupt attribute cannot have arguments!");
9891 
9892     StringRef Kind =
9893       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9894 
9895     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9896       report_fatal_error(
9897         "Function interrupt attribute argument not supported!");
9898   }
9899 
9900   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9901   MVT XLenVT = Subtarget.getXLenVT();
9902   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9903   // Used with vargs to acumulate store chains.
9904   std::vector<SDValue> OutChains;
9905 
9906   // Assign locations to all of the incoming arguments.
9907   SmallVector<CCValAssign, 16> ArgLocs;
9908   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9909 
9910   if (CallConv == CallingConv::GHC)
9911     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9912   else
9913     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9914                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9915                                                    : CC_RISCV);
9916 
9917   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9918     CCValAssign &VA = ArgLocs[i];
9919     SDValue ArgValue;
9920     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9921     // case.
9922     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9923       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9924     else if (VA.isRegLoc())
9925       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9926     else
9927       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9928 
9929     if (VA.getLocInfo() == CCValAssign::Indirect) {
9930       // If the original argument was split and passed by reference (e.g. i128
9931       // on RV32), we need to load all parts of it here (using the same
9932       // address). Vectors may be partly split to registers and partly to the
9933       // stack, in which case the base address is partly offset and subsequent
9934       // stores are relative to that.
9935       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9936                                    MachinePointerInfo()));
9937       unsigned ArgIndex = Ins[i].OrigArgIndex;
9938       unsigned ArgPartOffset = Ins[i].PartOffset;
9939       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9940       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9941         CCValAssign &PartVA = ArgLocs[i + 1];
9942         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9943         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9944         if (PartVA.getValVT().isScalableVector())
9945           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9946         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9947         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9948                                      MachinePointerInfo()));
9949         ++i;
9950       }
9951       continue;
9952     }
9953     InVals.push_back(ArgValue);
9954   }
9955 
9956   if (IsVarArg) {
9957     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9958     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9959     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9960     MachineFrameInfo &MFI = MF.getFrameInfo();
9961     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9962     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9963 
9964     // Offset of the first variable argument from stack pointer, and size of
9965     // the vararg save area. For now, the varargs save area is either zero or
9966     // large enough to hold a0-a7.
9967     int VaArgOffset, VarArgsSaveSize;
9968 
9969     // If all registers are allocated, then all varargs must be passed on the
9970     // stack and we don't need to save any argregs.
9971     if (ArgRegs.size() == Idx) {
9972       VaArgOffset = CCInfo.getNextStackOffset();
9973       VarArgsSaveSize = 0;
9974     } else {
9975       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9976       VaArgOffset = -VarArgsSaveSize;
9977     }
9978 
9979     // Record the frame index of the first variable argument
9980     // which is a value necessary to VASTART.
9981     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9982     RVFI->setVarArgsFrameIndex(FI);
9983 
9984     // If saving an odd number of registers then create an extra stack slot to
9985     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9986     // offsets to even-numbered registered remain 2*XLEN-aligned.
9987     if (Idx % 2) {
9988       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9989       VarArgsSaveSize += XLenInBytes;
9990     }
9991 
9992     // Copy the integer registers that may have been used for passing varargs
9993     // to the vararg save area.
9994     for (unsigned I = Idx; I < ArgRegs.size();
9995          ++I, VaArgOffset += XLenInBytes) {
9996       const Register Reg = RegInfo.createVirtualRegister(RC);
9997       RegInfo.addLiveIn(ArgRegs[I], Reg);
9998       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9999       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10000       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10001       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10002                                    MachinePointerInfo::getFixedStack(MF, FI));
10003       cast<StoreSDNode>(Store.getNode())
10004           ->getMemOperand()
10005           ->setValue((Value *)nullptr);
10006       OutChains.push_back(Store);
10007     }
10008     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10009   }
10010 
10011   // All stores are grouped in one node to allow the matching between
10012   // the size of Ins and InVals. This only happens for vararg functions.
10013   if (!OutChains.empty()) {
10014     OutChains.push_back(Chain);
10015     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10016   }
10017 
10018   return Chain;
10019 }
10020 
10021 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10022 /// for tail call optimization.
10023 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10024 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10025     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10026     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10027 
10028   auto &Callee = CLI.Callee;
10029   auto CalleeCC = CLI.CallConv;
10030   auto &Outs = CLI.Outs;
10031   auto &Caller = MF.getFunction();
10032   auto CallerCC = Caller.getCallingConv();
10033 
10034   // Exception-handling functions need a special set of instructions to
10035   // indicate a return to the hardware. Tail-calling another function would
10036   // probably break this.
10037   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10038   // should be expanded as new function attributes are introduced.
10039   if (Caller.hasFnAttribute("interrupt"))
10040     return false;
10041 
10042   // Do not tail call opt if the stack is used to pass parameters.
10043   if (CCInfo.getNextStackOffset() != 0)
10044     return false;
10045 
10046   // Do not tail call opt if any parameters need to be passed indirectly.
10047   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10048   // passed indirectly. So the address of the value will be passed in a
10049   // register, or if not available, then the address is put on the stack. In
10050   // order to pass indirectly, space on the stack often needs to be allocated
10051   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10052   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10053   // are passed CCValAssign::Indirect.
10054   for (auto &VA : ArgLocs)
10055     if (VA.getLocInfo() == CCValAssign::Indirect)
10056       return false;
10057 
10058   // Do not tail call opt if either caller or callee uses struct return
10059   // semantics.
10060   auto IsCallerStructRet = Caller.hasStructRetAttr();
10061   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10062   if (IsCallerStructRet || IsCalleeStructRet)
10063     return false;
10064 
10065   // Externally-defined functions with weak linkage should not be
10066   // tail-called. The behaviour of branch instructions in this situation (as
10067   // used for tail calls) is implementation-defined, so we cannot rely on the
10068   // linker replacing the tail call with a return.
10069   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10070     const GlobalValue *GV = G->getGlobal();
10071     if (GV->hasExternalWeakLinkage())
10072       return false;
10073   }
10074 
10075   // The callee has to preserve all registers the caller needs to preserve.
10076   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10077   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10078   if (CalleeCC != CallerCC) {
10079     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10080     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10081       return false;
10082   }
10083 
10084   // Byval parameters hand the function a pointer directly into the stack area
10085   // we want to reuse during a tail call. Working around this *is* possible
10086   // but less efficient and uglier in LowerCall.
10087   for (auto &Arg : Outs)
10088     if (Arg.Flags.isByVal())
10089       return false;
10090 
10091   return true;
10092 }
10093 
10094 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10095   return DAG.getDataLayout().getPrefTypeAlign(
10096       VT.getTypeForEVT(*DAG.getContext()));
10097 }
10098 
10099 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10100 // and output parameter nodes.
10101 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10102                                        SmallVectorImpl<SDValue> &InVals) const {
10103   SelectionDAG &DAG = CLI.DAG;
10104   SDLoc &DL = CLI.DL;
10105   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10106   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10107   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10108   SDValue Chain = CLI.Chain;
10109   SDValue Callee = CLI.Callee;
10110   bool &IsTailCall = CLI.IsTailCall;
10111   CallingConv::ID CallConv = CLI.CallConv;
10112   bool IsVarArg = CLI.IsVarArg;
10113   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10114   MVT XLenVT = Subtarget.getXLenVT();
10115 
10116   MachineFunction &MF = DAG.getMachineFunction();
10117 
10118   // Analyze the operands of the call, assigning locations to each operand.
10119   SmallVector<CCValAssign, 16> ArgLocs;
10120   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10121 
10122   if (CallConv == CallingConv::GHC)
10123     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10124   else
10125     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10126                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10127                                                     : CC_RISCV);
10128 
10129   // Check if it's really possible to do a tail call.
10130   if (IsTailCall)
10131     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10132 
10133   if (IsTailCall)
10134     ++NumTailCalls;
10135   else if (CLI.CB && CLI.CB->isMustTailCall())
10136     report_fatal_error("failed to perform tail call elimination on a call "
10137                        "site marked musttail");
10138 
10139   // Get a count of how many bytes are to be pushed on the stack.
10140   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10141 
10142   // Create local copies for byval args
10143   SmallVector<SDValue, 8> ByValArgs;
10144   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10145     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10146     if (!Flags.isByVal())
10147       continue;
10148 
10149     SDValue Arg = OutVals[i];
10150     unsigned Size = Flags.getByValSize();
10151     Align Alignment = Flags.getNonZeroByValAlign();
10152 
10153     int FI =
10154         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10155     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10156     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10157 
10158     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10159                           /*IsVolatile=*/false,
10160                           /*AlwaysInline=*/false, IsTailCall,
10161                           MachinePointerInfo(), MachinePointerInfo());
10162     ByValArgs.push_back(FIPtr);
10163   }
10164 
10165   if (!IsTailCall)
10166     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10167 
10168   // Copy argument values to their designated locations.
10169   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10170   SmallVector<SDValue, 8> MemOpChains;
10171   SDValue StackPtr;
10172   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10173     CCValAssign &VA = ArgLocs[i];
10174     SDValue ArgValue = OutVals[i];
10175     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10176 
10177     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10178     bool IsF64OnRV32DSoftABI =
10179         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10180     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10181       SDValue SplitF64 = DAG.getNode(
10182           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10183       SDValue Lo = SplitF64.getValue(0);
10184       SDValue Hi = SplitF64.getValue(1);
10185 
10186       Register RegLo = VA.getLocReg();
10187       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10188 
10189       if (RegLo == RISCV::X17) {
10190         // Second half of f64 is passed on the stack.
10191         // Work out the address of the stack slot.
10192         if (!StackPtr.getNode())
10193           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10194         // Emit the store.
10195         MemOpChains.push_back(
10196             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10197       } else {
10198         // Second half of f64 is passed in another GPR.
10199         assert(RegLo < RISCV::X31 && "Invalid register pair");
10200         Register RegHigh = RegLo + 1;
10201         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10202       }
10203       continue;
10204     }
10205 
10206     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10207     // as any other MemLoc.
10208 
10209     // Promote the value if needed.
10210     // For now, only handle fully promoted and indirect arguments.
10211     if (VA.getLocInfo() == CCValAssign::Indirect) {
10212       // Store the argument in a stack slot and pass its address.
10213       Align StackAlign =
10214           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10215                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10216       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10217       // If the original argument was split (e.g. i128), we need
10218       // to store the required parts of it here (and pass just one address).
10219       // Vectors may be partly split to registers and partly to the stack, in
10220       // which case the base address is partly offset and subsequent stores are
10221       // relative to that.
10222       unsigned ArgIndex = Outs[i].OrigArgIndex;
10223       unsigned ArgPartOffset = Outs[i].PartOffset;
10224       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10225       // Calculate the total size to store. We don't have access to what we're
10226       // actually storing other than performing the loop and collecting the
10227       // info.
10228       SmallVector<std::pair<SDValue, SDValue>> Parts;
10229       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10230         SDValue PartValue = OutVals[i + 1];
10231         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10232         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10233         EVT PartVT = PartValue.getValueType();
10234         if (PartVT.isScalableVector())
10235           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10236         StoredSize += PartVT.getStoreSize();
10237         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10238         Parts.push_back(std::make_pair(PartValue, Offset));
10239         ++i;
10240       }
10241       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10242       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10243       MemOpChains.push_back(
10244           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10245                        MachinePointerInfo::getFixedStack(MF, FI)));
10246       for (const auto &Part : Parts) {
10247         SDValue PartValue = Part.first;
10248         SDValue PartOffset = Part.second;
10249         SDValue Address =
10250             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10251         MemOpChains.push_back(
10252             DAG.getStore(Chain, DL, PartValue, Address,
10253                          MachinePointerInfo::getFixedStack(MF, FI)));
10254       }
10255       ArgValue = SpillSlot;
10256     } else {
10257       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10258     }
10259 
10260     // Use local copy if it is a byval arg.
10261     if (Flags.isByVal())
10262       ArgValue = ByValArgs[j++];
10263 
10264     if (VA.isRegLoc()) {
10265       // Queue up the argument copies and emit them at the end.
10266       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10267     } else {
10268       assert(VA.isMemLoc() && "Argument not register or memory");
10269       assert(!IsTailCall && "Tail call not allowed if stack is used "
10270                             "for passing parameters");
10271 
10272       // Work out the address of the stack slot.
10273       if (!StackPtr.getNode())
10274         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10275       SDValue Address =
10276           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10277                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10278 
10279       // Emit the store.
10280       MemOpChains.push_back(
10281           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10282     }
10283   }
10284 
10285   // Join the stores, which are independent of one another.
10286   if (!MemOpChains.empty())
10287     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10288 
10289   SDValue Glue;
10290 
10291   // Build a sequence of copy-to-reg nodes, chained and glued together.
10292   for (auto &Reg : RegsToPass) {
10293     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10294     Glue = Chain.getValue(1);
10295   }
10296 
10297   // Validate that none of the argument registers have been marked as
10298   // reserved, if so report an error. Do the same for the return address if this
10299   // is not a tailcall.
10300   validateCCReservedRegs(RegsToPass, MF);
10301   if (!IsTailCall &&
10302       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10303     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10304         MF.getFunction(),
10305         "Return address register required, but has been reserved."});
10306 
10307   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10308   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10309   // split it and then direct call can be matched by PseudoCALL.
10310   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10311     const GlobalValue *GV = S->getGlobal();
10312 
10313     unsigned OpFlags = RISCVII::MO_CALL;
10314     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10315       OpFlags = RISCVII::MO_PLT;
10316 
10317     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10318   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10319     unsigned OpFlags = RISCVII::MO_CALL;
10320 
10321     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10322                                                  nullptr))
10323       OpFlags = RISCVII::MO_PLT;
10324 
10325     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10326   }
10327 
10328   // The first call operand is the chain and the second is the target address.
10329   SmallVector<SDValue, 8> Ops;
10330   Ops.push_back(Chain);
10331   Ops.push_back(Callee);
10332 
10333   // Add argument registers to the end of the list so that they are
10334   // known live into the call.
10335   for (auto &Reg : RegsToPass)
10336     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10337 
10338   if (!IsTailCall) {
10339     // Add a register mask operand representing the call-preserved registers.
10340     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10341     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10342     assert(Mask && "Missing call preserved mask for calling convention");
10343     Ops.push_back(DAG.getRegisterMask(Mask));
10344   }
10345 
10346   // Glue the call to the argument copies, if any.
10347   if (Glue.getNode())
10348     Ops.push_back(Glue);
10349 
10350   // Emit the call.
10351   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10352 
10353   if (IsTailCall) {
10354     MF.getFrameInfo().setHasTailCall();
10355     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10356   }
10357 
10358   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10359   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10360   Glue = Chain.getValue(1);
10361 
10362   // Mark the end of the call, which is glued to the call itself.
10363   Chain = DAG.getCALLSEQ_END(Chain,
10364                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10365                              DAG.getConstant(0, DL, PtrVT, true),
10366                              Glue, DL);
10367   Glue = Chain.getValue(1);
10368 
10369   // Assign locations to each value returned by this call.
10370   SmallVector<CCValAssign, 16> RVLocs;
10371   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10372   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10373 
10374   // Copy all of the result registers out of their specified physreg.
10375   for (auto &VA : RVLocs) {
10376     // Copy the value out
10377     SDValue RetValue =
10378         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10379     // Glue the RetValue to the end of the call sequence
10380     Chain = RetValue.getValue(1);
10381     Glue = RetValue.getValue(2);
10382 
10383     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10384       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10385       SDValue RetValue2 =
10386           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10387       Chain = RetValue2.getValue(1);
10388       Glue = RetValue2.getValue(2);
10389       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10390                              RetValue2);
10391     }
10392 
10393     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10394 
10395     InVals.push_back(RetValue);
10396   }
10397 
10398   return Chain;
10399 }
10400 
10401 bool RISCVTargetLowering::CanLowerReturn(
10402     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10403     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10404   SmallVector<CCValAssign, 16> RVLocs;
10405   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10406 
10407   Optional<unsigned> FirstMaskArgument;
10408   if (Subtarget.hasVInstructions())
10409     FirstMaskArgument = preAssignMask(Outs);
10410 
10411   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10412     MVT VT = Outs[i].VT;
10413     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10414     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10415     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10416                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10417                  *this, FirstMaskArgument))
10418       return false;
10419   }
10420   return true;
10421 }
10422 
10423 SDValue
10424 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10425                                  bool IsVarArg,
10426                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10427                                  const SmallVectorImpl<SDValue> &OutVals,
10428                                  const SDLoc &DL, SelectionDAG &DAG) const {
10429   const MachineFunction &MF = DAG.getMachineFunction();
10430   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10431 
10432   // Stores the assignment of the return value to a location.
10433   SmallVector<CCValAssign, 16> RVLocs;
10434 
10435   // Info about the registers and stack slot.
10436   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10437                  *DAG.getContext());
10438 
10439   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10440                     nullptr, CC_RISCV);
10441 
10442   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10443     report_fatal_error("GHC functions return void only");
10444 
10445   SDValue Glue;
10446   SmallVector<SDValue, 4> RetOps(1, Chain);
10447 
10448   // Copy the result values into the output registers.
10449   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10450     SDValue Val = OutVals[i];
10451     CCValAssign &VA = RVLocs[i];
10452     assert(VA.isRegLoc() && "Can only return in registers!");
10453 
10454     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10455       // Handle returning f64 on RV32D with a soft float ABI.
10456       assert(VA.isRegLoc() && "Expected return via registers");
10457       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10458                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10459       SDValue Lo = SplitF64.getValue(0);
10460       SDValue Hi = SplitF64.getValue(1);
10461       Register RegLo = VA.getLocReg();
10462       assert(RegLo < RISCV::X31 && "Invalid register pair");
10463       Register RegHi = RegLo + 1;
10464 
10465       if (STI.isRegisterReservedByUser(RegLo) ||
10466           STI.isRegisterReservedByUser(RegHi))
10467         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10468             MF.getFunction(),
10469             "Return value register required, but has been reserved."});
10470 
10471       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10472       Glue = Chain.getValue(1);
10473       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10474       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10475       Glue = Chain.getValue(1);
10476       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10477     } else {
10478       // Handle a 'normal' return.
10479       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10480       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10481 
10482       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10483         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10484             MF.getFunction(),
10485             "Return value register required, but has been reserved."});
10486 
10487       // Guarantee that all emitted copies are stuck together.
10488       Glue = Chain.getValue(1);
10489       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10490     }
10491   }
10492 
10493   RetOps[0] = Chain; // Update chain.
10494 
10495   // Add the glue node if we have it.
10496   if (Glue.getNode()) {
10497     RetOps.push_back(Glue);
10498   }
10499 
10500   unsigned RetOpc = RISCVISD::RET_FLAG;
10501   // Interrupt service routines use different return instructions.
10502   const Function &Func = DAG.getMachineFunction().getFunction();
10503   if (Func.hasFnAttribute("interrupt")) {
10504     if (!Func.getReturnType()->isVoidTy())
10505       report_fatal_error(
10506           "Functions with the interrupt attribute must have void return type!");
10507 
10508     MachineFunction &MF = DAG.getMachineFunction();
10509     StringRef Kind =
10510       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10511 
10512     if (Kind == "user")
10513       RetOpc = RISCVISD::URET_FLAG;
10514     else if (Kind == "supervisor")
10515       RetOpc = RISCVISD::SRET_FLAG;
10516     else
10517       RetOpc = RISCVISD::MRET_FLAG;
10518   }
10519 
10520   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10521 }
10522 
10523 void RISCVTargetLowering::validateCCReservedRegs(
10524     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10525     MachineFunction &MF) const {
10526   const Function &F = MF.getFunction();
10527   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10528 
10529   if (llvm::any_of(Regs, [&STI](auto Reg) {
10530         return STI.isRegisterReservedByUser(Reg.first);
10531       }))
10532     F.getContext().diagnose(DiagnosticInfoUnsupported{
10533         F, "Argument register required, but has been reserved."});
10534 }
10535 
10536 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10537   return CI->isTailCall();
10538 }
10539 
10540 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10541 #define NODE_NAME_CASE(NODE)                                                   \
10542   case RISCVISD::NODE:                                                         \
10543     return "RISCVISD::" #NODE;
10544   // clang-format off
10545   switch ((RISCVISD::NodeType)Opcode) {
10546   case RISCVISD::FIRST_NUMBER:
10547     break;
10548   NODE_NAME_CASE(RET_FLAG)
10549   NODE_NAME_CASE(URET_FLAG)
10550   NODE_NAME_CASE(SRET_FLAG)
10551   NODE_NAME_CASE(MRET_FLAG)
10552   NODE_NAME_CASE(CALL)
10553   NODE_NAME_CASE(SELECT_CC)
10554   NODE_NAME_CASE(BR_CC)
10555   NODE_NAME_CASE(BuildPairF64)
10556   NODE_NAME_CASE(SplitF64)
10557   NODE_NAME_CASE(TAIL)
10558   NODE_NAME_CASE(MULHSU)
10559   NODE_NAME_CASE(SLLW)
10560   NODE_NAME_CASE(SRAW)
10561   NODE_NAME_CASE(SRLW)
10562   NODE_NAME_CASE(DIVW)
10563   NODE_NAME_CASE(DIVUW)
10564   NODE_NAME_CASE(REMUW)
10565   NODE_NAME_CASE(ROLW)
10566   NODE_NAME_CASE(RORW)
10567   NODE_NAME_CASE(CLZW)
10568   NODE_NAME_CASE(CTZW)
10569   NODE_NAME_CASE(FSLW)
10570   NODE_NAME_CASE(FSRW)
10571   NODE_NAME_CASE(FSL)
10572   NODE_NAME_CASE(FSR)
10573   NODE_NAME_CASE(FMV_H_X)
10574   NODE_NAME_CASE(FMV_X_ANYEXTH)
10575   NODE_NAME_CASE(FMV_W_X_RV64)
10576   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10577   NODE_NAME_CASE(FCVT_X)
10578   NODE_NAME_CASE(FCVT_XU)
10579   NODE_NAME_CASE(FCVT_W_RV64)
10580   NODE_NAME_CASE(FCVT_WU_RV64)
10581   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10582   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10583   NODE_NAME_CASE(READ_CYCLE_WIDE)
10584   NODE_NAME_CASE(GREV)
10585   NODE_NAME_CASE(GREVW)
10586   NODE_NAME_CASE(GORC)
10587   NODE_NAME_CASE(GORCW)
10588   NODE_NAME_CASE(SHFL)
10589   NODE_NAME_CASE(SHFLW)
10590   NODE_NAME_CASE(UNSHFL)
10591   NODE_NAME_CASE(UNSHFLW)
10592   NODE_NAME_CASE(BFP)
10593   NODE_NAME_CASE(BFPW)
10594   NODE_NAME_CASE(BCOMPRESS)
10595   NODE_NAME_CASE(BCOMPRESSW)
10596   NODE_NAME_CASE(BDECOMPRESS)
10597   NODE_NAME_CASE(BDECOMPRESSW)
10598   NODE_NAME_CASE(VMV_V_X_VL)
10599   NODE_NAME_CASE(VFMV_V_F_VL)
10600   NODE_NAME_CASE(VMV_X_S)
10601   NODE_NAME_CASE(VMV_S_X_VL)
10602   NODE_NAME_CASE(VFMV_S_F_VL)
10603   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10604   NODE_NAME_CASE(READ_VLENB)
10605   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10606   NODE_NAME_CASE(VSLIDEUP_VL)
10607   NODE_NAME_CASE(VSLIDE1UP_VL)
10608   NODE_NAME_CASE(VSLIDEDOWN_VL)
10609   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10610   NODE_NAME_CASE(VID_VL)
10611   NODE_NAME_CASE(VFNCVT_ROD_VL)
10612   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10613   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10614   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10615   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10616   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10617   NODE_NAME_CASE(VECREDUCE_AND_VL)
10618   NODE_NAME_CASE(VECREDUCE_OR_VL)
10619   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10620   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10621   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10622   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10623   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10624   NODE_NAME_CASE(ADD_VL)
10625   NODE_NAME_CASE(AND_VL)
10626   NODE_NAME_CASE(MUL_VL)
10627   NODE_NAME_CASE(OR_VL)
10628   NODE_NAME_CASE(SDIV_VL)
10629   NODE_NAME_CASE(SHL_VL)
10630   NODE_NAME_CASE(SREM_VL)
10631   NODE_NAME_CASE(SRA_VL)
10632   NODE_NAME_CASE(SRL_VL)
10633   NODE_NAME_CASE(SUB_VL)
10634   NODE_NAME_CASE(UDIV_VL)
10635   NODE_NAME_CASE(UREM_VL)
10636   NODE_NAME_CASE(XOR_VL)
10637   NODE_NAME_CASE(SADDSAT_VL)
10638   NODE_NAME_CASE(UADDSAT_VL)
10639   NODE_NAME_CASE(SSUBSAT_VL)
10640   NODE_NAME_CASE(USUBSAT_VL)
10641   NODE_NAME_CASE(FADD_VL)
10642   NODE_NAME_CASE(FSUB_VL)
10643   NODE_NAME_CASE(FMUL_VL)
10644   NODE_NAME_CASE(FDIV_VL)
10645   NODE_NAME_CASE(FNEG_VL)
10646   NODE_NAME_CASE(FABS_VL)
10647   NODE_NAME_CASE(FSQRT_VL)
10648   NODE_NAME_CASE(FMA_VL)
10649   NODE_NAME_CASE(FCOPYSIGN_VL)
10650   NODE_NAME_CASE(SMIN_VL)
10651   NODE_NAME_CASE(SMAX_VL)
10652   NODE_NAME_CASE(UMIN_VL)
10653   NODE_NAME_CASE(UMAX_VL)
10654   NODE_NAME_CASE(FMINNUM_VL)
10655   NODE_NAME_CASE(FMAXNUM_VL)
10656   NODE_NAME_CASE(MULHS_VL)
10657   NODE_NAME_CASE(MULHU_VL)
10658   NODE_NAME_CASE(FP_TO_SINT_VL)
10659   NODE_NAME_CASE(FP_TO_UINT_VL)
10660   NODE_NAME_CASE(SINT_TO_FP_VL)
10661   NODE_NAME_CASE(UINT_TO_FP_VL)
10662   NODE_NAME_CASE(FP_EXTEND_VL)
10663   NODE_NAME_CASE(FP_ROUND_VL)
10664   NODE_NAME_CASE(VWMUL_VL)
10665   NODE_NAME_CASE(VWMULU_VL)
10666   NODE_NAME_CASE(VWMULSU_VL)
10667   NODE_NAME_CASE(VWADD_VL)
10668   NODE_NAME_CASE(VWADDU_VL)
10669   NODE_NAME_CASE(VWSUB_VL)
10670   NODE_NAME_CASE(VWSUBU_VL)
10671   NODE_NAME_CASE(VWADD_W_VL)
10672   NODE_NAME_CASE(VWADDU_W_VL)
10673   NODE_NAME_CASE(VWSUB_W_VL)
10674   NODE_NAME_CASE(VWSUBU_W_VL)
10675   NODE_NAME_CASE(SETCC_VL)
10676   NODE_NAME_CASE(VSELECT_VL)
10677   NODE_NAME_CASE(VP_MERGE_VL)
10678   NODE_NAME_CASE(VMAND_VL)
10679   NODE_NAME_CASE(VMOR_VL)
10680   NODE_NAME_CASE(VMXOR_VL)
10681   NODE_NAME_CASE(VMCLR_VL)
10682   NODE_NAME_CASE(VMSET_VL)
10683   NODE_NAME_CASE(VRGATHER_VX_VL)
10684   NODE_NAME_CASE(VRGATHER_VV_VL)
10685   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10686   NODE_NAME_CASE(VSEXT_VL)
10687   NODE_NAME_CASE(VZEXT_VL)
10688   NODE_NAME_CASE(VCPOP_VL)
10689   NODE_NAME_CASE(VLE_VL)
10690   NODE_NAME_CASE(VSE_VL)
10691   NODE_NAME_CASE(READ_CSR)
10692   NODE_NAME_CASE(WRITE_CSR)
10693   NODE_NAME_CASE(SWAP_CSR)
10694   }
10695   // clang-format on
10696   return nullptr;
10697 #undef NODE_NAME_CASE
10698 }
10699 
10700 /// getConstraintType - Given a constraint letter, return the type of
10701 /// constraint it is for this target.
10702 RISCVTargetLowering::ConstraintType
10703 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10704   if (Constraint.size() == 1) {
10705     switch (Constraint[0]) {
10706     default:
10707       break;
10708     case 'f':
10709       return C_RegisterClass;
10710     case 'I':
10711     case 'J':
10712     case 'K':
10713       return C_Immediate;
10714     case 'A':
10715       return C_Memory;
10716     case 'S': // A symbolic address
10717       return C_Other;
10718     }
10719   } else {
10720     if (Constraint == "vr" || Constraint == "vm")
10721       return C_RegisterClass;
10722   }
10723   return TargetLowering::getConstraintType(Constraint);
10724 }
10725 
10726 std::pair<unsigned, const TargetRegisterClass *>
10727 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10728                                                   StringRef Constraint,
10729                                                   MVT VT) const {
10730   // First, see if this is a constraint that directly corresponds to a
10731   // RISCV register class.
10732   if (Constraint.size() == 1) {
10733     switch (Constraint[0]) {
10734     case 'r':
10735       // TODO: Support fixed vectors up to XLen for P extension?
10736       if (VT.isVector())
10737         break;
10738       return std::make_pair(0U, &RISCV::GPRRegClass);
10739     case 'f':
10740       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10741         return std::make_pair(0U, &RISCV::FPR16RegClass);
10742       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10743         return std::make_pair(0U, &RISCV::FPR32RegClass);
10744       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10745         return std::make_pair(0U, &RISCV::FPR64RegClass);
10746       break;
10747     default:
10748       break;
10749     }
10750   } else if (Constraint == "vr") {
10751     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10752                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10753       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10754         return std::make_pair(0U, RC);
10755     }
10756   } else if (Constraint == "vm") {
10757     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10758       return std::make_pair(0U, &RISCV::VMV0RegClass);
10759   }
10760 
10761   // Clang will correctly decode the usage of register name aliases into their
10762   // official names. However, other frontends like `rustc` do not. This allows
10763   // users of these frontends to use the ABI names for registers in LLVM-style
10764   // register constraints.
10765   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10766                                .Case("{zero}", RISCV::X0)
10767                                .Case("{ra}", RISCV::X1)
10768                                .Case("{sp}", RISCV::X2)
10769                                .Case("{gp}", RISCV::X3)
10770                                .Case("{tp}", RISCV::X4)
10771                                .Case("{t0}", RISCV::X5)
10772                                .Case("{t1}", RISCV::X6)
10773                                .Case("{t2}", RISCV::X7)
10774                                .Cases("{s0}", "{fp}", RISCV::X8)
10775                                .Case("{s1}", RISCV::X9)
10776                                .Case("{a0}", RISCV::X10)
10777                                .Case("{a1}", RISCV::X11)
10778                                .Case("{a2}", RISCV::X12)
10779                                .Case("{a3}", RISCV::X13)
10780                                .Case("{a4}", RISCV::X14)
10781                                .Case("{a5}", RISCV::X15)
10782                                .Case("{a6}", RISCV::X16)
10783                                .Case("{a7}", RISCV::X17)
10784                                .Case("{s2}", RISCV::X18)
10785                                .Case("{s3}", RISCV::X19)
10786                                .Case("{s4}", RISCV::X20)
10787                                .Case("{s5}", RISCV::X21)
10788                                .Case("{s6}", RISCV::X22)
10789                                .Case("{s7}", RISCV::X23)
10790                                .Case("{s8}", RISCV::X24)
10791                                .Case("{s9}", RISCV::X25)
10792                                .Case("{s10}", RISCV::X26)
10793                                .Case("{s11}", RISCV::X27)
10794                                .Case("{t3}", RISCV::X28)
10795                                .Case("{t4}", RISCV::X29)
10796                                .Case("{t5}", RISCV::X30)
10797                                .Case("{t6}", RISCV::X31)
10798                                .Default(RISCV::NoRegister);
10799   if (XRegFromAlias != RISCV::NoRegister)
10800     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10801 
10802   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10803   // TableGen record rather than the AsmName to choose registers for InlineAsm
10804   // constraints, plus we want to match those names to the widest floating point
10805   // register type available, manually select floating point registers here.
10806   //
10807   // The second case is the ABI name of the register, so that frontends can also
10808   // use the ABI names in register constraint lists.
10809   if (Subtarget.hasStdExtF()) {
10810     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10811                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10812                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10813                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10814                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10815                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10816                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10817                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10818                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10819                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10820                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10821                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10822                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10823                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10824                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10825                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10826                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10827                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10828                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10829                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10830                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10831                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10832                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10833                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10834                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10835                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10836                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10837                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10838                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10839                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10840                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10841                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10842                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10843                         .Default(RISCV::NoRegister);
10844     if (FReg != RISCV::NoRegister) {
10845       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10846       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10847         unsigned RegNo = FReg - RISCV::F0_F;
10848         unsigned DReg = RISCV::F0_D + RegNo;
10849         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10850       }
10851       if (VT == MVT::f32 || VT == MVT::Other)
10852         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10853       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10854         unsigned RegNo = FReg - RISCV::F0_F;
10855         unsigned HReg = RISCV::F0_H + RegNo;
10856         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10857       }
10858     }
10859   }
10860 
10861   if (Subtarget.hasVInstructions()) {
10862     Register VReg = StringSwitch<Register>(Constraint.lower())
10863                         .Case("{v0}", RISCV::V0)
10864                         .Case("{v1}", RISCV::V1)
10865                         .Case("{v2}", RISCV::V2)
10866                         .Case("{v3}", RISCV::V3)
10867                         .Case("{v4}", RISCV::V4)
10868                         .Case("{v5}", RISCV::V5)
10869                         .Case("{v6}", RISCV::V6)
10870                         .Case("{v7}", RISCV::V7)
10871                         .Case("{v8}", RISCV::V8)
10872                         .Case("{v9}", RISCV::V9)
10873                         .Case("{v10}", RISCV::V10)
10874                         .Case("{v11}", RISCV::V11)
10875                         .Case("{v12}", RISCV::V12)
10876                         .Case("{v13}", RISCV::V13)
10877                         .Case("{v14}", RISCV::V14)
10878                         .Case("{v15}", RISCV::V15)
10879                         .Case("{v16}", RISCV::V16)
10880                         .Case("{v17}", RISCV::V17)
10881                         .Case("{v18}", RISCV::V18)
10882                         .Case("{v19}", RISCV::V19)
10883                         .Case("{v20}", RISCV::V20)
10884                         .Case("{v21}", RISCV::V21)
10885                         .Case("{v22}", RISCV::V22)
10886                         .Case("{v23}", RISCV::V23)
10887                         .Case("{v24}", RISCV::V24)
10888                         .Case("{v25}", RISCV::V25)
10889                         .Case("{v26}", RISCV::V26)
10890                         .Case("{v27}", RISCV::V27)
10891                         .Case("{v28}", RISCV::V28)
10892                         .Case("{v29}", RISCV::V29)
10893                         .Case("{v30}", RISCV::V30)
10894                         .Case("{v31}", RISCV::V31)
10895                         .Default(RISCV::NoRegister);
10896     if (VReg != RISCV::NoRegister) {
10897       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10898         return std::make_pair(VReg, &RISCV::VMRegClass);
10899       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10900         return std::make_pair(VReg, &RISCV::VRRegClass);
10901       for (const auto *RC :
10902            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10903         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10904           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10905           return std::make_pair(VReg, RC);
10906         }
10907       }
10908     }
10909   }
10910 
10911   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10912 }
10913 
10914 unsigned
10915 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10916   // Currently only support length 1 constraints.
10917   if (ConstraintCode.size() == 1) {
10918     switch (ConstraintCode[0]) {
10919     case 'A':
10920       return InlineAsm::Constraint_A;
10921     default:
10922       break;
10923     }
10924   }
10925 
10926   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10927 }
10928 
10929 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10930     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10931     SelectionDAG &DAG) const {
10932   // Currently only support length 1 constraints.
10933   if (Constraint.length() == 1) {
10934     switch (Constraint[0]) {
10935     case 'I':
10936       // Validate & create a 12-bit signed immediate operand.
10937       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10938         uint64_t CVal = C->getSExtValue();
10939         if (isInt<12>(CVal))
10940           Ops.push_back(
10941               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10942       }
10943       return;
10944     case 'J':
10945       // Validate & create an integer zero operand.
10946       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10947         if (C->getZExtValue() == 0)
10948           Ops.push_back(
10949               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10950       return;
10951     case 'K':
10952       // Validate & create a 5-bit unsigned immediate operand.
10953       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10954         uint64_t CVal = C->getZExtValue();
10955         if (isUInt<5>(CVal))
10956           Ops.push_back(
10957               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10958       }
10959       return;
10960     case 'S':
10961       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10962         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10963                                                  GA->getValueType(0)));
10964       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10965         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10966                                                 BA->getValueType(0)));
10967       }
10968       return;
10969     default:
10970       break;
10971     }
10972   }
10973   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10974 }
10975 
10976 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10977                                                    Instruction *Inst,
10978                                                    AtomicOrdering Ord) const {
10979   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10980     return Builder.CreateFence(Ord);
10981   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10982     return Builder.CreateFence(AtomicOrdering::Release);
10983   return nullptr;
10984 }
10985 
10986 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10987                                                     Instruction *Inst,
10988                                                     AtomicOrdering Ord) const {
10989   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10990     return Builder.CreateFence(AtomicOrdering::Acquire);
10991   return nullptr;
10992 }
10993 
10994 TargetLowering::AtomicExpansionKind
10995 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10996   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10997   // point operations can't be used in an lr/sc sequence without breaking the
10998   // forward-progress guarantee.
10999   if (AI->isFloatingPointOperation())
11000     return AtomicExpansionKind::CmpXChg;
11001 
11002   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11003   if (Size == 8 || Size == 16)
11004     return AtomicExpansionKind::MaskedIntrinsic;
11005   return AtomicExpansionKind::None;
11006 }
11007 
11008 static Intrinsic::ID
11009 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11010   if (XLen == 32) {
11011     switch (BinOp) {
11012     default:
11013       llvm_unreachable("Unexpected AtomicRMW BinOp");
11014     case AtomicRMWInst::Xchg:
11015       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11016     case AtomicRMWInst::Add:
11017       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11018     case AtomicRMWInst::Sub:
11019       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11020     case AtomicRMWInst::Nand:
11021       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11022     case AtomicRMWInst::Max:
11023       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11024     case AtomicRMWInst::Min:
11025       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11026     case AtomicRMWInst::UMax:
11027       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11028     case AtomicRMWInst::UMin:
11029       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11030     }
11031   }
11032 
11033   if (XLen == 64) {
11034     switch (BinOp) {
11035     default:
11036       llvm_unreachable("Unexpected AtomicRMW BinOp");
11037     case AtomicRMWInst::Xchg:
11038       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11039     case AtomicRMWInst::Add:
11040       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11041     case AtomicRMWInst::Sub:
11042       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11043     case AtomicRMWInst::Nand:
11044       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11045     case AtomicRMWInst::Max:
11046       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11047     case AtomicRMWInst::Min:
11048       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11049     case AtomicRMWInst::UMax:
11050       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11051     case AtomicRMWInst::UMin:
11052       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11053     }
11054   }
11055 
11056   llvm_unreachable("Unexpected XLen\n");
11057 }
11058 
11059 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11060     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11061     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11062   unsigned XLen = Subtarget.getXLen();
11063   Value *Ordering =
11064       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11065   Type *Tys[] = {AlignedAddr->getType()};
11066   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11067       AI->getModule(),
11068       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11069 
11070   if (XLen == 64) {
11071     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11072     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11073     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11074   }
11075 
11076   Value *Result;
11077 
11078   // Must pass the shift amount needed to sign extend the loaded value prior
11079   // to performing a signed comparison for min/max. ShiftAmt is the number of
11080   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11081   // is the number of bits to left+right shift the value in order to
11082   // sign-extend.
11083   if (AI->getOperation() == AtomicRMWInst::Min ||
11084       AI->getOperation() == AtomicRMWInst::Max) {
11085     const DataLayout &DL = AI->getModule()->getDataLayout();
11086     unsigned ValWidth =
11087         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11088     Value *SextShamt =
11089         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11090     Result = Builder.CreateCall(LrwOpScwLoop,
11091                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11092   } else {
11093     Result =
11094         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11095   }
11096 
11097   if (XLen == 64)
11098     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11099   return Result;
11100 }
11101 
11102 TargetLowering::AtomicExpansionKind
11103 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11104     AtomicCmpXchgInst *CI) const {
11105   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11106   if (Size == 8 || Size == 16)
11107     return AtomicExpansionKind::MaskedIntrinsic;
11108   return AtomicExpansionKind::None;
11109 }
11110 
11111 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11112     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11113     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11114   unsigned XLen = Subtarget.getXLen();
11115   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11116   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11117   if (XLen == 64) {
11118     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11119     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11120     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11121     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11122   }
11123   Type *Tys[] = {AlignedAddr->getType()};
11124   Function *MaskedCmpXchg =
11125       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11126   Value *Result = Builder.CreateCall(
11127       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11128   if (XLen == 64)
11129     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11130   return Result;
11131 }
11132 
11133 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11134   return false;
11135 }
11136 
11137 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11138                                                EVT VT) const {
11139   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11140     return false;
11141 
11142   switch (FPVT.getSimpleVT().SimpleTy) {
11143   case MVT::f16:
11144     return Subtarget.hasStdExtZfh();
11145   case MVT::f32:
11146     return Subtarget.hasStdExtF();
11147   case MVT::f64:
11148     return Subtarget.hasStdExtD();
11149   default:
11150     return false;
11151   }
11152 }
11153 
11154 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11155   // If we are using the small code model, we can reduce size of jump table
11156   // entry to 4 bytes.
11157   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11158       getTargetMachine().getCodeModel() == CodeModel::Small) {
11159     return MachineJumpTableInfo::EK_Custom32;
11160   }
11161   return TargetLowering::getJumpTableEncoding();
11162 }
11163 
11164 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11165     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11166     unsigned uid, MCContext &Ctx) const {
11167   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11168          getTargetMachine().getCodeModel() == CodeModel::Small);
11169   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11170 }
11171 
11172 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11173                                                      EVT VT) const {
11174   VT = VT.getScalarType();
11175 
11176   if (!VT.isSimple())
11177     return false;
11178 
11179   switch (VT.getSimpleVT().SimpleTy) {
11180   case MVT::f16:
11181     return Subtarget.hasStdExtZfh();
11182   case MVT::f32:
11183     return Subtarget.hasStdExtF();
11184   case MVT::f64:
11185     return Subtarget.hasStdExtD();
11186   default:
11187     break;
11188   }
11189 
11190   return false;
11191 }
11192 
11193 Register RISCVTargetLowering::getExceptionPointerRegister(
11194     const Constant *PersonalityFn) const {
11195   return RISCV::X10;
11196 }
11197 
11198 Register RISCVTargetLowering::getExceptionSelectorRegister(
11199     const Constant *PersonalityFn) const {
11200   return RISCV::X11;
11201 }
11202 
11203 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11204   // Return false to suppress the unnecessary extensions if the LibCall
11205   // arguments or return value is f32 type for LP64 ABI.
11206   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11207   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11208     return false;
11209 
11210   return true;
11211 }
11212 
11213 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11214   if (Subtarget.is64Bit() && Type == MVT::i32)
11215     return true;
11216 
11217   return IsSigned;
11218 }
11219 
11220 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11221                                                  SDValue C) const {
11222   // Check integral scalar types.
11223   if (VT.isScalarInteger()) {
11224     // Omit the optimization if the sub target has the M extension and the data
11225     // size exceeds XLen.
11226     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11227       return false;
11228     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11229       // Break the MUL to a SLLI and an ADD/SUB.
11230       const APInt &Imm = ConstNode->getAPIntValue();
11231       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11232           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11233         return true;
11234       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11235       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11236           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11237            (Imm - 8).isPowerOf2()))
11238         return true;
11239       // Omit the following optimization if the sub target has the M extension
11240       // and the data size >= XLen.
11241       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11242         return false;
11243       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11244       // a pair of LUI/ADDI.
11245       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11246         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11247         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11248             (1 - ImmS).isPowerOf2())
11249         return true;
11250       }
11251     }
11252   }
11253 
11254   return false;
11255 }
11256 
11257 bool RISCVTargetLowering::isMulAddWithConstProfitable(
11258     const SDValue &AddNode, const SDValue &ConstNode) const {
11259   // Let the DAGCombiner decide for vectors.
11260   EVT VT = AddNode.getValueType();
11261   if (VT.isVector())
11262     return true;
11263 
11264   // Let the DAGCombiner decide for larger types.
11265   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11266     return true;
11267 
11268   // It is worse if c1 is simm12 while c1*c2 is not.
11269   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11270   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11271   const APInt &C1 = C1Node->getAPIntValue();
11272   const APInt &C2 = C2Node->getAPIntValue();
11273   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11274     return false;
11275 
11276   // Default to true and let the DAGCombiner decide.
11277   return true;
11278 }
11279 
11280 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11281     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11282     bool *Fast) const {
11283   if (!VT.isVector())
11284     return false;
11285 
11286   EVT ElemVT = VT.getVectorElementType();
11287   if (Alignment >= ElemVT.getStoreSize()) {
11288     if (Fast)
11289       *Fast = true;
11290     return true;
11291   }
11292 
11293   return false;
11294 }
11295 
11296 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11297     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11298     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11299   bool IsABIRegCopy = CC.hasValue();
11300   EVT ValueVT = Val.getValueType();
11301   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11302     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11303     // and cast to f32.
11304     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11305     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11306     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11307                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11308     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11309     Parts[0] = Val;
11310     return true;
11311   }
11312 
11313   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11314     LLVMContext &Context = *DAG.getContext();
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       // If the element types are different, bitcast to the same element type of
11322       // PartVT first.
11323       // Give an example here, we want copy a <vscale x 1 x i8> value to
11324       // <vscale x 4 x i16>.
11325       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11326       // subvector, then we can bitcast to <vscale x 4 x i16>.
11327       if (ValueEltVT != PartEltVT) {
11328         if (PartVTBitSize > ValueVTBitSize) {
11329           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11330           assert(Count != 0 && "The number of element should not be zero.");
11331           EVT SameEltTypeVT =
11332               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11333           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11334                             DAG.getUNDEF(SameEltTypeVT), Val,
11335                             DAG.getVectorIdxConstant(0, DL));
11336         }
11337         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11338       } else {
11339         Val =
11340             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11341                         Val, DAG.getVectorIdxConstant(0, DL));
11342       }
11343       Parts[0] = Val;
11344       return true;
11345     }
11346   }
11347   return false;
11348 }
11349 
11350 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11351     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11352     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11353   bool IsABIRegCopy = CC.hasValue();
11354   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11355     SDValue Val = Parts[0];
11356 
11357     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11358     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11359     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11360     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11361     return Val;
11362   }
11363 
11364   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11365     LLVMContext &Context = *DAG.getContext();
11366     SDValue Val = Parts[0];
11367     EVT ValueEltVT = ValueVT.getVectorElementType();
11368     EVT PartEltVT = PartVT.getVectorElementType();
11369     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11370     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11371     if (PartVTBitSize % ValueVTBitSize == 0) {
11372       assert(PartVTBitSize >= ValueVTBitSize);
11373       EVT SameEltTypeVT = ValueVT;
11374       // If the element types are different, convert it to the same element type
11375       // of PartVT.
11376       // Give an example here, we want copy a <vscale x 1 x i8> value from
11377       // <vscale x 4 x i16>.
11378       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11379       // then we can extract <vscale x 1 x i8>.
11380       if (ValueEltVT != PartEltVT) {
11381         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11382         assert(Count != 0 && "The number of element should not be zero.");
11383         SameEltTypeVT =
11384             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11385         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11386       }
11387       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11388                         DAG.getVectorIdxConstant(0, DL));
11389       return Val;
11390     }
11391   }
11392   return SDValue();
11393 }
11394 
11395 SDValue
11396 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11397                                    SelectionDAG &DAG,
11398                                    SmallVectorImpl<SDNode *> &Created) const {
11399   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11400   if (isIntDivCheap(N->getValueType(0), Attr))
11401     return SDValue(N, 0); // Lower SDIV as SDIV
11402 
11403   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11404          "Unexpected divisor!");
11405 
11406   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11407   if (!Subtarget.hasStdExtZbt())
11408     return SDValue();
11409 
11410   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11411   // Besides, more critical path instructions will be generated when dividing
11412   // by 2. So we keep using the original DAGs for these cases.
11413   unsigned Lg2 = Divisor.countTrailingZeros();
11414   if (Lg2 == 1 || Lg2 >= 12)
11415     return SDValue();
11416 
11417   // fold (sdiv X, pow2)
11418   EVT VT = N->getValueType(0);
11419   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11420     return SDValue();
11421 
11422   SDLoc DL(N);
11423   SDValue N0 = N->getOperand(0);
11424   SDValue Zero = DAG.getConstant(0, DL, VT);
11425   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11426 
11427   // Add (N0 < 0) ? Pow2 - 1 : 0;
11428   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11429   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11430   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11431 
11432   Created.push_back(Cmp.getNode());
11433   Created.push_back(Add.getNode());
11434   Created.push_back(Sel.getNode());
11435 
11436   // Divide by pow2.
11437   SDValue SRA =
11438       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11439 
11440   // If we're dividing by a positive value, we're done.  Otherwise, we must
11441   // negate the result.
11442   if (Divisor.isNonNegative())
11443     return SRA;
11444 
11445   Created.push_back(SRA.getNode());
11446   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11447 }
11448 
11449 #define GET_REGISTER_MATCHER
11450 #include "RISCVGenAsmMatcher.inc"
11451 
11452 Register
11453 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11454                                        const MachineFunction &MF) const {
11455   Register Reg = MatchRegisterAltName(RegName);
11456   if (Reg == RISCV::NoRegister)
11457     Reg = MatchRegisterName(RegName);
11458   if (Reg == RISCV::NoRegister)
11459     report_fatal_error(
11460         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11461   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11462   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11463     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11464                              StringRef(RegName) + "\"."));
11465   return Reg;
11466 }
11467 
11468 namespace llvm {
11469 namespace RISCVVIntrinsicsTable {
11470 
11471 #define GET_RISCVVIntrinsicsTable_IMPL
11472 #include "RISCVGenSearchableTables.inc"
11473 
11474 } // namespace RISCVVIntrinsicsTable
11475 
11476 } // namespace llvm
11477