1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/IntrinsicsRISCV.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "riscv-lower"
44 
45 STATISTIC(NumTailCalls, "Number of tail calls");
46 
47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
48                                          const RISCVSubtarget &STI)
49     : TargetLowering(TM), Subtarget(STI) {
50 
51   if (Subtarget.isRV32E())
52     report_fatal_error("Codegen not yet implemented for RV32E");
53 
54   RISCVABI::ABI ABI = Subtarget.getTargetABI();
55   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
56 
57   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
58       !Subtarget.hasStdExtF()) {
59     errs() << "Hard-float 'f' ABI can't be used for a target that "
60                 "doesn't support the F instruction set extension (ignoring "
61                           "target-abi)\n";
62     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
63   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
64              !Subtarget.hasStdExtD()) {
65     errs() << "Hard-float 'd' ABI can't be used for a target that "
66               "doesn't support the D instruction set extension (ignoring "
67               "target-abi)\n";
68     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
69   }
70 
71   switch (ABI) {
72   default:
73     report_fatal_error("Don't know how to lower this ABI");
74   case RISCVABI::ABI_ILP32:
75   case RISCVABI::ABI_ILP32F:
76   case RISCVABI::ABI_ILP32D:
77   case RISCVABI::ABI_LP64:
78   case RISCVABI::ABI_LP64F:
79   case RISCVABI::ABI_LP64D:
80     break;
81   }
82 
83   MVT XLenVT = Subtarget.getXLenVT();
84 
85   // Set up the register classes.
86   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
87 
88   if (Subtarget.hasStdExtZfh())
89     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
90   if (Subtarget.hasStdExtF())
91     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
92   if (Subtarget.hasStdExtD())
93     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
94 
95   static const MVT::SimpleValueType BoolVecVTs[] = {
96       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
97       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
98   static const MVT::SimpleValueType IntVecVTs[] = {
99       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
100       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
101       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
102       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
103       MVT::nxv4i64, MVT::nxv8i64};
104   static const MVT::SimpleValueType F16VecVTs[] = {
105       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
106       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
107   static const MVT::SimpleValueType F32VecVTs[] = {
108       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
109   static const MVT::SimpleValueType F64VecVTs[] = {
110       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
111 
112   if (Subtarget.hasStdExtV()) {
113     auto addRegClassForRVV = [this](MVT VT) {
114       unsigned Size = VT.getSizeInBits().getKnownMinValue();
115       assert(Size <= 512 && isPowerOf2_32(Size));
116       const TargetRegisterClass *RC;
117       if (Size <= 64)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 128)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 256)
122         RC = &RISCV::VRM4RegClass;
123       else
124         RC = &RISCV::VRM8RegClass;
125 
126       addRegisterClass(VT, RC);
127     };
128 
129     for (MVT VT : BoolVecVTs)
130       addRegClassForRVV(VT);
131     for (MVT VT : IntVecVTs)
132       addRegClassForRVV(VT);
133 
134     if (Subtarget.hasStdExtZfh())
135       for (MVT VT : F16VecVTs)
136         addRegClassForRVV(VT);
137 
138     if (Subtarget.hasStdExtF())
139       for (MVT VT : F32VecVTs)
140         addRegClassForRVV(VT);
141 
142     if (Subtarget.hasStdExtD())
143       for (MVT VT : F64VecVTs)
144         addRegClassForRVV(VT);
145 
146     if (Subtarget.useRVVForFixedLengthVectors()) {
147       auto addRegClassForFixedVectors = [this](MVT VT) {
148         MVT ContainerVT = getContainerForFixedLengthVector(VT);
149         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
150         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
151         addRegisterClass(VT, TRI.getRegClass(RCID));
152       };
153       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
154         if (useRVVForFixedLengthVectorVT(VT))
155           addRegClassForFixedVectors(VT);
156 
157       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
158         if (useRVVForFixedLengthVectorVT(VT))
159           addRegClassForFixedVectors(VT);
160     }
161   }
162 
163   // Compute derived properties from the register classes.
164   computeRegisterProperties(STI.getRegisterInfo());
165 
166   setStackPointerRegisterToSaveRestore(RISCV::X2);
167 
168   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
169     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
170 
171   // TODO: add all necessary setOperationAction calls.
172   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
173 
174   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
175   setOperationAction(ISD::BR_CC, XLenVT, Expand);
176   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
177   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
178 
179   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
180   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
181 
182   setOperationAction(ISD::VASTART, MVT::Other, Custom);
183   setOperationAction(ISD::VAARG, MVT::Other, Expand);
184   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
185   setOperationAction(ISD::VAEND, MVT::Other, Expand);
186 
187   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
188   if (!Subtarget.hasStdExtZbb()) {
189     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
190     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
191   }
192 
193   if (Subtarget.is64Bit()) {
194     setOperationAction(ISD::ADD, MVT::i32, Custom);
195     setOperationAction(ISD::SUB, MVT::i32, Custom);
196     setOperationAction(ISD::SHL, MVT::i32, Custom);
197     setOperationAction(ISD::SRA, MVT::i32, Custom);
198     setOperationAction(ISD::SRL, MVT::i32, Custom);
199 
200     setOperationAction(ISD::UADDO, MVT::i32, Custom);
201     setOperationAction(ISD::USUBO, MVT::i32, Custom);
202     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
203     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
204   } else {
205     setLibcallName(RTLIB::SHL_I128, nullptr);
206     setLibcallName(RTLIB::SRL_I128, nullptr);
207     setLibcallName(RTLIB::SRA_I128, nullptr);
208     setLibcallName(RTLIB::MUL_I128, nullptr);
209     setLibcallName(RTLIB::MULO_I64, nullptr);
210   }
211 
212   if (!Subtarget.hasStdExtM()) {
213     setOperationAction(ISD::MUL, XLenVT, Expand);
214     setOperationAction(ISD::MULHS, XLenVT, Expand);
215     setOperationAction(ISD::MULHU, XLenVT, Expand);
216     setOperationAction(ISD::SDIV, XLenVT, Expand);
217     setOperationAction(ISD::UDIV, XLenVT, Expand);
218     setOperationAction(ISD::SREM, XLenVT, Expand);
219     setOperationAction(ISD::UREM, XLenVT, Expand);
220   } else {
221     if (Subtarget.is64Bit()) {
222       setOperationAction(ISD::MUL, MVT::i32, Custom);
223       setOperationAction(ISD::MUL, MVT::i128, Custom);
224 
225       setOperationAction(ISD::SDIV, MVT::i8, Custom);
226       setOperationAction(ISD::UDIV, MVT::i8, Custom);
227       setOperationAction(ISD::UREM, MVT::i8, Custom);
228       setOperationAction(ISD::SDIV, MVT::i16, Custom);
229       setOperationAction(ISD::UDIV, MVT::i16, Custom);
230       setOperationAction(ISD::UREM, MVT::i16, Custom);
231       setOperationAction(ISD::SDIV, MVT::i32, Custom);
232       setOperationAction(ISD::UDIV, MVT::i32, Custom);
233       setOperationAction(ISD::UREM, MVT::i32, Custom);
234     } else {
235       setOperationAction(ISD::MUL, MVT::i64, Custom);
236     }
237   }
238 
239   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
240   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
241   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
242   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
243 
244   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
245   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
246   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
247 
248   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
249     if (Subtarget.is64Bit()) {
250       setOperationAction(ISD::ROTL, MVT::i32, Custom);
251       setOperationAction(ISD::ROTR, MVT::i32, Custom);
252     }
253   } else {
254     setOperationAction(ISD::ROTL, XLenVT, Expand);
255     setOperationAction(ISD::ROTR, XLenVT, Expand);
256   }
257 
258   if (Subtarget.hasStdExtZbp()) {
259     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
260     // more combining.
261     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
262     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
263     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
264     // BSWAP i8 doesn't exist.
265     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
266     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
267 
268     if (Subtarget.is64Bit()) {
269       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
270       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
271     }
272   } else {
273     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
274     // pattern match it directly in isel.
275     setOperationAction(ISD::BSWAP, XLenVT,
276                        Subtarget.hasStdExtZbb() ? Legal : Expand);
277   }
278 
279   if (Subtarget.hasStdExtZbb()) {
280     setOperationAction(ISD::SMIN, XLenVT, Legal);
281     setOperationAction(ISD::SMAX, XLenVT, Legal);
282     setOperationAction(ISD::UMIN, XLenVT, Legal);
283     setOperationAction(ISD::UMAX, XLenVT, Legal);
284 
285     if (Subtarget.is64Bit()) {
286       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
287       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
288       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
289       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
290     }
291   } else {
292     setOperationAction(ISD::CTTZ, XLenVT, Expand);
293     setOperationAction(ISD::CTLZ, XLenVT, Expand);
294     setOperationAction(ISD::CTPOP, XLenVT, Expand);
295   }
296 
297   if (Subtarget.hasStdExtZbt()) {
298     setOperationAction(ISD::FSHL, XLenVT, Custom);
299     setOperationAction(ISD::FSHR, XLenVT, Custom);
300     setOperationAction(ISD::SELECT, XLenVT, Legal);
301 
302     if (Subtarget.is64Bit()) {
303       setOperationAction(ISD::FSHL, MVT::i32, Custom);
304       setOperationAction(ISD::FSHR, MVT::i32, Custom);
305     }
306   } else {
307     setOperationAction(ISD::SELECT, XLenVT, Custom);
308   }
309 
310   static const ISD::CondCode FPCCToExpand[] = {
311       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
312       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
313       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
314 
315   static const ISD::NodeType FPOpToExpand[] = {
316       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
317       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
318 
319   if (Subtarget.hasStdExtZfh())
320     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
321 
322   if (Subtarget.hasStdExtZfh()) {
323     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
324     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
325     setOperationAction(ISD::LRINT, MVT::f16, Legal);
326     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
327     setOperationAction(ISD::LROUND, MVT::f16, Legal);
328     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
329     for (auto CC : FPCCToExpand)
330       setCondCodeAction(CC, MVT::f16, Expand);
331     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
332     setOperationAction(ISD::SELECT, MVT::f16, Custom);
333     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
334     for (auto Op : FPOpToExpand)
335       setOperationAction(Op, MVT::f16, Expand);
336   }
337 
338   if (Subtarget.hasStdExtF()) {
339     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
340     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
341     setOperationAction(ISD::LRINT, MVT::f32, Legal);
342     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
343     setOperationAction(ISD::LROUND, MVT::f32, Legal);
344     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
345     for (auto CC : FPCCToExpand)
346       setCondCodeAction(CC, MVT::f32, Expand);
347     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
348     setOperationAction(ISD::SELECT, MVT::f32, Custom);
349     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
350     for (auto Op : FPOpToExpand)
351       setOperationAction(Op, MVT::f32, Expand);
352     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
353     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
354   }
355 
356   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
357     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
358 
359   if (Subtarget.hasStdExtD()) {
360     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
361     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
362     setOperationAction(ISD::LRINT, MVT::f64, Legal);
363     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
364     setOperationAction(ISD::LROUND, MVT::f64, Legal);
365     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
366     for (auto CC : FPCCToExpand)
367       setCondCodeAction(CC, MVT::f64, Expand);
368     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
369     setOperationAction(ISD::SELECT, MVT::f64, Custom);
370     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
371     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
372     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
373     for (auto Op : FPOpToExpand)
374       setOperationAction(Op, MVT::f64, Expand);
375     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
376     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377   }
378 
379   if (Subtarget.is64Bit()) {
380     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
382     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
383     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
384   }
385 
386   if (Subtarget.hasStdExtF()) {
387     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
388     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
389 
390     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
391     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
392   }
393 
394   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
395   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
396   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
397   setOperationAction(ISD::JumpTable, XLenVT, Custom);
398 
399   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
400 
401   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
402   // Unfortunately this can't be determined just from the ISA naming string.
403   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
404                      Subtarget.is64Bit() ? Legal : Custom);
405 
406   setOperationAction(ISD::TRAP, MVT::Other, Legal);
407   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
408   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
409   if (Subtarget.is64Bit())
410     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
411 
412   if (Subtarget.hasStdExtA()) {
413     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
414     setMinCmpXchgSizeInBits(32);
415   } else {
416     setMaxAtomicSizeInBitsSupported(0);
417   }
418 
419   setBooleanContents(ZeroOrOneBooleanContent);
420 
421   if (Subtarget.hasStdExtV()) {
422     setBooleanVectorContents(ZeroOrOneBooleanContent);
423 
424     setOperationAction(ISD::VSCALE, XLenVT, Custom);
425 
426     // RVV intrinsics may have illegal operands.
427     // We also need to custom legalize vmv.x.s.
428     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
429     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
430     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
431     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
432     if (Subtarget.is64Bit()) {
433       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
434     } else {
435       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
436       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
437     }
438 
439     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
440     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
441 
442     static const unsigned IntegerVPOps[] = {
443         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
444         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
445         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
446         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
447         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
448         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
449         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN};
450 
451     static const unsigned FloatingPointVPOps[] = {
452         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
453         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
454         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX};
455 
456     if (!Subtarget.is64Bit()) {
457       // We must custom-lower certain vXi64 operations on RV32 due to the vector
458       // element type being illegal.
459       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
460       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
461 
462       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
463       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
464       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
465       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
466       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
467       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
468       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
469       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
470 
471       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
472       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
473       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
474       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
475       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
476       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
477       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
478       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
479     }
480 
481     for (MVT VT : BoolVecVTs) {
482       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
483 
484       // Mask VTs are custom-expanded into a series of standard nodes
485       setOperationAction(ISD::TRUNCATE, VT, Custom);
486       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
487       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
488       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
489 
490       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
491       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
492 
493       setOperationAction(ISD::SELECT, VT, Custom);
494       setOperationAction(ISD::SELECT_CC, VT, Expand);
495       setOperationAction(ISD::VSELECT, VT, Expand);
496 
497       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
498       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
499       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
500 
501       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
502       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
503       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
504 
505       // RVV has native int->float & float->int conversions where the
506       // element type sizes are within one power-of-two of each other. Any
507       // wider distances between type sizes have to be lowered as sequences
508       // which progressively narrow the gap in stages.
509       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
510       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
511       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
512       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
513 
514       // Expand all extending loads to types larger than this, and truncating
515       // stores from types larger than this.
516       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
517         setTruncStoreAction(OtherVT, VT, Expand);
518         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
519         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
520         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
521       }
522     }
523 
524     for (MVT VT : IntVecVTs) {
525       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
526       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
527 
528       setOperationAction(ISD::SMIN, VT, Legal);
529       setOperationAction(ISD::SMAX, VT, Legal);
530       setOperationAction(ISD::UMIN, VT, Legal);
531       setOperationAction(ISD::UMAX, VT, Legal);
532 
533       setOperationAction(ISD::ROTL, VT, Expand);
534       setOperationAction(ISD::ROTR, VT, Expand);
535 
536       // Custom-lower extensions and truncations from/to mask types.
537       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
538       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
539       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
540 
541       // RVV has native int->float & float->int conversions where the
542       // element type sizes are within one power-of-two of each other. Any
543       // wider distances between type sizes have to be lowered as sequences
544       // which progressively narrow the gap in stages.
545       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
546       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
547       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
548       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
549 
550       setOperationAction(ISD::SADDSAT, VT, Legal);
551       setOperationAction(ISD::UADDSAT, VT, Legal);
552       setOperationAction(ISD::SSUBSAT, VT, Legal);
553       setOperationAction(ISD::USUBSAT, VT, Legal);
554 
555       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
556       // nodes which truncate by one power of two at a time.
557       setOperationAction(ISD::TRUNCATE, VT, Custom);
558 
559       // Custom-lower insert/extract operations to simplify patterns.
560       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
561       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
562 
563       // Custom-lower reduction operations to set up the corresponding custom
564       // nodes' operands.
565       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
566       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
567       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
568       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
569       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
570       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
571       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
572       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
573 
574       for (unsigned VPOpc : IntegerVPOps)
575         setOperationAction(VPOpc, VT, Custom);
576 
577       setOperationAction(ISD::LOAD, VT, Custom);
578       setOperationAction(ISD::STORE, VT, Custom);
579 
580       setOperationAction(ISD::MLOAD, VT, Custom);
581       setOperationAction(ISD::MSTORE, VT, Custom);
582       setOperationAction(ISD::MGATHER, VT, Custom);
583       setOperationAction(ISD::MSCATTER, VT, Custom);
584 
585       setOperationAction(ISD::VP_LOAD, VT, Custom);
586       setOperationAction(ISD::VP_STORE, VT, Custom);
587       setOperationAction(ISD::VP_GATHER, VT, Custom);
588       setOperationAction(ISD::VP_SCATTER, VT, Custom);
589 
590       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
591       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
592       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
593 
594       setOperationAction(ISD::SELECT, VT, Custom);
595       setOperationAction(ISD::SELECT_CC, VT, Expand);
596 
597       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
598       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
599 
600       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
601         setTruncStoreAction(VT, OtherVT, Expand);
602         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
603         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
604         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
605       }
606     }
607 
608     // Expand various CCs to best match the RVV ISA, which natively supports UNE
609     // but no other unordered comparisons, and supports all ordered comparisons
610     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
611     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
612     // and we pattern-match those back to the "original", swapping operands once
613     // more. This way we catch both operations and both "vf" and "fv" forms with
614     // fewer patterns.
615     static const ISD::CondCode VFPCCToExpand[] = {
616         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
617         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
618         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
619     };
620 
621     // Sets common operation actions on RVV floating-point vector types.
622     const auto SetCommonVFPActions = [&](MVT VT) {
623       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
624       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
625       // sizes are within one power-of-two of each other. Therefore conversions
626       // between vXf16 and vXf64 must be lowered as sequences which convert via
627       // vXf32.
628       setOperationAction(ISD::FP_ROUND, VT, Custom);
629       setOperationAction(ISD::FP_EXTEND, VT, Custom);
630       // Custom-lower insert/extract operations to simplify patterns.
631       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
632       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
633       // Expand various condition codes (explained above).
634       for (auto CC : VFPCCToExpand)
635         setCondCodeAction(CC, VT, Expand);
636 
637       setOperationAction(ISD::FMINNUM, VT, Legal);
638       setOperationAction(ISD::FMAXNUM, VT, Legal);
639 
640       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
641       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
642       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
643       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
644 
645       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
646 
647       setOperationAction(ISD::LOAD, VT, Custom);
648       setOperationAction(ISD::STORE, VT, Custom);
649 
650       setOperationAction(ISD::MLOAD, VT, Custom);
651       setOperationAction(ISD::MSTORE, VT, Custom);
652       setOperationAction(ISD::MGATHER, VT, Custom);
653       setOperationAction(ISD::MSCATTER, VT, Custom);
654 
655       setOperationAction(ISD::VP_LOAD, VT, Custom);
656       setOperationAction(ISD::VP_STORE, VT, Custom);
657       setOperationAction(ISD::VP_GATHER, VT, Custom);
658       setOperationAction(ISD::VP_SCATTER, VT, Custom);
659 
660       setOperationAction(ISD::SELECT, VT, Custom);
661       setOperationAction(ISD::SELECT_CC, VT, Expand);
662 
663       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
664       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
665       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
666 
667       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
668 
669       for (unsigned VPOpc : FloatingPointVPOps)
670         setOperationAction(VPOpc, VT, Custom);
671     };
672 
673     // Sets common extload/truncstore actions on RVV floating-point vector
674     // types.
675     const auto SetCommonVFPExtLoadTruncStoreActions =
676         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
677           for (auto SmallVT : SmallerVTs) {
678             setTruncStoreAction(VT, SmallVT, Expand);
679             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
680           }
681         };
682 
683     if (Subtarget.hasStdExtZfh())
684       for (MVT VT : F16VecVTs)
685         SetCommonVFPActions(VT);
686 
687     for (MVT VT : F32VecVTs) {
688       if (Subtarget.hasStdExtF())
689         SetCommonVFPActions(VT);
690       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
691     }
692 
693     for (MVT VT : F64VecVTs) {
694       if (Subtarget.hasStdExtD())
695         SetCommonVFPActions(VT);
696       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
697       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
698     }
699 
700     if (Subtarget.useRVVForFixedLengthVectors()) {
701       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
702         if (!useRVVForFixedLengthVectorVT(VT))
703           continue;
704 
705         // By default everything must be expanded.
706         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
707           setOperationAction(Op, VT, Expand);
708         for (MVT OtherVT : MVT::integer_fixedlen_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         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
716         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
717         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
718 
719         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
720         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
721 
722         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
723         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
724 
725         setOperationAction(ISD::LOAD, VT, Custom);
726         setOperationAction(ISD::STORE, VT, Custom);
727 
728         setOperationAction(ISD::SETCC, VT, Custom);
729 
730         setOperationAction(ISD::SELECT, VT, Custom);
731 
732         setOperationAction(ISD::TRUNCATE, VT, Custom);
733 
734         setOperationAction(ISD::BITCAST, VT, Custom);
735 
736         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
737         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
738         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
739 
740         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
741         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
742         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
743 
744         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
745         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
746         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
747         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
748 
749         // Operations below are different for between masks and other vectors.
750         if (VT.getVectorElementType() == MVT::i1) {
751           setOperationAction(ISD::AND, VT, Custom);
752           setOperationAction(ISD::OR, VT, Custom);
753           setOperationAction(ISD::XOR, VT, Custom);
754           continue;
755         }
756 
757         // Use SPLAT_VECTOR to prevent type legalization from destroying the
758         // splats when type legalizing i64 scalar on RV32.
759         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
760         // improvements first.
761         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
762           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
763           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
764         }
765 
766         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
767         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
768 
769         setOperationAction(ISD::MLOAD, VT, Custom);
770         setOperationAction(ISD::MSTORE, VT, Custom);
771         setOperationAction(ISD::MGATHER, VT, Custom);
772         setOperationAction(ISD::MSCATTER, VT, Custom);
773 
774         setOperationAction(ISD::VP_LOAD, VT, Custom);
775         setOperationAction(ISD::VP_STORE, VT, Custom);
776         setOperationAction(ISD::VP_GATHER, VT, Custom);
777         setOperationAction(ISD::VP_SCATTER, VT, Custom);
778 
779         setOperationAction(ISD::ADD, VT, Custom);
780         setOperationAction(ISD::MUL, VT, Custom);
781         setOperationAction(ISD::SUB, VT, Custom);
782         setOperationAction(ISD::AND, VT, Custom);
783         setOperationAction(ISD::OR, VT, Custom);
784         setOperationAction(ISD::XOR, VT, Custom);
785         setOperationAction(ISD::SDIV, VT, Custom);
786         setOperationAction(ISD::SREM, VT, Custom);
787         setOperationAction(ISD::UDIV, VT, Custom);
788         setOperationAction(ISD::UREM, VT, Custom);
789         setOperationAction(ISD::SHL, VT, Custom);
790         setOperationAction(ISD::SRA, VT, Custom);
791         setOperationAction(ISD::SRL, VT, Custom);
792 
793         setOperationAction(ISD::SMIN, VT, Custom);
794         setOperationAction(ISD::SMAX, VT, Custom);
795         setOperationAction(ISD::UMIN, VT, Custom);
796         setOperationAction(ISD::UMAX, VT, Custom);
797         setOperationAction(ISD::ABS,  VT, Custom);
798 
799         setOperationAction(ISD::MULHS, VT, Custom);
800         setOperationAction(ISD::MULHU, VT, Custom);
801 
802         setOperationAction(ISD::SADDSAT, VT, Custom);
803         setOperationAction(ISD::UADDSAT, VT, Custom);
804         setOperationAction(ISD::SSUBSAT, VT, Custom);
805         setOperationAction(ISD::USUBSAT, VT, Custom);
806 
807         setOperationAction(ISD::VSELECT, VT, Custom);
808         setOperationAction(ISD::SELECT_CC, VT, Expand);
809 
810         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
811         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
812         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
813 
814         // Custom-lower reduction operations to set up the corresponding custom
815         // nodes' operands.
816         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
817         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
818         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
819         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
820         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
821 
822         for (unsigned VPOpc : IntegerVPOps)
823           setOperationAction(VPOpc, VT, Custom);
824       }
825 
826       for (MVT VT : MVT::fp_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::fp_fixedlen_vector_valuetypes()) {
834           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
835           setTruncStoreAction(VT, OtherVT, Expand);
836         }
837 
838         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
839         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
840         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
841 
842         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
843         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
844         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
845         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
846         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
847 
848         setOperationAction(ISD::LOAD, VT, Custom);
849         setOperationAction(ISD::STORE, VT, Custom);
850         setOperationAction(ISD::MLOAD, VT, Custom);
851         setOperationAction(ISD::MSTORE, VT, Custom);
852         setOperationAction(ISD::MGATHER, VT, Custom);
853         setOperationAction(ISD::MSCATTER, VT, Custom);
854 
855         setOperationAction(ISD::VP_LOAD, VT, Custom);
856         setOperationAction(ISD::VP_STORE, VT, Custom);
857         setOperationAction(ISD::VP_GATHER, VT, Custom);
858         setOperationAction(ISD::VP_SCATTER, VT, Custom);
859 
860         setOperationAction(ISD::FADD, VT, Custom);
861         setOperationAction(ISD::FSUB, VT, Custom);
862         setOperationAction(ISD::FMUL, VT, Custom);
863         setOperationAction(ISD::FDIV, VT, Custom);
864         setOperationAction(ISD::FNEG, VT, Custom);
865         setOperationAction(ISD::FABS, VT, Custom);
866         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
867         setOperationAction(ISD::FSQRT, VT, Custom);
868         setOperationAction(ISD::FMA, VT, Custom);
869         setOperationAction(ISD::FMINNUM, VT, Custom);
870         setOperationAction(ISD::FMAXNUM, VT, Custom);
871 
872         setOperationAction(ISD::FP_ROUND, VT, Custom);
873         setOperationAction(ISD::FP_EXTEND, VT, Custom);
874 
875         for (auto CC : VFPCCToExpand)
876           setCondCodeAction(CC, VT, Expand);
877 
878         setOperationAction(ISD::VSELECT, VT, Custom);
879         setOperationAction(ISD::SELECT, VT, Custom);
880         setOperationAction(ISD::SELECT_CC, VT, Expand);
881 
882         setOperationAction(ISD::BITCAST, VT, Custom);
883 
884         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
885         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
886         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
887         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
888 
889         for (unsigned VPOpc : FloatingPointVPOps)
890           setOperationAction(VPOpc, VT, Custom);
891       }
892 
893       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
894       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
895       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
896       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
897       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
898       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
899       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
900       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
901     }
902   }
903 
904   // Function alignments.
905   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
906   setMinFunctionAlignment(FunctionAlignment);
907   setPrefFunctionAlignment(FunctionAlignment);
908 
909   setMinimumJumpTableEntries(5);
910 
911   // Jumps are expensive, compared to logic
912   setJumpIsExpensive();
913 
914   // We can use any register for comparisons
915   setHasMultipleConditionRegisters();
916 
917   setTargetDAGCombine(ISD::ADD);
918   setTargetDAGCombine(ISD::SUB);
919   setTargetDAGCombine(ISD::AND);
920   setTargetDAGCombine(ISD::OR);
921   setTargetDAGCombine(ISD::XOR);
922   setTargetDAGCombine(ISD::ANY_EXTEND);
923   setTargetDAGCombine(ISD::ZERO_EXTEND);
924   if (Subtarget.hasStdExtV()) {
925     setTargetDAGCombine(ISD::FCOPYSIGN);
926     setTargetDAGCombine(ISD::MGATHER);
927     setTargetDAGCombine(ISD::MSCATTER);
928     setTargetDAGCombine(ISD::VP_GATHER);
929     setTargetDAGCombine(ISD::VP_SCATTER);
930     setTargetDAGCombine(ISD::SRA);
931     setTargetDAGCombine(ISD::SRL);
932     setTargetDAGCombine(ISD::SHL);
933   }
934 }
935 
936 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
937                                             LLVMContext &Context,
938                                             EVT VT) const {
939   if (!VT.isVector())
940     return getPointerTy(DL);
941   if (Subtarget.hasStdExtV() &&
942       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
943     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
944   return VT.changeVectorElementTypeToInteger();
945 }
946 
947 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
948   return Subtarget.getXLenVT();
949 }
950 
951 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
952                                              const CallInst &I,
953                                              MachineFunction &MF,
954                                              unsigned Intrinsic) const {
955   switch (Intrinsic) {
956   default:
957     return false;
958   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
959   case Intrinsic::riscv_masked_atomicrmw_add_i32:
960   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
961   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
962   case Intrinsic::riscv_masked_atomicrmw_max_i32:
963   case Intrinsic::riscv_masked_atomicrmw_min_i32:
964   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
965   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
966   case Intrinsic::riscv_masked_cmpxchg_i32: {
967     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
968     Info.opc = ISD::INTRINSIC_W_CHAIN;
969     Info.memVT = MVT::getVT(PtrTy->getElementType());
970     Info.ptrVal = I.getArgOperand(0);
971     Info.offset = 0;
972     Info.align = Align(4);
973     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
974                  MachineMemOperand::MOVolatile;
975     return true;
976   }
977   case Intrinsic::riscv_masked_strided_load:
978     Info.opc = ISD::INTRINSIC_W_CHAIN;
979     Info.ptrVal = I.getArgOperand(1);
980     Info.memVT = MVT::getVT(I.getType()->getScalarType());
981     Info.align = Align(I.getType()->getScalarSizeInBits() / 8);
982     Info.size = MemoryLocation::UnknownSize;
983     Info.flags |= MachineMemOperand::MOLoad;
984     return true;
985   case Intrinsic::riscv_masked_strided_store:
986     Info.opc = ISD::INTRINSIC_VOID;
987     Info.ptrVal = I.getArgOperand(1);
988     Info.memVT = MVT::getVT(I.getArgOperand(0)->getType()->getScalarType());
989     Info.align =
990         Align(I.getArgOperand(0)->getType()->getScalarSizeInBits() / 8);
991     Info.size = MemoryLocation::UnknownSize;
992     Info.flags |= MachineMemOperand::MOStore;
993     return true;
994   }
995 }
996 
997 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
998                                                 const AddrMode &AM, Type *Ty,
999                                                 unsigned AS,
1000                                                 Instruction *I) const {
1001   // No global is ever allowed as a base.
1002   if (AM.BaseGV)
1003     return false;
1004 
1005   // Require a 12-bit signed offset.
1006   if (!isInt<12>(AM.BaseOffs))
1007     return false;
1008 
1009   switch (AM.Scale) {
1010   case 0: // "r+i" or just "i", depending on HasBaseReg.
1011     break;
1012   case 1:
1013     if (!AM.HasBaseReg) // allow "r+i".
1014       break;
1015     return false; // disallow "r+r" or "r+r+i".
1016   default:
1017     return false;
1018   }
1019 
1020   return true;
1021 }
1022 
1023 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1024   return isInt<12>(Imm);
1025 }
1026 
1027 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1028   return isInt<12>(Imm);
1029 }
1030 
1031 // On RV32, 64-bit integers are split into their high and low parts and held
1032 // in two different registers, so the trunc is free since the low register can
1033 // just be used.
1034 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1035   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1036     return false;
1037   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1038   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1039   return (SrcBits == 64 && DestBits == 32);
1040 }
1041 
1042 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1043   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1044       !SrcVT.isInteger() || !DstVT.isInteger())
1045     return false;
1046   unsigned SrcBits = SrcVT.getSizeInBits();
1047   unsigned DestBits = DstVT.getSizeInBits();
1048   return (SrcBits == 64 && DestBits == 32);
1049 }
1050 
1051 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1052   // Zexts are free if they can be combined with a load.
1053   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1054     EVT MemVT = LD->getMemoryVT();
1055     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1056          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1057         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1058          LD->getExtensionType() == ISD::ZEXTLOAD))
1059       return true;
1060   }
1061 
1062   return TargetLowering::isZExtFree(Val, VT2);
1063 }
1064 
1065 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1066   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1067 }
1068 
1069 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1070   return Subtarget.hasStdExtZbb();
1071 }
1072 
1073 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1074   return Subtarget.hasStdExtZbb();
1075 }
1076 
1077 /// Check if sinking \p I's operands to I's basic block is profitable, because
1078 /// the operands can be folded into a target instruction, e.g.
1079 /// splats of scalars can fold into vector instructions.
1080 bool RISCVTargetLowering::shouldSinkOperands(
1081     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1082   using namespace llvm::PatternMatch;
1083 
1084   if (!I->getType()->isVectorTy() || !Subtarget.hasStdExtV())
1085     return false;
1086 
1087   auto IsSinker = [&](Instruction *I, int Operand) {
1088     switch (I->getOpcode()) {
1089     case Instruction::Add:
1090     case Instruction::Sub:
1091     case Instruction::Mul:
1092     case Instruction::And:
1093     case Instruction::Or:
1094     case Instruction::Xor:
1095     case Instruction::FAdd:
1096     case Instruction::FSub:
1097     case Instruction::FMul:
1098     case Instruction::FDiv:
1099       return true;
1100     case Instruction::Shl:
1101     case Instruction::LShr:
1102     case Instruction::AShr:
1103       return Operand == 1;
1104     case Instruction::Call:
1105       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1106         switch (II->getIntrinsicID()) {
1107         case Intrinsic::fma:
1108           return Operand == 0 || Operand == 1;
1109         default:
1110           return false;
1111         }
1112       }
1113       return false;
1114     default:
1115       return false;
1116     }
1117   };
1118 
1119   for (auto OpIdx : enumerate(I->operands())) {
1120     if (!IsSinker(I, OpIdx.index()))
1121       continue;
1122 
1123     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1124     // Make sure we are not already sinking this operand
1125     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1126       continue;
1127 
1128     // We are looking for a splat that can be sunk.
1129     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1130                              m_Undef(), m_ZeroMask())))
1131       continue;
1132 
1133     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1134     // and vector registers
1135     for (Use &U : Op->uses()) {
1136       Instruction *Insn = cast<Instruction>(U.getUser());
1137       if (!IsSinker(Insn, U.getOperandNo()))
1138         return false;
1139     }
1140 
1141     Ops.push_back(&Op->getOperandUse(0));
1142     Ops.push_back(&OpIdx.value());
1143   }
1144   return true;
1145 }
1146 
1147 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1148                                        bool ForCodeSize) const {
1149   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1150     return false;
1151   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1152     return false;
1153   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1154     return false;
1155   if (Imm.isNegZero())
1156     return false;
1157   return Imm.isZero();
1158 }
1159 
1160 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1161   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1162          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1163          (VT == MVT::f64 && Subtarget.hasStdExtD());
1164 }
1165 
1166 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1167                                                       CallingConv::ID CC,
1168                                                       EVT VT) const {
1169   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1170   // end up using a GPR but that will be decided based on ABI.
1171   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1172     return MVT::f32;
1173 
1174   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1175 }
1176 
1177 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1178                                                            CallingConv::ID CC,
1179                                                            EVT VT) const {
1180   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1181   // end up using a GPR but that will be decided based on ABI.
1182   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1183     return 1;
1184 
1185   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1186 }
1187 
1188 // Changes the condition code and swaps operands if necessary, so the SetCC
1189 // operation matches one of the comparisons supported directly by branches
1190 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1191 // with 1/-1.
1192 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1193                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1194   // Convert X > -1 to X >= 0.
1195   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1196     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1197     CC = ISD::SETGE;
1198     return;
1199   }
1200   // Convert X < 1 to 0 >= X.
1201   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1202     RHS = LHS;
1203     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1204     CC = ISD::SETGE;
1205     return;
1206   }
1207 
1208   switch (CC) {
1209   default:
1210     break;
1211   case ISD::SETGT:
1212   case ISD::SETLE:
1213   case ISD::SETUGT:
1214   case ISD::SETULE:
1215     CC = ISD::getSetCCSwappedOperands(CC);
1216     std::swap(LHS, RHS);
1217     break;
1218   }
1219 }
1220 
1221 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1222   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1223   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1224   if (VT.getVectorElementType() == MVT::i1)
1225     KnownSize *= 8;
1226 
1227   switch (KnownSize) {
1228   default:
1229     llvm_unreachable("Invalid LMUL.");
1230   case 8:
1231     return RISCVII::VLMUL::LMUL_F8;
1232   case 16:
1233     return RISCVII::VLMUL::LMUL_F4;
1234   case 32:
1235     return RISCVII::VLMUL::LMUL_F2;
1236   case 64:
1237     return RISCVII::VLMUL::LMUL_1;
1238   case 128:
1239     return RISCVII::VLMUL::LMUL_2;
1240   case 256:
1241     return RISCVII::VLMUL::LMUL_4;
1242   case 512:
1243     return RISCVII::VLMUL::LMUL_8;
1244   }
1245 }
1246 
1247 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1248   switch (LMul) {
1249   default:
1250     llvm_unreachable("Invalid LMUL.");
1251   case RISCVII::VLMUL::LMUL_F8:
1252   case RISCVII::VLMUL::LMUL_F4:
1253   case RISCVII::VLMUL::LMUL_F2:
1254   case RISCVII::VLMUL::LMUL_1:
1255     return RISCV::VRRegClassID;
1256   case RISCVII::VLMUL::LMUL_2:
1257     return RISCV::VRM2RegClassID;
1258   case RISCVII::VLMUL::LMUL_4:
1259     return RISCV::VRM4RegClassID;
1260   case RISCVII::VLMUL::LMUL_8:
1261     return RISCV::VRM8RegClassID;
1262   }
1263 }
1264 
1265 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1266   RISCVII::VLMUL LMUL = getLMUL(VT);
1267   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1268       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1269       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1270       LMUL == RISCVII::VLMUL::LMUL_1) {
1271     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1272                   "Unexpected subreg numbering");
1273     return RISCV::sub_vrm1_0 + Index;
1274   }
1275   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1276     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1277                   "Unexpected subreg numbering");
1278     return RISCV::sub_vrm2_0 + Index;
1279   }
1280   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1281     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1282                   "Unexpected subreg numbering");
1283     return RISCV::sub_vrm4_0 + Index;
1284   }
1285   llvm_unreachable("Invalid vector type.");
1286 }
1287 
1288 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1289   if (VT.getVectorElementType() == MVT::i1)
1290     return RISCV::VRRegClassID;
1291   return getRegClassIDForLMUL(getLMUL(VT));
1292 }
1293 
1294 // Attempt to decompose a subvector insert/extract between VecVT and
1295 // SubVecVT via subregister indices. Returns the subregister index that
1296 // can perform the subvector insert/extract with the given element index, as
1297 // well as the index corresponding to any leftover subvectors that must be
1298 // further inserted/extracted within the register class for SubVecVT.
1299 std::pair<unsigned, unsigned>
1300 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1301     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1302     const RISCVRegisterInfo *TRI) {
1303   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1304                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1305                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1306                 "Register classes not ordered");
1307   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1308   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1309   // Try to compose a subregister index that takes us from the incoming
1310   // LMUL>1 register class down to the outgoing one. At each step we half
1311   // the LMUL:
1312   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1313   // Note that this is not guaranteed to find a subregister index, such as
1314   // when we are extracting from one VR type to another.
1315   unsigned SubRegIdx = RISCV::NoSubRegister;
1316   for (const unsigned RCID :
1317        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1318     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1319       VecVT = VecVT.getHalfNumVectorElementsVT();
1320       bool IsHi =
1321           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1322       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1323                                             getSubregIndexByMVT(VecVT, IsHi));
1324       if (IsHi)
1325         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1326     }
1327   return {SubRegIdx, InsertExtractIdx};
1328 }
1329 
1330 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1331 // stores for those types.
1332 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1333   return !Subtarget.useRVVForFixedLengthVectors() ||
1334          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1335 }
1336 
1337 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1338   if (ScalarTy->isPointerTy())
1339     return true;
1340 
1341   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1342       ScalarTy->isIntegerTy(32) || ScalarTy->isIntegerTy(64))
1343     return true;
1344 
1345   if (ScalarTy->isHalfTy())
1346     return Subtarget.hasStdExtZfh();
1347   if (ScalarTy->isFloatTy())
1348     return Subtarget.hasStdExtF();
1349   if (ScalarTy->isDoubleTy())
1350     return Subtarget.hasStdExtD();
1351 
1352   return false;
1353 }
1354 
1355 static bool useRVVForFixedLengthVectorVT(MVT VT,
1356                                          const RISCVSubtarget &Subtarget) {
1357   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1358   if (!Subtarget.useRVVForFixedLengthVectors())
1359     return false;
1360 
1361   // We only support a set of vector types with a consistent maximum fixed size
1362   // across all supported vector element types to avoid legalization issues.
1363   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1364   // fixed-length vector type we support is 1024 bytes.
1365   if (VT.getFixedSizeInBits() > 1024 * 8)
1366     return false;
1367 
1368   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1369 
1370   MVT EltVT = VT.getVectorElementType();
1371 
1372   // Don't use RVV for vectors we cannot scalarize if required.
1373   switch (EltVT.SimpleTy) {
1374   // i1 is supported but has different rules.
1375   default:
1376     return false;
1377   case MVT::i1:
1378     // Masks can only use a single register.
1379     if (VT.getVectorNumElements() > MinVLen)
1380       return false;
1381     MinVLen /= 8;
1382     break;
1383   case MVT::i8:
1384   case MVT::i16:
1385   case MVT::i32:
1386   case MVT::i64:
1387     break;
1388   case MVT::f16:
1389     if (!Subtarget.hasStdExtZfh())
1390       return false;
1391     break;
1392   case MVT::f32:
1393     if (!Subtarget.hasStdExtF())
1394       return false;
1395     break;
1396   case MVT::f64:
1397     if (!Subtarget.hasStdExtD())
1398       return false;
1399     break;
1400   }
1401 
1402   // Reject elements larger than ELEN.
1403   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1404     return false;
1405 
1406   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1407   // Don't use RVV for types that don't fit.
1408   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1409     return false;
1410 
1411   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1412   // the base fixed length RVV support in place.
1413   if (!VT.isPow2VectorType())
1414     return false;
1415 
1416   return true;
1417 }
1418 
1419 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1420   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1421 }
1422 
1423 // Return the largest legal scalable vector type that matches VT's element type.
1424 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1425                                             const RISCVSubtarget &Subtarget) {
1426   // This may be called before legal types are setup.
1427   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1428           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1429          "Expected legal fixed length vector!");
1430 
1431   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1432   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1433 
1434   MVT EltVT = VT.getVectorElementType();
1435   switch (EltVT.SimpleTy) {
1436   default:
1437     llvm_unreachable("unexpected element type for RVV container");
1438   case MVT::i1:
1439   case MVT::i8:
1440   case MVT::i16:
1441   case MVT::i32:
1442   case MVT::i64:
1443   case MVT::f16:
1444   case MVT::f32:
1445   case MVT::f64: {
1446     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1447     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1448     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1449     unsigned NumElts =
1450         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1451     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1452     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1453     return MVT::getScalableVectorVT(EltVT, NumElts);
1454   }
1455   }
1456 }
1457 
1458 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1459                                             const RISCVSubtarget &Subtarget) {
1460   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1461                                           Subtarget);
1462 }
1463 
1464 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1465   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1466 }
1467 
1468 // Grow V to consume an entire RVV register.
1469 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1470                                        const RISCVSubtarget &Subtarget) {
1471   assert(VT.isScalableVector() &&
1472          "Expected to convert into a scalable vector!");
1473   assert(V.getValueType().isFixedLengthVector() &&
1474          "Expected a fixed length vector operand!");
1475   SDLoc DL(V);
1476   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1477   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1478 }
1479 
1480 // Shrink V so it's just big enough to maintain a VT's worth of data.
1481 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1482                                          const RISCVSubtarget &Subtarget) {
1483   assert(VT.isFixedLengthVector() &&
1484          "Expected to convert into a fixed length vector!");
1485   assert(V.getValueType().isScalableVector() &&
1486          "Expected a scalable vector operand!");
1487   SDLoc DL(V);
1488   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1489   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1490 }
1491 
1492 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1493 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1494 // the vector type that it is contained in.
1495 static std::pair<SDValue, SDValue>
1496 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1497                 const RISCVSubtarget &Subtarget) {
1498   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1499   MVT XLenVT = Subtarget.getXLenVT();
1500   SDValue VL = VecVT.isFixedLengthVector()
1501                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1502                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1503   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1504   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1505   return {Mask, VL};
1506 }
1507 
1508 // As above but assuming the given type is a scalable vector type.
1509 static std::pair<SDValue, SDValue>
1510 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1511                         const RISCVSubtarget &Subtarget) {
1512   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1513   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1514 }
1515 
1516 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1517 // of either is (currently) supported. This can get us into an infinite loop
1518 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1519 // as a ..., etc.
1520 // Until either (or both) of these can reliably lower any node, reporting that
1521 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1522 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1523 // which is not desirable.
1524 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1525     EVT VT, unsigned DefinedValues) const {
1526   return false;
1527 }
1528 
1529 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1530   // Only splats are currently supported.
1531   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1532     return true;
1533 
1534   return false;
1535 }
1536 
1537 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1538   // RISCV FP-to-int conversions saturate to the destination register size, but
1539   // don't produce 0 for nan. We can use a conversion instruction and fix the
1540   // nan case with a compare and a select.
1541   SDValue Src = Op.getOperand(0);
1542 
1543   EVT DstVT = Op.getValueType();
1544   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1545 
1546   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1547   unsigned Opc;
1548   if (SatVT == DstVT)
1549     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1550   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1551     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1552   else
1553     return SDValue();
1554   // FIXME: Support other SatVTs by clamping before or after the conversion.
1555 
1556   SDLoc DL(Op);
1557   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1558 
1559   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1560   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1561 }
1562 
1563 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1564                                  const RISCVSubtarget &Subtarget) {
1565   MVT VT = Op.getSimpleValueType();
1566   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1567 
1568   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1569 
1570   SDLoc DL(Op);
1571   SDValue Mask, VL;
1572   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1573 
1574   unsigned Opc =
1575       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1576   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1577   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1578 }
1579 
1580 struct VIDSequence {
1581   int64_t StepNumerator;
1582   unsigned StepDenominator;
1583   int64_t Addend;
1584 };
1585 
1586 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1587 // to the (non-zero) step S and start value X. This can be then lowered as the
1588 // RVV sequence (VID * S) + X, for example.
1589 // The step S is represented as an integer numerator divided by a positive
1590 // denominator. Note that the implementation currently only identifies
1591 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1592 // cannot detect 2/3, for example.
1593 // Note that this method will also match potentially unappealing index
1594 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1595 // determine whether this is worth generating code for.
1596 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1597   unsigned NumElts = Op.getNumOperands();
1598   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1599   if (!Op.getValueType().isInteger())
1600     return None;
1601 
1602   Optional<unsigned> SeqStepDenom;
1603   Optional<int64_t> SeqStepNum, SeqAddend;
1604   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1605   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1606   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1607     // Assume undef elements match the sequence; we just have to be careful
1608     // when interpolating across them.
1609     if (Op.getOperand(Idx).isUndef())
1610       continue;
1611     // The BUILD_VECTOR must be all constants.
1612     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1613       return None;
1614 
1615     uint64_t Val = Op.getConstantOperandVal(Idx) &
1616                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1617 
1618     if (PrevElt) {
1619       // Calculate the step since the last non-undef element, and ensure
1620       // it's consistent across the entire sequence.
1621       unsigned IdxDiff = Idx - PrevElt->second;
1622       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1623 
1624       // A zero-value value difference means that we're somewhere in the middle
1625       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1626       // step change before evaluating the sequence.
1627       if (ValDiff != 0) {
1628         int64_t Remainder = ValDiff % IdxDiff;
1629         // Normalize the step if it's greater than 1.
1630         if (Remainder != ValDiff) {
1631           // The difference must cleanly divide the element span.
1632           if (Remainder != 0)
1633             return None;
1634           ValDiff /= IdxDiff;
1635           IdxDiff = 1;
1636         }
1637 
1638         if (!SeqStepNum)
1639           SeqStepNum = ValDiff;
1640         else if (ValDiff != SeqStepNum)
1641           return None;
1642 
1643         if (!SeqStepDenom)
1644           SeqStepDenom = IdxDiff;
1645         else if (IdxDiff != *SeqStepDenom)
1646           return None;
1647       }
1648     }
1649 
1650     // Record and/or check any addend.
1651     if (SeqStepNum && SeqStepDenom) {
1652       uint64_t ExpectedVal =
1653           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1654       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1655       if (!SeqAddend)
1656         SeqAddend = Addend;
1657       else if (SeqAddend != Addend)
1658         return None;
1659     }
1660 
1661     // Record this non-undef element for later.
1662     if (!PrevElt || PrevElt->first != Val)
1663       PrevElt = std::make_pair(Val, Idx);
1664   }
1665   // We need to have logged both a step and an addend for this to count as
1666   // a legal index sequence.
1667   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1668     return None;
1669 
1670   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1671 }
1672 
1673 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1674                                  const RISCVSubtarget &Subtarget) {
1675   MVT VT = Op.getSimpleValueType();
1676   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1677 
1678   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1679 
1680   SDLoc DL(Op);
1681   SDValue Mask, VL;
1682   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1683 
1684   MVT XLenVT = Subtarget.getXLenVT();
1685   unsigned NumElts = Op.getNumOperands();
1686 
1687   if (VT.getVectorElementType() == MVT::i1) {
1688     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1689       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1690       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1691     }
1692 
1693     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1694       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1695       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1696     }
1697 
1698     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1699     // scalar integer chunks whose bit-width depends on the number of mask
1700     // bits and XLEN.
1701     // First, determine the most appropriate scalar integer type to use. This
1702     // is at most XLenVT, but may be shrunk to a smaller vector element type
1703     // according to the size of the final vector - use i8 chunks rather than
1704     // XLenVT if we're producing a v8i1. This results in more consistent
1705     // codegen across RV32 and RV64.
1706     unsigned NumViaIntegerBits =
1707         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1708     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1709       // If we have to use more than one INSERT_VECTOR_ELT then this
1710       // optimization is likely to increase code size; avoid peforming it in
1711       // such a case. We can use a load from a constant pool in this case.
1712       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1713         return SDValue();
1714       // Now we can create our integer vector type. Note that it may be larger
1715       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1716       MVT IntegerViaVecVT =
1717           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1718                            divideCeil(NumElts, NumViaIntegerBits));
1719 
1720       uint64_t Bits = 0;
1721       unsigned BitPos = 0, IntegerEltIdx = 0;
1722       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1723 
1724       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1725         // Once we accumulate enough bits to fill our scalar type, insert into
1726         // our vector and clear our accumulated data.
1727         if (I != 0 && I % NumViaIntegerBits == 0) {
1728           if (NumViaIntegerBits <= 32)
1729             Bits = SignExtend64(Bits, 32);
1730           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1731           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1732                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1733           Bits = 0;
1734           BitPos = 0;
1735           IntegerEltIdx++;
1736         }
1737         SDValue V = Op.getOperand(I);
1738         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1739         Bits |= ((uint64_t)BitValue << BitPos);
1740       }
1741 
1742       // Insert the (remaining) scalar value into position in our integer
1743       // vector type.
1744       if (NumViaIntegerBits <= 32)
1745         Bits = SignExtend64(Bits, 32);
1746       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1747       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1748                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1749 
1750       if (NumElts < NumViaIntegerBits) {
1751         // If we're producing a smaller vector than our minimum legal integer
1752         // type, bitcast to the equivalent (known-legal) mask type, and extract
1753         // our final mask.
1754         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1755         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1756         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1757                           DAG.getConstant(0, DL, XLenVT));
1758       } else {
1759         // Else we must have produced an integer type with the same size as the
1760         // mask type; bitcast for the final result.
1761         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1762         Vec = DAG.getBitcast(VT, Vec);
1763       }
1764 
1765       return Vec;
1766     }
1767 
1768     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1769     // vector type, we have a legal equivalently-sized i8 type, so we can use
1770     // that.
1771     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1772     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1773 
1774     SDValue WideVec;
1775     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1776       // For a splat, perform a scalar truncate before creating the wider
1777       // vector.
1778       assert(Splat.getValueType() == XLenVT &&
1779              "Unexpected type for i1 splat value");
1780       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1781                           DAG.getConstant(1, DL, XLenVT));
1782       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1783     } else {
1784       SmallVector<SDValue, 8> Ops(Op->op_values());
1785       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1786       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1787       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1788     }
1789 
1790     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1791   }
1792 
1793   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1794     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1795                                         : RISCVISD::VMV_V_X_VL;
1796     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1797     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1798   }
1799 
1800   // Try and match index sequences, which we can lower to the vid instruction
1801   // with optional modifications. An all-undef vector is matched by
1802   // getSplatValue, above.
1803   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1804     int64_t StepNumerator = SimpleVID->StepNumerator;
1805     unsigned StepDenominator = SimpleVID->StepDenominator;
1806     int64_t Addend = SimpleVID->Addend;
1807     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1808     // threshold since it's the immediate value many RVV instructions accept.
1809     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1810         isInt<5>(Addend)) {
1811       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1812       // Convert right out of the scalable type so we can use standard ISD
1813       // nodes for the rest of the computation. If we used scalable types with
1814       // these, we'd lose the fixed-length vector info and generate worse
1815       // vsetvli code.
1816       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1817       assert(StepNumerator != 0 && "Invalid step");
1818       bool Negate = false;
1819       if (StepNumerator != 1) {
1820         int64_t SplatStepVal = StepNumerator;
1821         unsigned Opcode = ISD::MUL;
1822         if (isPowerOf2_64(std::abs(StepNumerator))) {
1823           Negate = StepNumerator < 0;
1824           Opcode = ISD::SHL;
1825           SplatStepVal = Log2_64(std::abs(StepNumerator));
1826         }
1827         SDValue SplatStep = DAG.getSplatVector(
1828             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1829         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1830       }
1831       if (StepDenominator != 1) {
1832         SDValue SplatStep = DAG.getSplatVector(
1833             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1834         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1835       }
1836       if (Addend != 0 || Negate) {
1837         SDValue SplatAddend =
1838             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1839         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1840       }
1841       return VID;
1842     }
1843   }
1844 
1845   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1846   // when re-interpreted as a vector with a larger element type. For example,
1847   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1848   // could be instead splat as
1849   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1850   // TODO: This optimization could also work on non-constant splats, but it
1851   // would require bit-manipulation instructions to construct the splat value.
1852   SmallVector<SDValue> Sequence;
1853   unsigned EltBitSize = VT.getScalarSizeInBits();
1854   const auto *BV = cast<BuildVectorSDNode>(Op);
1855   if (VT.isInteger() && EltBitSize < 64 &&
1856       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1857       BV->getRepeatedSequence(Sequence) &&
1858       (Sequence.size() * EltBitSize) <= 64) {
1859     unsigned SeqLen = Sequence.size();
1860     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1861     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1862     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1863             ViaIntVT == MVT::i64) &&
1864            "Unexpected sequence type");
1865 
1866     unsigned EltIdx = 0;
1867     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1868     uint64_t SplatValue = 0;
1869     // Construct the amalgamated value which can be splatted as this larger
1870     // vector type.
1871     for (const auto &SeqV : Sequence) {
1872       if (!SeqV.isUndef())
1873         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1874                        << (EltIdx * EltBitSize));
1875       EltIdx++;
1876     }
1877 
1878     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1879     // achieve better constant materializion.
1880     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1881       SplatValue = SignExtend64(SplatValue, 32);
1882 
1883     // Since we can't introduce illegal i64 types at this stage, we can only
1884     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1885     // way we can use RVV instructions to splat.
1886     assert((ViaIntVT.bitsLE(XLenVT) ||
1887             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1888            "Unexpected bitcast sequence");
1889     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1890       SDValue ViaVL =
1891           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1892       MVT ViaContainerVT =
1893           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
1894       SDValue Splat =
1895           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1896                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1897       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1898       return DAG.getBitcast(VT, Splat);
1899     }
1900   }
1901 
1902   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1903   // which constitute a large proportion of the elements. In such cases we can
1904   // splat a vector with the dominant element and make up the shortfall with
1905   // INSERT_VECTOR_ELTs.
1906   // Note that this includes vectors of 2 elements by association. The
1907   // upper-most element is the "dominant" one, allowing us to use a splat to
1908   // "insert" the upper element, and an insert of the lower element at position
1909   // 0, which improves codegen.
1910   SDValue DominantValue;
1911   unsigned MostCommonCount = 0;
1912   DenseMap<SDValue, unsigned> ValueCounts;
1913   unsigned NumUndefElts =
1914       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1915 
1916   // Track the number of scalar loads we know we'd be inserting, estimated as
1917   // any non-zero floating-point constant. Other kinds of element are either
1918   // already in registers or are materialized on demand. The threshold at which
1919   // a vector load is more desirable than several scalar materializion and
1920   // vector-insertion instructions is not known.
1921   unsigned NumScalarLoads = 0;
1922 
1923   for (SDValue V : Op->op_values()) {
1924     if (V.isUndef())
1925       continue;
1926 
1927     ValueCounts.insert(std::make_pair(V, 0));
1928     unsigned &Count = ValueCounts[V];
1929 
1930     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
1931       NumScalarLoads += !CFP->isExactlyValue(+0.0);
1932 
1933     // Is this value dominant? In case of a tie, prefer the highest element as
1934     // it's cheaper to insert near the beginning of a vector than it is at the
1935     // end.
1936     if (++Count >= MostCommonCount) {
1937       DominantValue = V;
1938       MostCommonCount = Count;
1939     }
1940   }
1941 
1942   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1943   unsigned NumDefElts = NumElts - NumUndefElts;
1944   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1945 
1946   // Don't perform this optimization when optimizing for size, since
1947   // materializing elements and inserting them tends to cause code bloat.
1948   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
1949       ((MostCommonCount > DominantValueCountThreshold) ||
1950        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
1951     // Start by splatting the most common element.
1952     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
1953 
1954     DenseSet<SDValue> Processed{DominantValue};
1955     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
1956     for (const auto &OpIdx : enumerate(Op->ops())) {
1957       const SDValue &V = OpIdx.value();
1958       if (V.isUndef() || !Processed.insert(V).second)
1959         continue;
1960       if (ValueCounts[V] == 1) {
1961         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
1962                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
1963       } else {
1964         // Blend in all instances of this value using a VSELECT, using a
1965         // mask where each bit signals whether that element is the one
1966         // we're after.
1967         SmallVector<SDValue> Ops;
1968         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
1969           return DAG.getConstant(V == V1, DL, XLenVT);
1970         });
1971         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
1972                           DAG.getBuildVector(SelMaskTy, DL, Ops),
1973                           DAG.getSplatBuildVector(VT, DL, V), Vec);
1974       }
1975     }
1976 
1977     return Vec;
1978   }
1979 
1980   return SDValue();
1981 }
1982 
1983 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
1984                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
1985   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
1986     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
1987     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
1988     // If Hi constant is all the same sign bit as Lo, lower this as a custom
1989     // node in order to try and match RVV vector/scalar instructions.
1990     if ((LoC >> 31) == HiC)
1991       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
1992   }
1993 
1994   // Fall back to a stack store and stride x0 vector load.
1995   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
1996 }
1997 
1998 // Called by type legalization to handle splat of i64 on RV32.
1999 // FIXME: We can optimize this when the type has sign or zero bits in one
2000 // of the halves.
2001 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2002                                    SDValue VL, SelectionDAG &DAG) {
2003   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2004   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2005                            DAG.getConstant(0, DL, MVT::i32));
2006   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2007                            DAG.getConstant(1, DL, MVT::i32));
2008   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2009 }
2010 
2011 // This function lowers a splat of a scalar operand Splat with the vector
2012 // length VL. It ensures the final sequence is type legal, which is useful when
2013 // lowering a splat after type legalization.
2014 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2015                                 SelectionDAG &DAG,
2016                                 const RISCVSubtarget &Subtarget) {
2017   if (VT.isFloatingPoint())
2018     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2019 
2020   MVT XLenVT = Subtarget.getXLenVT();
2021 
2022   // Simplest case is that the operand needs to be promoted to XLenVT.
2023   if (Scalar.getValueType().bitsLE(XLenVT)) {
2024     // If the operand is a constant, sign extend to increase our chances
2025     // of being able to use a .vi instruction. ANY_EXTEND would become a
2026     // a zero extend and the simm5 check in isel would fail.
2027     // FIXME: Should we ignore the upper bits in isel instead?
2028     unsigned ExtOpc =
2029         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2030     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2031     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2032   }
2033 
2034   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2035          "Unexpected scalar for splat lowering!");
2036 
2037   // Otherwise use the more complicated splatting algorithm.
2038   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2039 }
2040 
2041 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2042                                    const RISCVSubtarget &Subtarget) {
2043   SDValue V1 = Op.getOperand(0);
2044   SDValue V2 = Op.getOperand(1);
2045   SDLoc DL(Op);
2046   MVT XLenVT = Subtarget.getXLenVT();
2047   MVT VT = Op.getSimpleValueType();
2048   unsigned NumElts = VT.getVectorNumElements();
2049   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2050 
2051   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2052 
2053   SDValue TrueMask, VL;
2054   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2055 
2056   if (SVN->isSplat()) {
2057     const int Lane = SVN->getSplatIndex();
2058     if (Lane >= 0) {
2059       MVT SVT = VT.getVectorElementType();
2060 
2061       // Turn splatted vector load into a strided load with an X0 stride.
2062       SDValue V = V1;
2063       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2064       // with undef.
2065       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2066       int Offset = Lane;
2067       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2068         int OpElements =
2069             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2070         V = V.getOperand(Offset / OpElements);
2071         Offset %= OpElements;
2072       }
2073 
2074       // We need to ensure the load isn't atomic or volatile.
2075       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2076         auto *Ld = cast<LoadSDNode>(V);
2077         Offset *= SVT.getStoreSize();
2078         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2079                                                    TypeSize::Fixed(Offset), DL);
2080 
2081         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2082         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2083           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2084           SDValue IntID =
2085               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2086           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2087                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2088           SDValue NewLoad = DAG.getMemIntrinsicNode(
2089               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2090               DAG.getMachineFunction().getMachineMemOperand(
2091                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2092           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2093           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2094         }
2095 
2096         // Otherwise use a scalar load and splat. This will give the best
2097         // opportunity to fold a splat into the operation. ISel can turn it into
2098         // the x0 strided load if we aren't able to fold away the select.
2099         if (SVT.isFloatingPoint())
2100           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2101                           Ld->getPointerInfo().getWithOffset(Offset),
2102                           Ld->getOriginalAlign(),
2103                           Ld->getMemOperand()->getFlags());
2104         else
2105           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2106                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2107                              Ld->getOriginalAlign(),
2108                              Ld->getMemOperand()->getFlags());
2109         DAG.makeEquivalentMemoryOrdering(Ld, V);
2110 
2111         unsigned Opc =
2112             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2113         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2114         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2115       }
2116 
2117       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2118       assert(Lane < (int)NumElts && "Unexpected lane!");
2119       SDValue Gather =
2120           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2121                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2122       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2123     }
2124   }
2125 
2126   // Detect shuffles which can be re-expressed as vector selects; these are
2127   // shuffles in which each element in the destination is taken from an element
2128   // at the corresponding index in either source vectors.
2129   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2130     int MaskIndex = MaskIdx.value();
2131     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2132   });
2133 
2134   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2135 
2136   SmallVector<SDValue> MaskVals;
2137   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2138   // merged with a second vrgather.
2139   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2140 
2141   // By default we preserve the original operand order, and use a mask to
2142   // select LHS as true and RHS as false. However, since RVV vector selects may
2143   // feature splats but only on the LHS, we may choose to invert our mask and
2144   // instead select between RHS and LHS.
2145   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2146   bool InvertMask = IsSelect == SwapOps;
2147 
2148   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2149   // half.
2150   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2151 
2152   // Now construct the mask that will be used by the vselect or blended
2153   // vrgather operation. For vrgathers, construct the appropriate indices into
2154   // each vector.
2155   for (int MaskIndex : SVN->getMask()) {
2156     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2157     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2158     if (!IsSelect) {
2159       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2160       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2161                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2162                                      : DAG.getUNDEF(XLenVT));
2163       GatherIndicesRHS.push_back(
2164           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2165                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2166       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2167         ++LHSIndexCounts[MaskIndex];
2168       if (!IsLHSOrUndefIndex)
2169         ++RHSIndexCounts[MaskIndex - NumElts];
2170     }
2171   }
2172 
2173   if (SwapOps) {
2174     std::swap(V1, V2);
2175     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2176   }
2177 
2178   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2179   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2180   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2181 
2182   if (IsSelect)
2183     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2184 
2185   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2186     // On such a large vector we're unable to use i8 as the index type.
2187     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2188     // may involve vector splitting if we're already at LMUL=8, or our
2189     // user-supplied maximum fixed-length LMUL.
2190     return SDValue();
2191   }
2192 
2193   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2194   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2195   MVT IndexVT = VT.changeTypeToInteger();
2196   // Since we can't introduce illegal index types at this stage, use i16 and
2197   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2198   // than XLenVT.
2199   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2200     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2201     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2202   }
2203 
2204   MVT IndexContainerVT =
2205       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2206 
2207   SDValue Gather;
2208   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2209   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2210   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2211     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2212   } else {
2213     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2214     // If only one index is used, we can use a "splat" vrgather.
2215     // TODO: We can splat the most-common index and fix-up any stragglers, if
2216     // that's beneficial.
2217     if (LHSIndexCounts.size() == 1) {
2218       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2219       Gather =
2220           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2221                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2222     } else {
2223       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2224       LHSIndices =
2225           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2226 
2227       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2228                            TrueMask, VL);
2229     }
2230   }
2231 
2232   // If a second vector operand is used by this shuffle, blend it in with an
2233   // additional vrgather.
2234   if (!V2.isUndef()) {
2235     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2236     // If only one index is used, we can use a "splat" vrgather.
2237     // TODO: We can splat the most-common index and fix-up any stragglers, if
2238     // that's beneficial.
2239     if (RHSIndexCounts.size() == 1) {
2240       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2241       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2242                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2243     } else {
2244       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2245       RHSIndices =
2246           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2247       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2248                        VL);
2249     }
2250 
2251     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2252     SelectMask =
2253         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2254 
2255     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2256                          Gather, VL);
2257   }
2258 
2259   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2260 }
2261 
2262 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2263                                      SDLoc DL, SelectionDAG &DAG,
2264                                      const RISCVSubtarget &Subtarget) {
2265   if (VT.isScalableVector())
2266     return DAG.getFPExtendOrRound(Op, DL, VT);
2267   assert(VT.isFixedLengthVector() &&
2268          "Unexpected value type for RVV FP extend/round lowering");
2269   SDValue Mask, VL;
2270   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2271   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2272                         ? RISCVISD::FP_EXTEND_VL
2273                         : RISCVISD::FP_ROUND_VL;
2274   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2275 }
2276 
2277 // While RVV has alignment restrictions, we should always be able to load as a
2278 // legal equivalently-sized byte-typed vector instead. This method is
2279 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2280 // the load is already correctly-aligned, it returns SDValue().
2281 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2282                                                     SelectionDAG &DAG) const {
2283   auto *Load = cast<LoadSDNode>(Op);
2284   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2285 
2286   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2287                                      Load->getMemoryVT(),
2288                                      *Load->getMemOperand()))
2289     return SDValue();
2290 
2291   SDLoc DL(Op);
2292   MVT VT = Op.getSimpleValueType();
2293   unsigned EltSizeBits = VT.getScalarSizeInBits();
2294   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2295          "Unexpected unaligned RVV load type");
2296   MVT NewVT =
2297       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2298   assert(NewVT.isValid() &&
2299          "Expecting equally-sized RVV vector types to be legal");
2300   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2301                           Load->getPointerInfo(), Load->getOriginalAlign(),
2302                           Load->getMemOperand()->getFlags());
2303   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2304 }
2305 
2306 // While RVV has alignment restrictions, we should always be able to store as a
2307 // legal equivalently-sized byte-typed vector instead. This method is
2308 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2309 // returns SDValue() if the store is already correctly aligned.
2310 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2311                                                      SelectionDAG &DAG) const {
2312   auto *Store = cast<StoreSDNode>(Op);
2313   assert(Store && Store->getValue().getValueType().isVector() &&
2314          "Expected vector store");
2315 
2316   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2317                                      Store->getMemoryVT(),
2318                                      *Store->getMemOperand()))
2319     return SDValue();
2320 
2321   SDLoc DL(Op);
2322   SDValue StoredVal = Store->getValue();
2323   MVT VT = StoredVal.getSimpleValueType();
2324   unsigned EltSizeBits = VT.getScalarSizeInBits();
2325   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2326          "Unexpected unaligned RVV store type");
2327   MVT NewVT =
2328       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2329   assert(NewVT.isValid() &&
2330          "Expecting equally-sized RVV vector types to be legal");
2331   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2332   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2333                       Store->getPointerInfo(), Store->getOriginalAlign(),
2334                       Store->getMemOperand()->getFlags());
2335 }
2336 
2337 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2338                                             SelectionDAG &DAG) const {
2339   switch (Op.getOpcode()) {
2340   default:
2341     report_fatal_error("unimplemented operand");
2342   case ISD::GlobalAddress:
2343     return lowerGlobalAddress(Op, DAG);
2344   case ISD::BlockAddress:
2345     return lowerBlockAddress(Op, DAG);
2346   case ISD::ConstantPool:
2347     return lowerConstantPool(Op, DAG);
2348   case ISD::JumpTable:
2349     return lowerJumpTable(Op, DAG);
2350   case ISD::GlobalTLSAddress:
2351     return lowerGlobalTLSAddress(Op, DAG);
2352   case ISD::SELECT:
2353     return lowerSELECT(Op, DAG);
2354   case ISD::BRCOND:
2355     return lowerBRCOND(Op, DAG);
2356   case ISD::VASTART:
2357     return lowerVASTART(Op, DAG);
2358   case ISD::FRAMEADDR:
2359     return lowerFRAMEADDR(Op, DAG);
2360   case ISD::RETURNADDR:
2361     return lowerRETURNADDR(Op, DAG);
2362   case ISD::SHL_PARTS:
2363     return lowerShiftLeftParts(Op, DAG);
2364   case ISD::SRA_PARTS:
2365     return lowerShiftRightParts(Op, DAG, true);
2366   case ISD::SRL_PARTS:
2367     return lowerShiftRightParts(Op, DAG, false);
2368   case ISD::BITCAST: {
2369     SDLoc DL(Op);
2370     EVT VT = Op.getValueType();
2371     SDValue Op0 = Op.getOperand(0);
2372     EVT Op0VT = Op0.getValueType();
2373     MVT XLenVT = Subtarget.getXLenVT();
2374     if (VT.isFixedLengthVector()) {
2375       // We can handle fixed length vector bitcasts with a simple replacement
2376       // in isel.
2377       if (Op0VT.isFixedLengthVector())
2378         return Op;
2379       // When bitcasting from scalar to fixed-length vector, insert the scalar
2380       // into a one-element vector of the result type, and perform a vector
2381       // bitcast.
2382       if (!Op0VT.isVector()) {
2383         auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2384         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2385                                               DAG.getUNDEF(BVT), Op0,
2386                                               DAG.getConstant(0, DL, XLenVT)));
2387       }
2388       return SDValue();
2389     }
2390     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2391     // thus: bitcast the vector to a one-element vector type whose element type
2392     // is the same as the result type, and extract the first element.
2393     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2394       LLVMContext &Context = *DAG.getContext();
2395       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
2396       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2397                          DAG.getConstant(0, DL, XLenVT));
2398     }
2399     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2400       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2401       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2402       return FPConv;
2403     }
2404     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2405         Subtarget.hasStdExtF()) {
2406       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2407       SDValue FPConv =
2408           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2409       return FPConv;
2410     }
2411     return SDValue();
2412   }
2413   case ISD::INTRINSIC_WO_CHAIN:
2414     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2415   case ISD::INTRINSIC_W_CHAIN:
2416     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2417   case ISD::INTRINSIC_VOID:
2418     return LowerINTRINSIC_VOID(Op, DAG);
2419   case ISD::BSWAP:
2420   case ISD::BITREVERSE: {
2421     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2422     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2423     MVT VT = Op.getSimpleValueType();
2424     SDLoc DL(Op);
2425     // Start with the maximum immediate value which is the bitwidth - 1.
2426     unsigned Imm = VT.getSizeInBits() - 1;
2427     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2428     if (Op.getOpcode() == ISD::BSWAP)
2429       Imm &= ~0x7U;
2430     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2431                        DAG.getConstant(Imm, DL, VT));
2432   }
2433   case ISD::FSHL:
2434   case ISD::FSHR: {
2435     MVT VT = Op.getSimpleValueType();
2436     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2437     SDLoc DL(Op);
2438     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2439       return Op;
2440     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2441     // use log(XLen) bits. Mask the shift amount accordingly.
2442     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2443     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2444                                 DAG.getConstant(ShAmtWidth, DL, VT));
2445     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2446     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2447   }
2448   case ISD::TRUNCATE: {
2449     SDLoc DL(Op);
2450     MVT VT = Op.getSimpleValueType();
2451     // Only custom-lower vector truncates
2452     if (!VT.isVector())
2453       return Op;
2454 
2455     // Truncates to mask types are handled differently
2456     if (VT.getVectorElementType() == MVT::i1)
2457       return lowerVectorMaskTrunc(Op, DAG);
2458 
2459     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2460     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2461     // truncate by one power of two at a time.
2462     MVT DstEltVT = VT.getVectorElementType();
2463 
2464     SDValue Src = Op.getOperand(0);
2465     MVT SrcVT = Src.getSimpleValueType();
2466     MVT SrcEltVT = SrcVT.getVectorElementType();
2467 
2468     assert(DstEltVT.bitsLT(SrcEltVT) &&
2469            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2470            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2471            "Unexpected vector truncate lowering");
2472 
2473     MVT ContainerVT = SrcVT;
2474     if (SrcVT.isFixedLengthVector()) {
2475       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2476       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2477     }
2478 
2479     SDValue Result = Src;
2480     SDValue Mask, VL;
2481     std::tie(Mask, VL) =
2482         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2483     LLVMContext &Context = *DAG.getContext();
2484     const ElementCount Count = ContainerVT.getVectorElementCount();
2485     do {
2486       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2487       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2488       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2489                            Mask, VL);
2490     } while (SrcEltVT != DstEltVT);
2491 
2492     if (SrcVT.isFixedLengthVector())
2493       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2494 
2495     return Result;
2496   }
2497   case ISD::ANY_EXTEND:
2498   case ISD::ZERO_EXTEND:
2499     if (Op.getOperand(0).getValueType().isVector() &&
2500         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2501       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2502     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2503   case ISD::SIGN_EXTEND:
2504     if (Op.getOperand(0).getValueType().isVector() &&
2505         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2506       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2507     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2508   case ISD::SPLAT_VECTOR_PARTS:
2509     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2510   case ISD::INSERT_VECTOR_ELT:
2511     return lowerINSERT_VECTOR_ELT(Op, DAG);
2512   case ISD::EXTRACT_VECTOR_ELT:
2513     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2514   case ISD::VSCALE: {
2515     MVT VT = Op.getSimpleValueType();
2516     SDLoc DL(Op);
2517     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2518     // We define our scalable vector types for lmul=1 to use a 64 bit known
2519     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2520     // vscale as VLENB / 8.
2521     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2522     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2523       // We assume VLENB is a multiple of 8. We manually choose the best shift
2524       // here because SimplifyDemandedBits isn't always able to simplify it.
2525       uint64_t Val = Op.getConstantOperandVal(0);
2526       if (isPowerOf2_64(Val)) {
2527         uint64_t Log2 = Log2_64(Val);
2528         if (Log2 < 3)
2529           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2530                              DAG.getConstant(3 - Log2, DL, VT));
2531         if (Log2 > 3)
2532           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2533                              DAG.getConstant(Log2 - 3, DL, VT));
2534         return VLENB;
2535       }
2536       // If the multiplier is a multiple of 8, scale it down to avoid needing
2537       // to shift the VLENB value.
2538       if ((Val % 8) == 0)
2539         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2540                            DAG.getConstant(Val / 8, DL, VT));
2541     }
2542 
2543     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2544                                  DAG.getConstant(3, DL, VT));
2545     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2546   }
2547   case ISD::FP_EXTEND: {
2548     // RVV can only do fp_extend to types double the size as the source. We
2549     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2550     // via f32.
2551     SDLoc DL(Op);
2552     MVT VT = Op.getSimpleValueType();
2553     SDValue Src = Op.getOperand(0);
2554     MVT SrcVT = Src.getSimpleValueType();
2555 
2556     // Prepare any fixed-length vector operands.
2557     MVT ContainerVT = VT;
2558     if (SrcVT.isFixedLengthVector()) {
2559       ContainerVT = getContainerForFixedLengthVector(VT);
2560       MVT SrcContainerVT =
2561           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2562       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2563     }
2564 
2565     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2566         SrcVT.getVectorElementType() != MVT::f16) {
2567       // For scalable vectors, we only need to close the gap between
2568       // vXf16->vXf64.
2569       if (!VT.isFixedLengthVector())
2570         return Op;
2571       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2572       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2573       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2574     }
2575 
2576     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2577     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2578     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2579         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2580 
2581     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2582                                            DL, DAG, Subtarget);
2583     if (VT.isFixedLengthVector())
2584       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2585     return Extend;
2586   }
2587   case ISD::FP_ROUND: {
2588     // RVV can only do fp_round to types half the size as the source. We
2589     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2590     // conversion instruction.
2591     SDLoc DL(Op);
2592     MVT VT = Op.getSimpleValueType();
2593     SDValue Src = Op.getOperand(0);
2594     MVT SrcVT = Src.getSimpleValueType();
2595 
2596     // Prepare any fixed-length vector operands.
2597     MVT ContainerVT = VT;
2598     if (VT.isFixedLengthVector()) {
2599       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2600       ContainerVT =
2601           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2602       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2603     }
2604 
2605     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2606         SrcVT.getVectorElementType() != MVT::f64) {
2607       // For scalable vectors, we only need to close the gap between
2608       // vXf64<->vXf16.
2609       if (!VT.isFixedLengthVector())
2610         return Op;
2611       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2612       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2613       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2614     }
2615 
2616     SDValue Mask, VL;
2617     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2618 
2619     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2620     SDValue IntermediateRound =
2621         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2622     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2623                                           DL, DAG, Subtarget);
2624 
2625     if (VT.isFixedLengthVector())
2626       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2627     return Round;
2628   }
2629   case ISD::FP_TO_SINT:
2630   case ISD::FP_TO_UINT:
2631   case ISD::SINT_TO_FP:
2632   case ISD::UINT_TO_FP: {
2633     // RVV can only do fp<->int conversions to types half/double the size as
2634     // the source. We custom-lower any conversions that do two hops into
2635     // sequences.
2636     MVT VT = Op.getSimpleValueType();
2637     if (!VT.isVector())
2638       return Op;
2639     SDLoc DL(Op);
2640     SDValue Src = Op.getOperand(0);
2641     MVT EltVT = VT.getVectorElementType();
2642     MVT SrcVT = Src.getSimpleValueType();
2643     MVT SrcEltVT = SrcVT.getVectorElementType();
2644     unsigned EltSize = EltVT.getSizeInBits();
2645     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2646     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2647            "Unexpected vector element types");
2648 
2649     bool IsInt2FP = SrcEltVT.isInteger();
2650     // Widening conversions
2651     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2652       if (IsInt2FP) {
2653         // Do a regular integer sign/zero extension then convert to float.
2654         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2655                                       VT.getVectorElementCount());
2656         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2657                                  ? ISD::ZERO_EXTEND
2658                                  : ISD::SIGN_EXTEND;
2659         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2660         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2661       }
2662       // FP2Int
2663       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2664       // Do one doubling fp_extend then complete the operation by converting
2665       // to int.
2666       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2667       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2668       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2669     }
2670 
2671     // Narrowing conversions
2672     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2673       if (IsInt2FP) {
2674         // One narrowing int_to_fp, then an fp_round.
2675         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2676         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2677         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2678         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2679       }
2680       // FP2Int
2681       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2682       // representable by the integer, the result is poison.
2683       MVT IVecVT =
2684           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2685                            VT.getVectorElementCount());
2686       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2687       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2688     }
2689 
2690     // Scalable vectors can exit here. Patterns will handle equally-sized
2691     // conversions halving/doubling ones.
2692     if (!VT.isFixedLengthVector())
2693       return Op;
2694 
2695     // For fixed-length vectors we lower to a custom "VL" node.
2696     unsigned RVVOpc = 0;
2697     switch (Op.getOpcode()) {
2698     default:
2699       llvm_unreachable("Impossible opcode");
2700     case ISD::FP_TO_SINT:
2701       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2702       break;
2703     case ISD::FP_TO_UINT:
2704       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2705       break;
2706     case ISD::SINT_TO_FP:
2707       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2708       break;
2709     case ISD::UINT_TO_FP:
2710       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2711       break;
2712     }
2713 
2714     MVT ContainerVT, SrcContainerVT;
2715     // Derive the reference container type from the larger vector type.
2716     if (SrcEltSize > EltSize) {
2717       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2718       ContainerVT =
2719           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2720     } else {
2721       ContainerVT = getContainerForFixedLengthVector(VT);
2722       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2723     }
2724 
2725     SDValue Mask, VL;
2726     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2727 
2728     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2729     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2730     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2731   }
2732   case ISD::FP_TO_SINT_SAT:
2733   case ISD::FP_TO_UINT_SAT:
2734     return lowerFP_TO_INT_SAT(Op, DAG);
2735   case ISD::VECREDUCE_ADD:
2736   case ISD::VECREDUCE_UMAX:
2737   case ISD::VECREDUCE_SMAX:
2738   case ISD::VECREDUCE_UMIN:
2739   case ISD::VECREDUCE_SMIN:
2740     return lowerVECREDUCE(Op, DAG);
2741   case ISD::VECREDUCE_AND:
2742   case ISD::VECREDUCE_OR:
2743   case ISD::VECREDUCE_XOR:
2744     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2745       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
2746     return lowerVECREDUCE(Op, DAG);
2747   case ISD::VECREDUCE_FADD:
2748   case ISD::VECREDUCE_SEQ_FADD:
2749   case ISD::VECREDUCE_FMIN:
2750   case ISD::VECREDUCE_FMAX:
2751     return lowerFPVECREDUCE(Op, DAG);
2752   case ISD::VP_REDUCE_ADD:
2753   case ISD::VP_REDUCE_UMAX:
2754   case ISD::VP_REDUCE_SMAX:
2755   case ISD::VP_REDUCE_UMIN:
2756   case ISD::VP_REDUCE_SMIN:
2757   case ISD::VP_REDUCE_FADD:
2758   case ISD::VP_REDUCE_SEQ_FADD:
2759   case ISD::VP_REDUCE_FMIN:
2760   case ISD::VP_REDUCE_FMAX:
2761     return lowerVPREDUCE(Op, DAG);
2762   case ISD::VP_REDUCE_AND:
2763   case ISD::VP_REDUCE_OR:
2764   case ISD::VP_REDUCE_XOR:
2765     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
2766       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
2767     return lowerVPREDUCE(Op, DAG);
2768   case ISD::INSERT_SUBVECTOR:
2769     return lowerINSERT_SUBVECTOR(Op, DAG);
2770   case ISD::EXTRACT_SUBVECTOR:
2771     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2772   case ISD::STEP_VECTOR:
2773     return lowerSTEP_VECTOR(Op, DAG);
2774   case ISD::VECTOR_REVERSE:
2775     return lowerVECTOR_REVERSE(Op, DAG);
2776   case ISD::BUILD_VECTOR:
2777     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2778   case ISD::SPLAT_VECTOR:
2779     if (Op.getValueType().getVectorElementType() == MVT::i1)
2780       return lowerVectorMaskSplat(Op, DAG);
2781     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
2782   case ISD::VECTOR_SHUFFLE:
2783     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2784   case ISD::CONCAT_VECTORS: {
2785     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2786     // better than going through the stack, as the default expansion does.
2787     SDLoc DL(Op);
2788     MVT VT = Op.getSimpleValueType();
2789     unsigned NumOpElts =
2790         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2791     SDValue Vec = DAG.getUNDEF(VT);
2792     for (const auto &OpIdx : enumerate(Op->ops()))
2793       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2794                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2795     return Vec;
2796   }
2797   case ISD::LOAD:
2798     if (auto V = expandUnalignedRVVLoad(Op, DAG))
2799       return V;
2800     if (Op.getValueType().isFixedLengthVector())
2801       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2802     return Op;
2803   case ISD::STORE:
2804     if (auto V = expandUnalignedRVVStore(Op, DAG))
2805       return V;
2806     if (Op.getOperand(1).getValueType().isFixedLengthVector())
2807       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2808     return Op;
2809   case ISD::MLOAD:
2810   case ISD::VP_LOAD:
2811     return lowerMaskedLoad(Op, DAG);
2812   case ISD::MSTORE:
2813   case ISD::VP_STORE:
2814     return lowerMaskedStore(Op, DAG);
2815   case ISD::SETCC:
2816     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2817   case ISD::ADD:
2818     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2819   case ISD::SUB:
2820     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2821   case ISD::MUL:
2822     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2823   case ISD::MULHS:
2824     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2825   case ISD::MULHU:
2826     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2827   case ISD::AND:
2828     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2829                                               RISCVISD::AND_VL);
2830   case ISD::OR:
2831     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2832                                               RISCVISD::OR_VL);
2833   case ISD::XOR:
2834     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2835                                               RISCVISD::XOR_VL);
2836   case ISD::SDIV:
2837     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2838   case ISD::SREM:
2839     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2840   case ISD::UDIV:
2841     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2842   case ISD::UREM:
2843     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2844   case ISD::SHL:
2845   case ISD::SRA:
2846   case ISD::SRL:
2847     if (Op.getSimpleValueType().isFixedLengthVector())
2848       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
2849     // This can be called for an i32 shift amount that needs to be promoted.
2850     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
2851            "Unexpected custom legalisation");
2852     return SDValue();
2853   case ISD::SADDSAT:
2854     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
2855   case ISD::UADDSAT:
2856     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
2857   case ISD::SSUBSAT:
2858     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
2859   case ISD::USUBSAT:
2860     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
2861   case ISD::FADD:
2862     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2863   case ISD::FSUB:
2864     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2865   case ISD::FMUL:
2866     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2867   case ISD::FDIV:
2868     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2869   case ISD::FNEG:
2870     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2871   case ISD::FABS:
2872     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2873   case ISD::FSQRT:
2874     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2875   case ISD::FMA:
2876     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2877   case ISD::SMIN:
2878     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2879   case ISD::SMAX:
2880     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2881   case ISD::UMIN:
2882     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2883   case ISD::UMAX:
2884     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2885   case ISD::FMINNUM:
2886     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
2887   case ISD::FMAXNUM:
2888     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
2889   case ISD::ABS:
2890     return lowerABS(Op, DAG);
2891   case ISD::VSELECT:
2892     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2893   case ISD::FCOPYSIGN:
2894     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2895   case ISD::MGATHER:
2896   case ISD::VP_GATHER:
2897     return lowerMaskedGather(Op, DAG);
2898   case ISD::MSCATTER:
2899   case ISD::VP_SCATTER:
2900     return lowerMaskedScatter(Op, DAG);
2901   case ISD::FLT_ROUNDS_:
2902     return lowerGET_ROUNDING(Op, DAG);
2903   case ISD::SET_ROUNDING:
2904     return lowerSET_ROUNDING(Op, DAG);
2905   case ISD::VP_ADD:
2906     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
2907   case ISD::VP_SUB:
2908     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
2909   case ISD::VP_MUL:
2910     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
2911   case ISD::VP_SDIV:
2912     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
2913   case ISD::VP_UDIV:
2914     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
2915   case ISD::VP_SREM:
2916     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
2917   case ISD::VP_UREM:
2918     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
2919   case ISD::VP_AND:
2920     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
2921   case ISD::VP_OR:
2922     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
2923   case ISD::VP_XOR:
2924     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
2925   case ISD::VP_ASHR:
2926     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
2927   case ISD::VP_LSHR:
2928     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
2929   case ISD::VP_SHL:
2930     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
2931   case ISD::VP_FADD:
2932     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
2933   case ISD::VP_FSUB:
2934     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
2935   case ISD::VP_FMUL:
2936     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
2937   case ISD::VP_FDIV:
2938     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
2939   }
2940 }
2941 
2942 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2943                              SelectionDAG &DAG, unsigned Flags) {
2944   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2945 }
2946 
2947 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
2948                              SelectionDAG &DAG, unsigned Flags) {
2949   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
2950                                    Flags);
2951 }
2952 
2953 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
2954                              SelectionDAG &DAG, unsigned Flags) {
2955   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
2956                                    N->getOffset(), Flags);
2957 }
2958 
2959 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
2960                              SelectionDAG &DAG, unsigned Flags) {
2961   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
2962 }
2963 
2964 template <class NodeTy>
2965 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
2966                                      bool IsLocal) const {
2967   SDLoc DL(N);
2968   EVT Ty = getPointerTy(DAG.getDataLayout());
2969 
2970   if (isPositionIndependent()) {
2971     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2972     if (IsLocal)
2973       // Use PC-relative addressing to access the symbol. This generates the
2974       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
2975       // %pcrel_lo(auipc)).
2976       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2977 
2978     // Use PC-relative addressing to access the GOT for this symbol, then load
2979     // the address from the GOT. This generates the pattern (PseudoLA sym),
2980     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
2981     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
2982   }
2983 
2984   switch (getTargetMachine().getCodeModel()) {
2985   default:
2986     report_fatal_error("Unsupported code model for lowering");
2987   case CodeModel::Small: {
2988     // Generate a sequence for accessing addresses within the first 2 GiB of
2989     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
2990     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
2991     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
2992     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
2993     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
2994   }
2995   case CodeModel::Medium: {
2996     // Generate a sequence for accessing addresses within any 2GiB range within
2997     // the address space. This generates the pattern (PseudoLLA sym), which
2998     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
2999     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3000     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3001   }
3002   }
3003 }
3004 
3005 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3006                                                 SelectionDAG &DAG) const {
3007   SDLoc DL(Op);
3008   EVT Ty = Op.getValueType();
3009   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3010   int64_t Offset = N->getOffset();
3011   MVT XLenVT = Subtarget.getXLenVT();
3012 
3013   const GlobalValue *GV = N->getGlobal();
3014   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3015   SDValue Addr = getAddr(N, DAG, IsLocal);
3016 
3017   // In order to maximise the opportunity for common subexpression elimination,
3018   // emit a separate ADD node for the global address offset instead of folding
3019   // it in the global address node. Later peephole optimisations may choose to
3020   // fold it back in when profitable.
3021   if (Offset != 0)
3022     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3023                        DAG.getConstant(Offset, DL, XLenVT));
3024   return Addr;
3025 }
3026 
3027 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3028                                                SelectionDAG &DAG) const {
3029   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3030 
3031   return getAddr(N, DAG);
3032 }
3033 
3034 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3035                                                SelectionDAG &DAG) const {
3036   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3037 
3038   return getAddr(N, DAG);
3039 }
3040 
3041 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3042                                             SelectionDAG &DAG) const {
3043   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3044 
3045   return getAddr(N, DAG);
3046 }
3047 
3048 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3049                                               SelectionDAG &DAG,
3050                                               bool UseGOT) const {
3051   SDLoc DL(N);
3052   EVT Ty = getPointerTy(DAG.getDataLayout());
3053   const GlobalValue *GV = N->getGlobal();
3054   MVT XLenVT = Subtarget.getXLenVT();
3055 
3056   if (UseGOT) {
3057     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3058     // load the address from the GOT and add the thread pointer. This generates
3059     // the pattern (PseudoLA_TLS_IE sym), which expands to
3060     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3061     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3062     SDValue Load =
3063         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3064 
3065     // Add the thread pointer.
3066     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3067     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3068   }
3069 
3070   // Generate a sequence for accessing the address relative to the thread
3071   // pointer, with the appropriate adjustment for the thread pointer offset.
3072   // This generates the pattern
3073   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3074   SDValue AddrHi =
3075       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3076   SDValue AddrAdd =
3077       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3078   SDValue AddrLo =
3079       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3080 
3081   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3082   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3083   SDValue MNAdd = SDValue(
3084       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3085       0);
3086   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3087 }
3088 
3089 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3090                                                SelectionDAG &DAG) const {
3091   SDLoc DL(N);
3092   EVT Ty = getPointerTy(DAG.getDataLayout());
3093   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3094   const GlobalValue *GV = N->getGlobal();
3095 
3096   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3097   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3098   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3099   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3100   SDValue Load =
3101       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3102 
3103   // Prepare argument list to generate call.
3104   ArgListTy Args;
3105   ArgListEntry Entry;
3106   Entry.Node = Load;
3107   Entry.Ty = CallTy;
3108   Args.push_back(Entry);
3109 
3110   // Setup call to __tls_get_addr.
3111   TargetLowering::CallLoweringInfo CLI(DAG);
3112   CLI.setDebugLoc(DL)
3113       .setChain(DAG.getEntryNode())
3114       .setLibCallee(CallingConv::C, CallTy,
3115                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3116                     std::move(Args));
3117 
3118   return LowerCallTo(CLI).first;
3119 }
3120 
3121 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3122                                                    SelectionDAG &DAG) const {
3123   SDLoc DL(Op);
3124   EVT Ty = Op.getValueType();
3125   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3126   int64_t Offset = N->getOffset();
3127   MVT XLenVT = Subtarget.getXLenVT();
3128 
3129   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3130 
3131   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3132       CallingConv::GHC)
3133     report_fatal_error("In GHC calling convention TLS is not supported");
3134 
3135   SDValue Addr;
3136   switch (Model) {
3137   case TLSModel::LocalExec:
3138     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3139     break;
3140   case TLSModel::InitialExec:
3141     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3142     break;
3143   case TLSModel::LocalDynamic:
3144   case TLSModel::GeneralDynamic:
3145     Addr = getDynamicTLSAddr(N, DAG);
3146     break;
3147   }
3148 
3149   // In order to maximise the opportunity for common subexpression elimination,
3150   // emit a separate ADD node for the global address offset instead of folding
3151   // it in the global address node. Later peephole optimisations may choose to
3152   // fold it back in when profitable.
3153   if (Offset != 0)
3154     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3155                        DAG.getConstant(Offset, DL, XLenVT));
3156   return Addr;
3157 }
3158 
3159 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3160   SDValue CondV = Op.getOperand(0);
3161   SDValue TrueV = Op.getOperand(1);
3162   SDValue FalseV = Op.getOperand(2);
3163   SDLoc DL(Op);
3164   MVT VT = Op.getSimpleValueType();
3165   MVT XLenVT = Subtarget.getXLenVT();
3166 
3167   // Lower vector SELECTs to VSELECTs by splatting the condition.
3168   if (VT.isVector()) {
3169     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3170     SDValue CondSplat = VT.isScalableVector()
3171                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3172                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3173     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3174   }
3175 
3176   // If the result type is XLenVT and CondV is the output of a SETCC node
3177   // which also operated on XLenVT inputs, then merge the SETCC node into the
3178   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3179   // compare+branch instructions. i.e.:
3180   // (select (setcc lhs, rhs, cc), truev, falsev)
3181   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3182   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3183       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3184     SDValue LHS = CondV.getOperand(0);
3185     SDValue RHS = CondV.getOperand(1);
3186     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3187     ISD::CondCode CCVal = CC->get();
3188 
3189     // Special case for a select of 2 constants that have a diffence of 1.
3190     // Normally this is done by DAGCombine, but if the select is introduced by
3191     // type legalization or op legalization, we miss it. Restricting to SETLT
3192     // case for now because that is what signed saturating add/sub need.
3193     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3194     // but we would probably want to swap the true/false values if the condition
3195     // is SETGE/SETLE to avoid an XORI.
3196     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3197         CCVal == ISD::SETLT) {
3198       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3199       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3200       if (TrueVal - 1 == FalseVal)
3201         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3202       if (TrueVal + 1 == FalseVal)
3203         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3204     }
3205 
3206     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3207 
3208     SDValue TargetCC = DAG.getCondCode(CCVal);
3209     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3210     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3211   }
3212 
3213   // Otherwise:
3214   // (select condv, truev, falsev)
3215   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3216   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3217   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3218 
3219   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3220 
3221   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3222 }
3223 
3224 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3225   SDValue CondV = Op.getOperand(1);
3226   SDLoc DL(Op);
3227   MVT XLenVT = Subtarget.getXLenVT();
3228 
3229   if (CondV.getOpcode() == ISD::SETCC &&
3230       CondV.getOperand(0).getValueType() == XLenVT) {
3231     SDValue LHS = CondV.getOperand(0);
3232     SDValue RHS = CondV.getOperand(1);
3233     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3234 
3235     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3236 
3237     SDValue TargetCC = DAG.getCondCode(CCVal);
3238     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3239                        LHS, RHS, TargetCC, Op.getOperand(2));
3240   }
3241 
3242   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3243                      CondV, DAG.getConstant(0, DL, XLenVT),
3244                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3245 }
3246 
3247 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3248   MachineFunction &MF = DAG.getMachineFunction();
3249   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3250 
3251   SDLoc DL(Op);
3252   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3253                                  getPointerTy(MF.getDataLayout()));
3254 
3255   // vastart just stores the address of the VarArgsFrameIndex slot into the
3256   // memory location argument.
3257   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3258   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3259                       MachinePointerInfo(SV));
3260 }
3261 
3262 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3263                                             SelectionDAG &DAG) const {
3264   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3265   MachineFunction &MF = DAG.getMachineFunction();
3266   MachineFrameInfo &MFI = MF.getFrameInfo();
3267   MFI.setFrameAddressIsTaken(true);
3268   Register FrameReg = RI.getFrameRegister(MF);
3269   int XLenInBytes = Subtarget.getXLen() / 8;
3270 
3271   EVT VT = Op.getValueType();
3272   SDLoc DL(Op);
3273   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3274   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3275   while (Depth--) {
3276     int Offset = -(XLenInBytes * 2);
3277     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3278                               DAG.getIntPtrConstant(Offset, DL));
3279     FrameAddr =
3280         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3281   }
3282   return FrameAddr;
3283 }
3284 
3285 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3286                                              SelectionDAG &DAG) const {
3287   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3288   MachineFunction &MF = DAG.getMachineFunction();
3289   MachineFrameInfo &MFI = MF.getFrameInfo();
3290   MFI.setReturnAddressIsTaken(true);
3291   MVT XLenVT = Subtarget.getXLenVT();
3292   int XLenInBytes = Subtarget.getXLen() / 8;
3293 
3294   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3295     return SDValue();
3296 
3297   EVT VT = Op.getValueType();
3298   SDLoc DL(Op);
3299   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3300   if (Depth) {
3301     int Off = -XLenInBytes;
3302     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3303     SDValue Offset = DAG.getConstant(Off, DL, VT);
3304     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3305                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3306                        MachinePointerInfo());
3307   }
3308 
3309   // Return the value of the return address register, marking it an implicit
3310   // live-in.
3311   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3312   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3313 }
3314 
3315 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3316                                                  SelectionDAG &DAG) const {
3317   SDLoc DL(Op);
3318   SDValue Lo = Op.getOperand(0);
3319   SDValue Hi = Op.getOperand(1);
3320   SDValue Shamt = Op.getOperand(2);
3321   EVT VT = Lo.getValueType();
3322 
3323   // if Shamt-XLEN < 0: // Shamt < XLEN
3324   //   Lo = Lo << Shamt
3325   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3326   // else:
3327   //   Lo = 0
3328   //   Hi = Lo << (Shamt-XLEN)
3329 
3330   SDValue Zero = DAG.getConstant(0, DL, VT);
3331   SDValue One = DAG.getConstant(1, DL, VT);
3332   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3333   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3334   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3335   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3336 
3337   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3338   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3339   SDValue ShiftRightLo =
3340       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3341   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3342   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3343   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3344 
3345   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3346 
3347   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3348   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3349 
3350   SDValue Parts[2] = {Lo, Hi};
3351   return DAG.getMergeValues(Parts, DL);
3352 }
3353 
3354 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3355                                                   bool IsSRA) const {
3356   SDLoc DL(Op);
3357   SDValue Lo = Op.getOperand(0);
3358   SDValue Hi = Op.getOperand(1);
3359   SDValue Shamt = Op.getOperand(2);
3360   EVT VT = Lo.getValueType();
3361 
3362   // SRA expansion:
3363   //   if Shamt-XLEN < 0: // Shamt < XLEN
3364   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3365   //     Hi = Hi >>s Shamt
3366   //   else:
3367   //     Lo = Hi >>s (Shamt-XLEN);
3368   //     Hi = Hi >>s (XLEN-1)
3369   //
3370   // SRL expansion:
3371   //   if Shamt-XLEN < 0: // Shamt < XLEN
3372   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3373   //     Hi = Hi >>u Shamt
3374   //   else:
3375   //     Lo = Hi >>u (Shamt-XLEN);
3376   //     Hi = 0;
3377 
3378   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3379 
3380   SDValue Zero = DAG.getConstant(0, DL, VT);
3381   SDValue One = DAG.getConstant(1, DL, VT);
3382   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3383   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3384   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3385   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3386 
3387   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3388   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3389   SDValue ShiftLeftHi =
3390       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3391   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3392   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3393   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3394   SDValue HiFalse =
3395       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3396 
3397   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3398 
3399   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3400   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3401 
3402   SDValue Parts[2] = {Lo, Hi};
3403   return DAG.getMergeValues(Parts, DL);
3404 }
3405 
3406 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3407 // legal equivalently-sized i8 type, so we can use that as a go-between.
3408 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3409                                                   SelectionDAG &DAG) const {
3410   SDLoc DL(Op);
3411   MVT VT = Op.getSimpleValueType();
3412   SDValue SplatVal = Op.getOperand(0);
3413   // All-zeros or all-ones splats are handled specially.
3414   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3415     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3416     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3417   }
3418   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3419     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3420     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3421   }
3422   MVT XLenVT = Subtarget.getXLenVT();
3423   assert(SplatVal.getValueType() == XLenVT &&
3424          "Unexpected type for i1 splat value");
3425   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3426   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3427                          DAG.getConstant(1, DL, XLenVT));
3428   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3429   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3430   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3431 }
3432 
3433 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3434 // illegal (currently only vXi64 RV32).
3435 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3436 // them to SPLAT_VECTOR_I64
3437 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3438                                                      SelectionDAG &DAG) const {
3439   SDLoc DL(Op);
3440   MVT VecVT = Op.getSimpleValueType();
3441   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3442          "Unexpected SPLAT_VECTOR_PARTS lowering");
3443 
3444   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3445   SDValue Lo = Op.getOperand(0);
3446   SDValue Hi = Op.getOperand(1);
3447 
3448   if (VecVT.isFixedLengthVector()) {
3449     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3450     SDLoc DL(Op);
3451     SDValue Mask, VL;
3452     std::tie(Mask, VL) =
3453         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3454 
3455     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3456     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3457   }
3458 
3459   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3460     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3461     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3462     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3463     // node in order to try and match RVV vector/scalar instructions.
3464     if ((LoC >> 31) == HiC)
3465       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3466   }
3467 
3468   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3469   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3470       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3471       Hi.getConstantOperandVal(1) == 31)
3472     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3473 
3474   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3475   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3476                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3477 }
3478 
3479 // Custom-lower extensions from mask vectors by using a vselect either with 1
3480 // for zero/any-extension or -1 for sign-extension:
3481 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3482 // Note that any-extension is lowered identically to zero-extension.
3483 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3484                                                 int64_t ExtTrueVal) const {
3485   SDLoc DL(Op);
3486   MVT VecVT = Op.getSimpleValueType();
3487   SDValue Src = Op.getOperand(0);
3488   // Only custom-lower extensions from mask types
3489   assert(Src.getValueType().isVector() &&
3490          Src.getValueType().getVectorElementType() == MVT::i1);
3491 
3492   MVT XLenVT = Subtarget.getXLenVT();
3493   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3494   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3495 
3496   if (VecVT.isScalableVector()) {
3497     // Be careful not to introduce illegal scalar types at this stage, and be
3498     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3499     // illegal and must be expanded. Since we know that the constants are
3500     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3501     bool IsRV32E64 =
3502         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3503 
3504     if (!IsRV32E64) {
3505       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3506       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3507     } else {
3508       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3509       SplatTrueVal =
3510           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3511     }
3512 
3513     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3514   }
3515 
3516   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3517   MVT I1ContainerVT =
3518       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3519 
3520   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3521 
3522   SDValue Mask, VL;
3523   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3524 
3525   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3526   SplatTrueVal =
3527       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3528   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3529                                SplatTrueVal, SplatZero, VL);
3530 
3531   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3532 }
3533 
3534 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3535     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3536   MVT ExtVT = Op.getSimpleValueType();
3537   // Only custom-lower extensions from fixed-length vector types.
3538   if (!ExtVT.isFixedLengthVector())
3539     return Op;
3540   MVT VT = Op.getOperand(0).getSimpleValueType();
3541   // Grab the canonical container type for the extended type. Infer the smaller
3542   // type from that to ensure the same number of vector elements, as we know
3543   // the LMUL will be sufficient to hold the smaller type.
3544   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3545   // Get the extended container type manually to ensure the same number of
3546   // vector elements between source and dest.
3547   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3548                                      ContainerExtVT.getVectorElementCount());
3549 
3550   SDValue Op1 =
3551       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3552 
3553   SDLoc DL(Op);
3554   SDValue Mask, VL;
3555   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3556 
3557   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3558 
3559   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3560 }
3561 
3562 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3563 // setcc operation:
3564 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3565 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3566                                                   SelectionDAG &DAG) const {
3567   SDLoc DL(Op);
3568   EVT MaskVT = Op.getValueType();
3569   // Only expect to custom-lower truncations to mask types
3570   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3571          "Unexpected type for vector mask lowering");
3572   SDValue Src = Op.getOperand(0);
3573   MVT VecVT = Src.getSimpleValueType();
3574 
3575   // If this is a fixed vector, we need to convert it to a scalable vector.
3576   MVT ContainerVT = VecVT;
3577   if (VecVT.isFixedLengthVector()) {
3578     ContainerVT = getContainerForFixedLengthVector(VecVT);
3579     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3580   }
3581 
3582   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3583   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3584 
3585   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3586   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3587 
3588   if (VecVT.isScalableVector()) {
3589     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3590     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3591   }
3592 
3593   SDValue Mask, VL;
3594   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3595 
3596   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3597   SDValue Trunc =
3598       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3599   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3600                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3601   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3602 }
3603 
3604 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3605 // first position of a vector, and that vector is slid up to the insert index.
3606 // By limiting the active vector length to index+1 and merging with the
3607 // original vector (with an undisturbed tail policy for elements >= VL), we
3608 // achieve the desired result of leaving all elements untouched except the one
3609 // at VL-1, which is replaced with the desired value.
3610 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3611                                                     SelectionDAG &DAG) const {
3612   SDLoc DL(Op);
3613   MVT VecVT = Op.getSimpleValueType();
3614   SDValue Vec = Op.getOperand(0);
3615   SDValue Val = Op.getOperand(1);
3616   SDValue Idx = Op.getOperand(2);
3617 
3618   if (VecVT.getVectorElementType() == MVT::i1) {
3619     // FIXME: For now we just promote to an i8 vector and insert into that,
3620     // but this is probably not optimal.
3621     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3622     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3623     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3624     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3625   }
3626 
3627   MVT ContainerVT = VecVT;
3628   // If the operand is a fixed-length vector, convert to a scalable one.
3629   if (VecVT.isFixedLengthVector()) {
3630     ContainerVT = getContainerForFixedLengthVector(VecVT);
3631     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3632   }
3633 
3634   MVT XLenVT = Subtarget.getXLenVT();
3635 
3636   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3637   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3638   // Even i64-element vectors on RV32 can be lowered without scalar
3639   // legalization if the most-significant 32 bits of the value are not affected
3640   // by the sign-extension of the lower 32 bits.
3641   // TODO: We could also catch sign extensions of a 32-bit value.
3642   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3643     const auto *CVal = cast<ConstantSDNode>(Val);
3644     if (isInt<32>(CVal->getSExtValue())) {
3645       IsLegalInsert = true;
3646       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3647     }
3648   }
3649 
3650   SDValue Mask, VL;
3651   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3652 
3653   SDValue ValInVec;
3654 
3655   if (IsLegalInsert) {
3656     unsigned Opc =
3657         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3658     if (isNullConstant(Idx)) {
3659       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3660       if (!VecVT.isFixedLengthVector())
3661         return Vec;
3662       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3663     }
3664     ValInVec =
3665         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3666   } else {
3667     // On RV32, i64-element vectors must be specially handled to place the
3668     // value at element 0, by using two vslide1up instructions in sequence on
3669     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3670     // this.
3671     SDValue One = DAG.getConstant(1, DL, XLenVT);
3672     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3673     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3674     MVT I32ContainerVT =
3675         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3676     SDValue I32Mask =
3677         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3678     // Limit the active VL to two.
3679     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3680     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3681     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3682     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3683                            InsertI64VL);
3684     // First slide in the hi value, then the lo in underneath it.
3685     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3686                            ValHi, I32Mask, InsertI64VL);
3687     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3688                            ValLo, I32Mask, InsertI64VL);
3689     // Bitcast back to the right container type.
3690     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3691   }
3692 
3693   // Now that the value is in a vector, slide it into position.
3694   SDValue InsertVL =
3695       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3696   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3697                                 ValInVec, Idx, Mask, InsertVL);
3698   if (!VecVT.isFixedLengthVector())
3699     return Slideup;
3700   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3701 }
3702 
3703 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3704 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3705 // types this is done using VMV_X_S to allow us to glean information about the
3706 // sign bits of the result.
3707 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3708                                                      SelectionDAG &DAG) const {
3709   SDLoc DL(Op);
3710   SDValue Idx = Op.getOperand(1);
3711   SDValue Vec = Op.getOperand(0);
3712   EVT EltVT = Op.getValueType();
3713   MVT VecVT = Vec.getSimpleValueType();
3714   MVT XLenVT = Subtarget.getXLenVT();
3715 
3716   if (VecVT.getVectorElementType() == MVT::i1) {
3717     // FIXME: For now we just promote to an i8 vector and extract from that,
3718     // but this is probably not optimal.
3719     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3720     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3721     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3722   }
3723 
3724   // If this is a fixed vector, we need to convert it to a scalable vector.
3725   MVT ContainerVT = VecVT;
3726   if (VecVT.isFixedLengthVector()) {
3727     ContainerVT = getContainerForFixedLengthVector(VecVT);
3728     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3729   }
3730 
3731   // If the index is 0, the vector is already in the right position.
3732   if (!isNullConstant(Idx)) {
3733     // Use a VL of 1 to avoid processing more elements than we need.
3734     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3735     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3736     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3737     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3738                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3739   }
3740 
3741   if (!EltVT.isInteger()) {
3742     // Floating-point extracts are handled in TableGen.
3743     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3744                        DAG.getConstant(0, DL, XLenVT));
3745   }
3746 
3747   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3748   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3749 }
3750 
3751 // Some RVV intrinsics may claim that they want an integer operand to be
3752 // promoted or expanded.
3753 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3754                                           const RISCVSubtarget &Subtarget) {
3755   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3756           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3757          "Unexpected opcode");
3758 
3759   if (!Subtarget.hasStdExtV())
3760     return SDValue();
3761 
3762   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3763   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3764   SDLoc DL(Op);
3765 
3766   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
3767       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3768   if (!II || !II->SplatOperand)
3769     return SDValue();
3770 
3771   unsigned SplatOp = II->SplatOperand + HasChain;
3772   assert(SplatOp < Op.getNumOperands());
3773 
3774   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
3775   SDValue &ScalarOp = Operands[SplatOp];
3776   MVT OpVT = ScalarOp.getSimpleValueType();
3777   MVT XLenVT = Subtarget.getXLenVT();
3778 
3779   // If this isn't a scalar, or its type is XLenVT we're done.
3780   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
3781     return SDValue();
3782 
3783   // Simplest case is that the operand needs to be promoted to XLenVT.
3784   if (OpVT.bitsLT(XLenVT)) {
3785     // If the operand is a constant, sign extend to increase our chances
3786     // of being able to use a .vi instruction. ANY_EXTEND would become a
3787     // a zero extend and the simm5 check in isel would fail.
3788     // FIXME: Should we ignore the upper bits in isel instead?
3789     unsigned ExtOpc =
3790         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
3791     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
3792     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3793   }
3794 
3795   // Use the previous operand to get the vXi64 VT. The result might be a mask
3796   // VT for compares. Using the previous operand assumes that the previous
3797   // operand will never have a smaller element size than a scalar operand and
3798   // that a widening operation never uses SEW=64.
3799   // NOTE: If this fails the below assert, we can probably just find the
3800   // element count from any operand or result and use it to construct the VT.
3801   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
3802   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
3803 
3804   // The more complex case is when the scalar is larger than XLenVT.
3805   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3806          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3807 
3808   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3809   // on the instruction to sign-extend since SEW>XLEN.
3810   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3811     if (isInt<32>(CVal->getSExtValue())) {
3812       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3813       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3814     }
3815   }
3816 
3817   // We need to convert the scalar to a splat vector.
3818   // FIXME: Can we implicitly truncate the scalar if it is known to
3819   // be sign extended?
3820   // VL should be the last operand.
3821   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3822   assert(VL.getValueType() == XLenVT);
3823   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3824   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3825 }
3826 
3827 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3828                                                      SelectionDAG &DAG) const {
3829   unsigned IntNo = Op.getConstantOperandVal(0);
3830   SDLoc DL(Op);
3831   MVT XLenVT = Subtarget.getXLenVT();
3832 
3833   switch (IntNo) {
3834   default:
3835     break; // Don't custom lower most intrinsics.
3836   case Intrinsic::thread_pointer: {
3837     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3838     return DAG.getRegister(RISCV::X4, PtrVT);
3839   }
3840   case Intrinsic::riscv_orc_b:
3841     // Lower to the GORCI encoding for orc.b.
3842     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3843                        DAG.getConstant(7, DL, XLenVT));
3844   case Intrinsic::riscv_grev:
3845   case Intrinsic::riscv_gorc: {
3846     unsigned Opc =
3847         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
3848     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3849   }
3850   case Intrinsic::riscv_shfl:
3851   case Intrinsic::riscv_unshfl: {
3852     unsigned Opc =
3853         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
3854     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3855   }
3856   case Intrinsic::riscv_bcompress:
3857   case Intrinsic::riscv_bdecompress: {
3858     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
3859                                                        : RISCVISD::BDECOMPRESS;
3860     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3861   }
3862   case Intrinsic::riscv_vmv_x_s:
3863     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3864     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3865                        Op.getOperand(1));
3866   case Intrinsic::riscv_vmv_v_x:
3867     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3868                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3869   case Intrinsic::riscv_vfmv_v_f:
3870     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3871                        Op.getOperand(1), Op.getOperand(2));
3872   case Intrinsic::riscv_vmv_s_x: {
3873     SDValue Scalar = Op.getOperand(2);
3874 
3875     if (Scalar.getValueType().bitsLE(XLenVT)) {
3876       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3877       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3878                          Op.getOperand(1), Scalar, Op.getOperand(3));
3879     }
3880 
3881     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3882 
3883     // This is an i64 value that lives in two scalar registers. We have to
3884     // insert this in a convoluted way. First we build vXi64 splat containing
3885     // the/ two values that we assemble using some bit math. Next we'll use
3886     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3887     // to merge element 0 from our splat into the source vector.
3888     // FIXME: This is probably not the best way to do this, but it is
3889     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3890     // point.
3891     //   sw lo, (a0)
3892     //   sw hi, 4(a0)
3893     //   vlse vX, (a0)
3894     //
3895     //   vid.v      vVid
3896     //   vmseq.vx   mMask, vVid, 0
3897     //   vmerge.vvm vDest, vSrc, vVal, mMask
3898     MVT VT = Op.getSimpleValueType();
3899     SDValue Vec = Op.getOperand(1);
3900     SDValue VL = Op.getOperand(3);
3901 
3902     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3903     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3904                                       DAG.getConstant(0, DL, MVT::i32), VL);
3905 
3906     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3907     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3908     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3909     SDValue SelectCond =
3910         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3911                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3912     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3913                        Vec, VL);
3914   }
3915   case Intrinsic::riscv_vslide1up:
3916   case Intrinsic::riscv_vslide1down:
3917   case Intrinsic::riscv_vslide1up_mask:
3918   case Intrinsic::riscv_vslide1down_mask: {
3919     // We need to special case these when the scalar is larger than XLen.
3920     unsigned NumOps = Op.getNumOperands();
3921     bool IsMasked = NumOps == 7;
3922     unsigned OpOffset = IsMasked ? 1 : 0;
3923     SDValue Scalar = Op.getOperand(2 + OpOffset);
3924     if (Scalar.getValueType().bitsLE(XLenVT))
3925       break;
3926 
3927     // Splatting a sign extended constant is fine.
3928     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3929       if (isInt<32>(CVal->getSExtValue()))
3930         break;
3931 
3932     MVT VT = Op.getSimpleValueType();
3933     assert(VT.getVectorElementType() == MVT::i64 &&
3934            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3935 
3936     // Convert the vector source to the equivalent nxvXi32 vector.
3937     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3938     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3939 
3940     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3941                                    DAG.getConstant(0, DL, XLenVT));
3942     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3943                                    DAG.getConstant(1, DL, XLenVT));
3944 
3945     // Double the VL since we halved SEW.
3946     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
3947     SDValue I32VL =
3948         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
3949 
3950     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
3951     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
3952 
3953     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
3954     // instructions.
3955     if (IntNo == Intrinsic::riscv_vslide1up ||
3956         IntNo == Intrinsic::riscv_vslide1up_mask) {
3957       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
3958                         I32Mask, I32VL);
3959       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
3960                         I32Mask, I32VL);
3961     } else {
3962       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
3963                         I32Mask, I32VL);
3964       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
3965                         I32Mask, I32VL);
3966     }
3967 
3968     // Convert back to nxvXi64.
3969     Vec = DAG.getBitcast(VT, Vec);
3970 
3971     if (!IsMasked)
3972       return Vec;
3973 
3974     // Apply mask after the operation.
3975     SDValue Mask = Op.getOperand(NumOps - 3);
3976     SDValue MaskedOff = Op.getOperand(1);
3977     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
3978   }
3979   }
3980 
3981   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3982 }
3983 
3984 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3985                                                     SelectionDAG &DAG) const {
3986   unsigned IntNo = Op.getConstantOperandVal(1);
3987   switch (IntNo) {
3988   default:
3989     break;
3990   case Intrinsic::riscv_masked_strided_load: {
3991     SDLoc DL(Op);
3992     MVT XLenVT = Subtarget.getXLenVT();
3993 
3994     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
3995     // the selection of the masked intrinsics doesn't do this for us.
3996     SDValue Mask = Op.getOperand(5);
3997     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
3998 
3999     MVT VT = Op->getSimpleValueType(0);
4000     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4001 
4002     SDValue PassThru = Op.getOperand(2);
4003     if (!IsUnmasked) {
4004       MVT MaskVT =
4005           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4006       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4007       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4008     }
4009 
4010     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4011 
4012     SDValue IntID = DAG.getTargetConstant(
4013         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4014         XLenVT);
4015 
4016     auto *Load = cast<MemIntrinsicSDNode>(Op);
4017     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4018     if (!IsUnmasked)
4019       Ops.push_back(PassThru);
4020     Ops.push_back(Op.getOperand(3)); // Ptr
4021     Ops.push_back(Op.getOperand(4)); // Stride
4022     if (!IsUnmasked)
4023       Ops.push_back(Mask);
4024     Ops.push_back(VL);
4025     if (!IsUnmasked) {
4026       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4027       Ops.push_back(Policy);
4028     }
4029 
4030     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4031     SDValue Result =
4032         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4033                                 Load->getMemoryVT(), Load->getMemOperand());
4034     SDValue Chain = Result.getValue(1);
4035     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4036     return DAG.getMergeValues({Result, Chain}, DL);
4037   }
4038   }
4039 
4040   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4041 }
4042 
4043 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4044                                                  SelectionDAG &DAG) const {
4045   unsigned IntNo = Op.getConstantOperandVal(1);
4046   switch (IntNo) {
4047   default:
4048     break;
4049   case Intrinsic::riscv_masked_strided_store: {
4050     SDLoc DL(Op);
4051     MVT XLenVT = Subtarget.getXLenVT();
4052 
4053     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4054     // the selection of the masked intrinsics doesn't do this for us.
4055     SDValue Mask = Op.getOperand(5);
4056     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4057 
4058     SDValue Val = Op.getOperand(2);
4059     MVT VT = Val.getSimpleValueType();
4060     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4061 
4062     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4063     if (!IsUnmasked) {
4064       MVT MaskVT =
4065           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4066       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4067     }
4068 
4069     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4070 
4071     SDValue IntID = DAG.getTargetConstant(
4072         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4073         XLenVT);
4074 
4075     auto *Store = cast<MemIntrinsicSDNode>(Op);
4076     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4077     Ops.push_back(Val);
4078     Ops.push_back(Op.getOperand(3)); // Ptr
4079     Ops.push_back(Op.getOperand(4)); // Stride
4080     if (!IsUnmasked)
4081       Ops.push_back(Mask);
4082     Ops.push_back(VL);
4083 
4084     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4085                                    Ops, Store->getMemoryVT(),
4086                                    Store->getMemOperand());
4087   }
4088   }
4089 
4090   return SDValue();
4091 }
4092 
4093 static MVT getLMUL1VT(MVT VT) {
4094   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4095          "Unexpected vector MVT");
4096   return MVT::getScalableVectorVT(
4097       VT.getVectorElementType(),
4098       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4099 }
4100 
4101 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4102   switch (ISDOpcode) {
4103   default:
4104     llvm_unreachable("Unhandled reduction");
4105   case ISD::VECREDUCE_ADD:
4106     return RISCVISD::VECREDUCE_ADD_VL;
4107   case ISD::VECREDUCE_UMAX:
4108     return RISCVISD::VECREDUCE_UMAX_VL;
4109   case ISD::VECREDUCE_SMAX:
4110     return RISCVISD::VECREDUCE_SMAX_VL;
4111   case ISD::VECREDUCE_UMIN:
4112     return RISCVISD::VECREDUCE_UMIN_VL;
4113   case ISD::VECREDUCE_SMIN:
4114     return RISCVISD::VECREDUCE_SMIN_VL;
4115   case ISD::VECREDUCE_AND:
4116     return RISCVISD::VECREDUCE_AND_VL;
4117   case ISD::VECREDUCE_OR:
4118     return RISCVISD::VECREDUCE_OR_VL;
4119   case ISD::VECREDUCE_XOR:
4120     return RISCVISD::VECREDUCE_XOR_VL;
4121   }
4122 }
4123 
4124 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4125                                                          SelectionDAG &DAG,
4126                                                          bool IsVP) const {
4127   SDLoc DL(Op);
4128   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4129   MVT VecVT = Vec.getSimpleValueType();
4130   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4131           Op.getOpcode() == ISD::VECREDUCE_OR ||
4132           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4133           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4134           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4135           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4136          "Unexpected reduction lowering");
4137 
4138   MVT XLenVT = Subtarget.getXLenVT();
4139   assert(Op.getValueType() == XLenVT &&
4140          "Expected reduction output to be legalized to XLenVT");
4141 
4142   MVT ContainerVT = VecVT;
4143   if (VecVT.isFixedLengthVector()) {
4144     ContainerVT = getContainerForFixedLengthVector(VecVT);
4145     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4146   }
4147 
4148   SDValue Mask, VL;
4149   if (IsVP) {
4150     Mask = Op.getOperand(2);
4151     VL = Op.getOperand(3);
4152   } else {
4153     std::tie(Mask, VL) =
4154         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4155   }
4156 
4157   unsigned BaseOpc;
4158   ISD::CondCode CC;
4159   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4160 
4161   switch (Op.getOpcode()) {
4162   default:
4163     llvm_unreachable("Unhandled reduction");
4164   case ISD::VECREDUCE_AND:
4165   case ISD::VP_REDUCE_AND: {
4166     // vpopc ~x == 0
4167     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4168     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4169     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4170     CC = ISD::SETEQ;
4171     BaseOpc = ISD::AND;
4172     break;
4173   }
4174   case ISD::VECREDUCE_OR:
4175   case ISD::VP_REDUCE_OR:
4176     // vpopc x != 0
4177     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4178     CC = ISD::SETNE;
4179     BaseOpc = ISD::OR;
4180     break;
4181   case ISD::VECREDUCE_XOR:
4182   case ISD::VP_REDUCE_XOR: {
4183     // ((vpopc x) & 1) != 0
4184     SDValue One = DAG.getConstant(1, DL, XLenVT);
4185     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4186     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4187     CC = ISD::SETNE;
4188     BaseOpc = ISD::XOR;
4189     break;
4190   }
4191   }
4192 
4193   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4194 
4195   if (!IsVP)
4196     return SetCC;
4197 
4198   // Now include the start value in the operation.
4199   // Note that we must return the start value when no elements are operated
4200   // upon. The vpopc instructions we've emitted in each case above will return
4201   // 0 for an inactive vector, and so we've already received the neutral value:
4202   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4203   // can simply include the start value.
4204   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4205 }
4206 
4207 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4208                                             SelectionDAG &DAG) const {
4209   SDLoc DL(Op);
4210   SDValue Vec = Op.getOperand(0);
4211   EVT VecEVT = Vec.getValueType();
4212 
4213   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4214 
4215   // Due to ordering in legalize types we may have a vector type that needs to
4216   // be split. Do that manually so we can get down to a legal type.
4217   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4218          TargetLowering::TypeSplitVector) {
4219     SDValue Lo, Hi;
4220     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4221     VecEVT = Lo.getValueType();
4222     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4223   }
4224 
4225   // TODO: The type may need to be widened rather than split. Or widened before
4226   // it can be split.
4227   if (!isTypeLegal(VecEVT))
4228     return SDValue();
4229 
4230   MVT VecVT = VecEVT.getSimpleVT();
4231   MVT VecEltVT = VecVT.getVectorElementType();
4232   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4233 
4234   MVT ContainerVT = VecVT;
4235   if (VecVT.isFixedLengthVector()) {
4236     ContainerVT = getContainerForFixedLengthVector(VecVT);
4237     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4238   }
4239 
4240   MVT M1VT = getLMUL1VT(ContainerVT);
4241 
4242   SDValue Mask, VL;
4243   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4244 
4245   // FIXME: This is a VLMAX splat which might be too large and can prevent
4246   // vsetvli removal.
4247   SDValue NeutralElem =
4248       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4249   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
4250   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4251                                   IdentitySplat, Mask, VL);
4252   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4253                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4254   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4255 }
4256 
4257 // Given a reduction op, this function returns the matching reduction opcode,
4258 // the vector SDValue and the scalar SDValue required to lower this to a
4259 // RISCVISD node.
4260 static std::tuple<unsigned, SDValue, SDValue>
4261 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4262   SDLoc DL(Op);
4263   auto Flags = Op->getFlags();
4264   unsigned Opcode = Op.getOpcode();
4265   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4266   switch (Opcode) {
4267   default:
4268     llvm_unreachable("Unhandled reduction");
4269   case ISD::VECREDUCE_FADD:
4270     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4271                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4272   case ISD::VECREDUCE_SEQ_FADD:
4273     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4274                            Op.getOperand(0));
4275   case ISD::VECREDUCE_FMIN:
4276     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4277                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4278   case ISD::VECREDUCE_FMAX:
4279     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4280                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4281   }
4282 }
4283 
4284 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4285                                               SelectionDAG &DAG) const {
4286   SDLoc DL(Op);
4287   MVT VecEltVT = Op.getSimpleValueType();
4288 
4289   unsigned RVVOpcode;
4290   SDValue VectorVal, ScalarVal;
4291   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4292       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4293   MVT VecVT = VectorVal.getSimpleValueType();
4294 
4295   MVT ContainerVT = VecVT;
4296   if (VecVT.isFixedLengthVector()) {
4297     ContainerVT = getContainerForFixedLengthVector(VecVT);
4298     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4299   }
4300 
4301   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4302 
4303   SDValue Mask, VL;
4304   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4305 
4306   // FIXME: This is a VLMAX splat which might be too large and can prevent
4307   // vsetvli removal.
4308   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
4309   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4310                                   VectorVal, ScalarSplat, Mask, VL);
4311   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4312                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4313 }
4314 
4315 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4316   switch (ISDOpcode) {
4317   default:
4318     llvm_unreachable("Unhandled reduction");
4319   case ISD::VP_REDUCE_ADD:
4320     return RISCVISD::VECREDUCE_ADD_VL;
4321   case ISD::VP_REDUCE_UMAX:
4322     return RISCVISD::VECREDUCE_UMAX_VL;
4323   case ISD::VP_REDUCE_SMAX:
4324     return RISCVISD::VECREDUCE_SMAX_VL;
4325   case ISD::VP_REDUCE_UMIN:
4326     return RISCVISD::VECREDUCE_UMIN_VL;
4327   case ISD::VP_REDUCE_SMIN:
4328     return RISCVISD::VECREDUCE_SMIN_VL;
4329   case ISD::VP_REDUCE_AND:
4330     return RISCVISD::VECREDUCE_AND_VL;
4331   case ISD::VP_REDUCE_OR:
4332     return RISCVISD::VECREDUCE_OR_VL;
4333   case ISD::VP_REDUCE_XOR:
4334     return RISCVISD::VECREDUCE_XOR_VL;
4335   case ISD::VP_REDUCE_FADD:
4336     return RISCVISD::VECREDUCE_FADD_VL;
4337   case ISD::VP_REDUCE_SEQ_FADD:
4338     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4339   case ISD::VP_REDUCE_FMAX:
4340     return RISCVISD::VECREDUCE_FMAX_VL;
4341   case ISD::VP_REDUCE_FMIN:
4342     return RISCVISD::VECREDUCE_FMIN_VL;
4343   }
4344 }
4345 
4346 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4347                                            SelectionDAG &DAG) const {
4348   SDLoc DL(Op);
4349   SDValue Vec = Op.getOperand(1);
4350   EVT VecEVT = Vec.getValueType();
4351 
4352   // TODO: The type may need to be widened rather than split. Or widened before
4353   // it can be split.
4354   if (!isTypeLegal(VecEVT))
4355     return SDValue();
4356 
4357   MVT VecVT = VecEVT.getSimpleVT();
4358   MVT VecEltVT = VecVT.getVectorElementType();
4359   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4360 
4361   MVT ContainerVT = VecVT;
4362   if (VecVT.isFixedLengthVector()) {
4363     ContainerVT = getContainerForFixedLengthVector(VecVT);
4364     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4365   }
4366 
4367   SDValue VL = Op.getOperand(3);
4368   SDValue Mask = Op.getOperand(2);
4369 
4370   MVT M1VT = getLMUL1VT(ContainerVT);
4371   MVT XLenVT = Subtarget.getXLenVT();
4372   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4373 
4374   // FIXME: This is a VLMAX splat which might be too large and can prevent
4375   // vsetvli removal.
4376   SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0));
4377   SDValue Reduction =
4378       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4379   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4380                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4381   if (!VecVT.isInteger())
4382     return Elt0;
4383   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4384 }
4385 
4386 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4387                                                    SelectionDAG &DAG) const {
4388   SDValue Vec = Op.getOperand(0);
4389   SDValue SubVec = Op.getOperand(1);
4390   MVT VecVT = Vec.getSimpleValueType();
4391   MVT SubVecVT = SubVec.getSimpleValueType();
4392 
4393   SDLoc DL(Op);
4394   MVT XLenVT = Subtarget.getXLenVT();
4395   unsigned OrigIdx = Op.getConstantOperandVal(2);
4396   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4397 
4398   // We don't have the ability to slide mask vectors up indexed by their i1
4399   // elements; the smallest we can do is i8. Often we are able to bitcast to
4400   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4401   // into a scalable one, we might not necessarily have enough scalable
4402   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4403   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4404       (OrigIdx != 0 || !Vec.isUndef())) {
4405     if (VecVT.getVectorMinNumElements() >= 8 &&
4406         SubVecVT.getVectorMinNumElements() >= 8) {
4407       assert(OrigIdx % 8 == 0 && "Invalid index");
4408       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4409              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4410              "Unexpected mask vector lowering");
4411       OrigIdx /= 8;
4412       SubVecVT =
4413           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4414                            SubVecVT.isScalableVector());
4415       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4416                                VecVT.isScalableVector());
4417       Vec = DAG.getBitcast(VecVT, Vec);
4418       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4419     } else {
4420       // We can't slide this mask vector up indexed by its i1 elements.
4421       // This poses a problem when we wish to insert a scalable vector which
4422       // can't be re-expressed as a larger type. Just choose the slow path and
4423       // extend to a larger type, then truncate back down.
4424       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4425       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4426       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4427       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4428       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4429                         Op.getOperand(2));
4430       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4431       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4432     }
4433   }
4434 
4435   // If the subvector vector is a fixed-length type, we cannot use subregister
4436   // manipulation to simplify the codegen; we don't know which register of a
4437   // LMUL group contains the specific subvector as we only know the minimum
4438   // register size. Therefore we must slide the vector group up the full
4439   // amount.
4440   if (SubVecVT.isFixedLengthVector()) {
4441     if (OrigIdx == 0 && Vec.isUndef())
4442       return Op;
4443     MVT ContainerVT = VecVT;
4444     if (VecVT.isFixedLengthVector()) {
4445       ContainerVT = getContainerForFixedLengthVector(VecVT);
4446       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4447     }
4448     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4449                          DAG.getUNDEF(ContainerVT), SubVec,
4450                          DAG.getConstant(0, DL, XLenVT));
4451     SDValue Mask =
4452         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4453     // Set the vector length to only the number of elements we care about. Note
4454     // that for slideup this includes the offset.
4455     SDValue VL =
4456         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4457     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4458     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4459                                   SubVec, SlideupAmt, Mask, VL);
4460     if (VecVT.isFixedLengthVector())
4461       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4462     return DAG.getBitcast(Op.getValueType(), Slideup);
4463   }
4464 
4465   unsigned SubRegIdx, RemIdx;
4466   std::tie(SubRegIdx, RemIdx) =
4467       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4468           VecVT, SubVecVT, OrigIdx, TRI);
4469 
4470   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4471   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4472                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4473                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4474 
4475   // 1. If the Idx has been completely eliminated and this subvector's size is
4476   // a vector register or a multiple thereof, or the surrounding elements are
4477   // undef, then this is a subvector insert which naturally aligns to a vector
4478   // register. These can easily be handled using subregister manipulation.
4479   // 2. If the subvector is smaller than a vector register, then the insertion
4480   // must preserve the undisturbed elements of the register. We do this by
4481   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4482   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4483   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4484   // LMUL=1 type back into the larger vector (resolving to another subregister
4485   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4486   // to avoid allocating a large register group to hold our subvector.
4487   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4488     return Op;
4489 
4490   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4491   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4492   // (in our case undisturbed). This means we can set up a subvector insertion
4493   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4494   // size of the subvector.
4495   MVT InterSubVT = VecVT;
4496   SDValue AlignedExtract = Vec;
4497   unsigned AlignedIdx = OrigIdx - RemIdx;
4498   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4499     InterSubVT = getLMUL1VT(VecVT);
4500     // Extract a subvector equal to the nearest full vector register type. This
4501     // should resolve to a EXTRACT_SUBREG instruction.
4502     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4503                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4504   }
4505 
4506   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4507   // For scalable vectors this must be further multiplied by vscale.
4508   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4509 
4510   SDValue Mask, VL;
4511   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4512 
4513   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4514   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4515   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4516   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4517 
4518   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4519                        DAG.getUNDEF(InterSubVT), SubVec,
4520                        DAG.getConstant(0, DL, XLenVT));
4521 
4522   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4523                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4524 
4525   // If required, insert this subvector back into the correct vector register.
4526   // This should resolve to an INSERT_SUBREG instruction.
4527   if (VecVT.bitsGT(InterSubVT))
4528     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4529                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4530 
4531   // We might have bitcast from a mask type: cast back to the original type if
4532   // required.
4533   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4534 }
4535 
4536 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4537                                                     SelectionDAG &DAG) const {
4538   SDValue Vec = Op.getOperand(0);
4539   MVT SubVecVT = Op.getSimpleValueType();
4540   MVT VecVT = Vec.getSimpleValueType();
4541 
4542   SDLoc DL(Op);
4543   MVT XLenVT = Subtarget.getXLenVT();
4544   unsigned OrigIdx = Op.getConstantOperandVal(1);
4545   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4546 
4547   // We don't have the ability to slide mask vectors down indexed by their i1
4548   // elements; the smallest we can do is i8. Often we are able to bitcast to
4549   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4550   // from a scalable one, we might not necessarily have enough scalable
4551   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4552   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4553     if (VecVT.getVectorMinNumElements() >= 8 &&
4554         SubVecVT.getVectorMinNumElements() >= 8) {
4555       assert(OrigIdx % 8 == 0 && "Invalid index");
4556       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4557              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4558              "Unexpected mask vector lowering");
4559       OrigIdx /= 8;
4560       SubVecVT =
4561           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4562                            SubVecVT.isScalableVector());
4563       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4564                                VecVT.isScalableVector());
4565       Vec = DAG.getBitcast(VecVT, Vec);
4566     } else {
4567       // We can't slide this mask vector down, indexed by its i1 elements.
4568       // This poses a problem when we wish to extract a scalable vector which
4569       // can't be re-expressed as a larger type. Just choose the slow path and
4570       // extend to a larger type, then truncate back down.
4571       // TODO: We could probably improve this when extracting certain fixed
4572       // from fixed, where we can extract as i8 and shift the correct element
4573       // right to reach the desired subvector?
4574       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4575       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4576       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4577       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4578                         Op.getOperand(1));
4579       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4580       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4581     }
4582   }
4583 
4584   // If the subvector vector is a fixed-length type, we cannot use subregister
4585   // manipulation to simplify the codegen; we don't know which register of a
4586   // LMUL group contains the specific subvector as we only know the minimum
4587   // register size. Therefore we must slide the vector group down the full
4588   // amount.
4589   if (SubVecVT.isFixedLengthVector()) {
4590     // With an index of 0 this is a cast-like subvector, which can be performed
4591     // with subregister operations.
4592     if (OrigIdx == 0)
4593       return Op;
4594     MVT ContainerVT = VecVT;
4595     if (VecVT.isFixedLengthVector()) {
4596       ContainerVT = getContainerForFixedLengthVector(VecVT);
4597       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4598     }
4599     SDValue Mask =
4600         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4601     // Set the vector length to only the number of elements we care about. This
4602     // avoids sliding down elements we're going to discard straight away.
4603     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4604     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4605     SDValue Slidedown =
4606         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4607                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4608     // Now we can use a cast-like subvector extract to get the result.
4609     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4610                             DAG.getConstant(0, DL, XLenVT));
4611     return DAG.getBitcast(Op.getValueType(), Slidedown);
4612   }
4613 
4614   unsigned SubRegIdx, RemIdx;
4615   std::tie(SubRegIdx, RemIdx) =
4616       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4617           VecVT, SubVecVT, OrigIdx, TRI);
4618 
4619   // If the Idx has been completely eliminated then this is a subvector extract
4620   // which naturally aligns to a vector register. These can easily be handled
4621   // using subregister manipulation.
4622   if (RemIdx == 0)
4623     return Op;
4624 
4625   // Else we must shift our vector register directly to extract the subvector.
4626   // Do this using VSLIDEDOWN.
4627 
4628   // If the vector type is an LMUL-group type, extract a subvector equal to the
4629   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4630   // instruction.
4631   MVT InterSubVT = VecVT;
4632   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4633     InterSubVT = getLMUL1VT(VecVT);
4634     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4635                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4636   }
4637 
4638   // Slide this vector register down by the desired number of elements in order
4639   // to place the desired subvector starting at element 0.
4640   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4641   // For scalable vectors this must be further multiplied by vscale.
4642   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4643 
4644   SDValue Mask, VL;
4645   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4646   SDValue Slidedown =
4647       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4648                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4649 
4650   // Now the vector is in the right position, extract our final subvector. This
4651   // should resolve to a COPY.
4652   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4653                           DAG.getConstant(0, DL, XLenVT));
4654 
4655   // We might have bitcast from a mask type: cast back to the original type if
4656   // required.
4657   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4658 }
4659 
4660 // Lower step_vector to the vid instruction. Any non-identity step value must
4661 // be accounted for my manual expansion.
4662 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4663                                               SelectionDAG &DAG) const {
4664   SDLoc DL(Op);
4665   MVT VT = Op.getSimpleValueType();
4666   MVT XLenVT = Subtarget.getXLenVT();
4667   SDValue Mask, VL;
4668   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4669   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4670   uint64_t StepValImm = Op.getConstantOperandVal(0);
4671   if (StepValImm != 1) {
4672     if (isPowerOf2_64(StepValImm)) {
4673       SDValue StepVal =
4674           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4675                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4676       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4677     } else {
4678       SDValue StepVal = lowerScalarSplat(
4679           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4680           DL, DAG, Subtarget);
4681       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4682     }
4683   }
4684   return StepVec;
4685 }
4686 
4687 // Implement vector_reverse using vrgather.vv with indices determined by
4688 // subtracting the id of each element from (VLMAX-1). This will convert
4689 // the indices like so:
4690 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4691 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4692 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4693                                                  SelectionDAG &DAG) const {
4694   SDLoc DL(Op);
4695   MVT VecVT = Op.getSimpleValueType();
4696   unsigned EltSize = VecVT.getScalarSizeInBits();
4697   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4698 
4699   unsigned MaxVLMAX = 0;
4700   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4701   if (VectorBitsMax != 0)
4702     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4703 
4704   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4705   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4706 
4707   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4708   // to use vrgatherei16.vv.
4709   // TODO: It's also possible to use vrgatherei16.vv for other types to
4710   // decrease register width for the index calculation.
4711   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4712     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4713     // Reverse each half, then reassemble them in reverse order.
4714     // NOTE: It's also possible that after splitting that VLMAX no longer
4715     // requires vrgatherei16.vv.
4716     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4717       SDValue Lo, Hi;
4718       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4719       EVT LoVT, HiVT;
4720       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4721       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4722       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4723       // Reassemble the low and high pieces reversed.
4724       // FIXME: This is a CONCAT_VECTORS.
4725       SDValue Res =
4726           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4727                       DAG.getIntPtrConstant(0, DL));
4728       return DAG.getNode(
4729           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4730           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4731     }
4732 
4733     // Just promote the int type to i16 which will double the LMUL.
4734     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4735     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4736   }
4737 
4738   MVT XLenVT = Subtarget.getXLenVT();
4739   SDValue Mask, VL;
4740   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4741 
4742   // Calculate VLMAX-1 for the desired SEW.
4743   unsigned MinElts = VecVT.getVectorMinNumElements();
4744   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4745                               DAG.getConstant(MinElts, DL, XLenVT));
4746   SDValue VLMinus1 =
4747       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4748 
4749   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4750   bool IsRV32E64 =
4751       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4752   SDValue SplatVL;
4753   if (!IsRV32E64)
4754     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4755   else
4756     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4757 
4758   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4759   SDValue Indices =
4760       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4761 
4762   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4763 }
4764 
4765 SDValue
4766 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
4767                                                      SelectionDAG &DAG) const {
4768   SDLoc DL(Op);
4769   auto *Load = cast<LoadSDNode>(Op);
4770 
4771   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4772                                         Load->getMemoryVT(),
4773                                         *Load->getMemOperand()) &&
4774          "Expecting a correctly-aligned load");
4775 
4776   MVT VT = Op.getSimpleValueType();
4777   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4778 
4779   SDValue VL =
4780       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4781 
4782   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4783   SDValue NewLoad = DAG.getMemIntrinsicNode(
4784       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
4785       Load->getMemoryVT(), Load->getMemOperand());
4786 
4787   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
4788   return DAG.getMergeValues({Result, Load->getChain()}, DL);
4789 }
4790 
4791 SDValue
4792 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
4793                                                       SelectionDAG &DAG) const {
4794   SDLoc DL(Op);
4795   auto *Store = cast<StoreSDNode>(Op);
4796 
4797   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4798                                         Store->getMemoryVT(),
4799                                         *Store->getMemOperand()) &&
4800          "Expecting a correctly-aligned store");
4801 
4802   SDValue StoreVal = Store->getValue();
4803   MVT VT = StoreVal.getSimpleValueType();
4804 
4805   // If the size less than a byte, we need to pad with zeros to make a byte.
4806   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
4807     VT = MVT::v8i1;
4808     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
4809                            DAG.getConstant(0, DL, VT), StoreVal,
4810                            DAG.getIntPtrConstant(0, DL));
4811   }
4812 
4813   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4814 
4815   SDValue VL =
4816       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4817 
4818   SDValue NewValue =
4819       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
4820   return DAG.getMemIntrinsicNode(
4821       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
4822       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
4823       Store->getMemoryVT(), Store->getMemOperand());
4824 }
4825 
4826 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
4827                                              SelectionDAG &DAG) const {
4828   SDLoc DL(Op);
4829   MVT VT = Op.getSimpleValueType();
4830 
4831   const auto *MemSD = cast<MemSDNode>(Op);
4832   EVT MemVT = MemSD->getMemoryVT();
4833   MachineMemOperand *MMO = MemSD->getMemOperand();
4834   SDValue Chain = MemSD->getChain();
4835   SDValue BasePtr = MemSD->getBasePtr();
4836 
4837   SDValue Mask, PassThru, VL;
4838   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
4839     Mask = VPLoad->getMask();
4840     PassThru = DAG.getUNDEF(VT);
4841     VL = VPLoad->getVectorLength();
4842   } else {
4843     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
4844     Mask = MLoad->getMask();
4845     PassThru = MLoad->getPassThru();
4846   }
4847 
4848   MVT XLenVT = Subtarget.getXLenVT();
4849 
4850   MVT ContainerVT = VT;
4851   if (VT.isFixedLengthVector()) {
4852     ContainerVT = getContainerForFixedLengthVector(VT);
4853     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4854 
4855     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4856     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4857   }
4858 
4859   if (!VL)
4860     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4861 
4862   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4863   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT);
4864   SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4865   SDValue Ops[] = {Chain, IntID, PassThru, BasePtr, Mask, VL, Policy};
4866   SDValue Result =
4867       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
4868   Chain = Result.getValue(1);
4869 
4870   if (VT.isFixedLengthVector())
4871     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4872 
4873   return DAG.getMergeValues({Result, Chain}, DL);
4874 }
4875 
4876 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
4877                                               SelectionDAG &DAG) const {
4878   SDLoc DL(Op);
4879 
4880   const auto *MemSD = cast<MemSDNode>(Op);
4881   EVT MemVT = MemSD->getMemoryVT();
4882   MachineMemOperand *MMO = MemSD->getMemOperand();
4883   SDValue Chain = MemSD->getChain();
4884   SDValue BasePtr = MemSD->getBasePtr();
4885   SDValue Val, Mask, VL;
4886 
4887   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
4888     Val = VPStore->getValue();
4889     Mask = VPStore->getMask();
4890     VL = VPStore->getVectorLength();
4891   } else {
4892     const auto *MStore = cast<MaskedStoreSDNode>(Op);
4893     Val = MStore->getValue();
4894     Mask = MStore->getMask();
4895   }
4896 
4897   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4898 
4899   MVT VT = Val.getSimpleValueType();
4900   MVT XLenVT = Subtarget.getXLenVT();
4901 
4902   MVT ContainerVT = VT;
4903   if (VT.isFixedLengthVector()) {
4904     ContainerVT = getContainerForFixedLengthVector(VT);
4905 
4906     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4907     if (!IsUnmasked) {
4908       MVT MaskVT =
4909           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4910       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4911     }
4912   }
4913 
4914   if (!VL)
4915     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4916 
4917   unsigned IntID =
4918       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
4919   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4920   Ops.push_back(Val);
4921   Ops.push_back(BasePtr);
4922   if (!IsUnmasked)
4923     Ops.push_back(Mask);
4924   Ops.push_back(VL);
4925 
4926   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
4927                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
4928 }
4929 
4930 SDValue
4931 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4932                                                       SelectionDAG &DAG) const {
4933   MVT InVT = Op.getOperand(0).getSimpleValueType();
4934   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
4935 
4936   MVT VT = Op.getSimpleValueType();
4937 
4938   SDValue Op1 =
4939       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4940   SDValue Op2 =
4941       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4942 
4943   SDLoc DL(Op);
4944   SDValue VL =
4945       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4946 
4947   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4948   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4949 
4950   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
4951                             Op.getOperand(2), Mask, VL);
4952 
4953   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
4954 }
4955 
4956 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
4957     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
4958   MVT VT = Op.getSimpleValueType();
4959 
4960   if (VT.getVectorElementType() == MVT::i1)
4961     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
4962 
4963   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
4964 }
4965 
4966 SDValue
4967 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
4968                                                       SelectionDAG &DAG) const {
4969   unsigned Opc;
4970   switch (Op.getOpcode()) {
4971   default: llvm_unreachable("Unexpected opcode!");
4972   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
4973   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
4974   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
4975   }
4976 
4977   return lowerToScalableOp(Op, DAG, Opc);
4978 }
4979 
4980 // Lower vector ABS to smax(X, sub(0, X)).
4981 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
4982   SDLoc DL(Op);
4983   MVT VT = Op.getSimpleValueType();
4984   SDValue X = Op.getOperand(0);
4985 
4986   assert(VT.isFixedLengthVector() && "Unexpected type");
4987 
4988   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4989   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
4990 
4991   SDValue Mask, VL;
4992   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4993 
4994   SDValue SplatZero =
4995       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4996                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4997   SDValue NegX =
4998       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
4999   SDValue Max =
5000       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5001 
5002   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5003 }
5004 
5005 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5006     SDValue Op, SelectionDAG &DAG) const {
5007   SDLoc DL(Op);
5008   MVT VT = Op.getSimpleValueType();
5009   SDValue Mag = Op.getOperand(0);
5010   SDValue Sign = Op.getOperand(1);
5011   assert(Mag.getValueType() == Sign.getValueType() &&
5012          "Can only handle COPYSIGN with matching types.");
5013 
5014   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5015   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5016   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5017 
5018   SDValue Mask, VL;
5019   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5020 
5021   SDValue CopySign =
5022       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5023 
5024   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5025 }
5026 
5027 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5028     SDValue Op, SelectionDAG &DAG) const {
5029   MVT VT = Op.getSimpleValueType();
5030   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5031 
5032   MVT I1ContainerVT =
5033       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5034 
5035   SDValue CC =
5036       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5037   SDValue Op1 =
5038       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5039   SDValue Op2 =
5040       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5041 
5042   SDLoc DL(Op);
5043   SDValue Mask, VL;
5044   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5045 
5046   SDValue Select =
5047       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5048 
5049   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5050 }
5051 
5052 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5053                                                unsigned NewOpc,
5054                                                bool HasMask) const {
5055   MVT VT = Op.getSimpleValueType();
5056   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5057 
5058   // Create list of operands by converting existing ones to scalable types.
5059   SmallVector<SDValue, 6> Ops;
5060   for (const SDValue &V : Op->op_values()) {
5061     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5062 
5063     // Pass through non-vector operands.
5064     if (!V.getValueType().isVector()) {
5065       Ops.push_back(V);
5066       continue;
5067     }
5068 
5069     // "cast" fixed length vector to a scalable vector.
5070     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5071            "Only fixed length vectors are supported!");
5072     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5073   }
5074 
5075   SDLoc DL(Op);
5076   SDValue Mask, VL;
5077   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5078   if (HasMask)
5079     Ops.push_back(Mask);
5080   Ops.push_back(VL);
5081 
5082   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5083   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5084 }
5085 
5086 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5087 // * Operands of each node are assumed to be in the same order.
5088 // * The EVL operand is promoted from i32 to i64 on RV64.
5089 // * Fixed-length vectors are converted to their scalable-vector container
5090 //   types.
5091 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5092                                        unsigned RISCVISDOpc) const {
5093   SDLoc DL(Op);
5094   MVT VT = Op.getSimpleValueType();
5095   SmallVector<SDValue, 4> Ops;
5096 
5097   for (const auto &OpIdx : enumerate(Op->ops())) {
5098     SDValue V = OpIdx.value();
5099     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5100     // Pass through operands which aren't fixed-length vectors.
5101     if (!V.getValueType().isFixedLengthVector()) {
5102       Ops.push_back(V);
5103       continue;
5104     }
5105     // "cast" fixed length vector to a scalable vector.
5106     MVT OpVT = V.getSimpleValueType();
5107     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5108     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5109            "Only fixed length vectors are supported!");
5110     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5111   }
5112 
5113   if (!VT.isFixedLengthVector())
5114     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5115 
5116   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5117 
5118   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5119 
5120   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5121 }
5122 
5123 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5124 // matched to a RVV indexed load. The RVV indexed load instructions only
5125 // support the "unsigned unscaled" addressing mode; indices are implicitly
5126 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5127 // signed or scaled indexing is extended to the XLEN value type and scaled
5128 // accordingly.
5129 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5130                                                SelectionDAG &DAG) const {
5131   SDLoc DL(Op);
5132   MVT VT = Op.getSimpleValueType();
5133 
5134   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5135   EVT MemVT = MemSD->getMemoryVT();
5136   MachineMemOperand *MMO = MemSD->getMemOperand();
5137   SDValue Chain = MemSD->getChain();
5138   SDValue BasePtr = MemSD->getBasePtr();
5139 
5140   ISD::LoadExtType LoadExtType;
5141   SDValue Index, Mask, PassThru, VL;
5142 
5143   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5144     Index = VPGN->getIndex();
5145     Mask = VPGN->getMask();
5146     PassThru = DAG.getUNDEF(VT);
5147     VL = VPGN->getVectorLength();
5148     // VP doesn't support extending loads.
5149     LoadExtType = ISD::NON_EXTLOAD;
5150   } else {
5151     // Else it must be a MGATHER.
5152     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5153     Index = MGN->getIndex();
5154     Mask = MGN->getMask();
5155     PassThru = MGN->getPassThru();
5156     LoadExtType = MGN->getExtensionType();
5157   }
5158 
5159   MVT IndexVT = Index.getSimpleValueType();
5160   MVT XLenVT = Subtarget.getXLenVT();
5161 
5162   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5163          "Unexpected VTs!");
5164   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5165   // Targets have to explicitly opt-in for extending vector loads.
5166   assert(LoadExtType == ISD::NON_EXTLOAD &&
5167          "Unexpected extending MGATHER/VP_GATHER");
5168   (void)LoadExtType;
5169 
5170   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5171   // the selection of the masked intrinsics doesn't do this for us.
5172   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5173 
5174   MVT ContainerVT = VT;
5175   if (VT.isFixedLengthVector()) {
5176     // We need to use the larger of the result and index type to determine the
5177     // scalable type to use so we don't increase LMUL for any operand/result.
5178     if (VT.bitsGE(IndexVT)) {
5179       ContainerVT = getContainerForFixedLengthVector(VT);
5180       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5181                                  ContainerVT.getVectorElementCount());
5182     } else {
5183       IndexVT = getContainerForFixedLengthVector(IndexVT);
5184       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5185                                      IndexVT.getVectorElementCount());
5186     }
5187 
5188     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5189 
5190     if (!IsUnmasked) {
5191       MVT MaskVT =
5192           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5193       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5194       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5195     }
5196   }
5197 
5198   if (!VL)
5199     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5200 
5201   unsigned IntID =
5202       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5203   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5204   if (!IsUnmasked)
5205     Ops.push_back(PassThru);
5206   Ops.push_back(BasePtr);
5207   Ops.push_back(Index);
5208   if (!IsUnmasked)
5209     Ops.push_back(Mask);
5210   Ops.push_back(VL);
5211   if (!IsUnmasked)
5212     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5213 
5214   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5215   SDValue Result =
5216       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5217   Chain = Result.getValue(1);
5218 
5219   if (VT.isFixedLengthVector())
5220     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5221 
5222   return DAG.getMergeValues({Result, Chain}, DL);
5223 }
5224 
5225 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5226 // matched to a RVV indexed store. The RVV indexed store instructions only
5227 // support the "unsigned unscaled" addressing mode; indices are implicitly
5228 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5229 // signed or scaled indexing is extended to the XLEN value type and scaled
5230 // accordingly.
5231 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5232                                                 SelectionDAG &DAG) const {
5233   SDLoc DL(Op);
5234   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5235   EVT MemVT = MemSD->getMemoryVT();
5236   MachineMemOperand *MMO = MemSD->getMemOperand();
5237   SDValue Chain = MemSD->getChain();
5238   SDValue BasePtr = MemSD->getBasePtr();
5239 
5240   bool IsTruncatingStore = false;
5241   SDValue Index, Mask, Val, VL;
5242 
5243   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5244     Index = VPSN->getIndex();
5245     Mask = VPSN->getMask();
5246     Val = VPSN->getValue();
5247     VL = VPSN->getVectorLength();
5248     // VP doesn't support truncating stores.
5249     IsTruncatingStore = false;
5250   } else {
5251     // Else it must be a MSCATTER.
5252     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5253     Index = MSN->getIndex();
5254     Mask = MSN->getMask();
5255     Val = MSN->getValue();
5256     IsTruncatingStore = MSN->isTruncatingStore();
5257   }
5258 
5259   MVT VT = Val.getSimpleValueType();
5260   MVT IndexVT = Index.getSimpleValueType();
5261   MVT XLenVT = Subtarget.getXLenVT();
5262 
5263   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5264          "Unexpected VTs!");
5265   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5266   // Targets have to explicitly opt-in for extending vector loads and
5267   // truncating vector stores.
5268   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5269   (void)IsTruncatingStore;
5270 
5271   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5272   // the selection of the masked intrinsics doesn't do this for us.
5273   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5274 
5275   MVT ContainerVT = VT;
5276   if (VT.isFixedLengthVector()) {
5277     // We need to use the larger of the value and index type to determine the
5278     // scalable type to use so we don't increase LMUL for any operand/result.
5279     if (VT.bitsGE(IndexVT)) {
5280       ContainerVT = getContainerForFixedLengthVector(VT);
5281       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5282                                  ContainerVT.getVectorElementCount());
5283     } else {
5284       IndexVT = getContainerForFixedLengthVector(IndexVT);
5285       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5286                                      IndexVT.getVectorElementCount());
5287     }
5288 
5289     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5290     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5291 
5292     if (!IsUnmasked) {
5293       MVT MaskVT =
5294           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5295       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5296     }
5297   }
5298 
5299   if (!VL)
5300     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5301 
5302   unsigned IntID =
5303       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5304   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5305   Ops.push_back(Val);
5306   Ops.push_back(BasePtr);
5307   Ops.push_back(Index);
5308   if (!IsUnmasked)
5309     Ops.push_back(Mask);
5310   Ops.push_back(VL);
5311 
5312   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5313                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5314 }
5315 
5316 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5317                                                SelectionDAG &DAG) const {
5318   const MVT XLenVT = Subtarget.getXLenVT();
5319   SDLoc DL(Op);
5320   SDValue Chain = Op->getOperand(0);
5321   SDValue SysRegNo = DAG.getConstant(
5322       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5323   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5324   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5325 
5326   // Encoding used for rounding mode in RISCV differs from that used in
5327   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5328   // table, which consists of a sequence of 4-bit fields, each representing
5329   // corresponding FLT_ROUNDS mode.
5330   static const int Table =
5331       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5332       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5333       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5334       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5335       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5336 
5337   SDValue Shift =
5338       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5339   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5340                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5341   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5342                                DAG.getConstant(7, DL, XLenVT));
5343 
5344   return DAG.getMergeValues({Masked, Chain}, DL);
5345 }
5346 
5347 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5348                                                SelectionDAG &DAG) const {
5349   const MVT XLenVT = Subtarget.getXLenVT();
5350   SDLoc DL(Op);
5351   SDValue Chain = Op->getOperand(0);
5352   SDValue RMValue = Op->getOperand(1);
5353   SDValue SysRegNo = DAG.getConstant(
5354       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5355 
5356   // Encoding used for rounding mode in RISCV differs from that used in
5357   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5358   // a table, which consists of a sequence of 4-bit fields, each representing
5359   // corresponding RISCV mode.
5360   static const unsigned Table =
5361       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5362       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5363       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5364       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5365       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5366 
5367   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5368                               DAG.getConstant(2, DL, XLenVT));
5369   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5370                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5371   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5372                         DAG.getConstant(0x7, DL, XLenVT));
5373   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5374                      RMValue);
5375 }
5376 
5377 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5378 // form of the given Opcode.
5379 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5380   switch (Opcode) {
5381   default:
5382     llvm_unreachable("Unexpected opcode");
5383   case ISD::SHL:
5384     return RISCVISD::SLLW;
5385   case ISD::SRA:
5386     return RISCVISD::SRAW;
5387   case ISD::SRL:
5388     return RISCVISD::SRLW;
5389   case ISD::SDIV:
5390     return RISCVISD::DIVW;
5391   case ISD::UDIV:
5392     return RISCVISD::DIVUW;
5393   case ISD::UREM:
5394     return RISCVISD::REMUW;
5395   case ISD::ROTL:
5396     return RISCVISD::ROLW;
5397   case ISD::ROTR:
5398     return RISCVISD::RORW;
5399   case RISCVISD::GREV:
5400     return RISCVISD::GREVW;
5401   case RISCVISD::GORC:
5402     return RISCVISD::GORCW;
5403   }
5404 }
5405 
5406 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5407 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5408 // otherwise be promoted to i64, making it difficult to select the
5409 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5410 // type i8/i16/i32 is lost.
5411 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5412                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5413   SDLoc DL(N);
5414   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5415   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5416   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5417   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5418   // ReplaceNodeResults requires we maintain the same type for the return value.
5419   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5420 }
5421 
5422 // Converts the given 32-bit operation to a i64 operation with signed extension
5423 // semantic to reduce the signed extension instructions.
5424 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5425   SDLoc DL(N);
5426   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5427   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5428   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5429   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5430                                DAG.getValueType(MVT::i32));
5431   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5432 }
5433 
5434 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5435                                              SmallVectorImpl<SDValue> &Results,
5436                                              SelectionDAG &DAG) const {
5437   SDLoc DL(N);
5438   switch (N->getOpcode()) {
5439   default:
5440     llvm_unreachable("Don't know how to custom type legalize this operation!");
5441   case ISD::STRICT_FP_TO_SINT:
5442   case ISD::STRICT_FP_TO_UINT:
5443   case ISD::FP_TO_SINT:
5444   case ISD::FP_TO_UINT: {
5445     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5446            "Unexpected custom legalisation");
5447     bool IsStrict = N->isStrictFPOpcode();
5448     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5449                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5450     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5451     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5452         TargetLowering::TypeSoftenFloat) {
5453       // FIXME: Support strict FP.
5454       if (IsStrict)
5455         return;
5456       if (!isTypeLegal(Op0.getValueType()))
5457         return;
5458       unsigned Opc =
5459           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5460       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5461       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5462       return;
5463     }
5464     // If the FP type needs to be softened, emit a library call using the 'si'
5465     // version. If we left it to default legalization we'd end up with 'di'. If
5466     // the FP type doesn't need to be softened just let generic type
5467     // legalization promote the result type.
5468     RTLIB::Libcall LC;
5469     if (IsSigned)
5470       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5471     else
5472       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5473     MakeLibCallOptions CallOptions;
5474     EVT OpVT = Op0.getValueType();
5475     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5476     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5477     SDValue Result;
5478     std::tie(Result, Chain) =
5479         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5480     Results.push_back(Result);
5481     if (IsStrict)
5482       Results.push_back(Chain);
5483     break;
5484   }
5485   case ISD::READCYCLECOUNTER: {
5486     assert(!Subtarget.is64Bit() &&
5487            "READCYCLECOUNTER only has custom type legalization on riscv32");
5488 
5489     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5490     SDValue RCW =
5491         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5492 
5493     Results.push_back(
5494         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5495     Results.push_back(RCW.getValue(2));
5496     break;
5497   }
5498   case ISD::MUL: {
5499     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5500     unsigned XLen = Subtarget.getXLen();
5501     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5502     if (Size > XLen) {
5503       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5504       SDValue LHS = N->getOperand(0);
5505       SDValue RHS = N->getOperand(1);
5506       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5507 
5508       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5509       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5510       // We need exactly one side to be unsigned.
5511       if (LHSIsU == RHSIsU)
5512         return;
5513 
5514       auto MakeMULPair = [&](SDValue S, SDValue U) {
5515         MVT XLenVT = Subtarget.getXLenVT();
5516         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5517         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5518         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5519         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5520         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5521       };
5522 
5523       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5524       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5525 
5526       // The other operand should be signed, but still prefer MULH when
5527       // possible.
5528       if (RHSIsU && LHSIsS && !RHSIsS)
5529         Results.push_back(MakeMULPair(LHS, RHS));
5530       else if (LHSIsU && RHSIsS && !LHSIsS)
5531         Results.push_back(MakeMULPair(RHS, LHS));
5532 
5533       return;
5534     }
5535     LLVM_FALLTHROUGH;
5536   }
5537   case ISD::ADD:
5538   case ISD::SUB:
5539     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5540            "Unexpected custom legalisation");
5541     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5542     break;
5543   case ISD::SHL:
5544   case ISD::SRA:
5545   case ISD::SRL:
5546     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5547            "Unexpected custom legalisation");
5548     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5549       Results.push_back(customLegalizeToWOp(N, DAG));
5550       break;
5551     }
5552 
5553     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5554     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5555     // shift amount.
5556     if (N->getOpcode() == ISD::SHL) {
5557       SDLoc DL(N);
5558       SDValue NewOp0 =
5559           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5560       SDValue NewOp1 =
5561           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5562       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5563       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5564                                    DAG.getValueType(MVT::i32));
5565       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5566     }
5567 
5568     break;
5569   case ISD::ROTL:
5570   case ISD::ROTR:
5571     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5572            "Unexpected custom legalisation");
5573     Results.push_back(customLegalizeToWOp(N, DAG));
5574     break;
5575   case ISD::CTTZ:
5576   case ISD::CTTZ_ZERO_UNDEF:
5577   case ISD::CTLZ:
5578   case ISD::CTLZ_ZERO_UNDEF: {
5579     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5580            "Unexpected custom legalisation");
5581 
5582     SDValue NewOp0 =
5583         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5584     bool IsCTZ =
5585         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5586     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5587     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5588     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5589     return;
5590   }
5591   case ISD::SDIV:
5592   case ISD::UDIV:
5593   case ISD::UREM: {
5594     MVT VT = N->getSimpleValueType(0);
5595     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5596            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5597            "Unexpected custom legalisation");
5598     // Don't promote division/remainder by constant since we should expand those
5599     // to multiply by magic constant.
5600     // FIXME: What if the expansion is disabled for minsize.
5601     if (N->getOperand(1).getOpcode() == ISD::Constant)
5602       return;
5603 
5604     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5605     // the upper 32 bits. For other types we need to sign or zero extend
5606     // based on the opcode.
5607     unsigned ExtOpc = ISD::ANY_EXTEND;
5608     if (VT != MVT::i32)
5609       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5610                                            : ISD::ZERO_EXTEND;
5611 
5612     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5613     break;
5614   }
5615   case ISD::UADDO:
5616   case ISD::USUBO: {
5617     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5618            "Unexpected custom legalisation");
5619     bool IsAdd = N->getOpcode() == ISD::UADDO;
5620     // Create an ADDW or SUBW.
5621     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5622     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5623     SDValue Res =
5624         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5625     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5626                       DAG.getValueType(MVT::i32));
5627 
5628     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5629     // Since the inputs are sign extended from i32, this is equivalent to
5630     // comparing the lower 32 bits.
5631     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5632     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5633                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5634 
5635     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5636     Results.push_back(Overflow);
5637     return;
5638   }
5639   case ISD::UADDSAT:
5640   case ISD::USUBSAT: {
5641     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5642            "Unexpected custom legalisation");
5643     if (Subtarget.hasStdExtZbb()) {
5644       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5645       // sign extend allows overflow of the lower 32 bits to be detected on
5646       // the promoted size.
5647       SDValue LHS =
5648           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5649       SDValue RHS =
5650           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5651       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5652       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5653       return;
5654     }
5655 
5656     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5657     // promotion for UADDO/USUBO.
5658     Results.push_back(expandAddSubSat(N, DAG));
5659     return;
5660   }
5661   case ISD::BITCAST: {
5662     EVT VT = N->getValueType(0);
5663     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5664     SDValue Op0 = N->getOperand(0);
5665     EVT Op0VT = Op0.getValueType();
5666     MVT XLenVT = Subtarget.getXLenVT();
5667     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5668       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5669       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5670     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5671                Subtarget.hasStdExtF()) {
5672       SDValue FPConv =
5673           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5674       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5675     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5676                isTypeLegal(Op0VT)) {
5677       // Custom-legalize bitcasts from fixed-length vector types to illegal
5678       // scalar types in order to improve codegen. Bitcast the vector to a
5679       // one-element vector type whose element type is the same as the result
5680       // type, and extract the first element.
5681       LLVMContext &Context = *DAG.getContext();
5682       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5683       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5684                                     DAG.getConstant(0, DL, XLenVT)));
5685     }
5686     break;
5687   }
5688   case RISCVISD::GREV:
5689   case RISCVISD::GORC: {
5690     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5691            "Unexpected custom legalisation");
5692     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5693     // This is similar to customLegalizeToWOp, except that we pass the second
5694     // operand (a TargetConstant) straight through: it is already of type
5695     // XLenVT.
5696     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5697     SDValue NewOp0 =
5698         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5699     SDValue NewOp1 =
5700         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5701     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5702     // ReplaceNodeResults requires we maintain the same type for the return
5703     // value.
5704     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5705     break;
5706   }
5707   case RISCVISD::SHFL: {
5708     // There is no SHFLIW instruction, but we can just promote the operation.
5709     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5710            "Unexpected custom legalisation");
5711     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5712     SDValue NewOp0 =
5713         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5714     SDValue NewOp1 =
5715         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5716     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5717     // ReplaceNodeResults requires we maintain the same type for the return
5718     // value.
5719     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5720     break;
5721   }
5722   case ISD::BSWAP:
5723   case ISD::BITREVERSE: {
5724     MVT VT = N->getSimpleValueType(0);
5725     MVT XLenVT = Subtarget.getXLenVT();
5726     assert((VT == MVT::i8 || VT == MVT::i16 ||
5727             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5728            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5729     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5730     unsigned Imm = VT.getSizeInBits() - 1;
5731     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5732     if (N->getOpcode() == ISD::BSWAP)
5733       Imm &= ~0x7U;
5734     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5735     SDValue GREVI =
5736         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5737     // ReplaceNodeResults requires we maintain the same type for the return
5738     // value.
5739     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5740     break;
5741   }
5742   case ISD::FSHL:
5743   case ISD::FSHR: {
5744     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5745            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5746     SDValue NewOp0 =
5747         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5748     SDValue NewOp1 =
5749         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5750     SDValue NewOp2 =
5751         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5752     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5753     // Mask the shift amount to 5 bits.
5754     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5755                          DAG.getConstant(0x1f, DL, MVT::i64));
5756     unsigned Opc =
5757         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5758     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5759     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5760     break;
5761   }
5762   case ISD::EXTRACT_VECTOR_ELT: {
5763     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5764     // type is illegal (currently only vXi64 RV32).
5765     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5766     // transferred to the destination register. We issue two of these from the
5767     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5768     // first element.
5769     SDValue Vec = N->getOperand(0);
5770     SDValue Idx = N->getOperand(1);
5771 
5772     // The vector type hasn't been legalized yet so we can't issue target
5773     // specific nodes if it needs legalization.
5774     // FIXME: We would manually legalize if it's important.
5775     if (!isTypeLegal(Vec.getValueType()))
5776       return;
5777 
5778     MVT VecVT = Vec.getSimpleValueType();
5779 
5780     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5781            VecVT.getVectorElementType() == MVT::i64 &&
5782            "Unexpected EXTRACT_VECTOR_ELT legalization");
5783 
5784     // If this is a fixed vector, we need to convert it to a scalable vector.
5785     MVT ContainerVT = VecVT;
5786     if (VecVT.isFixedLengthVector()) {
5787       ContainerVT = getContainerForFixedLengthVector(VecVT);
5788       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5789     }
5790 
5791     MVT XLenVT = Subtarget.getXLenVT();
5792 
5793     // Use a VL of 1 to avoid processing more elements than we need.
5794     MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5795     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5796     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5797 
5798     // Unless the index is known to be 0, we must slide the vector down to get
5799     // the desired element into index 0.
5800     if (!isNullConstant(Idx)) {
5801       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5802                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5803     }
5804 
5805     // Extract the lower XLEN bits of the correct vector element.
5806     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5807 
5808     // To extract the upper XLEN bits of the vector element, shift the first
5809     // element right by 32 bits and re-extract the lower XLEN bits.
5810     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5811                                      DAG.getConstant(32, DL, XLenVT), VL);
5812     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5813                                  ThirtyTwoV, Mask, VL);
5814 
5815     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5816 
5817     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5818     break;
5819   }
5820   case ISD::INTRINSIC_WO_CHAIN: {
5821     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5822     switch (IntNo) {
5823     default:
5824       llvm_unreachable(
5825           "Don't know how to custom type legalize this intrinsic!");
5826     case Intrinsic::riscv_orc_b: {
5827       // Lower to the GORCI encoding for orc.b with the operand extended.
5828       SDValue NewOp =
5829           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5830       // If Zbp is enabled, use GORCIW which will sign extend the result.
5831       unsigned Opc =
5832           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5833       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5834                                 DAG.getConstant(7, DL, MVT::i64));
5835       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5836       return;
5837     }
5838     case Intrinsic::riscv_grev:
5839     case Intrinsic::riscv_gorc: {
5840       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5841              "Unexpected custom legalisation");
5842       SDValue NewOp1 =
5843           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5844       SDValue NewOp2 =
5845           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5846       unsigned Opc =
5847           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5848       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5849       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5850       break;
5851     }
5852     case Intrinsic::riscv_shfl:
5853     case Intrinsic::riscv_unshfl: {
5854       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5855              "Unexpected custom legalisation");
5856       SDValue NewOp1 =
5857           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5858       SDValue NewOp2 =
5859           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5860       unsigned Opc =
5861           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5862       if (isa<ConstantSDNode>(N->getOperand(2))) {
5863         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5864                              DAG.getConstant(0xf, DL, MVT::i64));
5865         Opc =
5866             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5867       }
5868       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5869       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5870       break;
5871     }
5872     case Intrinsic::riscv_bcompress:
5873     case Intrinsic::riscv_bdecompress: {
5874       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5875              "Unexpected custom legalisation");
5876       SDValue NewOp1 =
5877           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5878       SDValue NewOp2 =
5879           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5880       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5881                          ? RISCVISD::BCOMPRESSW
5882                          : RISCVISD::BDECOMPRESSW;
5883       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5884       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5885       break;
5886     }
5887     case Intrinsic::riscv_vmv_x_s: {
5888       EVT VT = N->getValueType(0);
5889       MVT XLenVT = Subtarget.getXLenVT();
5890       if (VT.bitsLT(XLenVT)) {
5891         // Simple case just extract using vmv.x.s and truncate.
5892         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5893                                       Subtarget.getXLenVT(), N->getOperand(1));
5894         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5895         return;
5896       }
5897 
5898       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5899              "Unexpected custom legalization");
5900 
5901       // We need to do the move in two steps.
5902       SDValue Vec = N->getOperand(1);
5903       MVT VecVT = Vec.getSimpleValueType();
5904 
5905       // First extract the lower XLEN bits of the element.
5906       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5907 
5908       // To extract the upper XLEN bits of the vector element, shift the first
5909       // element right by 32 bits and re-extract the lower XLEN bits.
5910       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5911       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5912       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5913       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5914                                        DAG.getConstant(32, DL, XLenVT), VL);
5915       SDValue LShr32 =
5916           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5917       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5918 
5919       Results.push_back(
5920           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5921       break;
5922     }
5923     }
5924     break;
5925   }
5926   case ISD::VECREDUCE_ADD:
5927   case ISD::VECREDUCE_AND:
5928   case ISD::VECREDUCE_OR:
5929   case ISD::VECREDUCE_XOR:
5930   case ISD::VECREDUCE_SMAX:
5931   case ISD::VECREDUCE_UMAX:
5932   case ISD::VECREDUCE_SMIN:
5933   case ISD::VECREDUCE_UMIN:
5934     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5935       Results.push_back(V);
5936     break;
5937   case ISD::VP_REDUCE_ADD:
5938   case ISD::VP_REDUCE_AND:
5939   case ISD::VP_REDUCE_OR:
5940   case ISD::VP_REDUCE_XOR:
5941   case ISD::VP_REDUCE_SMAX:
5942   case ISD::VP_REDUCE_UMAX:
5943   case ISD::VP_REDUCE_SMIN:
5944   case ISD::VP_REDUCE_UMIN:
5945     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
5946       Results.push_back(V);
5947     break;
5948   case ISD::FLT_ROUNDS_: {
5949     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5950     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5951     Results.push_back(Res.getValue(0));
5952     Results.push_back(Res.getValue(1));
5953     break;
5954   }
5955   }
5956 }
5957 
5958 // A structure to hold one of the bit-manipulation patterns below. Together, a
5959 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
5960 //   (or (and (shl x, 1), 0xAAAAAAAA),
5961 //       (and (srl x, 1), 0x55555555))
5962 struct RISCVBitmanipPat {
5963   SDValue Op;
5964   unsigned ShAmt;
5965   bool IsSHL;
5966 
5967   bool formsPairWith(const RISCVBitmanipPat &Other) const {
5968     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
5969   }
5970 };
5971 
5972 // Matches patterns of the form
5973 //   (and (shl x, C2), (C1 << C2))
5974 //   (and (srl x, C2), C1)
5975 //   (shl (and x, C1), C2)
5976 //   (srl (and x, (C1 << C2)), C2)
5977 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
5978 // The expected masks for each shift amount are specified in BitmanipMasks where
5979 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
5980 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
5981 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
5982 // XLen is 64.
5983 static Optional<RISCVBitmanipPat>
5984 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
5985   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
5986          "Unexpected number of masks");
5987   Optional<uint64_t> Mask;
5988   // Optionally consume a mask around the shift operation.
5989   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
5990     Mask = Op.getConstantOperandVal(1);
5991     Op = Op.getOperand(0);
5992   }
5993   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
5994     return None;
5995   bool IsSHL = Op.getOpcode() == ISD::SHL;
5996 
5997   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5998     return None;
5999   uint64_t ShAmt = Op.getConstantOperandVal(1);
6000 
6001   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6002   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6003     return None;
6004   // If we don't have enough masks for 64 bit, then we must be trying to
6005   // match SHFL so we're only allowed to shift 1/4 of the width.
6006   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6007     return None;
6008 
6009   SDValue Src = Op.getOperand(0);
6010 
6011   // The expected mask is shifted left when the AND is found around SHL
6012   // patterns.
6013   //   ((x >> 1) & 0x55555555)
6014   //   ((x << 1) & 0xAAAAAAAA)
6015   bool SHLExpMask = IsSHL;
6016 
6017   if (!Mask) {
6018     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6019     // the mask is all ones: consume that now.
6020     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6021       Mask = Src.getConstantOperandVal(1);
6022       Src = Src.getOperand(0);
6023       // The expected mask is now in fact shifted left for SRL, so reverse the
6024       // decision.
6025       //   ((x & 0xAAAAAAAA) >> 1)
6026       //   ((x & 0x55555555) << 1)
6027       SHLExpMask = !SHLExpMask;
6028     } else {
6029       // Use a default shifted mask of all-ones if there's no AND, truncated
6030       // down to the expected width. This simplifies the logic later on.
6031       Mask = maskTrailingOnes<uint64_t>(Width);
6032       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6033     }
6034   }
6035 
6036   unsigned MaskIdx = Log2_32(ShAmt);
6037   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6038 
6039   if (SHLExpMask)
6040     ExpMask <<= ShAmt;
6041 
6042   if (Mask != ExpMask)
6043     return None;
6044 
6045   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6046 }
6047 
6048 // Matches any of the following bit-manipulation patterns:
6049 //   (and (shl x, 1), (0x55555555 << 1))
6050 //   (and (srl x, 1), 0x55555555)
6051 //   (shl (and x, 0x55555555), 1)
6052 //   (srl (and x, (0x55555555 << 1)), 1)
6053 // where the shift amount and mask may vary thus:
6054 //   [1]  = 0x55555555 / 0xAAAAAAAA
6055 //   [2]  = 0x33333333 / 0xCCCCCCCC
6056 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6057 //   [8]  = 0x00FF00FF / 0xFF00FF00
6058 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6059 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6060 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6061   // These are the unshifted masks which we use to match bit-manipulation
6062   // patterns. They may be shifted left in certain circumstances.
6063   static const uint64_t BitmanipMasks[] = {
6064       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6065       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6066 
6067   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6068 }
6069 
6070 // Match the following pattern as a GREVI(W) operation
6071 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6072 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6073                                const RISCVSubtarget &Subtarget) {
6074   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6075   EVT VT = Op.getValueType();
6076 
6077   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6078     auto LHS = matchGREVIPat(Op.getOperand(0));
6079     auto RHS = matchGREVIPat(Op.getOperand(1));
6080     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6081       SDLoc DL(Op);
6082       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6083                          DAG.getConstant(LHS->ShAmt, DL, VT));
6084     }
6085   }
6086   return SDValue();
6087 }
6088 
6089 // Matches any the following pattern as a GORCI(W) operation
6090 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6091 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6092 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6093 // Note that with the variant of 3.,
6094 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6095 // the inner pattern will first be matched as GREVI and then the outer
6096 // pattern will be matched to GORC via the first rule above.
6097 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6098 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6099                                const RISCVSubtarget &Subtarget) {
6100   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6101   EVT VT = Op.getValueType();
6102 
6103   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6104     SDLoc DL(Op);
6105     SDValue Op0 = Op.getOperand(0);
6106     SDValue Op1 = Op.getOperand(1);
6107 
6108     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6109       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6110           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6111           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6112         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6113       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6114       if ((Reverse.getOpcode() == ISD::ROTL ||
6115            Reverse.getOpcode() == ISD::ROTR) &&
6116           Reverse.getOperand(0) == X &&
6117           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6118         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6119         if (RotAmt == (VT.getSizeInBits() / 2))
6120           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6121                              DAG.getConstant(RotAmt, DL, VT));
6122       }
6123       return SDValue();
6124     };
6125 
6126     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6127     if (SDValue V = MatchOROfReverse(Op0, Op1))
6128       return V;
6129     if (SDValue V = MatchOROfReverse(Op1, Op0))
6130       return V;
6131 
6132     // OR is commutable so canonicalize its OR operand to the left
6133     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6134       std::swap(Op0, Op1);
6135     if (Op0.getOpcode() != ISD::OR)
6136       return SDValue();
6137     SDValue OrOp0 = Op0.getOperand(0);
6138     SDValue OrOp1 = Op0.getOperand(1);
6139     auto LHS = matchGREVIPat(OrOp0);
6140     // OR is commutable so swap the operands and try again: x might have been
6141     // on the left
6142     if (!LHS) {
6143       std::swap(OrOp0, OrOp1);
6144       LHS = matchGREVIPat(OrOp0);
6145     }
6146     auto RHS = matchGREVIPat(Op1);
6147     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6148       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6149                          DAG.getConstant(LHS->ShAmt, DL, VT));
6150     }
6151   }
6152   return SDValue();
6153 }
6154 
6155 // Matches any of the following bit-manipulation patterns:
6156 //   (and (shl x, 1), (0x22222222 << 1))
6157 //   (and (srl x, 1), 0x22222222)
6158 //   (shl (and x, 0x22222222), 1)
6159 //   (srl (and x, (0x22222222 << 1)), 1)
6160 // where the shift amount and mask may vary thus:
6161 //   [1]  = 0x22222222 / 0x44444444
6162 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6163 //   [4]  = 0x00F000F0 / 0x0F000F00
6164 //   [8]  = 0x0000FF00 / 0x00FF0000
6165 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6166 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6167   // These are the unshifted masks which we use to match bit-manipulation
6168   // patterns. They may be shifted left in certain circumstances.
6169   static const uint64_t BitmanipMasks[] = {
6170       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6171       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6172 
6173   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6174 }
6175 
6176 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6177 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6178                                const RISCVSubtarget &Subtarget) {
6179   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6180   EVT VT = Op.getValueType();
6181 
6182   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6183     return SDValue();
6184 
6185   SDValue Op0 = Op.getOperand(0);
6186   SDValue Op1 = Op.getOperand(1);
6187 
6188   // Or is commutable so canonicalize the second OR to the LHS.
6189   if (Op0.getOpcode() != ISD::OR)
6190     std::swap(Op0, Op1);
6191   if (Op0.getOpcode() != ISD::OR)
6192     return SDValue();
6193 
6194   // We found an inner OR, so our operands are the operands of the inner OR
6195   // and the other operand of the outer OR.
6196   SDValue A = Op0.getOperand(0);
6197   SDValue B = Op0.getOperand(1);
6198   SDValue C = Op1;
6199 
6200   auto Match1 = matchSHFLPat(A);
6201   auto Match2 = matchSHFLPat(B);
6202 
6203   // If neither matched, we failed.
6204   if (!Match1 && !Match2)
6205     return SDValue();
6206 
6207   // We had at least one match. if one failed, try the remaining C operand.
6208   if (!Match1) {
6209     std::swap(A, C);
6210     Match1 = matchSHFLPat(A);
6211     if (!Match1)
6212       return SDValue();
6213   } else if (!Match2) {
6214     std::swap(B, C);
6215     Match2 = matchSHFLPat(B);
6216     if (!Match2)
6217       return SDValue();
6218   }
6219   assert(Match1 && Match2);
6220 
6221   // Make sure our matches pair up.
6222   if (!Match1->formsPairWith(*Match2))
6223     return SDValue();
6224 
6225   // All the remains is to make sure C is an AND with the same input, that masks
6226   // out the bits that are being shuffled.
6227   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6228       C.getOperand(0) != Match1->Op)
6229     return SDValue();
6230 
6231   uint64_t Mask = C.getConstantOperandVal(1);
6232 
6233   static const uint64_t BitmanipMasks[] = {
6234       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6235       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6236   };
6237 
6238   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6239   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6240   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6241 
6242   if (Mask != ExpMask)
6243     return SDValue();
6244 
6245   SDLoc DL(Op);
6246   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6247                      DAG.getConstant(Match1->ShAmt, DL, VT));
6248 }
6249 
6250 // Optimize (add (shl x, c0), (shl y, c1)) ->
6251 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6252 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6253                                   const RISCVSubtarget &Subtarget) {
6254   // Perform this optimization only in the zba extension.
6255   if (!Subtarget.hasStdExtZba())
6256     return SDValue();
6257 
6258   // Skip for vector types and larger types.
6259   EVT VT = N->getValueType(0);
6260   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6261     return SDValue();
6262 
6263   // The two operand nodes must be SHL and have no other use.
6264   SDValue N0 = N->getOperand(0);
6265   SDValue N1 = N->getOperand(1);
6266   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6267       !N0->hasOneUse() || !N1->hasOneUse())
6268     return SDValue();
6269 
6270   // Check c0 and c1.
6271   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6272   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6273   if (!N0C || !N1C)
6274     return SDValue();
6275   int64_t C0 = N0C->getSExtValue();
6276   int64_t C1 = N1C->getSExtValue();
6277   if (C0 <= 0 || C1 <= 0)
6278     return SDValue();
6279 
6280   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6281   int64_t Bits = std::min(C0, C1);
6282   int64_t Diff = std::abs(C0 - C1);
6283   if (Diff != 1 && Diff != 2 && Diff != 3)
6284     return SDValue();
6285 
6286   // Build nodes.
6287   SDLoc DL(N);
6288   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6289   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6290   SDValue NA0 =
6291       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6292   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6293   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6294 }
6295 
6296 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6297 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6298 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6299 // not undo itself, but they are redundant.
6300 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6301   SDValue Src = N->getOperand(0);
6302 
6303   if (Src.getOpcode() != N->getOpcode())
6304     return SDValue();
6305 
6306   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6307       !isa<ConstantSDNode>(Src.getOperand(1)))
6308     return SDValue();
6309 
6310   unsigned ShAmt1 = N->getConstantOperandVal(1);
6311   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6312   Src = Src.getOperand(0);
6313 
6314   unsigned CombinedShAmt;
6315   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6316     CombinedShAmt = ShAmt1 | ShAmt2;
6317   else
6318     CombinedShAmt = ShAmt1 ^ ShAmt2;
6319 
6320   if (CombinedShAmt == 0)
6321     return Src;
6322 
6323   SDLoc DL(N);
6324   return DAG.getNode(
6325       N->getOpcode(), DL, N->getValueType(0), Src,
6326       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6327 }
6328 
6329 // Combine a constant select operand into its use:
6330 //
6331 // (and (select cond, -1, c), x)
6332 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6333 // (or  (select cond, 0, c), x)
6334 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6335 // (xor (select cond, 0, c), x)
6336 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6337 // (add (select cond, 0, c), x)
6338 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6339 // (sub x, (select cond, 0, c))
6340 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6341 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6342                                    SelectionDAG &DAG, bool AllOnes) {
6343   EVT VT = N->getValueType(0);
6344 
6345   // Skip vectors.
6346   if (VT.isVector())
6347     return SDValue();
6348 
6349   if ((Slct.getOpcode() != ISD::SELECT &&
6350        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6351       !Slct.hasOneUse())
6352     return SDValue();
6353 
6354   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6355     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6356   };
6357 
6358   bool SwapSelectOps;
6359   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6360   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6361   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6362   SDValue NonConstantVal;
6363   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6364     SwapSelectOps = false;
6365     NonConstantVal = FalseVal;
6366   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6367     SwapSelectOps = true;
6368     NonConstantVal = TrueVal;
6369   } else
6370     return SDValue();
6371 
6372   // Slct is now know to be the desired identity constant when CC is true.
6373   TrueVal = OtherOp;
6374   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6375   // Unless SwapSelectOps says the condition should be false.
6376   if (SwapSelectOps)
6377     std::swap(TrueVal, FalseVal);
6378 
6379   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6380     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6381                        {Slct.getOperand(0), Slct.getOperand(1),
6382                         Slct.getOperand(2), TrueVal, FalseVal});
6383 
6384   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6385                      {Slct.getOperand(0), TrueVal, FalseVal});
6386 }
6387 
6388 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6389 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6390                                               bool AllOnes) {
6391   SDValue N0 = N->getOperand(0);
6392   SDValue N1 = N->getOperand(1);
6393   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6394     return Result;
6395   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6396     return Result;
6397   return SDValue();
6398 }
6399 
6400 // Transform (add (mul x, c0), c1) ->
6401 //           (add (mul (add x, c1/c0), c0), c1%c0).
6402 // if c1/c0 and c1%c0 are simm12, while c1 is not.
6403 // Or transform (add (mul x, c0), c1) ->
6404 //              (mul (add x, c1/c0), c0).
6405 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6406 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6407                                      const RISCVSubtarget &Subtarget) {
6408   // Skip for vector types and larger types.
6409   EVT VT = N->getValueType(0);
6410   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6411     return SDValue();
6412   // The first operand node must be a MUL and has no other use.
6413   SDValue N0 = N->getOperand(0);
6414   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6415     return SDValue();
6416   // Check if c0 and c1 match above conditions.
6417   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6418   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6419   if (!N0C || !N1C)
6420     return SDValue();
6421   int64_t C0 = N0C->getSExtValue();
6422   int64_t C1 = N1C->getSExtValue();
6423   if (C0 == -1 || C0 == 0 || C0 == 1 || (C1 / C0) == 0 || isInt<12>(C1) ||
6424       !isInt<12>(C1 % C0) || !isInt<12>(C1 / C0))
6425     return SDValue();
6426   // If C0 * (C1 / C0) is a 12-bit integer, this transform will be reversed.
6427   if (isInt<12>(C0 * (C1 / C0)))
6428     return SDValue();
6429   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6430   SDLoc DL(N);
6431   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6432                              DAG.getConstant(C1 / C0, DL, VT));
6433   SDValue New1 =
6434       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6435   if ((C1 % C0) == 0)
6436     return New1;
6437   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(C1 % C0, DL, VT));
6438 }
6439 
6440 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6441                                  const RISCVSubtarget &Subtarget) {
6442   // Transform (add (mul x, c0), c1) ->
6443   //           (add (mul (add x, c1/c0), c0), c1%c0).
6444   // if c1/c0 and c1%c0 are simm12, while c1 is not.
6445   // Or transform (add (mul x, c0), c1) ->
6446   //              (mul (add x, c1/c0), c0).
6447   // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6448   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6449     return V;
6450   // Fold (add (shl x, c0), (shl y, c1)) ->
6451   //      (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6452   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6453     return V;
6454   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6455   //      (select lhs, rhs, cc, x, (add x, y))
6456   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6457 }
6458 
6459 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6460   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6461   //      (select lhs, rhs, cc, x, (sub x, y))
6462   SDValue N0 = N->getOperand(0);
6463   SDValue N1 = N->getOperand(1);
6464   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6465 }
6466 
6467 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6468   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6469   //      (select lhs, rhs, cc, x, (and x, y))
6470   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6471 }
6472 
6473 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6474                                 const RISCVSubtarget &Subtarget) {
6475   if (Subtarget.hasStdExtZbp()) {
6476     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6477       return GREV;
6478     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6479       return GORC;
6480     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6481       return SHFL;
6482   }
6483 
6484   // fold (or (select cond, 0, y), x) ->
6485   //      (select cond, x, (or x, y))
6486   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6487 }
6488 
6489 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6490   // fold (xor (select cond, 0, y), x) ->
6491   //      (select cond, x, (xor x, y))
6492   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6493 }
6494 
6495 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6496 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6497 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6498 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6499 // ADDW/SUBW/MULW.
6500 static SDValue performANY_EXTENDCombine(SDNode *N,
6501                                         TargetLowering::DAGCombinerInfo &DCI,
6502                                         const RISCVSubtarget &Subtarget) {
6503   if (!Subtarget.is64Bit())
6504     return SDValue();
6505 
6506   SelectionDAG &DAG = DCI.DAG;
6507 
6508   SDValue Src = N->getOperand(0);
6509   EVT VT = N->getValueType(0);
6510   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6511     return SDValue();
6512 
6513   // The opcode must be one that can implicitly sign_extend.
6514   // FIXME: Additional opcodes.
6515   switch (Src.getOpcode()) {
6516   default:
6517     return SDValue();
6518   case ISD::MUL:
6519     if (!Subtarget.hasStdExtM())
6520       return SDValue();
6521     LLVM_FALLTHROUGH;
6522   case ISD::ADD:
6523   case ISD::SUB:
6524     break;
6525   }
6526 
6527   // Only handle cases where the result is used by a CopyToReg. That likely
6528   // means the value is a liveout of the basic block. This helps prevent
6529   // infinite combine loops like PR51206.
6530   if (none_of(N->uses(),
6531               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6532     return SDValue();
6533 
6534   SmallVector<SDNode *, 4> SetCCs;
6535   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6536                             UE = Src.getNode()->use_end();
6537        UI != UE; ++UI) {
6538     SDNode *User = *UI;
6539     if (User == N)
6540       continue;
6541     if (UI.getUse().getResNo() != Src.getResNo())
6542       continue;
6543     // All i32 setccs are legalized by sign extending operands.
6544     if (User->getOpcode() == ISD::SETCC) {
6545       SetCCs.push_back(User);
6546       continue;
6547     }
6548     // We don't know if we can extend this user.
6549     break;
6550   }
6551 
6552   // If we don't have any SetCCs, this isn't worthwhile.
6553   if (SetCCs.empty())
6554     return SDValue();
6555 
6556   SDLoc DL(N);
6557   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6558   DCI.CombineTo(N, SExt);
6559 
6560   // Promote all the setccs.
6561   for (SDNode *SetCC : SetCCs) {
6562     SmallVector<SDValue, 4> Ops;
6563 
6564     for (unsigned j = 0; j != 2; ++j) {
6565       SDValue SOp = SetCC->getOperand(j);
6566       if (SOp == Src)
6567         Ops.push_back(SExt);
6568       else
6569         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6570     }
6571 
6572     Ops.push_back(SetCC->getOperand(2));
6573     DCI.CombineTo(SetCC,
6574                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6575   }
6576   return SDValue(N, 0);
6577 }
6578 
6579 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6580                                                DAGCombinerInfo &DCI) const {
6581   SelectionDAG &DAG = DCI.DAG;
6582 
6583   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6584   // bits are demanded. N will be added to the Worklist if it was not deleted.
6585   // Caller should return SDValue(N, 0) if this returns true.
6586   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6587     SDValue Op = N->getOperand(OpNo);
6588     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6589     if (!SimplifyDemandedBits(Op, Mask, DCI))
6590       return false;
6591 
6592     if (N->getOpcode() != ISD::DELETED_NODE)
6593       DCI.AddToWorklist(N);
6594     return true;
6595   };
6596 
6597   switch (N->getOpcode()) {
6598   default:
6599     break;
6600   case RISCVISD::SplitF64: {
6601     SDValue Op0 = N->getOperand(0);
6602     // If the input to SplitF64 is just BuildPairF64 then the operation is
6603     // redundant. Instead, use BuildPairF64's operands directly.
6604     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6605       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6606 
6607     SDLoc DL(N);
6608 
6609     // It's cheaper to materialise two 32-bit integers than to load a double
6610     // from the constant pool and transfer it to integer registers through the
6611     // stack.
6612     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6613       APInt V = C->getValueAPF().bitcastToAPInt();
6614       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6615       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6616       return DCI.CombineTo(N, Lo, Hi);
6617     }
6618 
6619     // This is a target-specific version of a DAGCombine performed in
6620     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6621     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6622     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6623     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6624         !Op0.getNode()->hasOneUse())
6625       break;
6626     SDValue NewSplitF64 =
6627         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6628                     Op0.getOperand(0));
6629     SDValue Lo = NewSplitF64.getValue(0);
6630     SDValue Hi = NewSplitF64.getValue(1);
6631     APInt SignBit = APInt::getSignMask(32);
6632     if (Op0.getOpcode() == ISD::FNEG) {
6633       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6634                                   DAG.getConstant(SignBit, DL, MVT::i32));
6635       return DCI.CombineTo(N, Lo, NewHi);
6636     }
6637     assert(Op0.getOpcode() == ISD::FABS);
6638     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6639                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6640     return DCI.CombineTo(N, Lo, NewHi);
6641   }
6642   case RISCVISD::SLLW:
6643   case RISCVISD::SRAW:
6644   case RISCVISD::SRLW:
6645   case RISCVISD::ROLW:
6646   case RISCVISD::RORW: {
6647     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6648     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6649         SimplifyDemandedLowBitsHelper(1, 5))
6650       return SDValue(N, 0);
6651     break;
6652   }
6653   case RISCVISD::CLZW:
6654   case RISCVISD::CTZW: {
6655     // Only the lower 32 bits of the first operand are read
6656     if (SimplifyDemandedLowBitsHelper(0, 32))
6657       return SDValue(N, 0);
6658     break;
6659   }
6660   case RISCVISD::FSL:
6661   case RISCVISD::FSR: {
6662     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6663     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6664     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6665     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6666       return SDValue(N, 0);
6667     break;
6668   }
6669   case RISCVISD::FSLW:
6670   case RISCVISD::FSRW: {
6671     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6672     // read.
6673     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6674         SimplifyDemandedLowBitsHelper(1, 32) ||
6675         SimplifyDemandedLowBitsHelper(2, 6))
6676       return SDValue(N, 0);
6677     break;
6678   }
6679   case RISCVISD::GREV:
6680   case RISCVISD::GORC: {
6681     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6682     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6683     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6684     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6685       return SDValue(N, 0);
6686 
6687     return combineGREVI_GORCI(N, DCI.DAG);
6688   }
6689   case RISCVISD::GREVW:
6690   case RISCVISD::GORCW: {
6691     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6692     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6693         SimplifyDemandedLowBitsHelper(1, 5))
6694       return SDValue(N, 0);
6695 
6696     return combineGREVI_GORCI(N, DCI.DAG);
6697   }
6698   case RISCVISD::SHFL:
6699   case RISCVISD::UNSHFL: {
6700     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6701     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6702     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6703     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6704       return SDValue(N, 0);
6705 
6706     break;
6707   }
6708   case RISCVISD::SHFLW:
6709   case RISCVISD::UNSHFLW: {
6710     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6711     SDValue LHS = N->getOperand(0);
6712     SDValue RHS = N->getOperand(1);
6713     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6714     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6715     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6716         SimplifyDemandedLowBitsHelper(1, 4))
6717       return SDValue(N, 0);
6718 
6719     break;
6720   }
6721   case RISCVISD::BCOMPRESSW:
6722   case RISCVISD::BDECOMPRESSW: {
6723     // Only the lower 32 bits of LHS and RHS are read.
6724     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6725         SimplifyDemandedLowBitsHelper(1, 32))
6726       return SDValue(N, 0);
6727 
6728     break;
6729   }
6730   case RISCVISD::FMV_X_ANYEXTH:
6731   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6732     SDLoc DL(N);
6733     SDValue Op0 = N->getOperand(0);
6734     MVT VT = N->getSimpleValueType(0);
6735     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6736     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6737     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6738     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6739          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6740         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6741          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6742       assert(Op0.getOperand(0).getValueType() == VT &&
6743              "Unexpected value type!");
6744       return Op0.getOperand(0);
6745     }
6746 
6747     // This is a target-specific version of a DAGCombine performed in
6748     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6749     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6750     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6751     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6752         !Op0.getNode()->hasOneUse())
6753       break;
6754     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6755     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6756     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6757     if (Op0.getOpcode() == ISD::FNEG)
6758       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6759                          DAG.getConstant(SignBit, DL, VT));
6760 
6761     assert(Op0.getOpcode() == ISD::FABS);
6762     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6763                        DAG.getConstant(~SignBit, DL, VT));
6764   }
6765   case ISD::ADD:
6766     return performADDCombine(N, DAG, Subtarget);
6767   case ISD::SUB:
6768     return performSUBCombine(N, DAG);
6769   case ISD::AND:
6770     return performANDCombine(N, DAG);
6771   case ISD::OR:
6772     return performORCombine(N, DAG, Subtarget);
6773   case ISD::XOR:
6774     return performXORCombine(N, DAG);
6775   case ISD::ANY_EXTEND:
6776     return performANY_EXTENDCombine(N, DCI, Subtarget);
6777   case ISD::ZERO_EXTEND:
6778     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6779     // type legalization. This is safe because fp_to_uint produces poison if
6780     // it overflows.
6781     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6782         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6783         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6784       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6785                          N->getOperand(0).getOperand(0));
6786     return SDValue();
6787   case RISCVISD::SELECT_CC: {
6788     // Transform
6789     SDValue LHS = N->getOperand(0);
6790     SDValue RHS = N->getOperand(1);
6791     SDValue TrueV = N->getOperand(3);
6792     SDValue FalseV = N->getOperand(4);
6793 
6794     // If the True and False values are the same, we don't need a select_cc.
6795     if (TrueV == FalseV)
6796       return TrueV;
6797 
6798     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6799     if (!ISD::isIntEqualitySetCC(CCVal))
6800       break;
6801 
6802     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6803     //      (select_cc X, Y, lt, trueV, falseV)
6804     // Sometimes the setcc is introduced after select_cc has been formed.
6805     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6806         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6807       // If we're looking for eq 0 instead of ne 0, we need to invert the
6808       // condition.
6809       bool Invert = CCVal == ISD::SETEQ;
6810       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6811       if (Invert)
6812         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6813 
6814       SDLoc DL(N);
6815       RHS = LHS.getOperand(1);
6816       LHS = LHS.getOperand(0);
6817       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6818 
6819       SDValue TargetCC = DAG.getCondCode(CCVal);
6820       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6821                          {LHS, RHS, TargetCC, TrueV, FalseV});
6822     }
6823 
6824     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6825     //      (select_cc X, Y, eq/ne, trueV, falseV)
6826     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6827       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6828                          {LHS.getOperand(0), LHS.getOperand(1),
6829                           N->getOperand(2), TrueV, FalseV});
6830     // (select_cc X, 1, setne, trueV, falseV) ->
6831     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6832     // This can occur when legalizing some floating point comparisons.
6833     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6834     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6835       SDLoc DL(N);
6836       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6837       SDValue TargetCC = DAG.getCondCode(CCVal);
6838       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6839       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6840                          {LHS, RHS, TargetCC, TrueV, FalseV});
6841     }
6842 
6843     break;
6844   }
6845   case RISCVISD::BR_CC: {
6846     SDValue LHS = N->getOperand(1);
6847     SDValue RHS = N->getOperand(2);
6848     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6849     if (!ISD::isIntEqualitySetCC(CCVal))
6850       break;
6851 
6852     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6853     //      (br_cc X, Y, lt, dest)
6854     // Sometimes the setcc is introduced after br_cc has been formed.
6855     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6856         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6857       // If we're looking for eq 0 instead of ne 0, we need to invert the
6858       // condition.
6859       bool Invert = CCVal == ISD::SETEQ;
6860       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6861       if (Invert)
6862         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6863 
6864       SDLoc DL(N);
6865       RHS = LHS.getOperand(1);
6866       LHS = LHS.getOperand(0);
6867       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6868 
6869       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6870                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
6871                          N->getOperand(4));
6872     }
6873 
6874     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
6875     //      (br_cc X, Y, eq/ne, trueV, falseV)
6876     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6877       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
6878                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
6879                          N->getOperand(3), N->getOperand(4));
6880 
6881     // (br_cc X, 1, setne, br_cc) ->
6882     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
6883     // This can occur when legalizing some floating point comparisons.
6884     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6885     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6886       SDLoc DL(N);
6887       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6888       SDValue TargetCC = DAG.getCondCode(CCVal);
6889       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6890       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6891                          N->getOperand(0), LHS, RHS, TargetCC,
6892                          N->getOperand(4));
6893     }
6894     break;
6895   }
6896   case ISD::FCOPYSIGN: {
6897     EVT VT = N->getValueType(0);
6898     if (!VT.isVector())
6899       break;
6900     // There is a form of VFSGNJ which injects the negated sign of its second
6901     // operand. Try and bubble any FNEG up after the extend/round to produce
6902     // this optimized pattern. Avoid modifying cases where FP_ROUND and
6903     // TRUNC=1.
6904     SDValue In2 = N->getOperand(1);
6905     // Avoid cases where the extend/round has multiple uses, as duplicating
6906     // those is typically more expensive than removing a fneg.
6907     if (!In2.hasOneUse())
6908       break;
6909     if (In2.getOpcode() != ISD::FP_EXTEND &&
6910         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
6911       break;
6912     In2 = In2.getOperand(0);
6913     if (In2.getOpcode() != ISD::FNEG)
6914       break;
6915     SDLoc DL(N);
6916     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
6917     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
6918                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
6919   }
6920   case ISD::MGATHER:
6921   case ISD::MSCATTER:
6922   case ISD::VP_GATHER:
6923   case ISD::VP_SCATTER: {
6924     if (!DCI.isBeforeLegalize())
6925       break;
6926     SDValue Index, ScaleOp;
6927     bool IsIndexScaled = false;
6928     bool IsIndexSigned = false;
6929     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
6930       Index = VPGSN->getIndex();
6931       ScaleOp = VPGSN->getScale();
6932       IsIndexScaled = VPGSN->isIndexScaled();
6933       IsIndexSigned = VPGSN->isIndexSigned();
6934     } else {
6935       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
6936       Index = MGSN->getIndex();
6937       ScaleOp = MGSN->getScale();
6938       IsIndexScaled = MGSN->isIndexScaled();
6939       IsIndexSigned = MGSN->isIndexSigned();
6940     }
6941     EVT IndexVT = Index.getValueType();
6942     MVT XLenVT = Subtarget.getXLenVT();
6943     // RISCV indexed loads only support the "unsigned unscaled" addressing
6944     // mode, so anything else must be manually legalized.
6945     bool NeedsIdxLegalization =
6946         IsIndexScaled ||
6947         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
6948     if (!NeedsIdxLegalization)
6949       break;
6950 
6951     SDLoc DL(N);
6952 
6953     // Any index legalization should first promote to XLenVT, so we don't lose
6954     // bits when scaling. This may create an illegal index type so we let
6955     // LLVM's legalization take care of the splitting.
6956     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
6957     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
6958       IndexVT = IndexVT.changeVectorElementType(XLenVT);
6959       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6960                           DL, IndexVT, Index);
6961     }
6962 
6963     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
6964     if (IsIndexScaled && Scale != 1) {
6965       // Manually scale the indices by the element size.
6966       // TODO: Sanitize the scale operand here?
6967       // TODO: For VP nodes, should we use VP_SHL here?
6968       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
6969       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
6970       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
6971     }
6972 
6973     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
6974     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
6975       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
6976                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
6977                               VPGN->getScale(), VPGN->getMask(),
6978                               VPGN->getVectorLength()},
6979                              VPGN->getMemOperand(), NewIndexTy);
6980     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
6981       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
6982                               {VPSN->getChain(), VPSN->getValue(),
6983                                VPSN->getBasePtr(), Index, VPSN->getScale(),
6984                                VPSN->getMask(), VPSN->getVectorLength()},
6985                               VPSN->getMemOperand(), NewIndexTy);
6986     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
6987       return DAG.getMaskedGather(
6988           N->getVTList(), MGN->getMemoryVT(), DL,
6989           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
6990            MGN->getBasePtr(), Index, MGN->getScale()},
6991           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
6992     const auto *MSN = cast<MaskedScatterSDNode>(N);
6993     return DAG.getMaskedScatter(
6994         N->getVTList(), MSN->getMemoryVT(), DL,
6995         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
6996          Index, MSN->getScale()},
6997         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
6998   }
6999   case RISCVISD::SRA_VL:
7000   case RISCVISD::SRL_VL:
7001   case RISCVISD::SHL_VL: {
7002     SDValue ShAmt = N->getOperand(1);
7003     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7004       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7005       SDLoc DL(N);
7006       SDValue VL = N->getOperand(3);
7007       EVT VT = N->getValueType(0);
7008       ShAmt =
7009           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7010       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7011                          N->getOperand(2), N->getOperand(3));
7012     }
7013     break;
7014   }
7015   case ISD::SRA:
7016   case ISD::SRL:
7017   case ISD::SHL: {
7018     SDValue ShAmt = N->getOperand(1);
7019     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7020       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7021       SDLoc DL(N);
7022       EVT VT = N->getValueType(0);
7023       ShAmt =
7024           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7025       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7026     }
7027     break;
7028   }
7029   case RISCVISD::MUL_VL: {
7030     // Try to form VWMUL or VWMULU.
7031     // FIXME: Look for splat of extended scalar as well.
7032     // FIXME: Support VWMULSU.
7033     SDValue Op0 = N->getOperand(0);
7034     SDValue Op1 = N->getOperand(1);
7035     bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7036     bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7037     if ((!IsSignExt && !IsZeroExt) || Op0.getOpcode() != Op1.getOpcode())
7038       return SDValue();
7039 
7040     // Make sure the extends have a single use.
7041     if (!Op0.hasOneUse() || !Op1.hasOneUse())
7042       return SDValue();
7043 
7044     SDValue Mask = N->getOperand(2);
7045     SDValue VL = N->getOperand(3);
7046     if (Op0.getOperand(1) != Mask || Op1.getOperand(1) != Mask ||
7047         Op0.getOperand(2) != VL || Op1.getOperand(2) != VL)
7048       return SDValue();
7049 
7050     Op0 = Op0.getOperand(0);
7051     Op1 = Op1.getOperand(0);
7052 
7053     MVT VT = N->getSimpleValueType(0);
7054     MVT NarrowVT =
7055         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() / 2),
7056                          VT.getVectorElementCount());
7057 
7058     SDLoc DL(N);
7059 
7060     // Re-introduce narrower extends if needed.
7061     unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7062     if (Op0.getValueType() != NarrowVT)
7063       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7064     if (Op1.getValueType() != NarrowVT)
7065       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7066 
7067     unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7068     return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7069   }
7070   }
7071 
7072   return SDValue();
7073 }
7074 
7075 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7076     const SDNode *N, CombineLevel Level) const {
7077   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7078   // materialised in fewer instructions than `(OP _, c1)`:
7079   //
7080   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7081   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7082   SDValue N0 = N->getOperand(0);
7083   EVT Ty = N0.getValueType();
7084   if (Ty.isScalarInteger() &&
7085       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7086     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7087     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7088     if (C1 && C2) {
7089       const APInt &C1Int = C1->getAPIntValue();
7090       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7091 
7092       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7093       // and the combine should happen, to potentially allow further combines
7094       // later.
7095       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7096           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7097         return true;
7098 
7099       // We can materialise `c1` in an add immediate, so it's "free", and the
7100       // combine should be prevented.
7101       if (C1Int.getMinSignedBits() <= 64 &&
7102           isLegalAddImmediate(C1Int.getSExtValue()))
7103         return false;
7104 
7105       // Neither constant will fit into an immediate, so find materialisation
7106       // costs.
7107       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7108                                               Subtarget.getFeatureBits(),
7109                                               /*CompressionCost*/true);
7110       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7111           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7112           /*CompressionCost*/true);
7113 
7114       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7115       // combine should be prevented.
7116       if (C1Cost < ShiftedC1Cost)
7117         return false;
7118     }
7119   }
7120   return true;
7121 }
7122 
7123 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7124     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7125     TargetLoweringOpt &TLO) const {
7126   // Delay this optimization as late as possible.
7127   if (!TLO.LegalOps)
7128     return false;
7129 
7130   EVT VT = Op.getValueType();
7131   if (VT.isVector())
7132     return false;
7133 
7134   // Only handle AND for now.
7135   if (Op.getOpcode() != ISD::AND)
7136     return false;
7137 
7138   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7139   if (!C)
7140     return false;
7141 
7142   const APInt &Mask = C->getAPIntValue();
7143 
7144   // Clear all non-demanded bits initially.
7145   APInt ShrunkMask = Mask & DemandedBits;
7146 
7147   // Try to make a smaller immediate by setting undemanded bits.
7148 
7149   APInt ExpandedMask = Mask | ~DemandedBits;
7150 
7151   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7152     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7153   };
7154   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7155     if (NewMask == Mask)
7156       return true;
7157     SDLoc DL(Op);
7158     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7159     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7160     return TLO.CombineTo(Op, NewOp);
7161   };
7162 
7163   // If the shrunk mask fits in sign extended 12 bits, let the target
7164   // independent code apply it.
7165   if (ShrunkMask.isSignedIntN(12))
7166     return false;
7167 
7168   // Preserve (and X, 0xffff) when zext.h is supported.
7169   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7170     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7171     if (IsLegalMask(NewMask))
7172       return UseMask(NewMask);
7173   }
7174 
7175   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7176   if (VT == MVT::i64) {
7177     APInt NewMask = APInt(64, 0xffffffff);
7178     if (IsLegalMask(NewMask))
7179       return UseMask(NewMask);
7180   }
7181 
7182   // For the remaining optimizations, we need to be able to make a negative
7183   // number through a combination of mask and undemanded bits.
7184   if (!ExpandedMask.isNegative())
7185     return false;
7186 
7187   // What is the fewest number of bits we need to represent the negative number.
7188   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7189 
7190   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7191   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7192   APInt NewMask = ShrunkMask;
7193   if (MinSignedBits <= 12)
7194     NewMask.setBitsFrom(11);
7195   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7196     NewMask.setBitsFrom(31);
7197   else
7198     return false;
7199 
7200   // Sanity check that our new mask is a subset of the demanded mask.
7201   assert(IsLegalMask(NewMask));
7202   return UseMask(NewMask);
7203 }
7204 
7205 static void computeGREV(APInt &Src, unsigned ShAmt) {
7206   ShAmt &= Src.getBitWidth() - 1;
7207   uint64_t x = Src.getZExtValue();
7208   if (ShAmt & 1)
7209     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7210   if (ShAmt & 2)
7211     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7212   if (ShAmt & 4)
7213     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7214   if (ShAmt & 8)
7215     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7216   if (ShAmt & 16)
7217     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7218   if (ShAmt & 32)
7219     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7220   Src = x;
7221 }
7222 
7223 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7224                                                         KnownBits &Known,
7225                                                         const APInt &DemandedElts,
7226                                                         const SelectionDAG &DAG,
7227                                                         unsigned Depth) const {
7228   unsigned BitWidth = Known.getBitWidth();
7229   unsigned Opc = Op.getOpcode();
7230   assert((Opc >= ISD::BUILTIN_OP_END ||
7231           Opc == ISD::INTRINSIC_WO_CHAIN ||
7232           Opc == ISD::INTRINSIC_W_CHAIN ||
7233           Opc == ISD::INTRINSIC_VOID) &&
7234          "Should use MaskedValueIsZero if you don't know whether Op"
7235          " is a target node!");
7236 
7237   Known.resetAll();
7238   switch (Opc) {
7239   default: break;
7240   case RISCVISD::SELECT_CC: {
7241     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7242     // If we don't know any bits, early out.
7243     if (Known.isUnknown())
7244       break;
7245     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7246 
7247     // Only known if known in both the LHS and RHS.
7248     Known = KnownBits::commonBits(Known, Known2);
7249     break;
7250   }
7251   case RISCVISD::REMUW: {
7252     KnownBits Known2;
7253     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7254     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7255     // We only care about the lower 32 bits.
7256     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7257     // Restore the original width by sign extending.
7258     Known = Known.sext(BitWidth);
7259     break;
7260   }
7261   case RISCVISD::DIVUW: {
7262     KnownBits Known2;
7263     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7264     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7265     // We only care about the lower 32 bits.
7266     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7267     // Restore the original width by sign extending.
7268     Known = Known.sext(BitWidth);
7269     break;
7270   }
7271   case RISCVISD::CTZW: {
7272     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7273     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7274     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7275     Known.Zero.setBitsFrom(LowBits);
7276     break;
7277   }
7278   case RISCVISD::CLZW: {
7279     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7280     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7281     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7282     Known.Zero.setBitsFrom(LowBits);
7283     break;
7284   }
7285   case RISCVISD::GREV:
7286   case RISCVISD::GREVW: {
7287     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7288       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7289       if (Opc == RISCVISD::GREVW)
7290         Known = Known.trunc(32);
7291       unsigned ShAmt = C->getZExtValue();
7292       computeGREV(Known.Zero, ShAmt);
7293       computeGREV(Known.One, ShAmt);
7294       if (Opc == RISCVISD::GREVW)
7295         Known = Known.sext(BitWidth);
7296     }
7297     break;
7298   }
7299   case RISCVISD::READ_VLENB:
7300     // We assume VLENB is at least 16 bytes.
7301     Known.Zero.setLowBits(4);
7302     // We assume VLENB is no more than 65536 / 8 bytes.
7303     Known.Zero.setBitsFrom(14);
7304     break;
7305   case ISD::INTRINSIC_W_CHAIN: {
7306     unsigned IntNo = Op.getConstantOperandVal(1);
7307     switch (IntNo) {
7308     default:
7309       // We can't do anything for most intrinsics.
7310       break;
7311     case Intrinsic::riscv_vsetvli:
7312     case Intrinsic::riscv_vsetvlimax:
7313       // Assume that VL output is positive and would fit in an int32_t.
7314       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7315       if (BitWidth >= 32)
7316         Known.Zero.setBitsFrom(31);
7317       break;
7318     }
7319     break;
7320   }
7321   }
7322 }
7323 
7324 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7325     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7326     unsigned Depth) const {
7327   switch (Op.getOpcode()) {
7328   default:
7329     break;
7330   case RISCVISD::SELECT_CC: {
7331     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7332     if (Tmp == 1) return 1;  // Early out.
7333     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7334     return std::min(Tmp, Tmp2);
7335   }
7336   case RISCVISD::SLLW:
7337   case RISCVISD::SRAW:
7338   case RISCVISD::SRLW:
7339   case RISCVISD::DIVW:
7340   case RISCVISD::DIVUW:
7341   case RISCVISD::REMUW:
7342   case RISCVISD::ROLW:
7343   case RISCVISD::RORW:
7344   case RISCVISD::GREVW:
7345   case RISCVISD::GORCW:
7346   case RISCVISD::FSLW:
7347   case RISCVISD::FSRW:
7348   case RISCVISD::SHFLW:
7349   case RISCVISD::UNSHFLW:
7350   case RISCVISD::BCOMPRESSW:
7351   case RISCVISD::BDECOMPRESSW:
7352   case RISCVISD::FCVT_W_RTZ_RV64:
7353   case RISCVISD::FCVT_WU_RTZ_RV64:
7354     // TODO: As the result is sign-extended, this is conservatively correct. A
7355     // more precise answer could be calculated for SRAW depending on known
7356     // bits in the shift amount.
7357     return 33;
7358   case RISCVISD::SHFL:
7359   case RISCVISD::UNSHFL: {
7360     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7361     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7362     // will stay within the upper 32 bits. If there were more than 32 sign bits
7363     // before there will be at least 33 sign bits after.
7364     if (Op.getValueType() == MVT::i64 &&
7365         isa<ConstantSDNode>(Op.getOperand(1)) &&
7366         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7367       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7368       if (Tmp > 32)
7369         return 33;
7370     }
7371     break;
7372   }
7373   case RISCVISD::VMV_X_S:
7374     // The number of sign bits of the scalar result is computed by obtaining the
7375     // element type of the input vector operand, subtracting its width from the
7376     // XLEN, and then adding one (sign bit within the element type). If the
7377     // element type is wider than XLen, the least-significant XLEN bits are
7378     // taken.
7379     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7380       return 1;
7381     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7382   }
7383 
7384   return 1;
7385 }
7386 
7387 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7388                                                   MachineBasicBlock *BB) {
7389   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7390 
7391   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7392   // Should the count have wrapped while it was being read, we need to try
7393   // again.
7394   // ...
7395   // read:
7396   // rdcycleh x3 # load high word of cycle
7397   // rdcycle  x2 # load low word of cycle
7398   // rdcycleh x4 # load high word of cycle
7399   // bne x3, x4, read # check if high word reads match, otherwise try again
7400   // ...
7401 
7402   MachineFunction &MF = *BB->getParent();
7403   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7404   MachineFunction::iterator It = ++BB->getIterator();
7405 
7406   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7407   MF.insert(It, LoopMBB);
7408 
7409   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7410   MF.insert(It, DoneMBB);
7411 
7412   // Transfer the remainder of BB and its successor edges to DoneMBB.
7413   DoneMBB->splice(DoneMBB->begin(), BB,
7414                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7415   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7416 
7417   BB->addSuccessor(LoopMBB);
7418 
7419   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7420   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7421   Register LoReg = MI.getOperand(0).getReg();
7422   Register HiReg = MI.getOperand(1).getReg();
7423   DebugLoc DL = MI.getDebugLoc();
7424 
7425   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7426   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7427       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7428       .addReg(RISCV::X0);
7429   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7430       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7431       .addReg(RISCV::X0);
7432   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7433       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7434       .addReg(RISCV::X0);
7435 
7436   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7437       .addReg(HiReg)
7438       .addReg(ReadAgainReg)
7439       .addMBB(LoopMBB);
7440 
7441   LoopMBB->addSuccessor(LoopMBB);
7442   LoopMBB->addSuccessor(DoneMBB);
7443 
7444   MI.eraseFromParent();
7445 
7446   return DoneMBB;
7447 }
7448 
7449 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7450                                              MachineBasicBlock *BB) {
7451   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7452 
7453   MachineFunction &MF = *BB->getParent();
7454   DebugLoc DL = MI.getDebugLoc();
7455   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7456   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7457   Register LoReg = MI.getOperand(0).getReg();
7458   Register HiReg = MI.getOperand(1).getReg();
7459   Register SrcReg = MI.getOperand(2).getReg();
7460   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7461   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7462 
7463   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7464                           RI);
7465   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7466   MachineMemOperand *MMOLo =
7467       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7468   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7469       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7470   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7471       .addFrameIndex(FI)
7472       .addImm(0)
7473       .addMemOperand(MMOLo);
7474   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7475       .addFrameIndex(FI)
7476       .addImm(4)
7477       .addMemOperand(MMOHi);
7478   MI.eraseFromParent(); // The pseudo instruction is gone now.
7479   return BB;
7480 }
7481 
7482 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7483                                                  MachineBasicBlock *BB) {
7484   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7485          "Unexpected instruction");
7486 
7487   MachineFunction &MF = *BB->getParent();
7488   DebugLoc DL = MI.getDebugLoc();
7489   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7490   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7491   Register DstReg = MI.getOperand(0).getReg();
7492   Register LoReg = MI.getOperand(1).getReg();
7493   Register HiReg = MI.getOperand(2).getReg();
7494   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7495   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7496 
7497   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7498   MachineMemOperand *MMOLo =
7499       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7500   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7501       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7502   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7503       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7504       .addFrameIndex(FI)
7505       .addImm(0)
7506       .addMemOperand(MMOLo);
7507   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7508       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7509       .addFrameIndex(FI)
7510       .addImm(4)
7511       .addMemOperand(MMOHi);
7512   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7513   MI.eraseFromParent(); // The pseudo instruction is gone now.
7514   return BB;
7515 }
7516 
7517 static bool isSelectPseudo(MachineInstr &MI) {
7518   switch (MI.getOpcode()) {
7519   default:
7520     return false;
7521   case RISCV::Select_GPR_Using_CC_GPR:
7522   case RISCV::Select_FPR16_Using_CC_GPR:
7523   case RISCV::Select_FPR32_Using_CC_GPR:
7524   case RISCV::Select_FPR64_Using_CC_GPR:
7525     return true;
7526   }
7527 }
7528 
7529 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7530                                            MachineBasicBlock *BB,
7531                                            const RISCVSubtarget &Subtarget) {
7532   // To "insert" Select_* instructions, we actually have to insert the triangle
7533   // control-flow pattern.  The incoming instructions know the destination vreg
7534   // to set, the condition code register to branch on, the true/false values to
7535   // select between, and the condcode to use to select the appropriate branch.
7536   //
7537   // We produce the following control flow:
7538   //     HeadMBB
7539   //     |  \
7540   //     |  IfFalseMBB
7541   //     | /
7542   //    TailMBB
7543   //
7544   // When we find a sequence of selects we attempt to optimize their emission
7545   // by sharing the control flow. Currently we only handle cases where we have
7546   // multiple selects with the exact same condition (same LHS, RHS and CC).
7547   // The selects may be interleaved with other instructions if the other
7548   // instructions meet some requirements we deem safe:
7549   // - They are debug instructions. Otherwise,
7550   // - They do not have side-effects, do not access memory and their inputs do
7551   //   not depend on the results of the select pseudo-instructions.
7552   // The TrueV/FalseV operands of the selects cannot depend on the result of
7553   // previous selects in the sequence.
7554   // These conditions could be further relaxed. See the X86 target for a
7555   // related approach and more information.
7556   Register LHS = MI.getOperand(1).getReg();
7557   Register RHS = MI.getOperand(2).getReg();
7558   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7559 
7560   SmallVector<MachineInstr *, 4> SelectDebugValues;
7561   SmallSet<Register, 4> SelectDests;
7562   SelectDests.insert(MI.getOperand(0).getReg());
7563 
7564   MachineInstr *LastSelectPseudo = &MI;
7565 
7566   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7567        SequenceMBBI != E; ++SequenceMBBI) {
7568     if (SequenceMBBI->isDebugInstr())
7569       continue;
7570     else if (isSelectPseudo(*SequenceMBBI)) {
7571       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7572           SequenceMBBI->getOperand(2).getReg() != RHS ||
7573           SequenceMBBI->getOperand(3).getImm() != CC ||
7574           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7575           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7576         break;
7577       LastSelectPseudo = &*SequenceMBBI;
7578       SequenceMBBI->collectDebugValues(SelectDebugValues);
7579       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7580     } else {
7581       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7582           SequenceMBBI->mayLoadOrStore())
7583         break;
7584       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7585             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7586           }))
7587         break;
7588     }
7589   }
7590 
7591   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7592   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7593   DebugLoc DL = MI.getDebugLoc();
7594   MachineFunction::iterator I = ++BB->getIterator();
7595 
7596   MachineBasicBlock *HeadMBB = BB;
7597   MachineFunction *F = BB->getParent();
7598   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7599   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7600 
7601   F->insert(I, IfFalseMBB);
7602   F->insert(I, TailMBB);
7603 
7604   // Transfer debug instructions associated with the selects to TailMBB.
7605   for (MachineInstr *DebugInstr : SelectDebugValues) {
7606     TailMBB->push_back(DebugInstr->removeFromParent());
7607   }
7608 
7609   // Move all instructions after the sequence to TailMBB.
7610   TailMBB->splice(TailMBB->end(), HeadMBB,
7611                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7612   // Update machine-CFG edges by transferring all successors of the current
7613   // block to the new block which will contain the Phi nodes for the selects.
7614   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7615   // Set the successors for HeadMBB.
7616   HeadMBB->addSuccessor(IfFalseMBB);
7617   HeadMBB->addSuccessor(TailMBB);
7618 
7619   // Insert appropriate branch.
7620   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7621     .addReg(LHS)
7622     .addReg(RHS)
7623     .addMBB(TailMBB);
7624 
7625   // IfFalseMBB just falls through to TailMBB.
7626   IfFalseMBB->addSuccessor(TailMBB);
7627 
7628   // Create PHIs for all of the select pseudo-instructions.
7629   auto SelectMBBI = MI.getIterator();
7630   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7631   auto InsertionPoint = TailMBB->begin();
7632   while (SelectMBBI != SelectEnd) {
7633     auto Next = std::next(SelectMBBI);
7634     if (isSelectPseudo(*SelectMBBI)) {
7635       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7636       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7637               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7638           .addReg(SelectMBBI->getOperand(4).getReg())
7639           .addMBB(HeadMBB)
7640           .addReg(SelectMBBI->getOperand(5).getReg())
7641           .addMBB(IfFalseMBB);
7642       SelectMBBI->eraseFromParent();
7643     }
7644     SelectMBBI = Next;
7645   }
7646 
7647   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7648   return TailMBB;
7649 }
7650 
7651 MachineBasicBlock *
7652 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7653                                                  MachineBasicBlock *BB) const {
7654   switch (MI.getOpcode()) {
7655   default:
7656     llvm_unreachable("Unexpected instr type to insert");
7657   case RISCV::ReadCycleWide:
7658     assert(!Subtarget.is64Bit() &&
7659            "ReadCycleWrite is only to be used on riscv32");
7660     return emitReadCycleWidePseudo(MI, BB);
7661   case RISCV::Select_GPR_Using_CC_GPR:
7662   case RISCV::Select_FPR16_Using_CC_GPR:
7663   case RISCV::Select_FPR32_Using_CC_GPR:
7664   case RISCV::Select_FPR64_Using_CC_GPR:
7665     return emitSelectPseudo(MI, BB, Subtarget);
7666   case RISCV::BuildPairF64Pseudo:
7667     return emitBuildPairF64Pseudo(MI, BB);
7668   case RISCV::SplitF64Pseudo:
7669     return emitSplitF64Pseudo(MI, BB);
7670   }
7671 }
7672 
7673 // Calling Convention Implementation.
7674 // The expectations for frontend ABI lowering vary from target to target.
7675 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7676 // details, but this is a longer term goal. For now, we simply try to keep the
7677 // role of the frontend as simple and well-defined as possible. The rules can
7678 // be summarised as:
7679 // * Never split up large scalar arguments. We handle them here.
7680 // * If a hardfloat calling convention is being used, and the struct may be
7681 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7682 // available, then pass as two separate arguments. If either the GPRs or FPRs
7683 // are exhausted, then pass according to the rule below.
7684 // * If a struct could never be passed in registers or directly in a stack
7685 // slot (as it is larger than 2*XLEN and the floating point rules don't
7686 // apply), then pass it using a pointer with the byval attribute.
7687 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7688 // word-sized array or a 2*XLEN scalar (depending on alignment).
7689 // * The frontend can determine whether a struct is returned by reference or
7690 // not based on its size and fields. If it will be returned by reference, the
7691 // frontend must modify the prototype so a pointer with the sret annotation is
7692 // passed as the first argument. This is not necessary for large scalar
7693 // returns.
7694 // * Struct return values and varargs should be coerced to structs containing
7695 // register-size fields in the same situations they would be for fixed
7696 // arguments.
7697 
7698 static const MCPhysReg ArgGPRs[] = {
7699   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7700   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7701 };
7702 static const MCPhysReg ArgFPR16s[] = {
7703   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7704   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7705 };
7706 static const MCPhysReg ArgFPR32s[] = {
7707   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7708   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7709 };
7710 static const MCPhysReg ArgFPR64s[] = {
7711   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7712   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7713 };
7714 // This is an interim calling convention and it may be changed in the future.
7715 static const MCPhysReg ArgVRs[] = {
7716     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7717     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7718     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7719 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7720                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7721                                      RISCV::V20M2, RISCV::V22M2};
7722 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7723                                      RISCV::V20M4};
7724 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7725 
7726 // Pass a 2*XLEN argument that has been split into two XLEN values through
7727 // registers or the stack as necessary.
7728 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7729                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7730                                 MVT ValVT2, MVT LocVT2,
7731                                 ISD::ArgFlagsTy ArgFlags2) {
7732   unsigned XLenInBytes = XLen / 8;
7733   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7734     // At least one half can be passed via register.
7735     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7736                                      VA1.getLocVT(), CCValAssign::Full));
7737   } else {
7738     // Both halves must be passed on the stack, with proper alignment.
7739     Align StackAlign =
7740         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7741     State.addLoc(
7742         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7743                             State.AllocateStack(XLenInBytes, StackAlign),
7744                             VA1.getLocVT(), CCValAssign::Full));
7745     State.addLoc(CCValAssign::getMem(
7746         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7747         LocVT2, CCValAssign::Full));
7748     return false;
7749   }
7750 
7751   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7752     // The second half can also be passed via register.
7753     State.addLoc(
7754         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7755   } else {
7756     // The second half is passed via the stack, without additional alignment.
7757     State.addLoc(CCValAssign::getMem(
7758         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7759         LocVT2, CCValAssign::Full));
7760   }
7761 
7762   return false;
7763 }
7764 
7765 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7766                                Optional<unsigned> FirstMaskArgument,
7767                                CCState &State, const RISCVTargetLowering &TLI) {
7768   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7769   if (RC == &RISCV::VRRegClass) {
7770     // Assign the first mask argument to V0.
7771     // This is an interim calling convention and it may be changed in the
7772     // future.
7773     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7774       return State.AllocateReg(RISCV::V0);
7775     return State.AllocateReg(ArgVRs);
7776   }
7777   if (RC == &RISCV::VRM2RegClass)
7778     return State.AllocateReg(ArgVRM2s);
7779   if (RC == &RISCV::VRM4RegClass)
7780     return State.AllocateReg(ArgVRM4s);
7781   if (RC == &RISCV::VRM8RegClass)
7782     return State.AllocateReg(ArgVRM8s);
7783   llvm_unreachable("Unhandled register class for ValueType");
7784 }
7785 
7786 // Implements the RISC-V calling convention. Returns true upon failure.
7787 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7788                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7789                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7790                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7791                      Optional<unsigned> FirstMaskArgument) {
7792   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7793   assert(XLen == 32 || XLen == 64);
7794   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7795 
7796   // Any return value split in to more than two values can't be returned
7797   // directly. Vectors are returned via the available vector registers.
7798   if (!LocVT.isVector() && IsRet && ValNo > 1)
7799     return true;
7800 
7801   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7802   // variadic argument, or if no F16/F32 argument registers are available.
7803   bool UseGPRForF16_F32 = true;
7804   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7805   // variadic argument, or if no F64 argument registers are available.
7806   bool UseGPRForF64 = true;
7807 
7808   switch (ABI) {
7809   default:
7810     llvm_unreachable("Unexpected ABI");
7811   case RISCVABI::ABI_ILP32:
7812   case RISCVABI::ABI_LP64:
7813     break;
7814   case RISCVABI::ABI_ILP32F:
7815   case RISCVABI::ABI_LP64F:
7816     UseGPRForF16_F32 = !IsFixed;
7817     break;
7818   case RISCVABI::ABI_ILP32D:
7819   case RISCVABI::ABI_LP64D:
7820     UseGPRForF16_F32 = !IsFixed;
7821     UseGPRForF64 = !IsFixed;
7822     break;
7823   }
7824 
7825   // FPR16, FPR32, and FPR64 alias each other.
7826   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7827     UseGPRForF16_F32 = true;
7828     UseGPRForF64 = true;
7829   }
7830 
7831   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7832   // similar local variables rather than directly checking against the target
7833   // ABI.
7834 
7835   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7836     LocVT = XLenVT;
7837     LocInfo = CCValAssign::BCvt;
7838   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7839     LocVT = MVT::i64;
7840     LocInfo = CCValAssign::BCvt;
7841   }
7842 
7843   // If this is a variadic argument, the RISC-V calling convention requires
7844   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7845   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7846   // be used regardless of whether the original argument was split during
7847   // legalisation or not. The argument will not be passed by registers if the
7848   // original type is larger than 2*XLEN, so the register alignment rule does
7849   // not apply.
7850   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7851   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7852       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7853     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7854     // Skip 'odd' register if necessary.
7855     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7856       State.AllocateReg(ArgGPRs);
7857   }
7858 
7859   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7860   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7861       State.getPendingArgFlags();
7862 
7863   assert(PendingLocs.size() == PendingArgFlags.size() &&
7864          "PendingLocs and PendingArgFlags out of sync");
7865 
7866   // Handle passing f64 on RV32D with a soft float ABI or when floating point
7867   // registers are exhausted.
7868   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
7869     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
7870            "Can't lower f64 if it is split");
7871     // Depending on available argument GPRS, f64 may be passed in a pair of
7872     // GPRs, split between a GPR and the stack, or passed completely on the
7873     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
7874     // cases.
7875     Register Reg = State.AllocateReg(ArgGPRs);
7876     LocVT = MVT::i32;
7877     if (!Reg) {
7878       unsigned StackOffset = State.AllocateStack(8, Align(8));
7879       State.addLoc(
7880           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7881       return false;
7882     }
7883     if (!State.AllocateReg(ArgGPRs))
7884       State.AllocateStack(4, Align(4));
7885     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7886     return false;
7887   }
7888 
7889   // Fixed-length vectors are located in the corresponding scalable-vector
7890   // container types.
7891   if (ValVT.isFixedLengthVector())
7892     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7893 
7894   // Split arguments might be passed indirectly, so keep track of the pending
7895   // values. Split vectors are passed via a mix of registers and indirectly, so
7896   // treat them as we would any other argument.
7897   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
7898     LocVT = XLenVT;
7899     LocInfo = CCValAssign::Indirect;
7900     PendingLocs.push_back(
7901         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
7902     PendingArgFlags.push_back(ArgFlags);
7903     if (!ArgFlags.isSplitEnd()) {
7904       return false;
7905     }
7906   }
7907 
7908   // If the split argument only had two elements, it should be passed directly
7909   // in registers or on the stack.
7910   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
7911       PendingLocs.size() <= 2) {
7912     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
7913     // Apply the normal calling convention rules to the first half of the
7914     // split argument.
7915     CCValAssign VA = PendingLocs[0];
7916     ISD::ArgFlagsTy AF = PendingArgFlags[0];
7917     PendingLocs.clear();
7918     PendingArgFlags.clear();
7919     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
7920                                ArgFlags);
7921   }
7922 
7923   // Allocate to a register if possible, or else a stack slot.
7924   Register Reg;
7925   unsigned StoreSizeBytes = XLen / 8;
7926   Align StackAlign = Align(XLen / 8);
7927 
7928   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
7929     Reg = State.AllocateReg(ArgFPR16s);
7930   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
7931     Reg = State.AllocateReg(ArgFPR32s);
7932   else if (ValVT == MVT::f64 && !UseGPRForF64)
7933     Reg = State.AllocateReg(ArgFPR64s);
7934   else if (ValVT.isVector()) {
7935     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
7936     if (!Reg) {
7937       // For return values, the vector must be passed fully via registers or
7938       // via the stack.
7939       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
7940       // but we're using all of them.
7941       if (IsRet)
7942         return true;
7943       // Try using a GPR to pass the address
7944       if ((Reg = State.AllocateReg(ArgGPRs))) {
7945         LocVT = XLenVT;
7946         LocInfo = CCValAssign::Indirect;
7947       } else if (ValVT.isScalableVector()) {
7948         report_fatal_error("Unable to pass scalable vector types on the stack");
7949       } else {
7950         // Pass fixed-length vectors on the stack.
7951         LocVT = ValVT;
7952         StoreSizeBytes = ValVT.getStoreSize();
7953         // Align vectors to their element sizes, being careful for vXi1
7954         // vectors.
7955         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7956       }
7957     }
7958   } else {
7959     Reg = State.AllocateReg(ArgGPRs);
7960   }
7961 
7962   unsigned StackOffset =
7963       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
7964 
7965   // If we reach this point and PendingLocs is non-empty, we must be at the
7966   // end of a split argument that must be passed indirectly.
7967   if (!PendingLocs.empty()) {
7968     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
7969     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
7970 
7971     for (auto &It : PendingLocs) {
7972       if (Reg)
7973         It.convertToReg(Reg);
7974       else
7975         It.convertToMem(StackOffset);
7976       State.addLoc(It);
7977     }
7978     PendingLocs.clear();
7979     PendingArgFlags.clear();
7980     return false;
7981   }
7982 
7983   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
7984           (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) &&
7985          "Expected an XLenVT or vector types at this stage");
7986 
7987   if (Reg) {
7988     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7989     return false;
7990   }
7991 
7992   // When a floating-point value is passed on the stack, no bit-conversion is
7993   // needed.
7994   if (ValVT.isFloatingPoint()) {
7995     LocVT = ValVT;
7996     LocInfo = CCValAssign::Full;
7997   }
7998   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7999   return false;
8000 }
8001 
8002 template <typename ArgTy>
8003 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8004   for (const auto &ArgIdx : enumerate(Args)) {
8005     MVT ArgVT = ArgIdx.value().VT;
8006     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8007       return ArgIdx.index();
8008   }
8009   return None;
8010 }
8011 
8012 void RISCVTargetLowering::analyzeInputArgs(
8013     MachineFunction &MF, CCState &CCInfo,
8014     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8015     RISCVCCAssignFn Fn) const {
8016   unsigned NumArgs = Ins.size();
8017   FunctionType *FType = MF.getFunction().getFunctionType();
8018 
8019   Optional<unsigned> FirstMaskArgument;
8020   if (Subtarget.hasStdExtV())
8021     FirstMaskArgument = preAssignMask(Ins);
8022 
8023   for (unsigned i = 0; i != NumArgs; ++i) {
8024     MVT ArgVT = Ins[i].VT;
8025     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8026 
8027     Type *ArgTy = nullptr;
8028     if (IsRet)
8029       ArgTy = FType->getReturnType();
8030     else if (Ins[i].isOrigArg())
8031       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8032 
8033     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8034     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8035            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8036            FirstMaskArgument)) {
8037       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8038                         << EVT(ArgVT).getEVTString() << '\n');
8039       llvm_unreachable(nullptr);
8040     }
8041   }
8042 }
8043 
8044 void RISCVTargetLowering::analyzeOutputArgs(
8045     MachineFunction &MF, CCState &CCInfo,
8046     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8047     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8048   unsigned NumArgs = Outs.size();
8049 
8050   Optional<unsigned> FirstMaskArgument;
8051   if (Subtarget.hasStdExtV())
8052     FirstMaskArgument = preAssignMask(Outs);
8053 
8054   for (unsigned i = 0; i != NumArgs; i++) {
8055     MVT ArgVT = Outs[i].VT;
8056     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8057     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8058 
8059     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8060     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8061            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8062            FirstMaskArgument)) {
8063       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8064                         << EVT(ArgVT).getEVTString() << "\n");
8065       llvm_unreachable(nullptr);
8066     }
8067   }
8068 }
8069 
8070 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8071 // values.
8072 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8073                                    const CCValAssign &VA, const SDLoc &DL,
8074                                    const RISCVSubtarget &Subtarget) {
8075   switch (VA.getLocInfo()) {
8076   default:
8077     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8078   case CCValAssign::Full:
8079     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8080       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8081     break;
8082   case CCValAssign::BCvt:
8083     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8084       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8085     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8086       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8087     else
8088       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8089     break;
8090   }
8091   return Val;
8092 }
8093 
8094 // The caller is responsible for loading the full value if the argument is
8095 // passed with CCValAssign::Indirect.
8096 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8097                                 const CCValAssign &VA, const SDLoc &DL,
8098                                 const RISCVTargetLowering &TLI) {
8099   MachineFunction &MF = DAG.getMachineFunction();
8100   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8101   EVT LocVT = VA.getLocVT();
8102   SDValue Val;
8103   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8104   Register VReg = RegInfo.createVirtualRegister(RC);
8105   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8106   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8107 
8108   if (VA.getLocInfo() == CCValAssign::Indirect)
8109     return Val;
8110 
8111   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8112 }
8113 
8114 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8115                                    const CCValAssign &VA, const SDLoc &DL,
8116                                    const RISCVSubtarget &Subtarget) {
8117   EVT LocVT = VA.getLocVT();
8118 
8119   switch (VA.getLocInfo()) {
8120   default:
8121     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8122   case CCValAssign::Full:
8123     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8124       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8125     break;
8126   case CCValAssign::BCvt:
8127     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8128       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8129     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8130       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8131     else
8132       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8133     break;
8134   }
8135   return Val;
8136 }
8137 
8138 // The caller is responsible for loading the full value if the argument is
8139 // passed with CCValAssign::Indirect.
8140 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8141                                 const CCValAssign &VA, const SDLoc &DL) {
8142   MachineFunction &MF = DAG.getMachineFunction();
8143   MachineFrameInfo &MFI = MF.getFrameInfo();
8144   EVT LocVT = VA.getLocVT();
8145   EVT ValVT = VA.getValVT();
8146   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8147   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8148                                  /*Immutable=*/true);
8149   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8150   SDValue Val;
8151 
8152   ISD::LoadExtType ExtType;
8153   switch (VA.getLocInfo()) {
8154   default:
8155     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8156   case CCValAssign::Full:
8157   case CCValAssign::Indirect:
8158   case CCValAssign::BCvt:
8159     ExtType = ISD::NON_EXTLOAD;
8160     break;
8161   }
8162   Val = DAG.getExtLoad(
8163       ExtType, DL, LocVT, Chain, FIN,
8164       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8165   return Val;
8166 }
8167 
8168 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8169                                        const CCValAssign &VA, const SDLoc &DL) {
8170   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8171          "Unexpected VA");
8172   MachineFunction &MF = DAG.getMachineFunction();
8173   MachineFrameInfo &MFI = MF.getFrameInfo();
8174   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8175 
8176   if (VA.isMemLoc()) {
8177     // f64 is passed on the stack.
8178     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8179     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8180     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8181                        MachinePointerInfo::getFixedStack(MF, FI));
8182   }
8183 
8184   assert(VA.isRegLoc() && "Expected register VA assignment");
8185 
8186   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8187   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8188   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8189   SDValue Hi;
8190   if (VA.getLocReg() == RISCV::X17) {
8191     // Second half of f64 is passed on the stack.
8192     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8193     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8194     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8195                      MachinePointerInfo::getFixedStack(MF, FI));
8196   } else {
8197     // Second half of f64 is passed in another GPR.
8198     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8199     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8200     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8201   }
8202   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8203 }
8204 
8205 // FastCC has less than 1% performance improvement for some particular
8206 // benchmark. But theoretically, it may has benenfit for some cases.
8207 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8208                             unsigned ValNo, MVT ValVT, MVT LocVT,
8209                             CCValAssign::LocInfo LocInfo,
8210                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8211                             bool IsFixed, bool IsRet, Type *OrigTy,
8212                             const RISCVTargetLowering &TLI,
8213                             Optional<unsigned> FirstMaskArgument) {
8214 
8215   // X5 and X6 might be used for save-restore libcall.
8216   static const MCPhysReg GPRList[] = {
8217       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8218       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8219       RISCV::X29, RISCV::X30, RISCV::X31};
8220 
8221   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8222     if (unsigned Reg = State.AllocateReg(GPRList)) {
8223       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8224       return false;
8225     }
8226   }
8227 
8228   if (LocVT == MVT::f16) {
8229     static const MCPhysReg FPR16List[] = {
8230         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8231         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8232         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8233         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8234     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8235       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8236       return false;
8237     }
8238   }
8239 
8240   if (LocVT == MVT::f32) {
8241     static const MCPhysReg FPR32List[] = {
8242         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8243         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8244         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8245         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8246     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8247       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8248       return false;
8249     }
8250   }
8251 
8252   if (LocVT == MVT::f64) {
8253     static const MCPhysReg FPR64List[] = {
8254         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8255         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8256         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8257         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8258     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8259       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8260       return false;
8261     }
8262   }
8263 
8264   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8265     unsigned Offset4 = State.AllocateStack(4, Align(4));
8266     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8267     return false;
8268   }
8269 
8270   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8271     unsigned Offset5 = State.AllocateStack(8, Align(8));
8272     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8273     return false;
8274   }
8275 
8276   if (LocVT.isVector()) {
8277     if (unsigned Reg =
8278             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8279       // Fixed-length vectors are located in the corresponding scalable-vector
8280       // container types.
8281       if (ValVT.isFixedLengthVector())
8282         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8283       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8284     } else {
8285       // Try and pass the address via a "fast" GPR.
8286       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8287         LocInfo = CCValAssign::Indirect;
8288         LocVT = TLI.getSubtarget().getXLenVT();
8289         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8290       } else if (ValVT.isFixedLengthVector()) {
8291         auto StackAlign =
8292             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8293         unsigned StackOffset =
8294             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8295         State.addLoc(
8296             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8297       } else {
8298         // Can't pass scalable vectors on the stack.
8299         return true;
8300       }
8301     }
8302 
8303     return false;
8304   }
8305 
8306   return true; // CC didn't match.
8307 }
8308 
8309 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8310                          CCValAssign::LocInfo LocInfo,
8311                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8312 
8313   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8314     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8315     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8316     static const MCPhysReg GPRList[] = {
8317         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8318         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8319     if (unsigned Reg = State.AllocateReg(GPRList)) {
8320       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8321       return false;
8322     }
8323   }
8324 
8325   if (LocVT == MVT::f32) {
8326     // Pass in STG registers: F1, ..., F6
8327     //                        fs0 ... fs5
8328     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8329                                           RISCV::F18_F, RISCV::F19_F,
8330                                           RISCV::F20_F, RISCV::F21_F};
8331     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8332       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8333       return false;
8334     }
8335   }
8336 
8337   if (LocVT == MVT::f64) {
8338     // Pass in STG registers: D1, ..., D6
8339     //                        fs6 ... fs11
8340     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8341                                           RISCV::F24_D, RISCV::F25_D,
8342                                           RISCV::F26_D, RISCV::F27_D};
8343     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8344       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8345       return false;
8346     }
8347   }
8348 
8349   report_fatal_error("No registers left in GHC calling convention");
8350   return true;
8351 }
8352 
8353 // Transform physical registers into virtual registers.
8354 SDValue RISCVTargetLowering::LowerFormalArguments(
8355     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8356     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8357     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8358 
8359   MachineFunction &MF = DAG.getMachineFunction();
8360 
8361   switch (CallConv) {
8362   default:
8363     report_fatal_error("Unsupported calling convention");
8364   case CallingConv::C:
8365   case CallingConv::Fast:
8366     break;
8367   case CallingConv::GHC:
8368     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8369         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8370       report_fatal_error(
8371         "GHC calling convention requires the F and D instruction set extensions");
8372   }
8373 
8374   const Function &Func = MF.getFunction();
8375   if (Func.hasFnAttribute("interrupt")) {
8376     if (!Func.arg_empty())
8377       report_fatal_error(
8378         "Functions with the interrupt attribute cannot have arguments!");
8379 
8380     StringRef Kind =
8381       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8382 
8383     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8384       report_fatal_error(
8385         "Function interrupt attribute argument not supported!");
8386   }
8387 
8388   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8389   MVT XLenVT = Subtarget.getXLenVT();
8390   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8391   // Used with vargs to acumulate store chains.
8392   std::vector<SDValue> OutChains;
8393 
8394   // Assign locations to all of the incoming arguments.
8395   SmallVector<CCValAssign, 16> ArgLocs;
8396   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8397 
8398   if (CallConv == CallingConv::GHC)
8399     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8400   else
8401     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8402                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8403                                                    : CC_RISCV);
8404 
8405   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8406     CCValAssign &VA = ArgLocs[i];
8407     SDValue ArgValue;
8408     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8409     // case.
8410     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8411       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8412     else if (VA.isRegLoc())
8413       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8414     else
8415       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8416 
8417     if (VA.getLocInfo() == CCValAssign::Indirect) {
8418       // If the original argument was split and passed by reference (e.g. i128
8419       // on RV32), we need to load all parts of it here (using the same
8420       // address). Vectors may be partly split to registers and partly to the
8421       // stack, in which case the base address is partly offset and subsequent
8422       // stores are relative to that.
8423       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8424                                    MachinePointerInfo()));
8425       unsigned ArgIndex = Ins[i].OrigArgIndex;
8426       unsigned ArgPartOffset = Ins[i].PartOffset;
8427       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8428       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8429         CCValAssign &PartVA = ArgLocs[i + 1];
8430         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8431         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8432         if (PartVA.getValVT().isScalableVector())
8433           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8434         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8435         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8436                                      MachinePointerInfo()));
8437         ++i;
8438       }
8439       continue;
8440     }
8441     InVals.push_back(ArgValue);
8442   }
8443 
8444   if (IsVarArg) {
8445     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8446     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8447     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8448     MachineFrameInfo &MFI = MF.getFrameInfo();
8449     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8450     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8451 
8452     // Offset of the first variable argument from stack pointer, and size of
8453     // the vararg save area. For now, the varargs save area is either zero or
8454     // large enough to hold a0-a7.
8455     int VaArgOffset, VarArgsSaveSize;
8456 
8457     // If all registers are allocated, then all varargs must be passed on the
8458     // stack and we don't need to save any argregs.
8459     if (ArgRegs.size() == Idx) {
8460       VaArgOffset = CCInfo.getNextStackOffset();
8461       VarArgsSaveSize = 0;
8462     } else {
8463       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8464       VaArgOffset = -VarArgsSaveSize;
8465     }
8466 
8467     // Record the frame index of the first variable argument
8468     // which is a value necessary to VASTART.
8469     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8470     RVFI->setVarArgsFrameIndex(FI);
8471 
8472     // If saving an odd number of registers then create an extra stack slot to
8473     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8474     // offsets to even-numbered registered remain 2*XLEN-aligned.
8475     if (Idx % 2) {
8476       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8477       VarArgsSaveSize += XLenInBytes;
8478     }
8479 
8480     // Copy the integer registers that may have been used for passing varargs
8481     // to the vararg save area.
8482     for (unsigned I = Idx; I < ArgRegs.size();
8483          ++I, VaArgOffset += XLenInBytes) {
8484       const Register Reg = RegInfo.createVirtualRegister(RC);
8485       RegInfo.addLiveIn(ArgRegs[I], Reg);
8486       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8487       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8488       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8489       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8490                                    MachinePointerInfo::getFixedStack(MF, FI));
8491       cast<StoreSDNode>(Store.getNode())
8492           ->getMemOperand()
8493           ->setValue((Value *)nullptr);
8494       OutChains.push_back(Store);
8495     }
8496     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8497   }
8498 
8499   // All stores are grouped in one node to allow the matching between
8500   // the size of Ins and InVals. This only happens for vararg functions.
8501   if (!OutChains.empty()) {
8502     OutChains.push_back(Chain);
8503     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8504   }
8505 
8506   return Chain;
8507 }
8508 
8509 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8510 /// for tail call optimization.
8511 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8512 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8513     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8514     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8515 
8516   auto &Callee = CLI.Callee;
8517   auto CalleeCC = CLI.CallConv;
8518   auto &Outs = CLI.Outs;
8519   auto &Caller = MF.getFunction();
8520   auto CallerCC = Caller.getCallingConv();
8521 
8522   // Exception-handling functions need a special set of instructions to
8523   // indicate a return to the hardware. Tail-calling another function would
8524   // probably break this.
8525   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8526   // should be expanded as new function attributes are introduced.
8527   if (Caller.hasFnAttribute("interrupt"))
8528     return false;
8529 
8530   // Do not tail call opt if the stack is used to pass parameters.
8531   if (CCInfo.getNextStackOffset() != 0)
8532     return false;
8533 
8534   // Do not tail call opt if any parameters need to be passed indirectly.
8535   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8536   // passed indirectly. So the address of the value will be passed in a
8537   // register, or if not available, then the address is put on the stack. In
8538   // order to pass indirectly, space on the stack often needs to be allocated
8539   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8540   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8541   // are passed CCValAssign::Indirect.
8542   for (auto &VA : ArgLocs)
8543     if (VA.getLocInfo() == CCValAssign::Indirect)
8544       return false;
8545 
8546   // Do not tail call opt if either caller or callee uses struct return
8547   // semantics.
8548   auto IsCallerStructRet = Caller.hasStructRetAttr();
8549   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8550   if (IsCallerStructRet || IsCalleeStructRet)
8551     return false;
8552 
8553   // Externally-defined functions with weak linkage should not be
8554   // tail-called. The behaviour of branch instructions in this situation (as
8555   // used for tail calls) is implementation-defined, so we cannot rely on the
8556   // linker replacing the tail call with a return.
8557   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8558     const GlobalValue *GV = G->getGlobal();
8559     if (GV->hasExternalWeakLinkage())
8560       return false;
8561   }
8562 
8563   // The callee has to preserve all registers the caller needs to preserve.
8564   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8565   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8566   if (CalleeCC != CallerCC) {
8567     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8568     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8569       return false;
8570   }
8571 
8572   // Byval parameters hand the function a pointer directly into the stack area
8573   // we want to reuse during a tail call. Working around this *is* possible
8574   // but less efficient and uglier in LowerCall.
8575   for (auto &Arg : Outs)
8576     if (Arg.Flags.isByVal())
8577       return false;
8578 
8579   return true;
8580 }
8581 
8582 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8583   return DAG.getDataLayout().getPrefTypeAlign(
8584       VT.getTypeForEVT(*DAG.getContext()));
8585 }
8586 
8587 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8588 // and output parameter nodes.
8589 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8590                                        SmallVectorImpl<SDValue> &InVals) const {
8591   SelectionDAG &DAG = CLI.DAG;
8592   SDLoc &DL = CLI.DL;
8593   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8594   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8595   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8596   SDValue Chain = CLI.Chain;
8597   SDValue Callee = CLI.Callee;
8598   bool &IsTailCall = CLI.IsTailCall;
8599   CallingConv::ID CallConv = CLI.CallConv;
8600   bool IsVarArg = CLI.IsVarArg;
8601   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8602   MVT XLenVT = Subtarget.getXLenVT();
8603 
8604   MachineFunction &MF = DAG.getMachineFunction();
8605 
8606   // Analyze the operands of the call, assigning locations to each operand.
8607   SmallVector<CCValAssign, 16> ArgLocs;
8608   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8609 
8610   if (CallConv == CallingConv::GHC)
8611     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8612   else
8613     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8614                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8615                                                     : CC_RISCV);
8616 
8617   // Check if it's really possible to do a tail call.
8618   if (IsTailCall)
8619     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8620 
8621   if (IsTailCall)
8622     ++NumTailCalls;
8623   else if (CLI.CB && CLI.CB->isMustTailCall())
8624     report_fatal_error("failed to perform tail call elimination on a call "
8625                        "site marked musttail");
8626 
8627   // Get a count of how many bytes are to be pushed on the stack.
8628   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8629 
8630   // Create local copies for byval args
8631   SmallVector<SDValue, 8> ByValArgs;
8632   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8633     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8634     if (!Flags.isByVal())
8635       continue;
8636 
8637     SDValue Arg = OutVals[i];
8638     unsigned Size = Flags.getByValSize();
8639     Align Alignment = Flags.getNonZeroByValAlign();
8640 
8641     int FI =
8642         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8643     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8644     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8645 
8646     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8647                           /*IsVolatile=*/false,
8648                           /*AlwaysInline=*/false, IsTailCall,
8649                           MachinePointerInfo(), MachinePointerInfo());
8650     ByValArgs.push_back(FIPtr);
8651   }
8652 
8653   if (!IsTailCall)
8654     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8655 
8656   // Copy argument values to their designated locations.
8657   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8658   SmallVector<SDValue, 8> MemOpChains;
8659   SDValue StackPtr;
8660   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8661     CCValAssign &VA = ArgLocs[i];
8662     SDValue ArgValue = OutVals[i];
8663     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8664 
8665     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8666     bool IsF64OnRV32DSoftABI =
8667         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8668     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8669       SDValue SplitF64 = DAG.getNode(
8670           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8671       SDValue Lo = SplitF64.getValue(0);
8672       SDValue Hi = SplitF64.getValue(1);
8673 
8674       Register RegLo = VA.getLocReg();
8675       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8676 
8677       if (RegLo == RISCV::X17) {
8678         // Second half of f64 is passed on the stack.
8679         // Work out the address of the stack slot.
8680         if (!StackPtr.getNode())
8681           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8682         // Emit the store.
8683         MemOpChains.push_back(
8684             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8685       } else {
8686         // Second half of f64 is passed in another GPR.
8687         assert(RegLo < RISCV::X31 && "Invalid register pair");
8688         Register RegHigh = RegLo + 1;
8689         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8690       }
8691       continue;
8692     }
8693 
8694     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8695     // as any other MemLoc.
8696 
8697     // Promote the value if needed.
8698     // For now, only handle fully promoted and indirect arguments.
8699     if (VA.getLocInfo() == CCValAssign::Indirect) {
8700       // Store the argument in a stack slot and pass its address.
8701       Align StackAlign =
8702           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8703                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8704       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8705       // If the original argument was split (e.g. i128), we need
8706       // to store the required parts of it here (and pass just one address).
8707       // Vectors may be partly split to registers and partly to the stack, in
8708       // which case the base address is partly offset and subsequent stores are
8709       // relative to that.
8710       unsigned ArgIndex = Outs[i].OrigArgIndex;
8711       unsigned ArgPartOffset = Outs[i].PartOffset;
8712       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8713       // Calculate the total size to store. We don't have access to what we're
8714       // actually storing other than performing the loop and collecting the
8715       // info.
8716       SmallVector<std::pair<SDValue, SDValue>> Parts;
8717       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8718         SDValue PartValue = OutVals[i + 1];
8719         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8720         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8721         EVT PartVT = PartValue.getValueType();
8722         if (PartVT.isScalableVector())
8723           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8724         StoredSize += PartVT.getStoreSize();
8725         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8726         Parts.push_back(std::make_pair(PartValue, Offset));
8727         ++i;
8728       }
8729       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8730       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8731       MemOpChains.push_back(
8732           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8733                        MachinePointerInfo::getFixedStack(MF, FI)));
8734       for (const auto &Part : Parts) {
8735         SDValue PartValue = Part.first;
8736         SDValue PartOffset = Part.second;
8737         SDValue Address =
8738             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8739         MemOpChains.push_back(
8740             DAG.getStore(Chain, DL, PartValue, Address,
8741                          MachinePointerInfo::getFixedStack(MF, FI)));
8742       }
8743       ArgValue = SpillSlot;
8744     } else {
8745       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8746     }
8747 
8748     // Use local copy if it is a byval arg.
8749     if (Flags.isByVal())
8750       ArgValue = ByValArgs[j++];
8751 
8752     if (VA.isRegLoc()) {
8753       // Queue up the argument copies and emit them at the end.
8754       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8755     } else {
8756       assert(VA.isMemLoc() && "Argument not register or memory");
8757       assert(!IsTailCall && "Tail call not allowed if stack is used "
8758                             "for passing parameters");
8759 
8760       // Work out the address of the stack slot.
8761       if (!StackPtr.getNode())
8762         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8763       SDValue Address =
8764           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8765                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8766 
8767       // Emit the store.
8768       MemOpChains.push_back(
8769           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8770     }
8771   }
8772 
8773   // Join the stores, which are independent of one another.
8774   if (!MemOpChains.empty())
8775     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8776 
8777   SDValue Glue;
8778 
8779   // Build a sequence of copy-to-reg nodes, chained and glued together.
8780   for (auto &Reg : RegsToPass) {
8781     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8782     Glue = Chain.getValue(1);
8783   }
8784 
8785   // Validate that none of the argument registers have been marked as
8786   // reserved, if so report an error. Do the same for the return address if this
8787   // is not a tailcall.
8788   validateCCReservedRegs(RegsToPass, MF);
8789   if (!IsTailCall &&
8790       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8791     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8792         MF.getFunction(),
8793         "Return address register required, but has been reserved."});
8794 
8795   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8796   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8797   // split it and then direct call can be matched by PseudoCALL.
8798   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8799     const GlobalValue *GV = S->getGlobal();
8800 
8801     unsigned OpFlags = RISCVII::MO_CALL;
8802     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8803       OpFlags = RISCVII::MO_PLT;
8804 
8805     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8806   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8807     unsigned OpFlags = RISCVII::MO_CALL;
8808 
8809     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8810                                                  nullptr))
8811       OpFlags = RISCVII::MO_PLT;
8812 
8813     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8814   }
8815 
8816   // The first call operand is the chain and the second is the target address.
8817   SmallVector<SDValue, 8> Ops;
8818   Ops.push_back(Chain);
8819   Ops.push_back(Callee);
8820 
8821   // Add argument registers to the end of the list so that they are
8822   // known live into the call.
8823   for (auto &Reg : RegsToPass)
8824     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8825 
8826   if (!IsTailCall) {
8827     // Add a register mask operand representing the call-preserved registers.
8828     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8829     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8830     assert(Mask && "Missing call preserved mask for calling convention");
8831     Ops.push_back(DAG.getRegisterMask(Mask));
8832   }
8833 
8834   // Glue the call to the argument copies, if any.
8835   if (Glue.getNode())
8836     Ops.push_back(Glue);
8837 
8838   // Emit the call.
8839   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8840 
8841   if (IsTailCall) {
8842     MF.getFrameInfo().setHasTailCall();
8843     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8844   }
8845 
8846   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8847   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8848   Glue = Chain.getValue(1);
8849 
8850   // Mark the end of the call, which is glued to the call itself.
8851   Chain = DAG.getCALLSEQ_END(Chain,
8852                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8853                              DAG.getConstant(0, DL, PtrVT, true),
8854                              Glue, DL);
8855   Glue = Chain.getValue(1);
8856 
8857   // Assign locations to each value returned by this call.
8858   SmallVector<CCValAssign, 16> RVLocs;
8859   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8860   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8861 
8862   // Copy all of the result registers out of their specified physreg.
8863   for (auto &VA : RVLocs) {
8864     // Copy the value out
8865     SDValue RetValue =
8866         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
8867     // Glue the RetValue to the end of the call sequence
8868     Chain = RetValue.getValue(1);
8869     Glue = RetValue.getValue(2);
8870 
8871     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8872       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
8873       SDValue RetValue2 =
8874           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
8875       Chain = RetValue2.getValue(1);
8876       Glue = RetValue2.getValue(2);
8877       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
8878                              RetValue2);
8879     }
8880 
8881     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
8882 
8883     InVals.push_back(RetValue);
8884   }
8885 
8886   return Chain;
8887 }
8888 
8889 bool RISCVTargetLowering::CanLowerReturn(
8890     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
8891     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
8892   SmallVector<CCValAssign, 16> RVLocs;
8893   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
8894 
8895   Optional<unsigned> FirstMaskArgument;
8896   if (Subtarget.hasStdExtV())
8897     FirstMaskArgument = preAssignMask(Outs);
8898 
8899   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8900     MVT VT = Outs[i].VT;
8901     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8902     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8903     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
8904                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
8905                  *this, FirstMaskArgument))
8906       return false;
8907   }
8908   return true;
8909 }
8910 
8911 SDValue
8912 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
8913                                  bool IsVarArg,
8914                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
8915                                  const SmallVectorImpl<SDValue> &OutVals,
8916                                  const SDLoc &DL, SelectionDAG &DAG) const {
8917   const MachineFunction &MF = DAG.getMachineFunction();
8918   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8919 
8920   // Stores the assignment of the return value to a location.
8921   SmallVector<CCValAssign, 16> RVLocs;
8922 
8923   // Info about the registers and stack slot.
8924   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
8925                  *DAG.getContext());
8926 
8927   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
8928                     nullptr, CC_RISCV);
8929 
8930   if (CallConv == CallingConv::GHC && !RVLocs.empty())
8931     report_fatal_error("GHC functions return void only");
8932 
8933   SDValue Glue;
8934   SmallVector<SDValue, 4> RetOps(1, Chain);
8935 
8936   // Copy the result values into the output registers.
8937   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
8938     SDValue Val = OutVals[i];
8939     CCValAssign &VA = RVLocs[i];
8940     assert(VA.isRegLoc() && "Can only return in registers!");
8941 
8942     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8943       // Handle returning f64 on RV32D with a soft float ABI.
8944       assert(VA.isRegLoc() && "Expected return via registers");
8945       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
8946                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
8947       SDValue Lo = SplitF64.getValue(0);
8948       SDValue Hi = SplitF64.getValue(1);
8949       Register RegLo = VA.getLocReg();
8950       assert(RegLo < RISCV::X31 && "Invalid register pair");
8951       Register RegHi = RegLo + 1;
8952 
8953       if (STI.isRegisterReservedByUser(RegLo) ||
8954           STI.isRegisterReservedByUser(RegHi))
8955         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8956             MF.getFunction(),
8957             "Return value register required, but has been reserved."});
8958 
8959       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
8960       Glue = Chain.getValue(1);
8961       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
8962       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
8963       Glue = Chain.getValue(1);
8964       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
8965     } else {
8966       // Handle a 'normal' return.
8967       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
8968       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
8969 
8970       if (STI.isRegisterReservedByUser(VA.getLocReg()))
8971         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8972             MF.getFunction(),
8973             "Return value register required, but has been reserved."});
8974 
8975       // Guarantee that all emitted copies are stuck together.
8976       Glue = Chain.getValue(1);
8977       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
8978     }
8979   }
8980 
8981   RetOps[0] = Chain; // Update chain.
8982 
8983   // Add the glue node if we have it.
8984   if (Glue.getNode()) {
8985     RetOps.push_back(Glue);
8986   }
8987 
8988   unsigned RetOpc = RISCVISD::RET_FLAG;
8989   // Interrupt service routines use different return instructions.
8990   const Function &Func = DAG.getMachineFunction().getFunction();
8991   if (Func.hasFnAttribute("interrupt")) {
8992     if (!Func.getReturnType()->isVoidTy())
8993       report_fatal_error(
8994           "Functions with the interrupt attribute must have void return type!");
8995 
8996     MachineFunction &MF = DAG.getMachineFunction();
8997     StringRef Kind =
8998       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8999 
9000     if (Kind == "user")
9001       RetOpc = RISCVISD::URET_FLAG;
9002     else if (Kind == "supervisor")
9003       RetOpc = RISCVISD::SRET_FLAG;
9004     else
9005       RetOpc = RISCVISD::MRET_FLAG;
9006   }
9007 
9008   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9009 }
9010 
9011 void RISCVTargetLowering::validateCCReservedRegs(
9012     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9013     MachineFunction &MF) const {
9014   const Function &F = MF.getFunction();
9015   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9016 
9017   if (llvm::any_of(Regs, [&STI](auto Reg) {
9018         return STI.isRegisterReservedByUser(Reg.first);
9019       }))
9020     F.getContext().diagnose(DiagnosticInfoUnsupported{
9021         F, "Argument register required, but has been reserved."});
9022 }
9023 
9024 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9025   return CI->isTailCall();
9026 }
9027 
9028 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9029 #define NODE_NAME_CASE(NODE)                                                   \
9030   case RISCVISD::NODE:                                                         \
9031     return "RISCVISD::" #NODE;
9032   // clang-format off
9033   switch ((RISCVISD::NodeType)Opcode) {
9034   case RISCVISD::FIRST_NUMBER:
9035     break;
9036   NODE_NAME_CASE(RET_FLAG)
9037   NODE_NAME_CASE(URET_FLAG)
9038   NODE_NAME_CASE(SRET_FLAG)
9039   NODE_NAME_CASE(MRET_FLAG)
9040   NODE_NAME_CASE(CALL)
9041   NODE_NAME_CASE(SELECT_CC)
9042   NODE_NAME_CASE(BR_CC)
9043   NODE_NAME_CASE(BuildPairF64)
9044   NODE_NAME_CASE(SplitF64)
9045   NODE_NAME_CASE(TAIL)
9046   NODE_NAME_CASE(MULHSU)
9047   NODE_NAME_CASE(SLLW)
9048   NODE_NAME_CASE(SRAW)
9049   NODE_NAME_CASE(SRLW)
9050   NODE_NAME_CASE(DIVW)
9051   NODE_NAME_CASE(DIVUW)
9052   NODE_NAME_CASE(REMUW)
9053   NODE_NAME_CASE(ROLW)
9054   NODE_NAME_CASE(RORW)
9055   NODE_NAME_CASE(CLZW)
9056   NODE_NAME_CASE(CTZW)
9057   NODE_NAME_CASE(FSLW)
9058   NODE_NAME_CASE(FSRW)
9059   NODE_NAME_CASE(FSL)
9060   NODE_NAME_CASE(FSR)
9061   NODE_NAME_CASE(FMV_H_X)
9062   NODE_NAME_CASE(FMV_X_ANYEXTH)
9063   NODE_NAME_CASE(FMV_W_X_RV64)
9064   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9065   NODE_NAME_CASE(FCVT_X_RTZ)
9066   NODE_NAME_CASE(FCVT_XU_RTZ)
9067   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9068   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9069   NODE_NAME_CASE(READ_CYCLE_WIDE)
9070   NODE_NAME_CASE(GREV)
9071   NODE_NAME_CASE(GREVW)
9072   NODE_NAME_CASE(GORC)
9073   NODE_NAME_CASE(GORCW)
9074   NODE_NAME_CASE(SHFL)
9075   NODE_NAME_CASE(SHFLW)
9076   NODE_NAME_CASE(UNSHFL)
9077   NODE_NAME_CASE(UNSHFLW)
9078   NODE_NAME_CASE(BCOMPRESS)
9079   NODE_NAME_CASE(BCOMPRESSW)
9080   NODE_NAME_CASE(BDECOMPRESS)
9081   NODE_NAME_CASE(BDECOMPRESSW)
9082   NODE_NAME_CASE(VMV_V_X_VL)
9083   NODE_NAME_CASE(VFMV_V_F_VL)
9084   NODE_NAME_CASE(VMV_X_S)
9085   NODE_NAME_CASE(VMV_S_X_VL)
9086   NODE_NAME_CASE(VFMV_S_F_VL)
9087   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9088   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9089   NODE_NAME_CASE(READ_VLENB)
9090   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9091   NODE_NAME_CASE(VSLIDEUP_VL)
9092   NODE_NAME_CASE(VSLIDE1UP_VL)
9093   NODE_NAME_CASE(VSLIDEDOWN_VL)
9094   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9095   NODE_NAME_CASE(VID_VL)
9096   NODE_NAME_CASE(VFNCVT_ROD_VL)
9097   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9098   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9099   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9100   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9101   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9102   NODE_NAME_CASE(VECREDUCE_AND_VL)
9103   NODE_NAME_CASE(VECREDUCE_OR_VL)
9104   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9105   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9106   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9107   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9108   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9109   NODE_NAME_CASE(ADD_VL)
9110   NODE_NAME_CASE(AND_VL)
9111   NODE_NAME_CASE(MUL_VL)
9112   NODE_NAME_CASE(OR_VL)
9113   NODE_NAME_CASE(SDIV_VL)
9114   NODE_NAME_CASE(SHL_VL)
9115   NODE_NAME_CASE(SREM_VL)
9116   NODE_NAME_CASE(SRA_VL)
9117   NODE_NAME_CASE(SRL_VL)
9118   NODE_NAME_CASE(SUB_VL)
9119   NODE_NAME_CASE(UDIV_VL)
9120   NODE_NAME_CASE(UREM_VL)
9121   NODE_NAME_CASE(XOR_VL)
9122   NODE_NAME_CASE(SADDSAT_VL)
9123   NODE_NAME_CASE(UADDSAT_VL)
9124   NODE_NAME_CASE(SSUBSAT_VL)
9125   NODE_NAME_CASE(USUBSAT_VL)
9126   NODE_NAME_CASE(FADD_VL)
9127   NODE_NAME_CASE(FSUB_VL)
9128   NODE_NAME_CASE(FMUL_VL)
9129   NODE_NAME_CASE(FDIV_VL)
9130   NODE_NAME_CASE(FNEG_VL)
9131   NODE_NAME_CASE(FABS_VL)
9132   NODE_NAME_CASE(FSQRT_VL)
9133   NODE_NAME_CASE(FMA_VL)
9134   NODE_NAME_CASE(FCOPYSIGN_VL)
9135   NODE_NAME_CASE(SMIN_VL)
9136   NODE_NAME_CASE(SMAX_VL)
9137   NODE_NAME_CASE(UMIN_VL)
9138   NODE_NAME_CASE(UMAX_VL)
9139   NODE_NAME_CASE(FMINNUM_VL)
9140   NODE_NAME_CASE(FMAXNUM_VL)
9141   NODE_NAME_CASE(MULHS_VL)
9142   NODE_NAME_CASE(MULHU_VL)
9143   NODE_NAME_CASE(FP_TO_SINT_VL)
9144   NODE_NAME_CASE(FP_TO_UINT_VL)
9145   NODE_NAME_CASE(SINT_TO_FP_VL)
9146   NODE_NAME_CASE(UINT_TO_FP_VL)
9147   NODE_NAME_CASE(FP_EXTEND_VL)
9148   NODE_NAME_CASE(FP_ROUND_VL)
9149   NODE_NAME_CASE(VWMUL_VL)
9150   NODE_NAME_CASE(VWMULU_VL)
9151   NODE_NAME_CASE(SETCC_VL)
9152   NODE_NAME_CASE(VSELECT_VL)
9153   NODE_NAME_CASE(VMAND_VL)
9154   NODE_NAME_CASE(VMOR_VL)
9155   NODE_NAME_CASE(VMXOR_VL)
9156   NODE_NAME_CASE(VMCLR_VL)
9157   NODE_NAME_CASE(VMSET_VL)
9158   NODE_NAME_CASE(VRGATHER_VX_VL)
9159   NODE_NAME_CASE(VRGATHER_VV_VL)
9160   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9161   NODE_NAME_CASE(VSEXT_VL)
9162   NODE_NAME_CASE(VZEXT_VL)
9163   NODE_NAME_CASE(VPOPC_VL)
9164   NODE_NAME_CASE(VLE_VL)
9165   NODE_NAME_CASE(VSE_VL)
9166   NODE_NAME_CASE(READ_CSR)
9167   NODE_NAME_CASE(WRITE_CSR)
9168   NODE_NAME_CASE(SWAP_CSR)
9169   }
9170   // clang-format on
9171   return nullptr;
9172 #undef NODE_NAME_CASE
9173 }
9174 
9175 /// getConstraintType - Given a constraint letter, return the type of
9176 /// constraint it is for this target.
9177 RISCVTargetLowering::ConstraintType
9178 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9179   if (Constraint.size() == 1) {
9180     switch (Constraint[0]) {
9181     default:
9182       break;
9183     case 'f':
9184       return C_RegisterClass;
9185     case 'I':
9186     case 'J':
9187     case 'K':
9188       return C_Immediate;
9189     case 'A':
9190       return C_Memory;
9191     case 'S': // A symbolic address
9192       return C_Other;
9193     }
9194   } else {
9195     if (Constraint == "vr" || Constraint == "vm")
9196       return C_RegisterClass;
9197   }
9198   return TargetLowering::getConstraintType(Constraint);
9199 }
9200 
9201 std::pair<unsigned, const TargetRegisterClass *>
9202 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9203                                                   StringRef Constraint,
9204                                                   MVT VT) const {
9205   // First, see if this is a constraint that directly corresponds to a
9206   // RISCV register class.
9207   if (Constraint.size() == 1) {
9208     switch (Constraint[0]) {
9209     case 'r':
9210       return std::make_pair(0U, &RISCV::GPRRegClass);
9211     case 'f':
9212       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9213         return std::make_pair(0U, &RISCV::FPR16RegClass);
9214       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9215         return std::make_pair(0U, &RISCV::FPR32RegClass);
9216       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9217         return std::make_pair(0U, &RISCV::FPR64RegClass);
9218       break;
9219     default:
9220       break;
9221     }
9222   } else {
9223     if (Constraint == "vr") {
9224       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9225                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9226         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9227           return std::make_pair(0U, RC);
9228       }
9229     } else if (Constraint == "vm") {
9230       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9231         return std::make_pair(0U, &RISCV::VMRegClass);
9232     }
9233   }
9234 
9235   // Clang will correctly decode the usage of register name aliases into their
9236   // official names. However, other frontends like `rustc` do not. This allows
9237   // users of these frontends to use the ABI names for registers in LLVM-style
9238   // register constraints.
9239   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9240                                .Case("{zero}", RISCV::X0)
9241                                .Case("{ra}", RISCV::X1)
9242                                .Case("{sp}", RISCV::X2)
9243                                .Case("{gp}", RISCV::X3)
9244                                .Case("{tp}", RISCV::X4)
9245                                .Case("{t0}", RISCV::X5)
9246                                .Case("{t1}", RISCV::X6)
9247                                .Case("{t2}", RISCV::X7)
9248                                .Cases("{s0}", "{fp}", RISCV::X8)
9249                                .Case("{s1}", RISCV::X9)
9250                                .Case("{a0}", RISCV::X10)
9251                                .Case("{a1}", RISCV::X11)
9252                                .Case("{a2}", RISCV::X12)
9253                                .Case("{a3}", RISCV::X13)
9254                                .Case("{a4}", RISCV::X14)
9255                                .Case("{a5}", RISCV::X15)
9256                                .Case("{a6}", RISCV::X16)
9257                                .Case("{a7}", RISCV::X17)
9258                                .Case("{s2}", RISCV::X18)
9259                                .Case("{s3}", RISCV::X19)
9260                                .Case("{s4}", RISCV::X20)
9261                                .Case("{s5}", RISCV::X21)
9262                                .Case("{s6}", RISCV::X22)
9263                                .Case("{s7}", RISCV::X23)
9264                                .Case("{s8}", RISCV::X24)
9265                                .Case("{s9}", RISCV::X25)
9266                                .Case("{s10}", RISCV::X26)
9267                                .Case("{s11}", RISCV::X27)
9268                                .Case("{t3}", RISCV::X28)
9269                                .Case("{t4}", RISCV::X29)
9270                                .Case("{t5}", RISCV::X30)
9271                                .Case("{t6}", RISCV::X31)
9272                                .Default(RISCV::NoRegister);
9273   if (XRegFromAlias != RISCV::NoRegister)
9274     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9275 
9276   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9277   // TableGen record rather than the AsmName to choose registers for InlineAsm
9278   // constraints, plus we want to match those names to the widest floating point
9279   // register type available, manually select floating point registers here.
9280   //
9281   // The second case is the ABI name of the register, so that frontends can also
9282   // use the ABI names in register constraint lists.
9283   if (Subtarget.hasStdExtF()) {
9284     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9285                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9286                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9287                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9288                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9289                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9290                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9291                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9292                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9293                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9294                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9295                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9296                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9297                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9298                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9299                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9300                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9301                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9302                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9303                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9304                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9305                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9306                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9307                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9308                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9309                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9310                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9311                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9312                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9313                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9314                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9315                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9316                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9317                         .Default(RISCV::NoRegister);
9318     if (FReg != RISCV::NoRegister) {
9319       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9320       if (Subtarget.hasStdExtD()) {
9321         unsigned RegNo = FReg - RISCV::F0_F;
9322         unsigned DReg = RISCV::F0_D + RegNo;
9323         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9324       }
9325       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9326     }
9327   }
9328 
9329   if (Subtarget.hasStdExtV()) {
9330     Register VReg = StringSwitch<Register>(Constraint.lower())
9331                         .Case("{v0}", RISCV::V0)
9332                         .Case("{v1}", RISCV::V1)
9333                         .Case("{v2}", RISCV::V2)
9334                         .Case("{v3}", RISCV::V3)
9335                         .Case("{v4}", RISCV::V4)
9336                         .Case("{v5}", RISCV::V5)
9337                         .Case("{v6}", RISCV::V6)
9338                         .Case("{v7}", RISCV::V7)
9339                         .Case("{v8}", RISCV::V8)
9340                         .Case("{v9}", RISCV::V9)
9341                         .Case("{v10}", RISCV::V10)
9342                         .Case("{v11}", RISCV::V11)
9343                         .Case("{v12}", RISCV::V12)
9344                         .Case("{v13}", RISCV::V13)
9345                         .Case("{v14}", RISCV::V14)
9346                         .Case("{v15}", RISCV::V15)
9347                         .Case("{v16}", RISCV::V16)
9348                         .Case("{v17}", RISCV::V17)
9349                         .Case("{v18}", RISCV::V18)
9350                         .Case("{v19}", RISCV::V19)
9351                         .Case("{v20}", RISCV::V20)
9352                         .Case("{v21}", RISCV::V21)
9353                         .Case("{v22}", RISCV::V22)
9354                         .Case("{v23}", RISCV::V23)
9355                         .Case("{v24}", RISCV::V24)
9356                         .Case("{v25}", RISCV::V25)
9357                         .Case("{v26}", RISCV::V26)
9358                         .Case("{v27}", RISCV::V27)
9359                         .Case("{v28}", RISCV::V28)
9360                         .Case("{v29}", RISCV::V29)
9361                         .Case("{v30}", RISCV::V30)
9362                         .Case("{v31}", RISCV::V31)
9363                         .Default(RISCV::NoRegister);
9364     if (VReg != RISCV::NoRegister) {
9365       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9366         return std::make_pair(VReg, &RISCV::VMRegClass);
9367       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9368         return std::make_pair(VReg, &RISCV::VRRegClass);
9369       for (const auto *RC :
9370            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9371         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9372           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9373           return std::make_pair(VReg, RC);
9374         }
9375       }
9376     }
9377   }
9378 
9379   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9380 }
9381 
9382 unsigned
9383 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9384   // Currently only support length 1 constraints.
9385   if (ConstraintCode.size() == 1) {
9386     switch (ConstraintCode[0]) {
9387     case 'A':
9388       return InlineAsm::Constraint_A;
9389     default:
9390       break;
9391     }
9392   }
9393 
9394   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9395 }
9396 
9397 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9398     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9399     SelectionDAG &DAG) const {
9400   // Currently only support length 1 constraints.
9401   if (Constraint.length() == 1) {
9402     switch (Constraint[0]) {
9403     case 'I':
9404       // Validate & create a 12-bit signed immediate operand.
9405       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9406         uint64_t CVal = C->getSExtValue();
9407         if (isInt<12>(CVal))
9408           Ops.push_back(
9409               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9410       }
9411       return;
9412     case 'J':
9413       // Validate & create an integer zero operand.
9414       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9415         if (C->getZExtValue() == 0)
9416           Ops.push_back(
9417               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9418       return;
9419     case 'K':
9420       // Validate & create a 5-bit unsigned immediate operand.
9421       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9422         uint64_t CVal = C->getZExtValue();
9423         if (isUInt<5>(CVal))
9424           Ops.push_back(
9425               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9426       }
9427       return;
9428     case 'S':
9429       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9430         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9431                                                  GA->getValueType(0)));
9432       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9433         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9434                                                 BA->getValueType(0)));
9435       }
9436       return;
9437     default:
9438       break;
9439     }
9440   }
9441   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9442 }
9443 
9444 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9445                                                    Instruction *Inst,
9446                                                    AtomicOrdering Ord) const {
9447   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9448     return Builder.CreateFence(Ord);
9449   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9450     return Builder.CreateFence(AtomicOrdering::Release);
9451   return nullptr;
9452 }
9453 
9454 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9455                                                     Instruction *Inst,
9456                                                     AtomicOrdering Ord) const {
9457   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9458     return Builder.CreateFence(AtomicOrdering::Acquire);
9459   return nullptr;
9460 }
9461 
9462 TargetLowering::AtomicExpansionKind
9463 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9464   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9465   // point operations can't be used in an lr/sc sequence without breaking the
9466   // forward-progress guarantee.
9467   if (AI->isFloatingPointOperation())
9468     return AtomicExpansionKind::CmpXChg;
9469 
9470   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9471   if (Size == 8 || Size == 16)
9472     return AtomicExpansionKind::MaskedIntrinsic;
9473   return AtomicExpansionKind::None;
9474 }
9475 
9476 static Intrinsic::ID
9477 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9478   if (XLen == 32) {
9479     switch (BinOp) {
9480     default:
9481       llvm_unreachable("Unexpected AtomicRMW BinOp");
9482     case AtomicRMWInst::Xchg:
9483       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9484     case AtomicRMWInst::Add:
9485       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9486     case AtomicRMWInst::Sub:
9487       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9488     case AtomicRMWInst::Nand:
9489       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9490     case AtomicRMWInst::Max:
9491       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9492     case AtomicRMWInst::Min:
9493       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9494     case AtomicRMWInst::UMax:
9495       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9496     case AtomicRMWInst::UMin:
9497       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9498     }
9499   }
9500 
9501   if (XLen == 64) {
9502     switch (BinOp) {
9503     default:
9504       llvm_unreachable("Unexpected AtomicRMW BinOp");
9505     case AtomicRMWInst::Xchg:
9506       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9507     case AtomicRMWInst::Add:
9508       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9509     case AtomicRMWInst::Sub:
9510       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9511     case AtomicRMWInst::Nand:
9512       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9513     case AtomicRMWInst::Max:
9514       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9515     case AtomicRMWInst::Min:
9516       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9517     case AtomicRMWInst::UMax:
9518       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9519     case AtomicRMWInst::UMin:
9520       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9521     }
9522   }
9523 
9524   llvm_unreachable("Unexpected XLen\n");
9525 }
9526 
9527 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9528     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9529     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9530   unsigned XLen = Subtarget.getXLen();
9531   Value *Ordering =
9532       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9533   Type *Tys[] = {AlignedAddr->getType()};
9534   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9535       AI->getModule(),
9536       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9537 
9538   if (XLen == 64) {
9539     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9540     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9541     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9542   }
9543 
9544   Value *Result;
9545 
9546   // Must pass the shift amount needed to sign extend the loaded value prior
9547   // to performing a signed comparison for min/max. ShiftAmt is the number of
9548   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9549   // is the number of bits to left+right shift the value in order to
9550   // sign-extend.
9551   if (AI->getOperation() == AtomicRMWInst::Min ||
9552       AI->getOperation() == AtomicRMWInst::Max) {
9553     const DataLayout &DL = AI->getModule()->getDataLayout();
9554     unsigned ValWidth =
9555         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9556     Value *SextShamt =
9557         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9558     Result = Builder.CreateCall(LrwOpScwLoop,
9559                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9560   } else {
9561     Result =
9562         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9563   }
9564 
9565   if (XLen == 64)
9566     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9567   return Result;
9568 }
9569 
9570 TargetLowering::AtomicExpansionKind
9571 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9572     AtomicCmpXchgInst *CI) const {
9573   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9574   if (Size == 8 || Size == 16)
9575     return AtomicExpansionKind::MaskedIntrinsic;
9576   return AtomicExpansionKind::None;
9577 }
9578 
9579 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9580     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9581     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9582   unsigned XLen = Subtarget.getXLen();
9583   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9584   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9585   if (XLen == 64) {
9586     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9587     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9588     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9589     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9590   }
9591   Type *Tys[] = {AlignedAddr->getType()};
9592   Function *MaskedCmpXchg =
9593       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9594   Value *Result = Builder.CreateCall(
9595       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9596   if (XLen == 64)
9597     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9598   return Result;
9599 }
9600 
9601 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9602   return false;
9603 }
9604 
9605 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9606                                                      EVT VT) const {
9607   VT = VT.getScalarType();
9608 
9609   if (!VT.isSimple())
9610     return false;
9611 
9612   switch (VT.getSimpleVT().SimpleTy) {
9613   case MVT::f16:
9614     return Subtarget.hasStdExtZfh();
9615   case MVT::f32:
9616     return Subtarget.hasStdExtF();
9617   case MVT::f64:
9618     return Subtarget.hasStdExtD();
9619   default:
9620     break;
9621   }
9622 
9623   return false;
9624 }
9625 
9626 Register RISCVTargetLowering::getExceptionPointerRegister(
9627     const Constant *PersonalityFn) const {
9628   return RISCV::X10;
9629 }
9630 
9631 Register RISCVTargetLowering::getExceptionSelectorRegister(
9632     const Constant *PersonalityFn) const {
9633   return RISCV::X11;
9634 }
9635 
9636 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9637   // Return false to suppress the unnecessary extensions if the LibCall
9638   // arguments or return value is f32 type for LP64 ABI.
9639   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9640   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9641     return false;
9642 
9643   return true;
9644 }
9645 
9646 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9647   if (Subtarget.is64Bit() && Type == MVT::i32)
9648     return true;
9649 
9650   return IsSigned;
9651 }
9652 
9653 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9654                                                  SDValue C) const {
9655   // Check integral scalar types.
9656   if (VT.isScalarInteger()) {
9657     // Omit the optimization if the sub target has the M extension and the data
9658     // size exceeds XLen.
9659     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9660       return false;
9661     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9662       // Break the MUL to a SLLI and an ADD/SUB.
9663       const APInt &Imm = ConstNode->getAPIntValue();
9664       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9665           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9666         return true;
9667       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9668       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9669           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9670            (Imm - 8).isPowerOf2()))
9671         return true;
9672       // Omit the following optimization if the sub target has the M extension
9673       // and the data size >= XLen.
9674       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9675         return false;
9676       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9677       // a pair of LUI/ADDI.
9678       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9679         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9680         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9681             (1 - ImmS).isPowerOf2())
9682         return true;
9683       }
9684     }
9685   }
9686 
9687   return false;
9688 }
9689 
9690 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9691     const SDValue &AddNode, const SDValue &ConstNode) const {
9692   // Let the DAGCombiner decide for vectors.
9693   EVT VT = AddNode.getValueType();
9694   if (VT.isVector())
9695     return true;
9696 
9697   // Let the DAGCombiner decide for larger types.
9698   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9699     return true;
9700 
9701   // It is worse if c1 is simm12 while c1*c2 is not.
9702   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9703   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9704   const APInt &C1 = C1Node->getAPIntValue();
9705   const APInt &C2 = C2Node->getAPIntValue();
9706   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9707     return false;
9708 
9709   // Default to true and let the DAGCombiner decide.
9710   return true;
9711 }
9712 
9713 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9714     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9715     bool *Fast) const {
9716   if (!VT.isVector())
9717     return false;
9718 
9719   EVT ElemVT = VT.getVectorElementType();
9720   if (Alignment >= ElemVT.getStoreSize()) {
9721     if (Fast)
9722       *Fast = true;
9723     return true;
9724   }
9725 
9726   return false;
9727 }
9728 
9729 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9730     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9731     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9732   bool IsABIRegCopy = CC.hasValue();
9733   EVT ValueVT = Val.getValueType();
9734   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9735     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9736     // and cast to f32.
9737     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9738     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9739     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9740                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9741     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9742     Parts[0] = Val;
9743     return true;
9744   }
9745 
9746   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9747     LLVMContext &Context = *DAG.getContext();
9748     EVT ValueEltVT = ValueVT.getVectorElementType();
9749     EVT PartEltVT = PartVT.getVectorElementType();
9750     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9751     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9752     if (PartVTBitSize % ValueVTBitSize == 0) {
9753       // If the element types are different, bitcast to the same element type of
9754       // PartVT first.
9755       if (ValueEltVT != PartEltVT) {
9756         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9757         assert(Count != 0 && "The number of element should not be zero.");
9758         EVT SameEltTypeVT =
9759             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9760         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9761       }
9762       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9763                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9764       Parts[0] = Val;
9765       return true;
9766     }
9767   }
9768   return false;
9769 }
9770 
9771 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9772     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9773     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9774   bool IsABIRegCopy = CC.hasValue();
9775   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9776     SDValue Val = Parts[0];
9777 
9778     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9779     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9780     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9781     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9782     return Val;
9783   }
9784 
9785   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9786     LLVMContext &Context = *DAG.getContext();
9787     SDValue Val = Parts[0];
9788     EVT ValueEltVT = ValueVT.getVectorElementType();
9789     EVT PartEltVT = PartVT.getVectorElementType();
9790     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9791     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9792     if (PartVTBitSize % ValueVTBitSize == 0) {
9793       EVT SameEltTypeVT = ValueVT;
9794       // If the element types are different, convert it to the same element type
9795       // of PartVT.
9796       if (ValueEltVT != PartEltVT) {
9797         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9798         assert(Count != 0 && "The number of element should not be zero.");
9799         SameEltTypeVT =
9800             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9801       }
9802       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9803                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9804       if (ValueEltVT != PartEltVT)
9805         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9806       return Val;
9807     }
9808   }
9809   return SDValue();
9810 }
9811 
9812 #define GET_REGISTER_MATCHER
9813 #include "RISCVGenAsmMatcher.inc"
9814 
9815 Register
9816 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9817                                        const MachineFunction &MF) const {
9818   Register Reg = MatchRegisterAltName(RegName);
9819   if (Reg == RISCV::NoRegister)
9820     Reg = MatchRegisterName(RegName);
9821   if (Reg == RISCV::NoRegister)
9822     report_fatal_error(
9823         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9824   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9825   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9826     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9827                              StringRef(RegName) + "\"."));
9828   return Reg;
9829 }
9830 
9831 namespace llvm {
9832 namespace RISCVVIntrinsicsTable {
9833 
9834 #define GET_RISCVVIntrinsicsTable_IMPL
9835 #include "RISCVGenSearchableTables.inc"
9836 
9837 } // namespace RISCVVIntrinsicsTable
9838 
9839 } // namespace llvm
9840