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.hasVInstructions()) {
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       if (VT.getVectorElementType() == MVT::i64 &&
133           !Subtarget.hasVInstructionsI64())
134         continue;
135       addRegClassForRVV(VT);
136     }
137 
138     if (Subtarget.hasVInstructionsF16())
139       for (MVT VT : F16VecVTs)
140         addRegClassForRVV(VT);
141 
142     if (Subtarget.hasVInstructionsF32())
143       for (MVT VT : F32VecVTs)
144         addRegClassForRVV(VT);
145 
146     if (Subtarget.hasVInstructionsF64())
147       for (MVT VT : F64VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.useRVVForFixedLengthVectors()) {
151       auto addRegClassForFixedVectors = [this](MVT VT) {
152         MVT ContainerVT = getContainerForFixedLengthVector(VT);
153         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
154         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
155         addRegisterClass(VT, TRI.getRegClass(RCID));
156       };
157       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
158         if (useRVVForFixedLengthVectorVT(VT))
159           addRegClassForFixedVectors(VT);
160 
161       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
162         if (useRVVForFixedLengthVectorVT(VT))
163           addRegClassForFixedVectors(VT);
164     }
165   }
166 
167   // Compute derived properties from the register classes.
168   computeRegisterProperties(STI.getRegisterInfo());
169 
170   setStackPointerRegisterToSaveRestore(RISCV::X2);
171 
172   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
173     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
174 
175   // TODO: add all necessary setOperationAction calls.
176   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
177 
178   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
179   setOperationAction(ISD::BR_CC, XLenVT, Expand);
180   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
181   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
182 
183   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
184   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
185 
186   setOperationAction(ISD::VASTART, MVT::Other, Custom);
187   setOperationAction(ISD::VAARG, MVT::Other, Expand);
188   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
189   setOperationAction(ISD::VAEND, MVT::Other, Expand);
190 
191   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
192   if (!Subtarget.hasStdExtZbb()) {
193     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
195   }
196 
197   if (Subtarget.is64Bit()) {
198     setOperationAction(ISD::ADD, MVT::i32, Custom);
199     setOperationAction(ISD::SUB, MVT::i32, Custom);
200     setOperationAction(ISD::SHL, MVT::i32, Custom);
201     setOperationAction(ISD::SRA, MVT::i32, Custom);
202     setOperationAction(ISD::SRL, MVT::i32, Custom);
203 
204     setOperationAction(ISD::UADDO, MVT::i32, Custom);
205     setOperationAction(ISD::USUBO, MVT::i32, Custom);
206     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
207     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
208   } else {
209     setLibcallName(RTLIB::SHL_I128, nullptr);
210     setLibcallName(RTLIB::SRL_I128, nullptr);
211     setLibcallName(RTLIB::SRA_I128, nullptr);
212     setLibcallName(RTLIB::MUL_I128, nullptr);
213     setLibcallName(RTLIB::MULO_I64, nullptr);
214   }
215 
216   if (!Subtarget.hasStdExtM()) {
217     setOperationAction(ISD::MUL, XLenVT, Expand);
218     setOperationAction(ISD::MULHS, XLenVT, Expand);
219     setOperationAction(ISD::MULHU, XLenVT, Expand);
220     setOperationAction(ISD::SDIV, XLenVT, Expand);
221     setOperationAction(ISD::UDIV, XLenVT, Expand);
222     setOperationAction(ISD::SREM, XLenVT, Expand);
223     setOperationAction(ISD::UREM, XLenVT, Expand);
224   } else {
225     if (Subtarget.is64Bit()) {
226       setOperationAction(ISD::MUL, MVT::i32, Custom);
227       setOperationAction(ISD::MUL, MVT::i128, Custom);
228 
229       setOperationAction(ISD::SDIV, MVT::i8, Custom);
230       setOperationAction(ISD::UDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UREM, MVT::i8, Custom);
232       setOperationAction(ISD::SDIV, MVT::i16, Custom);
233       setOperationAction(ISD::UDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UREM, MVT::i16, Custom);
235       setOperationAction(ISD::SDIV, MVT::i32, Custom);
236       setOperationAction(ISD::UDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UREM, MVT::i32, Custom);
238     } else {
239       setOperationAction(ISD::MUL, MVT::i64, Custom);
240     }
241   }
242 
243   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
244   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
246   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
247 
248   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
249   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
251 
252   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
253     if (Subtarget.is64Bit()) {
254       setOperationAction(ISD::ROTL, MVT::i32, Custom);
255       setOperationAction(ISD::ROTR, MVT::i32, Custom);
256     }
257   } else {
258     setOperationAction(ISD::ROTL, XLenVT, Expand);
259     setOperationAction(ISD::ROTR, XLenVT, Expand);
260   }
261 
262   if (Subtarget.hasStdExtZbp()) {
263     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
264     // more combining.
265     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
266     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
267     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
268     // BSWAP i8 doesn't exist.
269     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
270     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
271 
272     if (Subtarget.is64Bit()) {
273       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
274       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
275     }
276   } else {
277     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
278     // pattern match it directly in isel.
279     setOperationAction(ISD::BSWAP, XLenVT,
280                        Subtarget.hasStdExtZbb() ? Legal : Expand);
281   }
282 
283   if (Subtarget.hasStdExtZbb()) {
284     setOperationAction(ISD::SMIN, XLenVT, Legal);
285     setOperationAction(ISD::SMAX, XLenVT, Legal);
286     setOperationAction(ISD::UMIN, XLenVT, Legal);
287     setOperationAction(ISD::UMAX, XLenVT, Legal);
288 
289     if (Subtarget.is64Bit()) {
290       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
291       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
292       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
293       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
294     }
295   } else {
296     setOperationAction(ISD::CTTZ, XLenVT, Expand);
297     setOperationAction(ISD::CTLZ, XLenVT, Expand);
298     setOperationAction(ISD::CTPOP, XLenVT, Expand);
299   }
300 
301   if (Subtarget.hasStdExtZbt()) {
302     setOperationAction(ISD::FSHL, XLenVT, Custom);
303     setOperationAction(ISD::FSHR, XLenVT, Custom);
304     setOperationAction(ISD::SELECT, XLenVT, Legal);
305 
306     if (Subtarget.is64Bit()) {
307       setOperationAction(ISD::FSHL, MVT::i32, Custom);
308       setOperationAction(ISD::FSHR, MVT::i32, Custom);
309     }
310   } else {
311     setOperationAction(ISD::SELECT, XLenVT, Custom);
312   }
313 
314   static const ISD::CondCode FPCCToExpand[] = {
315       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
316       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
317       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
318 
319   static const ISD::NodeType FPOpToExpand[] = {
320       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
321       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
322 
323   if (Subtarget.hasStdExtZfh())
324     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
325 
326   if (Subtarget.hasStdExtZfh()) {
327     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
328     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
329     setOperationAction(ISD::LRINT, MVT::f16, Legal);
330     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
331     setOperationAction(ISD::LROUND, MVT::f16, Legal);
332     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
333     for (auto CC : FPCCToExpand)
334       setCondCodeAction(CC, MVT::f16, Expand);
335     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
336     setOperationAction(ISD::SELECT, MVT::f16, Custom);
337     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
338     for (auto Op : FPOpToExpand)
339       setOperationAction(Op, MVT::f16, Expand);
340 
341     setOperationAction(ISD::FREM,       MVT::f16, Promote);
342     setOperationAction(ISD::FCEIL,      MVT::f16,  Promote);
343     setOperationAction(ISD::FFLOOR,     MVT::f16,  Promote);
344     setOperationAction(ISD::FNEARBYINT, MVT::f16,  Promote);
345     setOperationAction(ISD::FRINT,      MVT::f16,  Promote);
346     setOperationAction(ISD::FROUND,     MVT::f16,  Promote);
347     setOperationAction(ISD::FROUNDEVEN, MVT::f16,  Promote);
348     setOperationAction(ISD::FTRUNC,     MVT::f16,  Promote);
349   }
350 
351   if (Subtarget.hasStdExtF()) {
352     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
353     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
354     setOperationAction(ISD::LRINT, MVT::f32, Legal);
355     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
356     setOperationAction(ISD::LROUND, MVT::f32, Legal);
357     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
358     for (auto CC : FPCCToExpand)
359       setCondCodeAction(CC, MVT::f32, Expand);
360     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
361     setOperationAction(ISD::SELECT, MVT::f32, Custom);
362     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
363     for (auto Op : FPOpToExpand)
364       setOperationAction(Op, MVT::f32, Expand);
365     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
366     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
367   }
368 
369   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
370     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
371 
372   if (Subtarget.hasStdExtD()) {
373     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
374     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
375     setOperationAction(ISD::LRINT, MVT::f64, Legal);
376     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
377     setOperationAction(ISD::LROUND, MVT::f64, Legal);
378     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
379     for (auto CC : FPCCToExpand)
380       setCondCodeAction(CC, MVT::f64, Expand);
381     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
382     setOperationAction(ISD::SELECT, MVT::f64, Custom);
383     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
384     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
385     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
386     for (auto Op : FPOpToExpand)
387       setOperationAction(Op, MVT::f64, Expand);
388     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
389     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
390   }
391 
392   if (Subtarget.is64Bit()) {
393     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
394     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
395     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
396     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
397   }
398 
399   if (Subtarget.hasStdExtF()) {
400     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
401     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
402 
403     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
404     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
405   }
406 
407   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
408   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
409   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
410   setOperationAction(ISD::JumpTable, XLenVT, Custom);
411 
412   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
413 
414   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
415   // Unfortunately this can't be determined just from the ISA naming string.
416   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
417                      Subtarget.is64Bit() ? Legal : Custom);
418 
419   setOperationAction(ISD::TRAP, MVT::Other, Legal);
420   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
421   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
422   if (Subtarget.is64Bit())
423     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
424 
425   if (Subtarget.hasStdExtA()) {
426     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
427     setMinCmpXchgSizeInBits(32);
428   } else {
429     setMaxAtomicSizeInBitsSupported(0);
430   }
431 
432   setBooleanContents(ZeroOrOneBooleanContent);
433 
434   if (Subtarget.hasVInstructions()) {
435     setBooleanVectorContents(ZeroOrOneBooleanContent);
436 
437     setOperationAction(ISD::VSCALE, XLenVT, Custom);
438 
439     // RVV intrinsics may have illegal operands.
440     // We also need to custom legalize vmv.x.s.
441     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
442     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
443     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
444     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
445     if (Subtarget.is64Bit()) {
446       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
447     } else {
448       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
449       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
450     }
451 
452     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
453     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
454 
455     static const unsigned IntegerVPOps[] = {
456         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
457         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
458         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
459         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
460         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
461         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
462         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN};
463 
464     static const unsigned FloatingPointVPOps[] = {
465         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
466         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
467         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX};
468 
469     if (!Subtarget.is64Bit()) {
470       // We must custom-lower certain vXi64 operations on RV32 due to the vector
471       // element type being illegal.
472       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
473       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
474 
475       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
476       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
477       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
478       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
479       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
480       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
481       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
482       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
483 
484       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
485       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
486       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
487       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
488       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
489       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
490       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
491       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
492     }
493 
494     for (MVT VT : BoolVecVTs) {
495       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
496 
497       // Mask VTs are custom-expanded into a series of standard nodes
498       setOperationAction(ISD::TRUNCATE, VT, Custom);
499       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
500       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
501       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
502 
503       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
504       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
505 
506       setOperationAction(ISD::SELECT, VT, Custom);
507       setOperationAction(ISD::SELECT_CC, VT, Expand);
508       setOperationAction(ISD::VSELECT, VT, Expand);
509 
510       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
511       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
512       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
513 
514       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
515       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
516       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
517 
518       // RVV has native int->float & float->int conversions where the
519       // element type sizes are within one power-of-two of each other. Any
520       // wider distances between type sizes have to be lowered as sequences
521       // which progressively narrow the gap in stages.
522       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
523       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
524       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
525       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
526 
527       // Expand all extending loads to types larger than this, and truncating
528       // stores from types larger than this.
529       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
530         setTruncStoreAction(OtherVT, VT, Expand);
531         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
532         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
533         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
534       }
535     }
536 
537     for (MVT VT : IntVecVTs) {
538       if (VT.getVectorElementType() == MVT::i64 &&
539           !Subtarget.hasVInstructionsI64())
540         continue;
541 
542       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
543       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
544 
545       // Vectors implement MULHS/MULHU.
546       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
547       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
548 
549       setOperationAction(ISD::SMIN, VT, Legal);
550       setOperationAction(ISD::SMAX, VT, Legal);
551       setOperationAction(ISD::UMIN, VT, Legal);
552       setOperationAction(ISD::UMAX, VT, Legal);
553 
554       setOperationAction(ISD::ROTL, VT, Expand);
555       setOperationAction(ISD::ROTR, VT, Expand);
556 
557       setOperationAction(ISD::CTTZ, VT, Expand);
558       setOperationAction(ISD::CTLZ, VT, Expand);
559       setOperationAction(ISD::CTPOP, VT, Expand);
560 
561       setOperationAction(ISD::BSWAP, VT, Expand);
562 
563       // Custom-lower extensions and truncations from/to mask types.
564       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
565       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
566       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
567 
568       // RVV has native int->float & float->int conversions where the
569       // element type sizes are within one power-of-two of each other. Any
570       // wider distances between type sizes have to be lowered as sequences
571       // which progressively narrow the gap in stages.
572       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
573       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
574       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
575       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
576 
577       setOperationAction(ISD::SADDSAT, VT, Legal);
578       setOperationAction(ISD::UADDSAT, VT, Legal);
579       setOperationAction(ISD::SSUBSAT, VT, Legal);
580       setOperationAction(ISD::USUBSAT, VT, Legal);
581 
582       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
583       // nodes which truncate by one power of two at a time.
584       setOperationAction(ISD::TRUNCATE, VT, Custom);
585 
586       // Custom-lower insert/extract operations to simplify patterns.
587       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
588       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
589 
590       // Custom-lower reduction operations to set up the corresponding custom
591       // nodes' operands.
592       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
593       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
594       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
595       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
596       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
597       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
598       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
599       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
600 
601       for (unsigned VPOpc : IntegerVPOps)
602         setOperationAction(VPOpc, VT, Custom);
603 
604       setOperationAction(ISD::LOAD, VT, Custom);
605       setOperationAction(ISD::STORE, VT, Custom);
606 
607       setOperationAction(ISD::MLOAD, VT, Custom);
608       setOperationAction(ISD::MSTORE, VT, Custom);
609       setOperationAction(ISD::MGATHER, VT, Custom);
610       setOperationAction(ISD::MSCATTER, VT, Custom);
611 
612       setOperationAction(ISD::VP_LOAD, VT, Custom);
613       setOperationAction(ISD::VP_STORE, VT, Custom);
614       setOperationAction(ISD::VP_GATHER, VT, Custom);
615       setOperationAction(ISD::VP_SCATTER, VT, Custom);
616 
617       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
618       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
619       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
620 
621       setOperationAction(ISD::SELECT, VT, Custom);
622       setOperationAction(ISD::SELECT_CC, VT, Expand);
623 
624       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
625       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
626 
627       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
628         setTruncStoreAction(VT, OtherVT, Expand);
629         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
630         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
631         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
632       }
633     }
634 
635     // Expand various CCs to best match the RVV ISA, which natively supports UNE
636     // but no other unordered comparisons, and supports all ordered comparisons
637     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
638     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
639     // and we pattern-match those back to the "original", swapping operands once
640     // more. This way we catch both operations and both "vf" and "fv" forms with
641     // fewer patterns.
642     static const ISD::CondCode VFPCCToExpand[] = {
643         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
644         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
645         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
646     };
647 
648     // Sets common operation actions on RVV floating-point vector types.
649     const auto SetCommonVFPActions = [&](MVT VT) {
650       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
651       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
652       // sizes are within one power-of-two of each other. Therefore conversions
653       // between vXf16 and vXf64 must be lowered as sequences which convert via
654       // vXf32.
655       setOperationAction(ISD::FP_ROUND, VT, Custom);
656       setOperationAction(ISD::FP_EXTEND, VT, Custom);
657       // Custom-lower insert/extract operations to simplify patterns.
658       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
659       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
660       // Expand various condition codes (explained above).
661       for (auto CC : VFPCCToExpand)
662         setCondCodeAction(CC, VT, Expand);
663 
664       setOperationAction(ISD::FMINNUM, VT, Legal);
665       setOperationAction(ISD::FMAXNUM, VT, Legal);
666 
667       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
668       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
669       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
670       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
671 
672       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
673 
674       setOperationAction(ISD::LOAD, VT, Custom);
675       setOperationAction(ISD::STORE, VT, Custom);
676 
677       setOperationAction(ISD::MLOAD, VT, Custom);
678       setOperationAction(ISD::MSTORE, VT, Custom);
679       setOperationAction(ISD::MGATHER, VT, Custom);
680       setOperationAction(ISD::MSCATTER, VT, Custom);
681 
682       setOperationAction(ISD::VP_LOAD, VT, Custom);
683       setOperationAction(ISD::VP_STORE, VT, Custom);
684       setOperationAction(ISD::VP_GATHER, VT, Custom);
685       setOperationAction(ISD::VP_SCATTER, VT, Custom);
686 
687       setOperationAction(ISD::SELECT, VT, Custom);
688       setOperationAction(ISD::SELECT_CC, VT, Expand);
689 
690       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
691       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
692       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
693 
694       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
695 
696       for (unsigned VPOpc : FloatingPointVPOps)
697         setOperationAction(VPOpc, VT, Custom);
698     };
699 
700     // Sets common extload/truncstore actions on RVV floating-point vector
701     // types.
702     const auto SetCommonVFPExtLoadTruncStoreActions =
703         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
704           for (auto SmallVT : SmallerVTs) {
705             setTruncStoreAction(VT, SmallVT, Expand);
706             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
707           }
708         };
709 
710     if (Subtarget.hasVInstructionsF16())
711       for (MVT VT : F16VecVTs)
712         SetCommonVFPActions(VT);
713 
714     for (MVT VT : F32VecVTs) {
715       if (Subtarget.hasVInstructionsF32())
716         SetCommonVFPActions(VT);
717       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
718     }
719 
720     for (MVT VT : F64VecVTs) {
721       if (Subtarget.hasVInstructionsF64())
722         SetCommonVFPActions(VT);
723       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
724       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
725     }
726 
727     if (Subtarget.useRVVForFixedLengthVectors()) {
728       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
729         if (!useRVVForFixedLengthVectorVT(VT))
730           continue;
731 
732         // By default everything must be expanded.
733         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
734           setOperationAction(Op, VT, Expand);
735         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
736           setTruncStoreAction(VT, OtherVT, Expand);
737           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
738           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
739           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
740         }
741 
742         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
743         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
744         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
745 
746         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
747         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
748 
749         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
750         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
751 
752         setOperationAction(ISD::LOAD, VT, Custom);
753         setOperationAction(ISD::STORE, VT, Custom);
754 
755         setOperationAction(ISD::SETCC, VT, Custom);
756 
757         setOperationAction(ISD::SELECT, VT, Custom);
758 
759         setOperationAction(ISD::TRUNCATE, VT, Custom);
760 
761         setOperationAction(ISD::BITCAST, VT, Custom);
762 
763         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
764         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
765         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
766 
767         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
768         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
769         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
770 
771         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
772         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
773         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
774         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
775 
776         // Operations below are different for between masks and other vectors.
777         if (VT.getVectorElementType() == MVT::i1) {
778           setOperationAction(ISD::AND, VT, Custom);
779           setOperationAction(ISD::OR, VT, Custom);
780           setOperationAction(ISD::XOR, VT, Custom);
781           continue;
782         }
783 
784         // Use SPLAT_VECTOR to prevent type legalization from destroying the
785         // splats when type legalizing i64 scalar on RV32.
786         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
787         // improvements first.
788         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
789           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
790           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
791         }
792 
793         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
794         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
795 
796         setOperationAction(ISD::MLOAD, VT, Custom);
797         setOperationAction(ISD::MSTORE, VT, Custom);
798         setOperationAction(ISD::MGATHER, VT, Custom);
799         setOperationAction(ISD::MSCATTER, VT, Custom);
800 
801         setOperationAction(ISD::VP_LOAD, VT, Custom);
802         setOperationAction(ISD::VP_STORE, VT, Custom);
803         setOperationAction(ISD::VP_GATHER, VT, Custom);
804         setOperationAction(ISD::VP_SCATTER, VT, Custom);
805 
806         setOperationAction(ISD::ADD, VT, Custom);
807         setOperationAction(ISD::MUL, VT, Custom);
808         setOperationAction(ISD::SUB, VT, Custom);
809         setOperationAction(ISD::AND, VT, Custom);
810         setOperationAction(ISD::OR, VT, Custom);
811         setOperationAction(ISD::XOR, VT, Custom);
812         setOperationAction(ISD::SDIV, VT, Custom);
813         setOperationAction(ISD::SREM, VT, Custom);
814         setOperationAction(ISD::UDIV, VT, Custom);
815         setOperationAction(ISD::UREM, VT, Custom);
816         setOperationAction(ISD::SHL, VT, Custom);
817         setOperationAction(ISD::SRA, VT, Custom);
818         setOperationAction(ISD::SRL, VT, Custom);
819 
820         setOperationAction(ISD::SMIN, VT, Custom);
821         setOperationAction(ISD::SMAX, VT, Custom);
822         setOperationAction(ISD::UMIN, VT, Custom);
823         setOperationAction(ISD::UMAX, VT, Custom);
824         setOperationAction(ISD::ABS,  VT, Custom);
825 
826         setOperationAction(ISD::MULHS, VT, Custom);
827         setOperationAction(ISD::MULHU, VT, Custom);
828 
829         setOperationAction(ISD::SADDSAT, VT, Custom);
830         setOperationAction(ISD::UADDSAT, VT, Custom);
831         setOperationAction(ISD::SSUBSAT, VT, Custom);
832         setOperationAction(ISD::USUBSAT, VT, Custom);
833 
834         setOperationAction(ISD::VSELECT, VT, Custom);
835         setOperationAction(ISD::SELECT_CC, VT, Expand);
836 
837         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
838         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
839         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
840 
841         // Custom-lower reduction operations to set up the corresponding custom
842         // nodes' operands.
843         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
844         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
845         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
846         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
847         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
848 
849         for (unsigned VPOpc : IntegerVPOps)
850           setOperationAction(VPOpc, VT, Custom);
851       }
852 
853       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
854         if (!useRVVForFixedLengthVectorVT(VT))
855           continue;
856 
857         // By default everything must be expanded.
858         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
859           setOperationAction(Op, VT, Expand);
860         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
861           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
862           setTruncStoreAction(VT, OtherVT, Expand);
863         }
864 
865         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
866         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
867         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
868 
869         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
870         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
871         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
872         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
873         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
874 
875         setOperationAction(ISD::LOAD, VT, Custom);
876         setOperationAction(ISD::STORE, VT, Custom);
877         setOperationAction(ISD::MLOAD, VT, Custom);
878         setOperationAction(ISD::MSTORE, VT, Custom);
879         setOperationAction(ISD::MGATHER, VT, Custom);
880         setOperationAction(ISD::MSCATTER, VT, Custom);
881 
882         setOperationAction(ISD::VP_LOAD, VT, Custom);
883         setOperationAction(ISD::VP_STORE, VT, Custom);
884         setOperationAction(ISD::VP_GATHER, VT, Custom);
885         setOperationAction(ISD::VP_SCATTER, VT, Custom);
886 
887         setOperationAction(ISD::FADD, VT, Custom);
888         setOperationAction(ISD::FSUB, VT, Custom);
889         setOperationAction(ISD::FMUL, VT, Custom);
890         setOperationAction(ISD::FDIV, VT, Custom);
891         setOperationAction(ISD::FNEG, VT, Custom);
892         setOperationAction(ISD::FABS, VT, Custom);
893         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
894         setOperationAction(ISD::FSQRT, VT, Custom);
895         setOperationAction(ISD::FMA, VT, Custom);
896         setOperationAction(ISD::FMINNUM, VT, Custom);
897         setOperationAction(ISD::FMAXNUM, VT, Custom);
898 
899         setOperationAction(ISD::FP_ROUND, VT, Custom);
900         setOperationAction(ISD::FP_EXTEND, VT, Custom);
901 
902         for (auto CC : VFPCCToExpand)
903           setCondCodeAction(CC, VT, Expand);
904 
905         setOperationAction(ISD::VSELECT, VT, Custom);
906         setOperationAction(ISD::SELECT, VT, Custom);
907         setOperationAction(ISD::SELECT_CC, VT, Expand);
908 
909         setOperationAction(ISD::BITCAST, VT, Custom);
910 
911         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
912         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
913         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
914         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
915 
916         for (unsigned VPOpc : FloatingPointVPOps)
917           setOperationAction(VPOpc, VT, Custom);
918       }
919 
920       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
921       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
922       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
923       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
924       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
925       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
926       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
927       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
928     }
929   }
930 
931   // Function alignments.
932   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
933   setMinFunctionAlignment(FunctionAlignment);
934   setPrefFunctionAlignment(FunctionAlignment);
935 
936   setMinimumJumpTableEntries(5);
937 
938   // Jumps are expensive, compared to logic
939   setJumpIsExpensive();
940 
941   // We can use any register for comparisons
942   setHasMultipleConditionRegisters();
943 
944   setTargetDAGCombine(ISD::ADD);
945   setTargetDAGCombine(ISD::SUB);
946   setTargetDAGCombine(ISD::AND);
947   setTargetDAGCombine(ISD::OR);
948   setTargetDAGCombine(ISD::XOR);
949   setTargetDAGCombine(ISD::ANY_EXTEND);
950   setTargetDAGCombine(ISD::ZERO_EXTEND);
951   if (Subtarget.hasVInstructions()) {
952     setTargetDAGCombine(ISD::FCOPYSIGN);
953     setTargetDAGCombine(ISD::MGATHER);
954     setTargetDAGCombine(ISD::MSCATTER);
955     setTargetDAGCombine(ISD::VP_GATHER);
956     setTargetDAGCombine(ISD::VP_SCATTER);
957     setTargetDAGCombine(ISD::SRA);
958     setTargetDAGCombine(ISD::SRL);
959     setTargetDAGCombine(ISD::SHL);
960     setTargetDAGCombine(ISD::STORE);
961   }
962 }
963 
964 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
965                                             LLVMContext &Context,
966                                             EVT VT) const {
967   if (!VT.isVector())
968     return getPointerTy(DL);
969   if (Subtarget.hasVInstructions() &&
970       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
971     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
972   return VT.changeVectorElementTypeToInteger();
973 }
974 
975 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
976   return Subtarget.getXLenVT();
977 }
978 
979 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
980                                              const CallInst &I,
981                                              MachineFunction &MF,
982                                              unsigned Intrinsic) const {
983   auto &DL = I.getModule()->getDataLayout();
984   switch (Intrinsic) {
985   default:
986     return false;
987   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
988   case Intrinsic::riscv_masked_atomicrmw_add_i32:
989   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
990   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
991   case Intrinsic::riscv_masked_atomicrmw_max_i32:
992   case Intrinsic::riscv_masked_atomicrmw_min_i32:
993   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
994   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
995   case Intrinsic::riscv_masked_cmpxchg_i32: {
996     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
997     Info.opc = ISD::INTRINSIC_W_CHAIN;
998     Info.memVT = MVT::getVT(PtrTy->getElementType());
999     Info.ptrVal = I.getArgOperand(0);
1000     Info.offset = 0;
1001     Info.align = Align(4);
1002     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1003                  MachineMemOperand::MOVolatile;
1004     return true;
1005   }
1006   case Intrinsic::riscv_masked_strided_load:
1007     Info.opc = ISD::INTRINSIC_W_CHAIN;
1008     Info.ptrVal = I.getArgOperand(1);
1009     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1010     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1011     Info.size = MemoryLocation::UnknownSize;
1012     Info.flags |= MachineMemOperand::MOLoad;
1013     return true;
1014   case Intrinsic::riscv_masked_strided_store:
1015     Info.opc = ISD::INTRINSIC_VOID;
1016     Info.ptrVal = I.getArgOperand(1);
1017     Info.memVT =
1018         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1019     Info.align = Align(
1020         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1021         8);
1022     Info.size = MemoryLocation::UnknownSize;
1023     Info.flags |= MachineMemOperand::MOStore;
1024     return true;
1025   }
1026 }
1027 
1028 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1029                                                 const AddrMode &AM, Type *Ty,
1030                                                 unsigned AS,
1031                                                 Instruction *I) const {
1032   // No global is ever allowed as a base.
1033   if (AM.BaseGV)
1034     return false;
1035 
1036   // Require a 12-bit signed offset.
1037   if (!isInt<12>(AM.BaseOffs))
1038     return false;
1039 
1040   switch (AM.Scale) {
1041   case 0: // "r+i" or just "i", depending on HasBaseReg.
1042     break;
1043   case 1:
1044     if (!AM.HasBaseReg) // allow "r+i".
1045       break;
1046     return false; // disallow "r+r" or "r+r+i".
1047   default:
1048     return false;
1049   }
1050 
1051   return true;
1052 }
1053 
1054 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1055   return isInt<12>(Imm);
1056 }
1057 
1058 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1059   return isInt<12>(Imm);
1060 }
1061 
1062 // On RV32, 64-bit integers are split into their high and low parts and held
1063 // in two different registers, so the trunc is free since the low register can
1064 // just be used.
1065 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1066   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1067     return false;
1068   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1069   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1070   return (SrcBits == 64 && DestBits == 32);
1071 }
1072 
1073 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1074   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1075       !SrcVT.isInteger() || !DstVT.isInteger())
1076     return false;
1077   unsigned SrcBits = SrcVT.getSizeInBits();
1078   unsigned DestBits = DstVT.getSizeInBits();
1079   return (SrcBits == 64 && DestBits == 32);
1080 }
1081 
1082 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1083   // Zexts are free if they can be combined with a load.
1084   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1085     EVT MemVT = LD->getMemoryVT();
1086     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1087          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1088         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1089          LD->getExtensionType() == ISD::ZEXTLOAD))
1090       return true;
1091   }
1092 
1093   return TargetLowering::isZExtFree(Val, VT2);
1094 }
1095 
1096 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1097   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1098 }
1099 
1100 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1101   return Subtarget.hasStdExtZbb();
1102 }
1103 
1104 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1105   return Subtarget.hasStdExtZbb();
1106 }
1107 
1108 bool RISCVTargetLowering::hasAndNot(SDValue Y) const {
1109   EVT VT = Y.getValueType();
1110 
1111   // FIXME: Support vectors once we have tests.
1112   if (VT.isVector())
1113     return false;
1114 
1115   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1116 }
1117 
1118 /// Check if sinking \p I's operands to I's basic block is profitable, because
1119 /// the operands can be folded into a target instruction, e.g.
1120 /// splats of scalars can fold into vector instructions.
1121 bool RISCVTargetLowering::shouldSinkOperands(
1122     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1123   using namespace llvm::PatternMatch;
1124 
1125   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1126     return false;
1127 
1128   auto IsSinker = [&](Instruction *I, int Operand) {
1129     switch (I->getOpcode()) {
1130     case Instruction::Add:
1131     case Instruction::Sub:
1132     case Instruction::Mul:
1133     case Instruction::And:
1134     case Instruction::Or:
1135     case Instruction::Xor:
1136     case Instruction::FAdd:
1137     case Instruction::FSub:
1138     case Instruction::FMul:
1139     case Instruction::FDiv:
1140     case Instruction::ICmp:
1141     case Instruction::FCmp:
1142       return true;
1143     case Instruction::Shl:
1144     case Instruction::LShr:
1145     case Instruction::AShr:
1146       return Operand == 1;
1147     case Instruction::Call:
1148       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1149         switch (II->getIntrinsicID()) {
1150         case Intrinsic::fma:
1151           return Operand == 0 || Operand == 1;
1152         default:
1153           return false;
1154         }
1155       }
1156       return false;
1157     default:
1158       return false;
1159     }
1160   };
1161 
1162   for (auto OpIdx : enumerate(I->operands())) {
1163     if (!IsSinker(I, OpIdx.index()))
1164       continue;
1165 
1166     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1167     // Make sure we are not already sinking this operand
1168     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1169       continue;
1170 
1171     // We are looking for a splat that can be sunk.
1172     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1173                              m_Undef(), m_ZeroMask())))
1174       continue;
1175 
1176     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1177     // and vector registers
1178     for (Use &U : Op->uses()) {
1179       Instruction *Insn = cast<Instruction>(U.getUser());
1180       if (!IsSinker(Insn, U.getOperandNo()))
1181         return false;
1182     }
1183 
1184     Ops.push_back(&Op->getOperandUse(0));
1185     Ops.push_back(&OpIdx.value());
1186   }
1187   return true;
1188 }
1189 
1190 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1191                                        bool ForCodeSize) const {
1192   if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin())
1193     return false;
1194   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1195     return false;
1196   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1197     return false;
1198   if (Imm.isNegZero())
1199     return false;
1200   return Imm.isZero();
1201 }
1202 
1203 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1204   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1205          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1206          (VT == MVT::f64 && Subtarget.hasStdExtD());
1207 }
1208 
1209 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1210                                                       CallingConv::ID CC,
1211                                                       EVT VT) const {
1212   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1213   // We might still end up using a GPR but that will be decided based on ABI.
1214   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1215     return MVT::f32;
1216 
1217   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1218 }
1219 
1220 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1221                                                            CallingConv::ID CC,
1222                                                            EVT VT) const {
1223   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1224   // We might still end up using a GPR but that will be decided based on ABI.
1225   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1226     return 1;
1227 
1228   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1229 }
1230 
1231 // Changes the condition code and swaps operands if necessary, so the SetCC
1232 // operation matches one of the comparisons supported directly by branches
1233 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1234 // with 1/-1.
1235 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1236                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1237   // Convert X > -1 to X >= 0.
1238   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1239     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1240     CC = ISD::SETGE;
1241     return;
1242   }
1243   // Convert X < 1 to 0 >= X.
1244   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1245     RHS = LHS;
1246     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1247     CC = ISD::SETGE;
1248     return;
1249   }
1250 
1251   switch (CC) {
1252   default:
1253     break;
1254   case ISD::SETGT:
1255   case ISD::SETLE:
1256   case ISD::SETUGT:
1257   case ISD::SETULE:
1258     CC = ISD::getSetCCSwappedOperands(CC);
1259     std::swap(LHS, RHS);
1260     break;
1261   }
1262 }
1263 
1264 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1265   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1266   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1267   if (VT.getVectorElementType() == MVT::i1)
1268     KnownSize *= 8;
1269 
1270   switch (KnownSize) {
1271   default:
1272     llvm_unreachable("Invalid LMUL.");
1273   case 8:
1274     return RISCVII::VLMUL::LMUL_F8;
1275   case 16:
1276     return RISCVII::VLMUL::LMUL_F4;
1277   case 32:
1278     return RISCVII::VLMUL::LMUL_F2;
1279   case 64:
1280     return RISCVII::VLMUL::LMUL_1;
1281   case 128:
1282     return RISCVII::VLMUL::LMUL_2;
1283   case 256:
1284     return RISCVII::VLMUL::LMUL_4;
1285   case 512:
1286     return RISCVII::VLMUL::LMUL_8;
1287   }
1288 }
1289 
1290 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1291   switch (LMul) {
1292   default:
1293     llvm_unreachable("Invalid LMUL.");
1294   case RISCVII::VLMUL::LMUL_F8:
1295   case RISCVII::VLMUL::LMUL_F4:
1296   case RISCVII::VLMUL::LMUL_F2:
1297   case RISCVII::VLMUL::LMUL_1:
1298     return RISCV::VRRegClassID;
1299   case RISCVII::VLMUL::LMUL_2:
1300     return RISCV::VRM2RegClassID;
1301   case RISCVII::VLMUL::LMUL_4:
1302     return RISCV::VRM4RegClassID;
1303   case RISCVII::VLMUL::LMUL_8:
1304     return RISCV::VRM8RegClassID;
1305   }
1306 }
1307 
1308 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1309   RISCVII::VLMUL LMUL = getLMUL(VT);
1310   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1311       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1312       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1313       LMUL == RISCVII::VLMUL::LMUL_1) {
1314     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1315                   "Unexpected subreg numbering");
1316     return RISCV::sub_vrm1_0 + Index;
1317   }
1318   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1319     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1320                   "Unexpected subreg numbering");
1321     return RISCV::sub_vrm2_0 + Index;
1322   }
1323   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1324     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1325                   "Unexpected subreg numbering");
1326     return RISCV::sub_vrm4_0 + Index;
1327   }
1328   llvm_unreachable("Invalid vector type.");
1329 }
1330 
1331 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1332   if (VT.getVectorElementType() == MVT::i1)
1333     return RISCV::VRRegClassID;
1334   return getRegClassIDForLMUL(getLMUL(VT));
1335 }
1336 
1337 // Attempt to decompose a subvector insert/extract between VecVT and
1338 // SubVecVT via subregister indices. Returns the subregister index that
1339 // can perform the subvector insert/extract with the given element index, as
1340 // well as the index corresponding to any leftover subvectors that must be
1341 // further inserted/extracted within the register class for SubVecVT.
1342 std::pair<unsigned, unsigned>
1343 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1344     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1345     const RISCVRegisterInfo *TRI) {
1346   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1347                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1348                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1349                 "Register classes not ordered");
1350   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1351   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1352   // Try to compose a subregister index that takes us from the incoming
1353   // LMUL>1 register class down to the outgoing one. At each step we half
1354   // the LMUL:
1355   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1356   // Note that this is not guaranteed to find a subregister index, such as
1357   // when we are extracting from one VR type to another.
1358   unsigned SubRegIdx = RISCV::NoSubRegister;
1359   for (const unsigned RCID :
1360        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1361     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1362       VecVT = VecVT.getHalfNumVectorElementsVT();
1363       bool IsHi =
1364           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1365       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1366                                             getSubregIndexByMVT(VecVT, IsHi));
1367       if (IsHi)
1368         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1369     }
1370   return {SubRegIdx, InsertExtractIdx};
1371 }
1372 
1373 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1374 // stores for those types.
1375 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1376   return !Subtarget.useRVVForFixedLengthVectors() ||
1377          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1378 }
1379 
1380 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1381   if (ScalarTy->isPointerTy())
1382     return true;
1383 
1384   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1385       ScalarTy->isIntegerTy(32))
1386     return true;
1387 
1388   if (ScalarTy->isIntegerTy(64))
1389     return Subtarget.hasVInstructionsI64();
1390 
1391   if (ScalarTy->isHalfTy())
1392     return Subtarget.hasVInstructionsF16();
1393   if (ScalarTy->isFloatTy())
1394     return Subtarget.hasVInstructionsF32();
1395   if (ScalarTy->isDoubleTy())
1396     return Subtarget.hasVInstructionsF64();
1397 
1398   return false;
1399 }
1400 
1401 static bool useRVVForFixedLengthVectorVT(MVT VT,
1402                                          const RISCVSubtarget &Subtarget) {
1403   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1404   if (!Subtarget.useRVVForFixedLengthVectors())
1405     return false;
1406 
1407   // We only support a set of vector types with a consistent maximum fixed size
1408   // across all supported vector element types to avoid legalization issues.
1409   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1410   // fixed-length vector type we support is 1024 bytes.
1411   if (VT.getFixedSizeInBits() > 1024 * 8)
1412     return false;
1413 
1414   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1415 
1416   MVT EltVT = VT.getVectorElementType();
1417 
1418   // Don't use RVV for vectors we cannot scalarize if required.
1419   switch (EltVT.SimpleTy) {
1420   // i1 is supported but has different rules.
1421   default:
1422     return false;
1423   case MVT::i1:
1424     // Masks can only use a single register.
1425     if (VT.getVectorNumElements() > MinVLen)
1426       return false;
1427     MinVLen /= 8;
1428     break;
1429   case MVT::i8:
1430   case MVT::i16:
1431   case MVT::i32:
1432     break;
1433   case MVT::i64:
1434     if (!Subtarget.hasVInstructionsI64())
1435       return false;
1436     break;
1437   case MVT::f16:
1438     if (!Subtarget.hasVInstructionsF16())
1439       return false;
1440     break;
1441   case MVT::f32:
1442     if (!Subtarget.hasVInstructionsF32())
1443       return false;
1444     break;
1445   case MVT::f64:
1446     if (!Subtarget.hasVInstructionsF64())
1447       return false;
1448     break;
1449   }
1450 
1451   // Reject elements larger than ELEN.
1452   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1453     return false;
1454 
1455   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1456   // Don't use RVV for types that don't fit.
1457   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1458     return false;
1459 
1460   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1461   // the base fixed length RVV support in place.
1462   if (!VT.isPow2VectorType())
1463     return false;
1464 
1465   return true;
1466 }
1467 
1468 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1469   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1470 }
1471 
1472 // Return the largest legal scalable vector type that matches VT's element type.
1473 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1474                                             const RISCVSubtarget &Subtarget) {
1475   // This may be called before legal types are setup.
1476   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1477           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1478          "Expected legal fixed length vector!");
1479 
1480   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1481   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1482 
1483   MVT EltVT = VT.getVectorElementType();
1484   switch (EltVT.SimpleTy) {
1485   default:
1486     llvm_unreachable("unexpected element type for RVV container");
1487   case MVT::i1:
1488   case MVT::i8:
1489   case MVT::i16:
1490   case MVT::i32:
1491   case MVT::i64:
1492   case MVT::f16:
1493   case MVT::f32:
1494   case MVT::f64: {
1495     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1496     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1497     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1498     unsigned NumElts =
1499         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1500     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1501     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1502     return MVT::getScalableVectorVT(EltVT, NumElts);
1503   }
1504   }
1505 }
1506 
1507 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1508                                             const RISCVSubtarget &Subtarget) {
1509   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1510                                           Subtarget);
1511 }
1512 
1513 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1514   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1515 }
1516 
1517 // Grow V to consume an entire RVV register.
1518 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1519                                        const RISCVSubtarget &Subtarget) {
1520   assert(VT.isScalableVector() &&
1521          "Expected to convert into a scalable vector!");
1522   assert(V.getValueType().isFixedLengthVector() &&
1523          "Expected a fixed length vector operand!");
1524   SDLoc DL(V);
1525   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1526   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1527 }
1528 
1529 // Shrink V so it's just big enough to maintain a VT's worth of data.
1530 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1531                                          const RISCVSubtarget &Subtarget) {
1532   assert(VT.isFixedLengthVector() &&
1533          "Expected to convert into a fixed length vector!");
1534   assert(V.getValueType().isScalableVector() &&
1535          "Expected a scalable vector operand!");
1536   SDLoc DL(V);
1537   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1538   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1539 }
1540 
1541 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1542 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1543 // the vector type that it is contained in.
1544 static std::pair<SDValue, SDValue>
1545 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1546                 const RISCVSubtarget &Subtarget) {
1547   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1548   MVT XLenVT = Subtarget.getXLenVT();
1549   SDValue VL = VecVT.isFixedLengthVector()
1550                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1551                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1552   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1553   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1554   return {Mask, VL};
1555 }
1556 
1557 // As above but assuming the given type is a scalable vector type.
1558 static std::pair<SDValue, SDValue>
1559 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1560                         const RISCVSubtarget &Subtarget) {
1561   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1562   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1563 }
1564 
1565 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1566 // of either is (currently) supported. This can get us into an infinite loop
1567 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1568 // as a ..., etc.
1569 // Until either (or both) of these can reliably lower any node, reporting that
1570 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1571 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1572 // which is not desirable.
1573 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1574     EVT VT, unsigned DefinedValues) const {
1575   return false;
1576 }
1577 
1578 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1579   // Only splats are currently supported.
1580   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1581     return true;
1582 
1583   return false;
1584 }
1585 
1586 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1587   // RISCV FP-to-int conversions saturate to the destination register size, but
1588   // don't produce 0 for nan. We can use a conversion instruction and fix the
1589   // nan case with a compare and a select.
1590   SDValue Src = Op.getOperand(0);
1591 
1592   EVT DstVT = Op.getValueType();
1593   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1594 
1595   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1596   unsigned Opc;
1597   if (SatVT == DstVT)
1598     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1599   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1600     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1601   else
1602     return SDValue();
1603   // FIXME: Support other SatVTs by clamping before or after the conversion.
1604 
1605   SDLoc DL(Op);
1606   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1607 
1608   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1609   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1610 }
1611 
1612 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1613                                  const RISCVSubtarget &Subtarget) {
1614   MVT VT = Op.getSimpleValueType();
1615   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1616 
1617   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1618 
1619   SDLoc DL(Op);
1620   SDValue Mask, VL;
1621   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1622 
1623   unsigned Opc =
1624       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1625   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1626   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1627 }
1628 
1629 struct VIDSequence {
1630   int64_t StepNumerator;
1631   unsigned StepDenominator;
1632   int64_t Addend;
1633 };
1634 
1635 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1636 // to the (non-zero) step S and start value X. This can be then lowered as the
1637 // RVV sequence (VID * S) + X, for example.
1638 // The step S is represented as an integer numerator divided by a positive
1639 // denominator. Note that the implementation currently only identifies
1640 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1641 // cannot detect 2/3, for example.
1642 // Note that this method will also match potentially unappealing index
1643 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1644 // determine whether this is worth generating code for.
1645 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1646   unsigned NumElts = Op.getNumOperands();
1647   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1648   if (!Op.getValueType().isInteger())
1649     return None;
1650 
1651   Optional<unsigned> SeqStepDenom;
1652   Optional<int64_t> SeqStepNum, SeqAddend;
1653   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1654   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1655   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1656     // Assume undef elements match the sequence; we just have to be careful
1657     // when interpolating across them.
1658     if (Op.getOperand(Idx).isUndef())
1659       continue;
1660     // The BUILD_VECTOR must be all constants.
1661     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1662       return None;
1663 
1664     uint64_t Val = Op.getConstantOperandVal(Idx) &
1665                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1666 
1667     if (PrevElt) {
1668       // Calculate the step since the last non-undef element, and ensure
1669       // it's consistent across the entire sequence.
1670       unsigned IdxDiff = Idx - PrevElt->second;
1671       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1672 
1673       // A zero-value value difference means that we're somewhere in the middle
1674       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1675       // step change before evaluating the sequence.
1676       if (ValDiff != 0) {
1677         int64_t Remainder = ValDiff % IdxDiff;
1678         // Normalize the step if it's greater than 1.
1679         if (Remainder != ValDiff) {
1680           // The difference must cleanly divide the element span.
1681           if (Remainder != 0)
1682             return None;
1683           ValDiff /= IdxDiff;
1684           IdxDiff = 1;
1685         }
1686 
1687         if (!SeqStepNum)
1688           SeqStepNum = ValDiff;
1689         else if (ValDiff != SeqStepNum)
1690           return None;
1691 
1692         if (!SeqStepDenom)
1693           SeqStepDenom = IdxDiff;
1694         else if (IdxDiff != *SeqStepDenom)
1695           return None;
1696       }
1697     }
1698 
1699     // Record and/or check any addend.
1700     if (SeqStepNum && SeqStepDenom) {
1701       uint64_t ExpectedVal =
1702           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1703       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1704       if (!SeqAddend)
1705         SeqAddend = Addend;
1706       else if (SeqAddend != Addend)
1707         return None;
1708     }
1709 
1710     // Record this non-undef element for later.
1711     if (!PrevElt || PrevElt->first != Val)
1712       PrevElt = std::make_pair(Val, Idx);
1713   }
1714   // We need to have logged both a step and an addend for this to count as
1715   // a legal index sequence.
1716   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1717     return None;
1718 
1719   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1720 }
1721 
1722 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1723                                  const RISCVSubtarget &Subtarget) {
1724   MVT VT = Op.getSimpleValueType();
1725   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1726 
1727   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1728 
1729   SDLoc DL(Op);
1730   SDValue Mask, VL;
1731   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1732 
1733   MVT XLenVT = Subtarget.getXLenVT();
1734   unsigned NumElts = Op.getNumOperands();
1735 
1736   if (VT.getVectorElementType() == MVT::i1) {
1737     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1738       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1739       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1740     }
1741 
1742     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1743       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1744       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1745     }
1746 
1747     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1748     // scalar integer chunks whose bit-width depends on the number of mask
1749     // bits and XLEN.
1750     // First, determine the most appropriate scalar integer type to use. This
1751     // is at most XLenVT, but may be shrunk to a smaller vector element type
1752     // according to the size of the final vector - use i8 chunks rather than
1753     // XLenVT if we're producing a v8i1. This results in more consistent
1754     // codegen across RV32 and RV64.
1755     unsigned NumViaIntegerBits =
1756         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1757     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1758       // If we have to use more than one INSERT_VECTOR_ELT then this
1759       // optimization is likely to increase code size; avoid peforming it in
1760       // such a case. We can use a load from a constant pool in this case.
1761       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1762         return SDValue();
1763       // Now we can create our integer vector type. Note that it may be larger
1764       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1765       MVT IntegerViaVecVT =
1766           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1767                            divideCeil(NumElts, NumViaIntegerBits));
1768 
1769       uint64_t Bits = 0;
1770       unsigned BitPos = 0, IntegerEltIdx = 0;
1771       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1772 
1773       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1774         // Once we accumulate enough bits to fill our scalar type, insert into
1775         // our vector and clear our accumulated data.
1776         if (I != 0 && I % NumViaIntegerBits == 0) {
1777           if (NumViaIntegerBits <= 32)
1778             Bits = SignExtend64(Bits, 32);
1779           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1780           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1781                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1782           Bits = 0;
1783           BitPos = 0;
1784           IntegerEltIdx++;
1785         }
1786         SDValue V = Op.getOperand(I);
1787         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1788         Bits |= ((uint64_t)BitValue << BitPos);
1789       }
1790 
1791       // Insert the (remaining) scalar value into position in our integer
1792       // vector type.
1793       if (NumViaIntegerBits <= 32)
1794         Bits = SignExtend64(Bits, 32);
1795       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1796       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1797                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1798 
1799       if (NumElts < NumViaIntegerBits) {
1800         // If we're producing a smaller vector than our minimum legal integer
1801         // type, bitcast to the equivalent (known-legal) mask type, and extract
1802         // our final mask.
1803         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1804         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1805         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1806                           DAG.getConstant(0, DL, XLenVT));
1807       } else {
1808         // Else we must have produced an integer type with the same size as the
1809         // mask type; bitcast for the final result.
1810         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1811         Vec = DAG.getBitcast(VT, Vec);
1812       }
1813 
1814       return Vec;
1815     }
1816 
1817     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1818     // vector type, we have a legal equivalently-sized i8 type, so we can use
1819     // that.
1820     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1821     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1822 
1823     SDValue WideVec;
1824     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1825       // For a splat, perform a scalar truncate before creating the wider
1826       // vector.
1827       assert(Splat.getValueType() == XLenVT &&
1828              "Unexpected type for i1 splat value");
1829       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1830                           DAG.getConstant(1, DL, XLenVT));
1831       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1832     } else {
1833       SmallVector<SDValue, 8> Ops(Op->op_values());
1834       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1835       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1836       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1837     }
1838 
1839     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1840   }
1841 
1842   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1843     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1844                                         : RISCVISD::VMV_V_X_VL;
1845     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1846     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1847   }
1848 
1849   // Try and match index sequences, which we can lower to the vid instruction
1850   // with optional modifications. An all-undef vector is matched by
1851   // getSplatValue, above.
1852   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1853     int64_t StepNumerator = SimpleVID->StepNumerator;
1854     unsigned StepDenominator = SimpleVID->StepDenominator;
1855     int64_t Addend = SimpleVID->Addend;
1856     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1857     // threshold since it's the immediate value many RVV instructions accept.
1858     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1859         isInt<5>(Addend)) {
1860       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1861       // Convert right out of the scalable type so we can use standard ISD
1862       // nodes for the rest of the computation. If we used scalable types with
1863       // these, we'd lose the fixed-length vector info and generate worse
1864       // vsetvli code.
1865       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1866       assert(StepNumerator != 0 && "Invalid step");
1867       bool Negate = false;
1868       if (StepNumerator != 1) {
1869         int64_t SplatStepVal = StepNumerator;
1870         unsigned Opcode = ISD::MUL;
1871         if (isPowerOf2_64(std::abs(StepNumerator))) {
1872           Negate = StepNumerator < 0;
1873           Opcode = ISD::SHL;
1874           SplatStepVal = Log2_64(std::abs(StepNumerator));
1875         }
1876         SDValue SplatStep = DAG.getSplatVector(
1877             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1878         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1879       }
1880       if (StepDenominator != 1) {
1881         SDValue SplatStep = DAG.getSplatVector(
1882             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1883         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1884       }
1885       if (Addend != 0 || Negate) {
1886         SDValue SplatAddend =
1887             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1888         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1889       }
1890       return VID;
1891     }
1892   }
1893 
1894   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1895   // when re-interpreted as a vector with a larger element type. For example,
1896   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1897   // could be instead splat as
1898   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1899   // TODO: This optimization could also work on non-constant splats, but it
1900   // would require bit-manipulation instructions to construct the splat value.
1901   SmallVector<SDValue> Sequence;
1902   unsigned EltBitSize = VT.getScalarSizeInBits();
1903   const auto *BV = cast<BuildVectorSDNode>(Op);
1904   if (VT.isInteger() && EltBitSize < 64 &&
1905       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1906       BV->getRepeatedSequence(Sequence) &&
1907       (Sequence.size() * EltBitSize) <= 64) {
1908     unsigned SeqLen = Sequence.size();
1909     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1910     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1911     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1912             ViaIntVT == MVT::i64) &&
1913            "Unexpected sequence type");
1914 
1915     unsigned EltIdx = 0;
1916     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1917     uint64_t SplatValue = 0;
1918     // Construct the amalgamated value which can be splatted as this larger
1919     // vector type.
1920     for (const auto &SeqV : Sequence) {
1921       if (!SeqV.isUndef())
1922         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1923                        << (EltIdx * EltBitSize));
1924       EltIdx++;
1925     }
1926 
1927     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1928     // achieve better constant materializion.
1929     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1930       SplatValue = SignExtend64(SplatValue, 32);
1931 
1932     // Since we can't introduce illegal i64 types at this stage, we can only
1933     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1934     // way we can use RVV instructions to splat.
1935     assert((ViaIntVT.bitsLE(XLenVT) ||
1936             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1937            "Unexpected bitcast sequence");
1938     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1939       SDValue ViaVL =
1940           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1941       MVT ViaContainerVT =
1942           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
1943       SDValue Splat =
1944           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1945                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1946       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1947       return DAG.getBitcast(VT, Splat);
1948     }
1949   }
1950 
1951   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1952   // which constitute a large proportion of the elements. In such cases we can
1953   // splat a vector with the dominant element and make up the shortfall with
1954   // INSERT_VECTOR_ELTs.
1955   // Note that this includes vectors of 2 elements by association. The
1956   // upper-most element is the "dominant" one, allowing us to use a splat to
1957   // "insert" the upper element, and an insert of the lower element at position
1958   // 0, which improves codegen.
1959   SDValue DominantValue;
1960   unsigned MostCommonCount = 0;
1961   DenseMap<SDValue, unsigned> ValueCounts;
1962   unsigned NumUndefElts =
1963       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1964 
1965   // Track the number of scalar loads we know we'd be inserting, estimated as
1966   // any non-zero floating-point constant. Other kinds of element are either
1967   // already in registers or are materialized on demand. The threshold at which
1968   // a vector load is more desirable than several scalar materializion and
1969   // vector-insertion instructions is not known.
1970   unsigned NumScalarLoads = 0;
1971 
1972   for (SDValue V : Op->op_values()) {
1973     if (V.isUndef())
1974       continue;
1975 
1976     ValueCounts.insert(std::make_pair(V, 0));
1977     unsigned &Count = ValueCounts[V];
1978 
1979     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
1980       NumScalarLoads += !CFP->isExactlyValue(+0.0);
1981 
1982     // Is this value dominant? In case of a tie, prefer the highest element as
1983     // it's cheaper to insert near the beginning of a vector than it is at the
1984     // end.
1985     if (++Count >= MostCommonCount) {
1986       DominantValue = V;
1987       MostCommonCount = Count;
1988     }
1989   }
1990 
1991   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1992   unsigned NumDefElts = NumElts - NumUndefElts;
1993   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1994 
1995   // Don't perform this optimization when optimizing for size, since
1996   // materializing elements and inserting them tends to cause code bloat.
1997   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
1998       ((MostCommonCount > DominantValueCountThreshold) ||
1999        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2000     // Start by splatting the most common element.
2001     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2002 
2003     DenseSet<SDValue> Processed{DominantValue};
2004     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2005     for (const auto &OpIdx : enumerate(Op->ops())) {
2006       const SDValue &V = OpIdx.value();
2007       if (V.isUndef() || !Processed.insert(V).second)
2008         continue;
2009       if (ValueCounts[V] == 1) {
2010         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2011                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2012       } else {
2013         // Blend in all instances of this value using a VSELECT, using a
2014         // mask where each bit signals whether that element is the one
2015         // we're after.
2016         SmallVector<SDValue> Ops;
2017         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2018           return DAG.getConstant(V == V1, DL, XLenVT);
2019         });
2020         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2021                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2022                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2023       }
2024     }
2025 
2026     return Vec;
2027   }
2028 
2029   return SDValue();
2030 }
2031 
2032 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2033                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2034   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2035     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2036     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2037     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2038     // node in order to try and match RVV vector/scalar instructions.
2039     if ((LoC >> 31) == HiC)
2040       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2041   }
2042 
2043   // Fall back to a stack store and stride x0 vector load.
2044   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2045 }
2046 
2047 // Called by type legalization to handle splat of i64 on RV32.
2048 // FIXME: We can optimize this when the type has sign or zero bits in one
2049 // of the halves.
2050 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2051                                    SDValue VL, SelectionDAG &DAG) {
2052   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2053   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2054                            DAG.getConstant(0, DL, MVT::i32));
2055   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2056                            DAG.getConstant(1, DL, MVT::i32));
2057   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2058 }
2059 
2060 // This function lowers a splat of a scalar operand Splat with the vector
2061 // length VL. It ensures the final sequence is type legal, which is useful when
2062 // lowering a splat after type legalization.
2063 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2064                                 SelectionDAG &DAG,
2065                                 const RISCVSubtarget &Subtarget) {
2066   if (VT.isFloatingPoint())
2067     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2068 
2069   MVT XLenVT = Subtarget.getXLenVT();
2070 
2071   // Simplest case is that the operand needs to be promoted to XLenVT.
2072   if (Scalar.getValueType().bitsLE(XLenVT)) {
2073     // If the operand is a constant, sign extend to increase our chances
2074     // of being able to use a .vi instruction. ANY_EXTEND would become a
2075     // a zero extend and the simm5 check in isel would fail.
2076     // FIXME: Should we ignore the upper bits in isel instead?
2077     unsigned ExtOpc =
2078         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2079     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2080     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2081   }
2082 
2083   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2084          "Unexpected scalar for splat lowering!");
2085 
2086   // Otherwise use the more complicated splatting algorithm.
2087   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2088 }
2089 
2090 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2091                                    const RISCVSubtarget &Subtarget) {
2092   SDValue V1 = Op.getOperand(0);
2093   SDValue V2 = Op.getOperand(1);
2094   SDLoc DL(Op);
2095   MVT XLenVT = Subtarget.getXLenVT();
2096   MVT VT = Op.getSimpleValueType();
2097   unsigned NumElts = VT.getVectorNumElements();
2098   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2099 
2100   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2101 
2102   SDValue TrueMask, VL;
2103   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2104 
2105   if (SVN->isSplat()) {
2106     const int Lane = SVN->getSplatIndex();
2107     if (Lane >= 0) {
2108       MVT SVT = VT.getVectorElementType();
2109 
2110       // Turn splatted vector load into a strided load with an X0 stride.
2111       SDValue V = V1;
2112       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2113       // with undef.
2114       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2115       int Offset = Lane;
2116       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2117         int OpElements =
2118             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2119         V = V.getOperand(Offset / OpElements);
2120         Offset %= OpElements;
2121       }
2122 
2123       // We need to ensure the load isn't atomic or volatile.
2124       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2125         auto *Ld = cast<LoadSDNode>(V);
2126         Offset *= SVT.getStoreSize();
2127         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2128                                                    TypeSize::Fixed(Offset), DL);
2129 
2130         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2131         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2132           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2133           SDValue IntID =
2134               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2135           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2136                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2137           SDValue NewLoad = DAG.getMemIntrinsicNode(
2138               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2139               DAG.getMachineFunction().getMachineMemOperand(
2140                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2141           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2142           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2143         }
2144 
2145         // Otherwise use a scalar load and splat. This will give the best
2146         // opportunity to fold a splat into the operation. ISel can turn it into
2147         // the x0 strided load if we aren't able to fold away the select.
2148         if (SVT.isFloatingPoint())
2149           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2150                           Ld->getPointerInfo().getWithOffset(Offset),
2151                           Ld->getOriginalAlign(),
2152                           Ld->getMemOperand()->getFlags());
2153         else
2154           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2155                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2156                              Ld->getOriginalAlign(),
2157                              Ld->getMemOperand()->getFlags());
2158         DAG.makeEquivalentMemoryOrdering(Ld, V);
2159 
2160         unsigned Opc =
2161             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2162         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2163         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2164       }
2165 
2166       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2167       assert(Lane < (int)NumElts && "Unexpected lane!");
2168       SDValue Gather =
2169           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2170                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2171       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2172     }
2173   }
2174 
2175   // Detect shuffles which can be re-expressed as vector selects; these are
2176   // shuffles in which each element in the destination is taken from an element
2177   // at the corresponding index in either source vectors.
2178   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2179     int MaskIndex = MaskIdx.value();
2180     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2181   });
2182 
2183   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2184 
2185   SmallVector<SDValue> MaskVals;
2186   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2187   // merged with a second vrgather.
2188   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2189 
2190   // By default we preserve the original operand order, and use a mask to
2191   // select LHS as true and RHS as false. However, since RVV vector selects may
2192   // feature splats but only on the LHS, we may choose to invert our mask and
2193   // instead select between RHS and LHS.
2194   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2195   bool InvertMask = IsSelect == SwapOps;
2196 
2197   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2198   // half.
2199   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2200 
2201   // Now construct the mask that will be used by the vselect or blended
2202   // vrgather operation. For vrgathers, construct the appropriate indices into
2203   // each vector.
2204   for (int MaskIndex : SVN->getMask()) {
2205     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2206     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2207     if (!IsSelect) {
2208       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2209       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2210                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2211                                      : DAG.getUNDEF(XLenVT));
2212       GatherIndicesRHS.push_back(
2213           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2214                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2215       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2216         ++LHSIndexCounts[MaskIndex];
2217       if (!IsLHSOrUndefIndex)
2218         ++RHSIndexCounts[MaskIndex - NumElts];
2219     }
2220   }
2221 
2222   if (SwapOps) {
2223     std::swap(V1, V2);
2224     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2225   }
2226 
2227   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2228   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2229   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2230 
2231   if (IsSelect)
2232     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2233 
2234   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2235     // On such a large vector we're unable to use i8 as the index type.
2236     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2237     // may involve vector splitting if we're already at LMUL=8, or our
2238     // user-supplied maximum fixed-length LMUL.
2239     return SDValue();
2240   }
2241 
2242   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2243   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2244   MVT IndexVT = VT.changeTypeToInteger();
2245   // Since we can't introduce illegal index types at this stage, use i16 and
2246   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2247   // than XLenVT.
2248   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2249     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2250     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2251   }
2252 
2253   MVT IndexContainerVT =
2254       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2255 
2256   SDValue Gather;
2257   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2258   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2259   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2260     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2261   } else {
2262     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2263     // If only one index is used, we can use a "splat" vrgather.
2264     // TODO: We can splat the most-common index and fix-up any stragglers, if
2265     // that's beneficial.
2266     if (LHSIndexCounts.size() == 1) {
2267       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2268       Gather =
2269           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2270                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2271     } else {
2272       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2273       LHSIndices =
2274           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2275 
2276       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2277                            TrueMask, VL);
2278     }
2279   }
2280 
2281   // If a second vector operand is used by this shuffle, blend it in with an
2282   // additional vrgather.
2283   if (!V2.isUndef()) {
2284     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2285     // If only one index is used, we can use a "splat" vrgather.
2286     // TODO: We can splat the most-common index and fix-up any stragglers, if
2287     // that's beneficial.
2288     if (RHSIndexCounts.size() == 1) {
2289       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2290       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2291                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2292     } else {
2293       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2294       RHSIndices =
2295           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2296       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2297                        VL);
2298     }
2299 
2300     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2301     SelectMask =
2302         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2303 
2304     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2305                          Gather, VL);
2306   }
2307 
2308   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2309 }
2310 
2311 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2312                                      SDLoc DL, SelectionDAG &DAG,
2313                                      const RISCVSubtarget &Subtarget) {
2314   if (VT.isScalableVector())
2315     return DAG.getFPExtendOrRound(Op, DL, VT);
2316   assert(VT.isFixedLengthVector() &&
2317          "Unexpected value type for RVV FP extend/round lowering");
2318   SDValue Mask, VL;
2319   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2320   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2321                         ? RISCVISD::FP_EXTEND_VL
2322                         : RISCVISD::FP_ROUND_VL;
2323   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2324 }
2325 
2326 // While RVV has alignment restrictions, we should always be able to load as a
2327 // legal equivalently-sized byte-typed vector instead. This method is
2328 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2329 // the load is already correctly-aligned, it returns SDValue().
2330 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2331                                                     SelectionDAG &DAG) const {
2332   auto *Load = cast<LoadSDNode>(Op);
2333   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2334 
2335   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2336                                      Load->getMemoryVT(),
2337                                      *Load->getMemOperand()))
2338     return SDValue();
2339 
2340   SDLoc DL(Op);
2341   MVT VT = Op.getSimpleValueType();
2342   unsigned EltSizeBits = VT.getScalarSizeInBits();
2343   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2344          "Unexpected unaligned RVV load type");
2345   MVT NewVT =
2346       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2347   assert(NewVT.isValid() &&
2348          "Expecting equally-sized RVV vector types to be legal");
2349   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2350                           Load->getPointerInfo(), Load->getOriginalAlign(),
2351                           Load->getMemOperand()->getFlags());
2352   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2353 }
2354 
2355 // While RVV has alignment restrictions, we should always be able to store as a
2356 // legal equivalently-sized byte-typed vector instead. This method is
2357 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2358 // returns SDValue() if the store is already correctly aligned.
2359 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2360                                                      SelectionDAG &DAG) const {
2361   auto *Store = cast<StoreSDNode>(Op);
2362   assert(Store && Store->getValue().getValueType().isVector() &&
2363          "Expected vector store");
2364 
2365   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2366                                      Store->getMemoryVT(),
2367                                      *Store->getMemOperand()))
2368     return SDValue();
2369 
2370   SDLoc DL(Op);
2371   SDValue StoredVal = Store->getValue();
2372   MVT VT = StoredVal.getSimpleValueType();
2373   unsigned EltSizeBits = VT.getScalarSizeInBits();
2374   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2375          "Unexpected unaligned RVV store type");
2376   MVT NewVT =
2377       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2378   assert(NewVT.isValid() &&
2379          "Expecting equally-sized RVV vector types to be legal");
2380   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2381   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2382                       Store->getPointerInfo(), Store->getOriginalAlign(),
2383                       Store->getMemOperand()->getFlags());
2384 }
2385 
2386 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2387                                             SelectionDAG &DAG) const {
2388   switch (Op.getOpcode()) {
2389   default:
2390     report_fatal_error("unimplemented operand");
2391   case ISD::GlobalAddress:
2392     return lowerGlobalAddress(Op, DAG);
2393   case ISD::BlockAddress:
2394     return lowerBlockAddress(Op, DAG);
2395   case ISD::ConstantPool:
2396     return lowerConstantPool(Op, DAG);
2397   case ISD::JumpTable:
2398     return lowerJumpTable(Op, DAG);
2399   case ISD::GlobalTLSAddress:
2400     return lowerGlobalTLSAddress(Op, DAG);
2401   case ISD::SELECT:
2402     return lowerSELECT(Op, DAG);
2403   case ISD::BRCOND:
2404     return lowerBRCOND(Op, DAG);
2405   case ISD::VASTART:
2406     return lowerVASTART(Op, DAG);
2407   case ISD::FRAMEADDR:
2408     return lowerFRAMEADDR(Op, DAG);
2409   case ISD::RETURNADDR:
2410     return lowerRETURNADDR(Op, DAG);
2411   case ISD::SHL_PARTS:
2412     return lowerShiftLeftParts(Op, DAG);
2413   case ISD::SRA_PARTS:
2414     return lowerShiftRightParts(Op, DAG, true);
2415   case ISD::SRL_PARTS:
2416     return lowerShiftRightParts(Op, DAG, false);
2417   case ISD::BITCAST: {
2418     SDLoc DL(Op);
2419     EVT VT = Op.getValueType();
2420     SDValue Op0 = Op.getOperand(0);
2421     EVT Op0VT = Op0.getValueType();
2422     MVT XLenVT = Subtarget.getXLenVT();
2423     if (VT.isFixedLengthVector()) {
2424       // We can handle fixed length vector bitcasts with a simple replacement
2425       // in isel.
2426       if (Op0VT.isFixedLengthVector())
2427         return Op;
2428       // When bitcasting from scalar to fixed-length vector, insert the scalar
2429       // into a one-element vector of the result type, and perform a vector
2430       // bitcast.
2431       if (!Op0VT.isVector()) {
2432         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2433         if (!isTypeLegal(BVT))
2434           return SDValue();
2435         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2436                                               DAG.getUNDEF(BVT), Op0,
2437                                               DAG.getConstant(0, DL, XLenVT)));
2438       }
2439       return SDValue();
2440     }
2441     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2442     // thus: bitcast the vector to a one-element vector type whose element type
2443     // is the same as the result type, and extract the first element.
2444     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2445       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2446       if (!isTypeLegal(BVT))
2447         return SDValue();
2448       SDValue BVec = DAG.getBitcast(BVT, Op0);
2449       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2450                          DAG.getConstant(0, DL, XLenVT));
2451     }
2452     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2453       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2454       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2455       return FPConv;
2456     }
2457     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2458         Subtarget.hasStdExtF()) {
2459       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2460       SDValue FPConv =
2461           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2462       return FPConv;
2463     }
2464     return SDValue();
2465   }
2466   case ISD::INTRINSIC_WO_CHAIN:
2467     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2468   case ISD::INTRINSIC_W_CHAIN:
2469     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2470   case ISD::INTRINSIC_VOID:
2471     return LowerINTRINSIC_VOID(Op, DAG);
2472   case ISD::BSWAP:
2473   case ISD::BITREVERSE: {
2474     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2475     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2476     MVT VT = Op.getSimpleValueType();
2477     SDLoc DL(Op);
2478     // Start with the maximum immediate value which is the bitwidth - 1.
2479     unsigned Imm = VT.getSizeInBits() - 1;
2480     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2481     if (Op.getOpcode() == ISD::BSWAP)
2482       Imm &= ~0x7U;
2483     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2484                        DAG.getConstant(Imm, DL, VT));
2485   }
2486   case ISD::FSHL:
2487   case ISD::FSHR: {
2488     MVT VT = Op.getSimpleValueType();
2489     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2490     SDLoc DL(Op);
2491     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2492       return Op;
2493     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2494     // use log(XLen) bits. Mask the shift amount accordingly.
2495     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2496     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2497                                 DAG.getConstant(ShAmtWidth, DL, VT));
2498     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2499     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2500   }
2501   case ISD::TRUNCATE: {
2502     SDLoc DL(Op);
2503     MVT VT = Op.getSimpleValueType();
2504     // Only custom-lower vector truncates
2505     if (!VT.isVector())
2506       return Op;
2507 
2508     // Truncates to mask types are handled differently
2509     if (VT.getVectorElementType() == MVT::i1)
2510       return lowerVectorMaskTrunc(Op, DAG);
2511 
2512     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2513     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2514     // truncate by one power of two at a time.
2515     MVT DstEltVT = VT.getVectorElementType();
2516 
2517     SDValue Src = Op.getOperand(0);
2518     MVT SrcVT = Src.getSimpleValueType();
2519     MVT SrcEltVT = SrcVT.getVectorElementType();
2520 
2521     assert(DstEltVT.bitsLT(SrcEltVT) &&
2522            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2523            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2524            "Unexpected vector truncate lowering");
2525 
2526     MVT ContainerVT = SrcVT;
2527     if (SrcVT.isFixedLengthVector()) {
2528       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2529       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2530     }
2531 
2532     SDValue Result = Src;
2533     SDValue Mask, VL;
2534     std::tie(Mask, VL) =
2535         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2536     LLVMContext &Context = *DAG.getContext();
2537     const ElementCount Count = ContainerVT.getVectorElementCount();
2538     do {
2539       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2540       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2541       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2542                            Mask, VL);
2543     } while (SrcEltVT != DstEltVT);
2544 
2545     if (SrcVT.isFixedLengthVector())
2546       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2547 
2548     return Result;
2549   }
2550   case ISD::ANY_EXTEND:
2551   case ISD::ZERO_EXTEND:
2552     if (Op.getOperand(0).getValueType().isVector() &&
2553         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2554       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2555     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2556   case ISD::SIGN_EXTEND:
2557     if (Op.getOperand(0).getValueType().isVector() &&
2558         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2559       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2560     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2561   case ISD::SPLAT_VECTOR_PARTS:
2562     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2563   case ISD::INSERT_VECTOR_ELT:
2564     return lowerINSERT_VECTOR_ELT(Op, DAG);
2565   case ISD::EXTRACT_VECTOR_ELT:
2566     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2567   case ISD::VSCALE: {
2568     MVT VT = Op.getSimpleValueType();
2569     SDLoc DL(Op);
2570     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2571     // We define our scalable vector types for lmul=1 to use a 64 bit known
2572     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2573     // vscale as VLENB / 8.
2574     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2575     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2576       // We assume VLENB is a multiple of 8. We manually choose the best shift
2577       // here because SimplifyDemandedBits isn't always able to simplify it.
2578       uint64_t Val = Op.getConstantOperandVal(0);
2579       if (isPowerOf2_64(Val)) {
2580         uint64_t Log2 = Log2_64(Val);
2581         if (Log2 < 3)
2582           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2583                              DAG.getConstant(3 - Log2, DL, VT));
2584         if (Log2 > 3)
2585           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2586                              DAG.getConstant(Log2 - 3, DL, VT));
2587         return VLENB;
2588       }
2589       // If the multiplier is a multiple of 8, scale it down to avoid needing
2590       // to shift the VLENB value.
2591       if ((Val % 8) == 0)
2592         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2593                            DAG.getConstant(Val / 8, DL, VT));
2594     }
2595 
2596     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2597                                  DAG.getConstant(3, DL, VT));
2598     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2599   }
2600   case ISD::FP_EXTEND: {
2601     // RVV can only do fp_extend to types double the size as the source. We
2602     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2603     // via f32.
2604     SDLoc DL(Op);
2605     MVT VT = Op.getSimpleValueType();
2606     SDValue Src = Op.getOperand(0);
2607     MVT SrcVT = Src.getSimpleValueType();
2608 
2609     // Prepare any fixed-length vector operands.
2610     MVT ContainerVT = VT;
2611     if (SrcVT.isFixedLengthVector()) {
2612       ContainerVT = getContainerForFixedLengthVector(VT);
2613       MVT SrcContainerVT =
2614           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2615       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2616     }
2617 
2618     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2619         SrcVT.getVectorElementType() != MVT::f16) {
2620       // For scalable vectors, we only need to close the gap between
2621       // vXf16->vXf64.
2622       if (!VT.isFixedLengthVector())
2623         return Op;
2624       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2625       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2626       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2627     }
2628 
2629     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2630     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2631     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2632         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2633 
2634     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2635                                            DL, DAG, Subtarget);
2636     if (VT.isFixedLengthVector())
2637       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2638     return Extend;
2639   }
2640   case ISD::FP_ROUND: {
2641     // RVV can only do fp_round to types half the size as the source. We
2642     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2643     // conversion instruction.
2644     SDLoc DL(Op);
2645     MVT VT = Op.getSimpleValueType();
2646     SDValue Src = Op.getOperand(0);
2647     MVT SrcVT = Src.getSimpleValueType();
2648 
2649     // Prepare any fixed-length vector operands.
2650     MVT ContainerVT = VT;
2651     if (VT.isFixedLengthVector()) {
2652       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2653       ContainerVT =
2654           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2655       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2656     }
2657 
2658     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2659         SrcVT.getVectorElementType() != MVT::f64) {
2660       // For scalable vectors, we only need to close the gap between
2661       // vXf64<->vXf16.
2662       if (!VT.isFixedLengthVector())
2663         return Op;
2664       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2665       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2666       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2667     }
2668 
2669     SDValue Mask, VL;
2670     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2671 
2672     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2673     SDValue IntermediateRound =
2674         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2675     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2676                                           DL, DAG, Subtarget);
2677 
2678     if (VT.isFixedLengthVector())
2679       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2680     return Round;
2681   }
2682   case ISD::FP_TO_SINT:
2683   case ISD::FP_TO_UINT:
2684   case ISD::SINT_TO_FP:
2685   case ISD::UINT_TO_FP: {
2686     // RVV can only do fp<->int conversions to types half/double the size as
2687     // the source. We custom-lower any conversions that do two hops into
2688     // sequences.
2689     MVT VT = Op.getSimpleValueType();
2690     if (!VT.isVector())
2691       return Op;
2692     SDLoc DL(Op);
2693     SDValue Src = Op.getOperand(0);
2694     MVT EltVT = VT.getVectorElementType();
2695     MVT SrcVT = Src.getSimpleValueType();
2696     MVT SrcEltVT = SrcVT.getVectorElementType();
2697     unsigned EltSize = EltVT.getSizeInBits();
2698     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2699     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2700            "Unexpected vector element types");
2701 
2702     bool IsInt2FP = SrcEltVT.isInteger();
2703     // Widening conversions
2704     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2705       if (IsInt2FP) {
2706         // Do a regular integer sign/zero extension then convert to float.
2707         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2708                                       VT.getVectorElementCount());
2709         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2710                                  ? ISD::ZERO_EXTEND
2711                                  : ISD::SIGN_EXTEND;
2712         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2713         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2714       }
2715       // FP2Int
2716       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2717       // Do one doubling fp_extend then complete the operation by converting
2718       // to int.
2719       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2720       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2721       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2722     }
2723 
2724     // Narrowing conversions
2725     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2726       if (IsInt2FP) {
2727         // One narrowing int_to_fp, then an fp_round.
2728         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2729         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2730         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2731         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2732       }
2733       // FP2Int
2734       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2735       // representable by the integer, the result is poison.
2736       MVT IVecVT =
2737           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2738                            VT.getVectorElementCount());
2739       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2740       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2741     }
2742 
2743     // Scalable vectors can exit here. Patterns will handle equally-sized
2744     // conversions halving/doubling ones.
2745     if (!VT.isFixedLengthVector())
2746       return Op;
2747 
2748     // For fixed-length vectors we lower to a custom "VL" node.
2749     unsigned RVVOpc = 0;
2750     switch (Op.getOpcode()) {
2751     default:
2752       llvm_unreachable("Impossible opcode");
2753     case ISD::FP_TO_SINT:
2754       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2755       break;
2756     case ISD::FP_TO_UINT:
2757       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2758       break;
2759     case ISD::SINT_TO_FP:
2760       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2761       break;
2762     case ISD::UINT_TO_FP:
2763       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2764       break;
2765     }
2766 
2767     MVT ContainerVT, SrcContainerVT;
2768     // Derive the reference container type from the larger vector type.
2769     if (SrcEltSize > EltSize) {
2770       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2771       ContainerVT =
2772           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2773     } else {
2774       ContainerVT = getContainerForFixedLengthVector(VT);
2775       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2776     }
2777 
2778     SDValue Mask, VL;
2779     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2780 
2781     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2782     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2783     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2784   }
2785   case ISD::FP_TO_SINT_SAT:
2786   case ISD::FP_TO_UINT_SAT:
2787     return lowerFP_TO_INT_SAT(Op, DAG);
2788   case ISD::VECREDUCE_ADD:
2789   case ISD::VECREDUCE_UMAX:
2790   case ISD::VECREDUCE_SMAX:
2791   case ISD::VECREDUCE_UMIN:
2792   case ISD::VECREDUCE_SMIN:
2793     return lowerVECREDUCE(Op, DAG);
2794   case ISD::VECREDUCE_AND:
2795   case ISD::VECREDUCE_OR:
2796   case ISD::VECREDUCE_XOR:
2797     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2798       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
2799     return lowerVECREDUCE(Op, DAG);
2800   case ISD::VECREDUCE_FADD:
2801   case ISD::VECREDUCE_SEQ_FADD:
2802   case ISD::VECREDUCE_FMIN:
2803   case ISD::VECREDUCE_FMAX:
2804     return lowerFPVECREDUCE(Op, DAG);
2805   case ISD::VP_REDUCE_ADD:
2806   case ISD::VP_REDUCE_UMAX:
2807   case ISD::VP_REDUCE_SMAX:
2808   case ISD::VP_REDUCE_UMIN:
2809   case ISD::VP_REDUCE_SMIN:
2810   case ISD::VP_REDUCE_FADD:
2811   case ISD::VP_REDUCE_SEQ_FADD:
2812   case ISD::VP_REDUCE_FMIN:
2813   case ISD::VP_REDUCE_FMAX:
2814     return lowerVPREDUCE(Op, DAG);
2815   case ISD::VP_REDUCE_AND:
2816   case ISD::VP_REDUCE_OR:
2817   case ISD::VP_REDUCE_XOR:
2818     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
2819       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
2820     return lowerVPREDUCE(Op, DAG);
2821   case ISD::INSERT_SUBVECTOR:
2822     return lowerINSERT_SUBVECTOR(Op, DAG);
2823   case ISD::EXTRACT_SUBVECTOR:
2824     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2825   case ISD::STEP_VECTOR:
2826     return lowerSTEP_VECTOR(Op, DAG);
2827   case ISD::VECTOR_REVERSE:
2828     return lowerVECTOR_REVERSE(Op, DAG);
2829   case ISD::BUILD_VECTOR:
2830     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2831   case ISD::SPLAT_VECTOR:
2832     if (Op.getValueType().getVectorElementType() == MVT::i1)
2833       return lowerVectorMaskSplat(Op, DAG);
2834     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
2835   case ISD::VECTOR_SHUFFLE:
2836     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2837   case ISD::CONCAT_VECTORS: {
2838     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2839     // better than going through the stack, as the default expansion does.
2840     SDLoc DL(Op);
2841     MVT VT = Op.getSimpleValueType();
2842     unsigned NumOpElts =
2843         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2844     SDValue Vec = DAG.getUNDEF(VT);
2845     for (const auto &OpIdx : enumerate(Op->ops()))
2846       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2847                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2848     return Vec;
2849   }
2850   case ISD::LOAD:
2851     if (auto V = expandUnalignedRVVLoad(Op, DAG))
2852       return V;
2853     if (Op.getValueType().isFixedLengthVector())
2854       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2855     return Op;
2856   case ISD::STORE:
2857     if (auto V = expandUnalignedRVVStore(Op, DAG))
2858       return V;
2859     if (Op.getOperand(1).getValueType().isFixedLengthVector())
2860       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2861     return Op;
2862   case ISD::MLOAD:
2863   case ISD::VP_LOAD:
2864     return lowerMaskedLoad(Op, DAG);
2865   case ISD::MSTORE:
2866   case ISD::VP_STORE:
2867     return lowerMaskedStore(Op, DAG);
2868   case ISD::SETCC:
2869     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2870   case ISD::ADD:
2871     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2872   case ISD::SUB:
2873     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2874   case ISD::MUL:
2875     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2876   case ISD::MULHS:
2877     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2878   case ISD::MULHU:
2879     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2880   case ISD::AND:
2881     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2882                                               RISCVISD::AND_VL);
2883   case ISD::OR:
2884     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2885                                               RISCVISD::OR_VL);
2886   case ISD::XOR:
2887     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2888                                               RISCVISD::XOR_VL);
2889   case ISD::SDIV:
2890     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2891   case ISD::SREM:
2892     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2893   case ISD::UDIV:
2894     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2895   case ISD::UREM:
2896     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2897   case ISD::SHL:
2898   case ISD::SRA:
2899   case ISD::SRL:
2900     if (Op.getSimpleValueType().isFixedLengthVector())
2901       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
2902     // This can be called for an i32 shift amount that needs to be promoted.
2903     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
2904            "Unexpected custom legalisation");
2905     return SDValue();
2906   case ISD::SADDSAT:
2907     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
2908   case ISD::UADDSAT:
2909     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
2910   case ISD::SSUBSAT:
2911     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
2912   case ISD::USUBSAT:
2913     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
2914   case ISD::FADD:
2915     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2916   case ISD::FSUB:
2917     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2918   case ISD::FMUL:
2919     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2920   case ISD::FDIV:
2921     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2922   case ISD::FNEG:
2923     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2924   case ISD::FABS:
2925     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2926   case ISD::FSQRT:
2927     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2928   case ISD::FMA:
2929     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2930   case ISD::SMIN:
2931     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2932   case ISD::SMAX:
2933     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2934   case ISD::UMIN:
2935     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2936   case ISD::UMAX:
2937     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2938   case ISD::FMINNUM:
2939     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
2940   case ISD::FMAXNUM:
2941     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
2942   case ISD::ABS:
2943     return lowerABS(Op, DAG);
2944   case ISD::VSELECT:
2945     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2946   case ISD::FCOPYSIGN:
2947     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2948   case ISD::MGATHER:
2949   case ISD::VP_GATHER:
2950     return lowerMaskedGather(Op, DAG);
2951   case ISD::MSCATTER:
2952   case ISD::VP_SCATTER:
2953     return lowerMaskedScatter(Op, DAG);
2954   case ISD::FLT_ROUNDS_:
2955     return lowerGET_ROUNDING(Op, DAG);
2956   case ISD::SET_ROUNDING:
2957     return lowerSET_ROUNDING(Op, DAG);
2958   case ISD::VP_ADD:
2959     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
2960   case ISD::VP_SUB:
2961     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
2962   case ISD::VP_MUL:
2963     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
2964   case ISD::VP_SDIV:
2965     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
2966   case ISD::VP_UDIV:
2967     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
2968   case ISD::VP_SREM:
2969     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
2970   case ISD::VP_UREM:
2971     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
2972   case ISD::VP_AND:
2973     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
2974   case ISD::VP_OR:
2975     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
2976   case ISD::VP_XOR:
2977     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
2978   case ISD::VP_ASHR:
2979     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
2980   case ISD::VP_LSHR:
2981     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
2982   case ISD::VP_SHL:
2983     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
2984   case ISD::VP_FADD:
2985     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
2986   case ISD::VP_FSUB:
2987     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
2988   case ISD::VP_FMUL:
2989     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
2990   case ISD::VP_FDIV:
2991     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
2992   }
2993 }
2994 
2995 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2996                              SelectionDAG &DAG, unsigned Flags) {
2997   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2998 }
2999 
3000 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3001                              SelectionDAG &DAG, unsigned Flags) {
3002   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3003                                    Flags);
3004 }
3005 
3006 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3007                              SelectionDAG &DAG, unsigned Flags) {
3008   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3009                                    N->getOffset(), Flags);
3010 }
3011 
3012 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3013                              SelectionDAG &DAG, unsigned Flags) {
3014   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3015 }
3016 
3017 template <class NodeTy>
3018 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3019                                      bool IsLocal) const {
3020   SDLoc DL(N);
3021   EVT Ty = getPointerTy(DAG.getDataLayout());
3022 
3023   if (isPositionIndependent()) {
3024     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3025     if (IsLocal)
3026       // Use PC-relative addressing to access the symbol. This generates the
3027       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3028       // %pcrel_lo(auipc)).
3029       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3030 
3031     // Use PC-relative addressing to access the GOT for this symbol, then load
3032     // the address from the GOT. This generates the pattern (PseudoLA sym),
3033     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3034     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3035   }
3036 
3037   switch (getTargetMachine().getCodeModel()) {
3038   default:
3039     report_fatal_error("Unsupported code model for lowering");
3040   case CodeModel::Small: {
3041     // Generate a sequence for accessing addresses within the first 2 GiB of
3042     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3043     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3044     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3045     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3046     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3047   }
3048   case CodeModel::Medium: {
3049     // Generate a sequence for accessing addresses within any 2GiB range within
3050     // the address space. This generates the pattern (PseudoLLA sym), which
3051     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3052     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3053     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3054   }
3055   }
3056 }
3057 
3058 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3059                                                 SelectionDAG &DAG) const {
3060   SDLoc DL(Op);
3061   EVT Ty = Op.getValueType();
3062   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3063   int64_t Offset = N->getOffset();
3064   MVT XLenVT = Subtarget.getXLenVT();
3065 
3066   const GlobalValue *GV = N->getGlobal();
3067   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3068   SDValue Addr = getAddr(N, DAG, IsLocal);
3069 
3070   // In order to maximise the opportunity for common subexpression elimination,
3071   // emit a separate ADD node for the global address offset instead of folding
3072   // it in the global address node. Later peephole optimisations may choose to
3073   // fold it back in when profitable.
3074   if (Offset != 0)
3075     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3076                        DAG.getConstant(Offset, DL, XLenVT));
3077   return Addr;
3078 }
3079 
3080 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3081                                                SelectionDAG &DAG) const {
3082   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3083 
3084   return getAddr(N, DAG);
3085 }
3086 
3087 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3088                                                SelectionDAG &DAG) const {
3089   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3090 
3091   return getAddr(N, DAG);
3092 }
3093 
3094 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3095                                             SelectionDAG &DAG) const {
3096   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3097 
3098   return getAddr(N, DAG);
3099 }
3100 
3101 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3102                                               SelectionDAG &DAG,
3103                                               bool UseGOT) const {
3104   SDLoc DL(N);
3105   EVT Ty = getPointerTy(DAG.getDataLayout());
3106   const GlobalValue *GV = N->getGlobal();
3107   MVT XLenVT = Subtarget.getXLenVT();
3108 
3109   if (UseGOT) {
3110     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3111     // load the address from the GOT and add the thread pointer. This generates
3112     // the pattern (PseudoLA_TLS_IE sym), which expands to
3113     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3114     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3115     SDValue Load =
3116         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3117 
3118     // Add the thread pointer.
3119     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3120     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3121   }
3122 
3123   // Generate a sequence for accessing the address relative to the thread
3124   // pointer, with the appropriate adjustment for the thread pointer offset.
3125   // This generates the pattern
3126   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3127   SDValue AddrHi =
3128       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3129   SDValue AddrAdd =
3130       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3131   SDValue AddrLo =
3132       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3133 
3134   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3135   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3136   SDValue MNAdd = SDValue(
3137       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3138       0);
3139   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3140 }
3141 
3142 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3143                                                SelectionDAG &DAG) const {
3144   SDLoc DL(N);
3145   EVT Ty = getPointerTy(DAG.getDataLayout());
3146   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3147   const GlobalValue *GV = N->getGlobal();
3148 
3149   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3150   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3151   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3152   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3153   SDValue Load =
3154       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3155 
3156   // Prepare argument list to generate call.
3157   ArgListTy Args;
3158   ArgListEntry Entry;
3159   Entry.Node = Load;
3160   Entry.Ty = CallTy;
3161   Args.push_back(Entry);
3162 
3163   // Setup call to __tls_get_addr.
3164   TargetLowering::CallLoweringInfo CLI(DAG);
3165   CLI.setDebugLoc(DL)
3166       .setChain(DAG.getEntryNode())
3167       .setLibCallee(CallingConv::C, CallTy,
3168                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3169                     std::move(Args));
3170 
3171   return LowerCallTo(CLI).first;
3172 }
3173 
3174 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3175                                                    SelectionDAG &DAG) const {
3176   SDLoc DL(Op);
3177   EVT Ty = Op.getValueType();
3178   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3179   int64_t Offset = N->getOffset();
3180   MVT XLenVT = Subtarget.getXLenVT();
3181 
3182   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3183 
3184   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3185       CallingConv::GHC)
3186     report_fatal_error("In GHC calling convention TLS is not supported");
3187 
3188   SDValue Addr;
3189   switch (Model) {
3190   case TLSModel::LocalExec:
3191     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3192     break;
3193   case TLSModel::InitialExec:
3194     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3195     break;
3196   case TLSModel::LocalDynamic:
3197   case TLSModel::GeneralDynamic:
3198     Addr = getDynamicTLSAddr(N, DAG);
3199     break;
3200   }
3201 
3202   // In order to maximise the opportunity for common subexpression elimination,
3203   // emit a separate ADD node for the global address offset instead of folding
3204   // it in the global address node. Later peephole optimisations may choose to
3205   // fold it back in when profitable.
3206   if (Offset != 0)
3207     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3208                        DAG.getConstant(Offset, DL, XLenVT));
3209   return Addr;
3210 }
3211 
3212 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3213   SDValue CondV = Op.getOperand(0);
3214   SDValue TrueV = Op.getOperand(1);
3215   SDValue FalseV = Op.getOperand(2);
3216   SDLoc DL(Op);
3217   MVT VT = Op.getSimpleValueType();
3218   MVT XLenVT = Subtarget.getXLenVT();
3219 
3220   // Lower vector SELECTs to VSELECTs by splatting the condition.
3221   if (VT.isVector()) {
3222     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3223     SDValue CondSplat = VT.isScalableVector()
3224                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3225                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3226     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3227   }
3228 
3229   // If the result type is XLenVT and CondV is the output of a SETCC node
3230   // which also operated on XLenVT inputs, then merge the SETCC node into the
3231   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3232   // compare+branch instructions. i.e.:
3233   // (select (setcc lhs, rhs, cc), truev, falsev)
3234   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3235   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3236       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3237     SDValue LHS = CondV.getOperand(0);
3238     SDValue RHS = CondV.getOperand(1);
3239     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3240     ISD::CondCode CCVal = CC->get();
3241 
3242     // Special case for a select of 2 constants that have a diffence of 1.
3243     // Normally this is done by DAGCombine, but if the select is introduced by
3244     // type legalization or op legalization, we miss it. Restricting to SETLT
3245     // case for now because that is what signed saturating add/sub need.
3246     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3247     // but we would probably want to swap the true/false values if the condition
3248     // is SETGE/SETLE to avoid an XORI.
3249     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3250         CCVal == ISD::SETLT) {
3251       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3252       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3253       if (TrueVal - 1 == FalseVal)
3254         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3255       if (TrueVal + 1 == FalseVal)
3256         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3257     }
3258 
3259     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3260 
3261     SDValue TargetCC = DAG.getCondCode(CCVal);
3262     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3263     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3264   }
3265 
3266   // Otherwise:
3267   // (select condv, truev, falsev)
3268   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3269   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3270   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3271 
3272   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3273 
3274   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3275 }
3276 
3277 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3278   SDValue CondV = Op.getOperand(1);
3279   SDLoc DL(Op);
3280   MVT XLenVT = Subtarget.getXLenVT();
3281 
3282   if (CondV.getOpcode() == ISD::SETCC &&
3283       CondV.getOperand(0).getValueType() == XLenVT) {
3284     SDValue LHS = CondV.getOperand(0);
3285     SDValue RHS = CondV.getOperand(1);
3286     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3287 
3288     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3289 
3290     SDValue TargetCC = DAG.getCondCode(CCVal);
3291     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3292                        LHS, RHS, TargetCC, Op.getOperand(2));
3293   }
3294 
3295   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3296                      CondV, DAG.getConstant(0, DL, XLenVT),
3297                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3298 }
3299 
3300 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3301   MachineFunction &MF = DAG.getMachineFunction();
3302   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3303 
3304   SDLoc DL(Op);
3305   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3306                                  getPointerTy(MF.getDataLayout()));
3307 
3308   // vastart just stores the address of the VarArgsFrameIndex slot into the
3309   // memory location argument.
3310   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3311   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3312                       MachinePointerInfo(SV));
3313 }
3314 
3315 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3316                                             SelectionDAG &DAG) const {
3317   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3318   MachineFunction &MF = DAG.getMachineFunction();
3319   MachineFrameInfo &MFI = MF.getFrameInfo();
3320   MFI.setFrameAddressIsTaken(true);
3321   Register FrameReg = RI.getFrameRegister(MF);
3322   int XLenInBytes = Subtarget.getXLen() / 8;
3323 
3324   EVT VT = Op.getValueType();
3325   SDLoc DL(Op);
3326   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3327   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3328   while (Depth--) {
3329     int Offset = -(XLenInBytes * 2);
3330     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3331                               DAG.getIntPtrConstant(Offset, DL));
3332     FrameAddr =
3333         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3334   }
3335   return FrameAddr;
3336 }
3337 
3338 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3339                                              SelectionDAG &DAG) const {
3340   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3341   MachineFunction &MF = DAG.getMachineFunction();
3342   MachineFrameInfo &MFI = MF.getFrameInfo();
3343   MFI.setReturnAddressIsTaken(true);
3344   MVT XLenVT = Subtarget.getXLenVT();
3345   int XLenInBytes = Subtarget.getXLen() / 8;
3346 
3347   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3348     return SDValue();
3349 
3350   EVT VT = Op.getValueType();
3351   SDLoc DL(Op);
3352   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3353   if (Depth) {
3354     int Off = -XLenInBytes;
3355     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3356     SDValue Offset = DAG.getConstant(Off, DL, VT);
3357     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3358                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3359                        MachinePointerInfo());
3360   }
3361 
3362   // Return the value of the return address register, marking it an implicit
3363   // live-in.
3364   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3365   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3366 }
3367 
3368 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3369                                                  SelectionDAG &DAG) const {
3370   SDLoc DL(Op);
3371   SDValue Lo = Op.getOperand(0);
3372   SDValue Hi = Op.getOperand(1);
3373   SDValue Shamt = Op.getOperand(2);
3374   EVT VT = Lo.getValueType();
3375 
3376   // if Shamt-XLEN < 0: // Shamt < XLEN
3377   //   Lo = Lo << Shamt
3378   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3379   // else:
3380   //   Lo = 0
3381   //   Hi = Lo << (Shamt-XLEN)
3382 
3383   SDValue Zero = DAG.getConstant(0, DL, VT);
3384   SDValue One = DAG.getConstant(1, DL, VT);
3385   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3386   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3387   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3388   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3389 
3390   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3391   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3392   SDValue ShiftRightLo =
3393       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3394   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3395   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3396   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3397 
3398   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3399 
3400   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3401   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3402 
3403   SDValue Parts[2] = {Lo, Hi};
3404   return DAG.getMergeValues(Parts, DL);
3405 }
3406 
3407 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3408                                                   bool IsSRA) const {
3409   SDLoc DL(Op);
3410   SDValue Lo = Op.getOperand(0);
3411   SDValue Hi = Op.getOperand(1);
3412   SDValue Shamt = Op.getOperand(2);
3413   EVT VT = Lo.getValueType();
3414 
3415   // SRA expansion:
3416   //   if Shamt-XLEN < 0: // Shamt < XLEN
3417   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3418   //     Hi = Hi >>s Shamt
3419   //   else:
3420   //     Lo = Hi >>s (Shamt-XLEN);
3421   //     Hi = Hi >>s (XLEN-1)
3422   //
3423   // SRL expansion:
3424   //   if Shamt-XLEN < 0: // Shamt < XLEN
3425   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3426   //     Hi = Hi >>u Shamt
3427   //   else:
3428   //     Lo = Hi >>u (Shamt-XLEN);
3429   //     Hi = 0;
3430 
3431   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3432 
3433   SDValue Zero = DAG.getConstant(0, DL, VT);
3434   SDValue One = DAG.getConstant(1, DL, VT);
3435   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3436   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3437   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3438   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3439 
3440   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3441   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3442   SDValue ShiftLeftHi =
3443       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3444   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3445   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3446   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3447   SDValue HiFalse =
3448       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3449 
3450   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3451 
3452   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3453   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3454 
3455   SDValue Parts[2] = {Lo, Hi};
3456   return DAG.getMergeValues(Parts, DL);
3457 }
3458 
3459 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3460 // legal equivalently-sized i8 type, so we can use that as a go-between.
3461 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3462                                                   SelectionDAG &DAG) const {
3463   SDLoc DL(Op);
3464   MVT VT = Op.getSimpleValueType();
3465   SDValue SplatVal = Op.getOperand(0);
3466   // All-zeros or all-ones splats are handled specially.
3467   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3468     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3469     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3470   }
3471   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3472     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3473     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3474   }
3475   MVT XLenVT = Subtarget.getXLenVT();
3476   assert(SplatVal.getValueType() == XLenVT &&
3477          "Unexpected type for i1 splat value");
3478   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3479   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3480                          DAG.getConstant(1, DL, XLenVT));
3481   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3482   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3483   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3484 }
3485 
3486 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3487 // illegal (currently only vXi64 RV32).
3488 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3489 // them to SPLAT_VECTOR_I64
3490 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3491                                                      SelectionDAG &DAG) const {
3492   SDLoc DL(Op);
3493   MVT VecVT = Op.getSimpleValueType();
3494   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3495          "Unexpected SPLAT_VECTOR_PARTS lowering");
3496 
3497   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3498   SDValue Lo = Op.getOperand(0);
3499   SDValue Hi = Op.getOperand(1);
3500 
3501   if (VecVT.isFixedLengthVector()) {
3502     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3503     SDLoc DL(Op);
3504     SDValue Mask, VL;
3505     std::tie(Mask, VL) =
3506         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3507 
3508     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3509     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3510   }
3511 
3512   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3513     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3514     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3515     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3516     // node in order to try and match RVV vector/scalar instructions.
3517     if ((LoC >> 31) == HiC)
3518       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3519   }
3520 
3521   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3522   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3523       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3524       Hi.getConstantOperandVal(1) == 31)
3525     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3526 
3527   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3528   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3529                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3530 }
3531 
3532 // Custom-lower extensions from mask vectors by using a vselect either with 1
3533 // for zero/any-extension or -1 for sign-extension:
3534 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3535 // Note that any-extension is lowered identically to zero-extension.
3536 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3537                                                 int64_t ExtTrueVal) const {
3538   SDLoc DL(Op);
3539   MVT VecVT = Op.getSimpleValueType();
3540   SDValue Src = Op.getOperand(0);
3541   // Only custom-lower extensions from mask types
3542   assert(Src.getValueType().isVector() &&
3543          Src.getValueType().getVectorElementType() == MVT::i1);
3544 
3545   MVT XLenVT = Subtarget.getXLenVT();
3546   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3547   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3548 
3549   if (VecVT.isScalableVector()) {
3550     // Be careful not to introduce illegal scalar types at this stage, and be
3551     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3552     // illegal and must be expanded. Since we know that the constants are
3553     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3554     bool IsRV32E64 =
3555         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3556 
3557     if (!IsRV32E64) {
3558       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3559       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3560     } else {
3561       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3562       SplatTrueVal =
3563           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3564     }
3565 
3566     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3567   }
3568 
3569   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3570   MVT I1ContainerVT =
3571       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3572 
3573   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3574 
3575   SDValue Mask, VL;
3576   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3577 
3578   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3579   SplatTrueVal =
3580       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3581   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3582                                SplatTrueVal, SplatZero, VL);
3583 
3584   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3585 }
3586 
3587 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3588     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3589   MVT ExtVT = Op.getSimpleValueType();
3590   // Only custom-lower extensions from fixed-length vector types.
3591   if (!ExtVT.isFixedLengthVector())
3592     return Op;
3593   MVT VT = Op.getOperand(0).getSimpleValueType();
3594   // Grab the canonical container type for the extended type. Infer the smaller
3595   // type from that to ensure the same number of vector elements, as we know
3596   // the LMUL will be sufficient to hold the smaller type.
3597   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3598   // Get the extended container type manually to ensure the same number of
3599   // vector elements between source and dest.
3600   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3601                                      ContainerExtVT.getVectorElementCount());
3602 
3603   SDValue Op1 =
3604       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3605 
3606   SDLoc DL(Op);
3607   SDValue Mask, VL;
3608   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3609 
3610   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3611 
3612   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3613 }
3614 
3615 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3616 // setcc operation:
3617 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3618 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3619                                                   SelectionDAG &DAG) const {
3620   SDLoc DL(Op);
3621   EVT MaskVT = Op.getValueType();
3622   // Only expect to custom-lower truncations to mask types
3623   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3624          "Unexpected type for vector mask lowering");
3625   SDValue Src = Op.getOperand(0);
3626   MVT VecVT = Src.getSimpleValueType();
3627 
3628   // If this is a fixed vector, we need to convert it to a scalable vector.
3629   MVT ContainerVT = VecVT;
3630   if (VecVT.isFixedLengthVector()) {
3631     ContainerVT = getContainerForFixedLengthVector(VecVT);
3632     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3633   }
3634 
3635   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3636   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3637 
3638   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3639   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3640 
3641   if (VecVT.isScalableVector()) {
3642     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3643     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3644   }
3645 
3646   SDValue Mask, VL;
3647   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3648 
3649   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3650   SDValue Trunc =
3651       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3652   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3653                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3654   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3655 }
3656 
3657 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3658 // first position of a vector, and that vector is slid up to the insert index.
3659 // By limiting the active vector length to index+1 and merging with the
3660 // original vector (with an undisturbed tail policy for elements >= VL), we
3661 // achieve the desired result of leaving all elements untouched except the one
3662 // at VL-1, which is replaced with the desired value.
3663 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3664                                                     SelectionDAG &DAG) const {
3665   SDLoc DL(Op);
3666   MVT VecVT = Op.getSimpleValueType();
3667   SDValue Vec = Op.getOperand(0);
3668   SDValue Val = Op.getOperand(1);
3669   SDValue Idx = Op.getOperand(2);
3670 
3671   if (VecVT.getVectorElementType() == MVT::i1) {
3672     // FIXME: For now we just promote to an i8 vector and insert into that,
3673     // but this is probably not optimal.
3674     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3675     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3676     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3677     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3678   }
3679 
3680   MVT ContainerVT = VecVT;
3681   // If the operand is a fixed-length vector, convert to a scalable one.
3682   if (VecVT.isFixedLengthVector()) {
3683     ContainerVT = getContainerForFixedLengthVector(VecVT);
3684     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3685   }
3686 
3687   MVT XLenVT = Subtarget.getXLenVT();
3688 
3689   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3690   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3691   // Even i64-element vectors on RV32 can be lowered without scalar
3692   // legalization if the most-significant 32 bits of the value are not affected
3693   // by the sign-extension of the lower 32 bits.
3694   // TODO: We could also catch sign extensions of a 32-bit value.
3695   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3696     const auto *CVal = cast<ConstantSDNode>(Val);
3697     if (isInt<32>(CVal->getSExtValue())) {
3698       IsLegalInsert = true;
3699       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3700     }
3701   }
3702 
3703   SDValue Mask, VL;
3704   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3705 
3706   SDValue ValInVec;
3707 
3708   if (IsLegalInsert) {
3709     unsigned Opc =
3710         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3711     if (isNullConstant(Idx)) {
3712       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3713       if (!VecVT.isFixedLengthVector())
3714         return Vec;
3715       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3716     }
3717     ValInVec =
3718         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3719   } else {
3720     // On RV32, i64-element vectors must be specially handled to place the
3721     // value at element 0, by using two vslide1up instructions in sequence on
3722     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3723     // this.
3724     SDValue One = DAG.getConstant(1, DL, XLenVT);
3725     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3726     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3727     MVT I32ContainerVT =
3728         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3729     SDValue I32Mask =
3730         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3731     // Limit the active VL to two.
3732     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3733     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3734     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3735     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3736                            InsertI64VL);
3737     // First slide in the hi value, then the lo in underneath it.
3738     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3739                            ValHi, I32Mask, InsertI64VL);
3740     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3741                            ValLo, I32Mask, InsertI64VL);
3742     // Bitcast back to the right container type.
3743     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3744   }
3745 
3746   // Now that the value is in a vector, slide it into position.
3747   SDValue InsertVL =
3748       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3749   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3750                                 ValInVec, Idx, Mask, InsertVL);
3751   if (!VecVT.isFixedLengthVector())
3752     return Slideup;
3753   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3754 }
3755 
3756 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3757 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3758 // types this is done using VMV_X_S to allow us to glean information about the
3759 // sign bits of the result.
3760 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3761                                                      SelectionDAG &DAG) const {
3762   SDLoc DL(Op);
3763   SDValue Idx = Op.getOperand(1);
3764   SDValue Vec = Op.getOperand(0);
3765   EVT EltVT = Op.getValueType();
3766   MVT VecVT = Vec.getSimpleValueType();
3767   MVT XLenVT = Subtarget.getXLenVT();
3768 
3769   if (VecVT.getVectorElementType() == MVT::i1) {
3770     // FIXME: For now we just promote to an i8 vector and extract from that,
3771     // but this is probably not optimal.
3772     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3773     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3774     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3775   }
3776 
3777   // If this is a fixed vector, we need to convert it to a scalable vector.
3778   MVT ContainerVT = VecVT;
3779   if (VecVT.isFixedLengthVector()) {
3780     ContainerVT = getContainerForFixedLengthVector(VecVT);
3781     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3782   }
3783 
3784   // If the index is 0, the vector is already in the right position.
3785   if (!isNullConstant(Idx)) {
3786     // Use a VL of 1 to avoid processing more elements than we need.
3787     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3788     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3789     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3790     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3791                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3792   }
3793 
3794   if (!EltVT.isInteger()) {
3795     // Floating-point extracts are handled in TableGen.
3796     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3797                        DAG.getConstant(0, DL, XLenVT));
3798   }
3799 
3800   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3801   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3802 }
3803 
3804 // Some RVV intrinsics may claim that they want an integer operand to be
3805 // promoted or expanded.
3806 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3807                                           const RISCVSubtarget &Subtarget) {
3808   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3809           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3810          "Unexpected opcode");
3811 
3812   if (!Subtarget.hasVInstructions())
3813     return SDValue();
3814 
3815   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3816   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3817   SDLoc DL(Op);
3818 
3819   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
3820       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3821   if (!II || !II->SplatOperand)
3822     return SDValue();
3823 
3824   unsigned SplatOp = II->SplatOperand + HasChain;
3825   assert(SplatOp < Op.getNumOperands());
3826 
3827   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
3828   SDValue &ScalarOp = Operands[SplatOp];
3829   MVT OpVT = ScalarOp.getSimpleValueType();
3830   MVT XLenVT = Subtarget.getXLenVT();
3831 
3832   // If this isn't a scalar, or its type is XLenVT we're done.
3833   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
3834     return SDValue();
3835 
3836   // Simplest case is that the operand needs to be promoted to XLenVT.
3837   if (OpVT.bitsLT(XLenVT)) {
3838     // If the operand is a constant, sign extend to increase our chances
3839     // of being able to use a .vi instruction. ANY_EXTEND would become a
3840     // a zero extend and the simm5 check in isel would fail.
3841     // FIXME: Should we ignore the upper bits in isel instead?
3842     unsigned ExtOpc =
3843         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
3844     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
3845     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3846   }
3847 
3848   // Use the previous operand to get the vXi64 VT. The result might be a mask
3849   // VT for compares. Using the previous operand assumes that the previous
3850   // operand will never have a smaller element size than a scalar operand and
3851   // that a widening operation never uses SEW=64.
3852   // NOTE: If this fails the below assert, we can probably just find the
3853   // element count from any operand or result and use it to construct the VT.
3854   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
3855   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
3856 
3857   // The more complex case is when the scalar is larger than XLenVT.
3858   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3859          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3860 
3861   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3862   // on the instruction to sign-extend since SEW>XLEN.
3863   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3864     if (isInt<32>(CVal->getSExtValue())) {
3865       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3866       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3867     }
3868   }
3869 
3870   // We need to convert the scalar to a splat vector.
3871   // FIXME: Can we implicitly truncate the scalar if it is known to
3872   // be sign extended?
3873   // VL should be the last operand.
3874   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3875   assert(VL.getValueType() == XLenVT);
3876   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3877   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3878 }
3879 
3880 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3881                                                      SelectionDAG &DAG) const {
3882   unsigned IntNo = Op.getConstantOperandVal(0);
3883   SDLoc DL(Op);
3884   MVT XLenVT = Subtarget.getXLenVT();
3885 
3886   switch (IntNo) {
3887   default:
3888     break; // Don't custom lower most intrinsics.
3889   case Intrinsic::thread_pointer: {
3890     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3891     return DAG.getRegister(RISCV::X4, PtrVT);
3892   }
3893   case Intrinsic::riscv_orc_b:
3894     // Lower to the GORCI encoding for orc.b.
3895     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3896                        DAG.getConstant(7, DL, XLenVT));
3897   case Intrinsic::riscv_grev:
3898   case Intrinsic::riscv_gorc: {
3899     unsigned Opc =
3900         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
3901     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3902   }
3903   case Intrinsic::riscv_shfl:
3904   case Intrinsic::riscv_unshfl: {
3905     unsigned Opc =
3906         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
3907     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3908   }
3909   case Intrinsic::riscv_bcompress:
3910   case Intrinsic::riscv_bdecompress: {
3911     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
3912                                                        : RISCVISD::BDECOMPRESS;
3913     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3914   }
3915   case Intrinsic::riscv_vmv_x_s:
3916     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3917     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3918                        Op.getOperand(1));
3919   case Intrinsic::riscv_vmv_v_x:
3920     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3921                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3922   case Intrinsic::riscv_vfmv_v_f:
3923     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3924                        Op.getOperand(1), Op.getOperand(2));
3925   case Intrinsic::riscv_vmv_s_x: {
3926     SDValue Scalar = Op.getOperand(2);
3927 
3928     if (Scalar.getValueType().bitsLE(XLenVT)) {
3929       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3930       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3931                          Op.getOperand(1), Scalar, Op.getOperand(3));
3932     }
3933 
3934     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3935 
3936     // This is an i64 value that lives in two scalar registers. We have to
3937     // insert this in a convoluted way. First we build vXi64 splat containing
3938     // the/ two values that we assemble using some bit math. Next we'll use
3939     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3940     // to merge element 0 from our splat into the source vector.
3941     // FIXME: This is probably not the best way to do this, but it is
3942     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3943     // point.
3944     //   sw lo, (a0)
3945     //   sw hi, 4(a0)
3946     //   vlse vX, (a0)
3947     //
3948     //   vid.v      vVid
3949     //   vmseq.vx   mMask, vVid, 0
3950     //   vmerge.vvm vDest, vSrc, vVal, mMask
3951     MVT VT = Op.getSimpleValueType();
3952     SDValue Vec = Op.getOperand(1);
3953     SDValue VL = Op.getOperand(3);
3954 
3955     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3956     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3957                                       DAG.getConstant(0, DL, MVT::i32), VL);
3958 
3959     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3960     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3961     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3962     SDValue SelectCond =
3963         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3964                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3965     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3966                        Vec, VL);
3967   }
3968   case Intrinsic::riscv_vslide1up:
3969   case Intrinsic::riscv_vslide1down:
3970   case Intrinsic::riscv_vslide1up_mask:
3971   case Intrinsic::riscv_vslide1down_mask: {
3972     // We need to special case these when the scalar is larger than XLen.
3973     unsigned NumOps = Op.getNumOperands();
3974     bool IsMasked = NumOps == 7;
3975     unsigned OpOffset = IsMasked ? 1 : 0;
3976     SDValue Scalar = Op.getOperand(2 + OpOffset);
3977     if (Scalar.getValueType().bitsLE(XLenVT))
3978       break;
3979 
3980     // Splatting a sign extended constant is fine.
3981     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3982       if (isInt<32>(CVal->getSExtValue()))
3983         break;
3984 
3985     MVT VT = Op.getSimpleValueType();
3986     assert(VT.getVectorElementType() == MVT::i64 &&
3987            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3988 
3989     // Convert the vector source to the equivalent nxvXi32 vector.
3990     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3991     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3992 
3993     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3994                                    DAG.getConstant(0, DL, XLenVT));
3995     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3996                                    DAG.getConstant(1, DL, XLenVT));
3997 
3998     // Double the VL since we halved SEW.
3999     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4000     SDValue I32VL =
4001         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4002 
4003     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4004     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4005 
4006     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4007     // instructions.
4008     if (IntNo == Intrinsic::riscv_vslide1up ||
4009         IntNo == Intrinsic::riscv_vslide1up_mask) {
4010       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4011                         I32Mask, I32VL);
4012       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4013                         I32Mask, I32VL);
4014     } else {
4015       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4016                         I32Mask, I32VL);
4017       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4018                         I32Mask, I32VL);
4019     }
4020 
4021     // Convert back to nxvXi64.
4022     Vec = DAG.getBitcast(VT, Vec);
4023 
4024     if (!IsMasked)
4025       return Vec;
4026 
4027     // Apply mask after the operation.
4028     SDValue Mask = Op.getOperand(NumOps - 3);
4029     SDValue MaskedOff = Op.getOperand(1);
4030     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4031   }
4032   }
4033 
4034   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4035 }
4036 
4037 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4038                                                     SelectionDAG &DAG) const {
4039   unsigned IntNo = Op.getConstantOperandVal(1);
4040   switch (IntNo) {
4041   default:
4042     break;
4043   case Intrinsic::riscv_masked_strided_load: {
4044     SDLoc DL(Op);
4045     MVT XLenVT = Subtarget.getXLenVT();
4046 
4047     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4048     // the selection of the masked intrinsics doesn't do this for us.
4049     SDValue Mask = Op.getOperand(5);
4050     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4051 
4052     MVT VT = Op->getSimpleValueType(0);
4053     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4054 
4055     SDValue PassThru = Op.getOperand(2);
4056     if (!IsUnmasked) {
4057       MVT MaskVT =
4058           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4059       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4060       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4061     }
4062 
4063     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4064 
4065     SDValue IntID = DAG.getTargetConstant(
4066         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4067         XLenVT);
4068 
4069     auto *Load = cast<MemIntrinsicSDNode>(Op);
4070     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4071     if (!IsUnmasked)
4072       Ops.push_back(PassThru);
4073     Ops.push_back(Op.getOperand(3)); // Ptr
4074     Ops.push_back(Op.getOperand(4)); // Stride
4075     if (!IsUnmasked)
4076       Ops.push_back(Mask);
4077     Ops.push_back(VL);
4078     if (!IsUnmasked) {
4079       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4080       Ops.push_back(Policy);
4081     }
4082 
4083     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4084     SDValue Result =
4085         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4086                                 Load->getMemoryVT(), Load->getMemOperand());
4087     SDValue Chain = Result.getValue(1);
4088     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4089     return DAG.getMergeValues({Result, Chain}, DL);
4090   }
4091   }
4092 
4093   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4094 }
4095 
4096 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4097                                                  SelectionDAG &DAG) const {
4098   unsigned IntNo = Op.getConstantOperandVal(1);
4099   switch (IntNo) {
4100   default:
4101     break;
4102   case Intrinsic::riscv_masked_strided_store: {
4103     SDLoc DL(Op);
4104     MVT XLenVT = Subtarget.getXLenVT();
4105 
4106     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4107     // the selection of the masked intrinsics doesn't do this for us.
4108     SDValue Mask = Op.getOperand(5);
4109     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4110 
4111     SDValue Val = Op.getOperand(2);
4112     MVT VT = Val.getSimpleValueType();
4113     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4114 
4115     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4116     if (!IsUnmasked) {
4117       MVT MaskVT =
4118           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4119       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4120     }
4121 
4122     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4123 
4124     SDValue IntID = DAG.getTargetConstant(
4125         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4126         XLenVT);
4127 
4128     auto *Store = cast<MemIntrinsicSDNode>(Op);
4129     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4130     Ops.push_back(Val);
4131     Ops.push_back(Op.getOperand(3)); // Ptr
4132     Ops.push_back(Op.getOperand(4)); // Stride
4133     if (!IsUnmasked)
4134       Ops.push_back(Mask);
4135     Ops.push_back(VL);
4136 
4137     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4138                                    Ops, Store->getMemoryVT(),
4139                                    Store->getMemOperand());
4140   }
4141   }
4142 
4143   return SDValue();
4144 }
4145 
4146 static MVT getLMUL1VT(MVT VT) {
4147   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4148          "Unexpected vector MVT");
4149   return MVT::getScalableVectorVT(
4150       VT.getVectorElementType(),
4151       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4152 }
4153 
4154 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4155   switch (ISDOpcode) {
4156   default:
4157     llvm_unreachable("Unhandled reduction");
4158   case ISD::VECREDUCE_ADD:
4159     return RISCVISD::VECREDUCE_ADD_VL;
4160   case ISD::VECREDUCE_UMAX:
4161     return RISCVISD::VECREDUCE_UMAX_VL;
4162   case ISD::VECREDUCE_SMAX:
4163     return RISCVISD::VECREDUCE_SMAX_VL;
4164   case ISD::VECREDUCE_UMIN:
4165     return RISCVISD::VECREDUCE_UMIN_VL;
4166   case ISD::VECREDUCE_SMIN:
4167     return RISCVISD::VECREDUCE_SMIN_VL;
4168   case ISD::VECREDUCE_AND:
4169     return RISCVISD::VECREDUCE_AND_VL;
4170   case ISD::VECREDUCE_OR:
4171     return RISCVISD::VECREDUCE_OR_VL;
4172   case ISD::VECREDUCE_XOR:
4173     return RISCVISD::VECREDUCE_XOR_VL;
4174   }
4175 }
4176 
4177 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4178                                                          SelectionDAG &DAG,
4179                                                          bool IsVP) const {
4180   SDLoc DL(Op);
4181   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4182   MVT VecVT = Vec.getSimpleValueType();
4183   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4184           Op.getOpcode() == ISD::VECREDUCE_OR ||
4185           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4186           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4187           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4188           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4189          "Unexpected reduction lowering");
4190 
4191   MVT XLenVT = Subtarget.getXLenVT();
4192   assert(Op.getValueType() == XLenVT &&
4193          "Expected reduction output to be legalized to XLenVT");
4194 
4195   MVT ContainerVT = VecVT;
4196   if (VecVT.isFixedLengthVector()) {
4197     ContainerVT = getContainerForFixedLengthVector(VecVT);
4198     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4199   }
4200 
4201   SDValue Mask, VL;
4202   if (IsVP) {
4203     Mask = Op.getOperand(2);
4204     VL = Op.getOperand(3);
4205   } else {
4206     std::tie(Mask, VL) =
4207         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4208   }
4209 
4210   unsigned BaseOpc;
4211   ISD::CondCode CC;
4212   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4213 
4214   switch (Op.getOpcode()) {
4215   default:
4216     llvm_unreachable("Unhandled reduction");
4217   case ISD::VECREDUCE_AND:
4218   case ISD::VP_REDUCE_AND: {
4219     // vcpop ~x == 0
4220     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4221     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4222     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4223     CC = ISD::SETEQ;
4224     BaseOpc = ISD::AND;
4225     break;
4226   }
4227   case ISD::VECREDUCE_OR:
4228   case ISD::VP_REDUCE_OR:
4229     // vcpop x != 0
4230     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4231     CC = ISD::SETNE;
4232     BaseOpc = ISD::OR;
4233     break;
4234   case ISD::VECREDUCE_XOR:
4235   case ISD::VP_REDUCE_XOR: {
4236     // ((vcpop x) & 1) != 0
4237     SDValue One = DAG.getConstant(1, DL, XLenVT);
4238     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4239     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4240     CC = ISD::SETNE;
4241     BaseOpc = ISD::XOR;
4242     break;
4243   }
4244   }
4245 
4246   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4247 
4248   if (!IsVP)
4249     return SetCC;
4250 
4251   // Now include the start value in the operation.
4252   // Note that we must return the start value when no elements are operated
4253   // upon. The vcpop instructions we've emitted in each case above will return
4254   // 0 for an inactive vector, and so we've already received the neutral value:
4255   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4256   // can simply include the start value.
4257   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4258 }
4259 
4260 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4261                                             SelectionDAG &DAG) const {
4262   SDLoc DL(Op);
4263   SDValue Vec = Op.getOperand(0);
4264   EVT VecEVT = Vec.getValueType();
4265 
4266   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4267 
4268   // Due to ordering in legalize types we may have a vector type that needs to
4269   // be split. Do that manually so we can get down to a legal type.
4270   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4271          TargetLowering::TypeSplitVector) {
4272     SDValue Lo, Hi;
4273     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4274     VecEVT = Lo.getValueType();
4275     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4276   }
4277 
4278   // TODO: The type may need to be widened rather than split. Or widened before
4279   // it can be split.
4280   if (!isTypeLegal(VecEVT))
4281     return SDValue();
4282 
4283   MVT VecVT = VecEVT.getSimpleVT();
4284   MVT VecEltVT = VecVT.getVectorElementType();
4285   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4286 
4287   MVT ContainerVT = VecVT;
4288   if (VecVT.isFixedLengthVector()) {
4289     ContainerVT = getContainerForFixedLengthVector(VecVT);
4290     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4291   }
4292 
4293   MVT M1VT = getLMUL1VT(ContainerVT);
4294 
4295   SDValue Mask, VL;
4296   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4297 
4298   // FIXME: This is a VLMAX splat which might be too large and can prevent
4299   // vsetvli removal.
4300   SDValue NeutralElem =
4301       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4302   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
4303   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4304                                   IdentitySplat, Mask, VL);
4305   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4306                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4307   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4308 }
4309 
4310 // Given a reduction op, this function returns the matching reduction opcode,
4311 // the vector SDValue and the scalar SDValue required to lower this to a
4312 // RISCVISD node.
4313 static std::tuple<unsigned, SDValue, SDValue>
4314 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4315   SDLoc DL(Op);
4316   auto Flags = Op->getFlags();
4317   unsigned Opcode = Op.getOpcode();
4318   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4319   switch (Opcode) {
4320   default:
4321     llvm_unreachable("Unhandled reduction");
4322   case ISD::VECREDUCE_FADD:
4323     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4324                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4325   case ISD::VECREDUCE_SEQ_FADD:
4326     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4327                            Op.getOperand(0));
4328   case ISD::VECREDUCE_FMIN:
4329     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4330                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4331   case ISD::VECREDUCE_FMAX:
4332     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4333                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4334   }
4335 }
4336 
4337 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4338                                               SelectionDAG &DAG) const {
4339   SDLoc DL(Op);
4340   MVT VecEltVT = Op.getSimpleValueType();
4341 
4342   unsigned RVVOpcode;
4343   SDValue VectorVal, ScalarVal;
4344   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4345       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4346   MVT VecVT = VectorVal.getSimpleValueType();
4347 
4348   MVT ContainerVT = VecVT;
4349   if (VecVT.isFixedLengthVector()) {
4350     ContainerVT = getContainerForFixedLengthVector(VecVT);
4351     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4352   }
4353 
4354   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4355 
4356   SDValue Mask, VL;
4357   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4358 
4359   // FIXME: This is a VLMAX splat which might be too large and can prevent
4360   // vsetvli removal.
4361   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
4362   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4363                                   VectorVal, ScalarSplat, Mask, VL);
4364   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4365                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4366 }
4367 
4368 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4369   switch (ISDOpcode) {
4370   default:
4371     llvm_unreachable("Unhandled reduction");
4372   case ISD::VP_REDUCE_ADD:
4373     return RISCVISD::VECREDUCE_ADD_VL;
4374   case ISD::VP_REDUCE_UMAX:
4375     return RISCVISD::VECREDUCE_UMAX_VL;
4376   case ISD::VP_REDUCE_SMAX:
4377     return RISCVISD::VECREDUCE_SMAX_VL;
4378   case ISD::VP_REDUCE_UMIN:
4379     return RISCVISD::VECREDUCE_UMIN_VL;
4380   case ISD::VP_REDUCE_SMIN:
4381     return RISCVISD::VECREDUCE_SMIN_VL;
4382   case ISD::VP_REDUCE_AND:
4383     return RISCVISD::VECREDUCE_AND_VL;
4384   case ISD::VP_REDUCE_OR:
4385     return RISCVISD::VECREDUCE_OR_VL;
4386   case ISD::VP_REDUCE_XOR:
4387     return RISCVISD::VECREDUCE_XOR_VL;
4388   case ISD::VP_REDUCE_FADD:
4389     return RISCVISD::VECREDUCE_FADD_VL;
4390   case ISD::VP_REDUCE_SEQ_FADD:
4391     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4392   case ISD::VP_REDUCE_FMAX:
4393     return RISCVISD::VECREDUCE_FMAX_VL;
4394   case ISD::VP_REDUCE_FMIN:
4395     return RISCVISD::VECREDUCE_FMIN_VL;
4396   }
4397 }
4398 
4399 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4400                                            SelectionDAG &DAG) const {
4401   SDLoc DL(Op);
4402   SDValue Vec = Op.getOperand(1);
4403   EVT VecEVT = Vec.getValueType();
4404 
4405   // TODO: The type may need to be widened rather than split. Or widened before
4406   // it can be split.
4407   if (!isTypeLegal(VecEVT))
4408     return SDValue();
4409 
4410   MVT VecVT = VecEVT.getSimpleVT();
4411   MVT VecEltVT = VecVT.getVectorElementType();
4412   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4413 
4414   MVT ContainerVT = VecVT;
4415   if (VecVT.isFixedLengthVector()) {
4416     ContainerVT = getContainerForFixedLengthVector(VecVT);
4417     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4418   }
4419 
4420   SDValue VL = Op.getOperand(3);
4421   SDValue Mask = Op.getOperand(2);
4422 
4423   MVT M1VT = getLMUL1VT(ContainerVT);
4424   MVT XLenVT = Subtarget.getXLenVT();
4425   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4426 
4427   // FIXME: This is a VLMAX splat which might be too large and can prevent
4428   // vsetvli removal.
4429   SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0));
4430   SDValue Reduction =
4431       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4432   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4433                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4434   if (!VecVT.isInteger())
4435     return Elt0;
4436   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4437 }
4438 
4439 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4440                                                    SelectionDAG &DAG) const {
4441   SDValue Vec = Op.getOperand(0);
4442   SDValue SubVec = Op.getOperand(1);
4443   MVT VecVT = Vec.getSimpleValueType();
4444   MVT SubVecVT = SubVec.getSimpleValueType();
4445 
4446   SDLoc DL(Op);
4447   MVT XLenVT = Subtarget.getXLenVT();
4448   unsigned OrigIdx = Op.getConstantOperandVal(2);
4449   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4450 
4451   // We don't have the ability to slide mask vectors up indexed by their i1
4452   // elements; the smallest we can do is i8. Often we are able to bitcast to
4453   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4454   // into a scalable one, we might not necessarily have enough scalable
4455   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4456   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4457       (OrigIdx != 0 || !Vec.isUndef())) {
4458     if (VecVT.getVectorMinNumElements() >= 8 &&
4459         SubVecVT.getVectorMinNumElements() >= 8) {
4460       assert(OrigIdx % 8 == 0 && "Invalid index");
4461       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4462              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4463              "Unexpected mask vector lowering");
4464       OrigIdx /= 8;
4465       SubVecVT =
4466           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4467                            SubVecVT.isScalableVector());
4468       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4469                                VecVT.isScalableVector());
4470       Vec = DAG.getBitcast(VecVT, Vec);
4471       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4472     } else {
4473       // We can't slide this mask vector up indexed by its i1 elements.
4474       // This poses a problem when we wish to insert a scalable vector which
4475       // can't be re-expressed as a larger type. Just choose the slow path and
4476       // extend to a larger type, then truncate back down.
4477       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4478       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4479       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4480       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4481       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4482                         Op.getOperand(2));
4483       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4484       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4485     }
4486   }
4487 
4488   // If the subvector vector is a fixed-length type, we cannot use subregister
4489   // manipulation to simplify the codegen; we don't know which register of a
4490   // LMUL group contains the specific subvector as we only know the minimum
4491   // register size. Therefore we must slide the vector group up the full
4492   // amount.
4493   if (SubVecVT.isFixedLengthVector()) {
4494     if (OrigIdx == 0 && Vec.isUndef())
4495       return Op;
4496     MVT ContainerVT = VecVT;
4497     if (VecVT.isFixedLengthVector()) {
4498       ContainerVT = getContainerForFixedLengthVector(VecVT);
4499       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4500     }
4501     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4502                          DAG.getUNDEF(ContainerVT), SubVec,
4503                          DAG.getConstant(0, DL, XLenVT));
4504     SDValue Mask =
4505         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4506     // Set the vector length to only the number of elements we care about. Note
4507     // that for slideup this includes the offset.
4508     SDValue VL =
4509         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4510     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4511     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4512                                   SubVec, SlideupAmt, Mask, VL);
4513     if (VecVT.isFixedLengthVector())
4514       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4515     return DAG.getBitcast(Op.getValueType(), Slideup);
4516   }
4517 
4518   unsigned SubRegIdx, RemIdx;
4519   std::tie(SubRegIdx, RemIdx) =
4520       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4521           VecVT, SubVecVT, OrigIdx, TRI);
4522 
4523   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4524   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4525                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4526                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4527 
4528   // 1. If the Idx has been completely eliminated and this subvector's size is
4529   // a vector register or a multiple thereof, or the surrounding elements are
4530   // undef, then this is a subvector insert which naturally aligns to a vector
4531   // register. These can easily be handled using subregister manipulation.
4532   // 2. If the subvector is smaller than a vector register, then the insertion
4533   // must preserve the undisturbed elements of the register. We do this by
4534   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4535   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4536   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4537   // LMUL=1 type back into the larger vector (resolving to another subregister
4538   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4539   // to avoid allocating a large register group to hold our subvector.
4540   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4541     return Op;
4542 
4543   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4544   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4545   // (in our case undisturbed). This means we can set up a subvector insertion
4546   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4547   // size of the subvector.
4548   MVT InterSubVT = VecVT;
4549   SDValue AlignedExtract = Vec;
4550   unsigned AlignedIdx = OrigIdx - RemIdx;
4551   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4552     InterSubVT = getLMUL1VT(VecVT);
4553     // Extract a subvector equal to the nearest full vector register type. This
4554     // should resolve to a EXTRACT_SUBREG instruction.
4555     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4556                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4557   }
4558 
4559   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4560   // For scalable vectors this must be further multiplied by vscale.
4561   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4562 
4563   SDValue Mask, VL;
4564   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4565 
4566   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4567   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4568   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4569   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4570 
4571   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4572                        DAG.getUNDEF(InterSubVT), SubVec,
4573                        DAG.getConstant(0, DL, XLenVT));
4574 
4575   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4576                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4577 
4578   // If required, insert this subvector back into the correct vector register.
4579   // This should resolve to an INSERT_SUBREG instruction.
4580   if (VecVT.bitsGT(InterSubVT))
4581     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4582                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4583 
4584   // We might have bitcast from a mask type: cast back to the original type if
4585   // required.
4586   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4587 }
4588 
4589 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4590                                                     SelectionDAG &DAG) const {
4591   SDValue Vec = Op.getOperand(0);
4592   MVT SubVecVT = Op.getSimpleValueType();
4593   MVT VecVT = Vec.getSimpleValueType();
4594 
4595   SDLoc DL(Op);
4596   MVT XLenVT = Subtarget.getXLenVT();
4597   unsigned OrigIdx = Op.getConstantOperandVal(1);
4598   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4599 
4600   // We don't have the ability to slide mask vectors down indexed by their i1
4601   // elements; the smallest we can do is i8. Often we are able to bitcast to
4602   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4603   // from a scalable one, we might not necessarily have enough scalable
4604   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4605   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4606     if (VecVT.getVectorMinNumElements() >= 8 &&
4607         SubVecVT.getVectorMinNumElements() >= 8) {
4608       assert(OrigIdx % 8 == 0 && "Invalid index");
4609       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4610              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4611              "Unexpected mask vector lowering");
4612       OrigIdx /= 8;
4613       SubVecVT =
4614           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4615                            SubVecVT.isScalableVector());
4616       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4617                                VecVT.isScalableVector());
4618       Vec = DAG.getBitcast(VecVT, Vec);
4619     } else {
4620       // We can't slide this mask vector down, indexed by its i1 elements.
4621       // This poses a problem when we wish to extract a scalable vector which
4622       // can't be re-expressed as a larger type. Just choose the slow path and
4623       // extend to a larger type, then truncate back down.
4624       // TODO: We could probably improve this when extracting certain fixed
4625       // from fixed, where we can extract as i8 and shift the correct element
4626       // right to reach the desired subvector?
4627       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4628       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4629       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4630       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4631                         Op.getOperand(1));
4632       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4633       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4634     }
4635   }
4636 
4637   // If the subvector vector is a fixed-length type, we cannot use subregister
4638   // manipulation to simplify the codegen; we don't know which register of a
4639   // LMUL group contains the specific subvector as we only know the minimum
4640   // register size. Therefore we must slide the vector group down the full
4641   // amount.
4642   if (SubVecVT.isFixedLengthVector()) {
4643     // With an index of 0 this is a cast-like subvector, which can be performed
4644     // with subregister operations.
4645     if (OrigIdx == 0)
4646       return Op;
4647     MVT ContainerVT = VecVT;
4648     if (VecVT.isFixedLengthVector()) {
4649       ContainerVT = getContainerForFixedLengthVector(VecVT);
4650       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4651     }
4652     SDValue Mask =
4653         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4654     // Set the vector length to only the number of elements we care about. This
4655     // avoids sliding down elements we're going to discard straight away.
4656     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4657     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4658     SDValue Slidedown =
4659         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4660                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4661     // Now we can use a cast-like subvector extract to get the result.
4662     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4663                             DAG.getConstant(0, DL, XLenVT));
4664     return DAG.getBitcast(Op.getValueType(), Slidedown);
4665   }
4666 
4667   unsigned SubRegIdx, RemIdx;
4668   std::tie(SubRegIdx, RemIdx) =
4669       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4670           VecVT, SubVecVT, OrigIdx, TRI);
4671 
4672   // If the Idx has been completely eliminated then this is a subvector extract
4673   // which naturally aligns to a vector register. These can easily be handled
4674   // using subregister manipulation.
4675   if (RemIdx == 0)
4676     return Op;
4677 
4678   // Else we must shift our vector register directly to extract the subvector.
4679   // Do this using VSLIDEDOWN.
4680 
4681   // If the vector type is an LMUL-group type, extract a subvector equal to the
4682   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4683   // instruction.
4684   MVT InterSubVT = VecVT;
4685   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4686     InterSubVT = getLMUL1VT(VecVT);
4687     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4688                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4689   }
4690 
4691   // Slide this vector register down by the desired number of elements in order
4692   // to place the desired subvector starting at element 0.
4693   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4694   // For scalable vectors this must be further multiplied by vscale.
4695   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4696 
4697   SDValue Mask, VL;
4698   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4699   SDValue Slidedown =
4700       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4701                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4702 
4703   // Now the vector is in the right position, extract our final subvector. This
4704   // should resolve to a COPY.
4705   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4706                           DAG.getConstant(0, DL, XLenVT));
4707 
4708   // We might have bitcast from a mask type: cast back to the original type if
4709   // required.
4710   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4711 }
4712 
4713 // Lower step_vector to the vid instruction. Any non-identity step value must
4714 // be accounted for my manual expansion.
4715 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4716                                               SelectionDAG &DAG) const {
4717   SDLoc DL(Op);
4718   MVT VT = Op.getSimpleValueType();
4719   MVT XLenVT = Subtarget.getXLenVT();
4720   SDValue Mask, VL;
4721   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4722   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4723   uint64_t StepValImm = Op.getConstantOperandVal(0);
4724   if (StepValImm != 1) {
4725     if (isPowerOf2_64(StepValImm)) {
4726       SDValue StepVal =
4727           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4728                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4729       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4730     } else {
4731       SDValue StepVal = lowerScalarSplat(
4732           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4733           DL, DAG, Subtarget);
4734       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4735     }
4736   }
4737   return StepVec;
4738 }
4739 
4740 // Implement vector_reverse using vrgather.vv with indices determined by
4741 // subtracting the id of each element from (VLMAX-1). This will convert
4742 // the indices like so:
4743 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4744 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4745 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4746                                                  SelectionDAG &DAG) const {
4747   SDLoc DL(Op);
4748   MVT VecVT = Op.getSimpleValueType();
4749   unsigned EltSize = VecVT.getScalarSizeInBits();
4750   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4751 
4752   unsigned MaxVLMAX = 0;
4753   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4754   if (VectorBitsMax != 0)
4755     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4756 
4757   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4758   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4759 
4760   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4761   // to use vrgatherei16.vv.
4762   // TODO: It's also possible to use vrgatherei16.vv for other types to
4763   // decrease register width for the index calculation.
4764   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4765     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4766     // Reverse each half, then reassemble them in reverse order.
4767     // NOTE: It's also possible that after splitting that VLMAX no longer
4768     // requires vrgatherei16.vv.
4769     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4770       SDValue Lo, Hi;
4771       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4772       EVT LoVT, HiVT;
4773       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4774       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4775       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4776       // Reassemble the low and high pieces reversed.
4777       // FIXME: This is a CONCAT_VECTORS.
4778       SDValue Res =
4779           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4780                       DAG.getIntPtrConstant(0, DL));
4781       return DAG.getNode(
4782           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4783           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4784     }
4785 
4786     // Just promote the int type to i16 which will double the LMUL.
4787     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4788     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4789   }
4790 
4791   MVT XLenVT = Subtarget.getXLenVT();
4792   SDValue Mask, VL;
4793   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4794 
4795   // Calculate VLMAX-1 for the desired SEW.
4796   unsigned MinElts = VecVT.getVectorMinNumElements();
4797   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4798                               DAG.getConstant(MinElts, DL, XLenVT));
4799   SDValue VLMinus1 =
4800       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4801 
4802   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4803   bool IsRV32E64 =
4804       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4805   SDValue SplatVL;
4806   if (!IsRV32E64)
4807     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4808   else
4809     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4810 
4811   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4812   SDValue Indices =
4813       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4814 
4815   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4816 }
4817 
4818 SDValue
4819 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
4820                                                      SelectionDAG &DAG) const {
4821   SDLoc DL(Op);
4822   auto *Load = cast<LoadSDNode>(Op);
4823 
4824   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4825                                         Load->getMemoryVT(),
4826                                         *Load->getMemOperand()) &&
4827          "Expecting a correctly-aligned load");
4828 
4829   MVT VT = Op.getSimpleValueType();
4830   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4831 
4832   SDValue VL =
4833       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4834 
4835   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4836   SDValue NewLoad = DAG.getMemIntrinsicNode(
4837       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
4838       Load->getMemoryVT(), Load->getMemOperand());
4839 
4840   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
4841   return DAG.getMergeValues({Result, Load->getChain()}, DL);
4842 }
4843 
4844 SDValue
4845 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
4846                                                       SelectionDAG &DAG) const {
4847   SDLoc DL(Op);
4848   auto *Store = cast<StoreSDNode>(Op);
4849 
4850   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4851                                         Store->getMemoryVT(),
4852                                         *Store->getMemOperand()) &&
4853          "Expecting a correctly-aligned store");
4854 
4855   SDValue StoreVal = Store->getValue();
4856   MVT VT = StoreVal.getSimpleValueType();
4857 
4858   // If the size less than a byte, we need to pad with zeros to make a byte.
4859   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
4860     VT = MVT::v8i1;
4861     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
4862                            DAG.getConstant(0, DL, VT), StoreVal,
4863                            DAG.getIntPtrConstant(0, DL));
4864   }
4865 
4866   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4867 
4868   SDValue VL =
4869       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4870 
4871   SDValue NewValue =
4872       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
4873   return DAG.getMemIntrinsicNode(
4874       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
4875       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
4876       Store->getMemoryVT(), Store->getMemOperand());
4877 }
4878 
4879 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
4880                                              SelectionDAG &DAG) const {
4881   SDLoc DL(Op);
4882   MVT VT = Op.getSimpleValueType();
4883 
4884   const auto *MemSD = cast<MemSDNode>(Op);
4885   EVT MemVT = MemSD->getMemoryVT();
4886   MachineMemOperand *MMO = MemSD->getMemOperand();
4887   SDValue Chain = MemSD->getChain();
4888   SDValue BasePtr = MemSD->getBasePtr();
4889 
4890   SDValue Mask, PassThru, VL;
4891   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
4892     Mask = VPLoad->getMask();
4893     PassThru = DAG.getUNDEF(VT);
4894     VL = VPLoad->getVectorLength();
4895   } else {
4896     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
4897     Mask = MLoad->getMask();
4898     PassThru = MLoad->getPassThru();
4899   }
4900 
4901   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4902 
4903   MVT XLenVT = Subtarget.getXLenVT();
4904 
4905   MVT ContainerVT = VT;
4906   if (VT.isFixedLengthVector()) {
4907     ContainerVT = getContainerForFixedLengthVector(VT);
4908     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4909     if (!IsUnmasked) {
4910       MVT MaskVT =
4911           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4912       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4913     }
4914   }
4915 
4916   if (!VL)
4917     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4918 
4919   unsigned IntID =
4920       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
4921   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4922   if (!IsUnmasked)
4923     Ops.push_back(PassThru);
4924   Ops.push_back(BasePtr);
4925   if (!IsUnmasked)
4926     Ops.push_back(Mask);
4927   Ops.push_back(VL);
4928   if (!IsUnmasked)
4929     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
4930 
4931   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4932 
4933   SDValue Result =
4934       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
4935   Chain = Result.getValue(1);
4936 
4937   if (VT.isFixedLengthVector())
4938     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4939 
4940   return DAG.getMergeValues({Result, Chain}, DL);
4941 }
4942 
4943 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
4944                                               SelectionDAG &DAG) const {
4945   SDLoc DL(Op);
4946 
4947   const auto *MemSD = cast<MemSDNode>(Op);
4948   EVT MemVT = MemSD->getMemoryVT();
4949   MachineMemOperand *MMO = MemSD->getMemOperand();
4950   SDValue Chain = MemSD->getChain();
4951   SDValue BasePtr = MemSD->getBasePtr();
4952   SDValue Val, Mask, VL;
4953 
4954   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
4955     Val = VPStore->getValue();
4956     Mask = VPStore->getMask();
4957     VL = VPStore->getVectorLength();
4958   } else {
4959     const auto *MStore = cast<MaskedStoreSDNode>(Op);
4960     Val = MStore->getValue();
4961     Mask = MStore->getMask();
4962   }
4963 
4964   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4965 
4966   MVT VT = Val.getSimpleValueType();
4967   MVT XLenVT = Subtarget.getXLenVT();
4968 
4969   MVT ContainerVT = VT;
4970   if (VT.isFixedLengthVector()) {
4971     ContainerVT = getContainerForFixedLengthVector(VT);
4972 
4973     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4974     if (!IsUnmasked) {
4975       MVT MaskVT =
4976           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4977       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4978     }
4979   }
4980 
4981   if (!VL)
4982     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4983 
4984   unsigned IntID =
4985       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
4986   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4987   Ops.push_back(Val);
4988   Ops.push_back(BasePtr);
4989   if (!IsUnmasked)
4990     Ops.push_back(Mask);
4991   Ops.push_back(VL);
4992 
4993   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
4994                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
4995 }
4996 
4997 SDValue
4998 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4999                                                       SelectionDAG &DAG) const {
5000   MVT InVT = Op.getOperand(0).getSimpleValueType();
5001   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5002 
5003   MVT VT = Op.getSimpleValueType();
5004 
5005   SDValue Op1 =
5006       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5007   SDValue Op2 =
5008       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5009 
5010   SDLoc DL(Op);
5011   SDValue VL =
5012       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5013 
5014   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5015   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5016 
5017   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5018                             Op.getOperand(2), Mask, VL);
5019 
5020   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5021 }
5022 
5023 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5024     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5025   MVT VT = Op.getSimpleValueType();
5026 
5027   if (VT.getVectorElementType() == MVT::i1)
5028     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5029 
5030   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5031 }
5032 
5033 SDValue
5034 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5035                                                       SelectionDAG &DAG) const {
5036   unsigned Opc;
5037   switch (Op.getOpcode()) {
5038   default: llvm_unreachable("Unexpected opcode!");
5039   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5040   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5041   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5042   }
5043 
5044   return lowerToScalableOp(Op, DAG, Opc);
5045 }
5046 
5047 // Lower vector ABS to smax(X, sub(0, X)).
5048 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5049   SDLoc DL(Op);
5050   MVT VT = Op.getSimpleValueType();
5051   SDValue X = Op.getOperand(0);
5052 
5053   assert(VT.isFixedLengthVector() && "Unexpected type");
5054 
5055   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5056   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5057 
5058   SDValue Mask, VL;
5059   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5060 
5061   SDValue SplatZero =
5062       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5063                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5064   SDValue NegX =
5065       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5066   SDValue Max =
5067       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5068 
5069   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5070 }
5071 
5072 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5073     SDValue Op, SelectionDAG &DAG) const {
5074   SDLoc DL(Op);
5075   MVT VT = Op.getSimpleValueType();
5076   SDValue Mag = Op.getOperand(0);
5077   SDValue Sign = Op.getOperand(1);
5078   assert(Mag.getValueType() == Sign.getValueType() &&
5079          "Can only handle COPYSIGN with matching types.");
5080 
5081   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5082   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5083   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5084 
5085   SDValue Mask, VL;
5086   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5087 
5088   SDValue CopySign =
5089       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5090 
5091   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5092 }
5093 
5094 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5095     SDValue Op, SelectionDAG &DAG) const {
5096   MVT VT = Op.getSimpleValueType();
5097   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5098 
5099   MVT I1ContainerVT =
5100       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5101 
5102   SDValue CC =
5103       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5104   SDValue Op1 =
5105       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5106   SDValue Op2 =
5107       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5108 
5109   SDLoc DL(Op);
5110   SDValue Mask, VL;
5111   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5112 
5113   SDValue Select =
5114       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5115 
5116   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5117 }
5118 
5119 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5120                                                unsigned NewOpc,
5121                                                bool HasMask) const {
5122   MVT VT = Op.getSimpleValueType();
5123   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5124 
5125   // Create list of operands by converting existing ones to scalable types.
5126   SmallVector<SDValue, 6> Ops;
5127   for (const SDValue &V : Op->op_values()) {
5128     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5129 
5130     // Pass through non-vector operands.
5131     if (!V.getValueType().isVector()) {
5132       Ops.push_back(V);
5133       continue;
5134     }
5135 
5136     // "cast" fixed length vector to a scalable vector.
5137     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5138            "Only fixed length vectors are supported!");
5139     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5140   }
5141 
5142   SDLoc DL(Op);
5143   SDValue Mask, VL;
5144   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5145   if (HasMask)
5146     Ops.push_back(Mask);
5147   Ops.push_back(VL);
5148 
5149   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5150   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5151 }
5152 
5153 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5154 // * Operands of each node are assumed to be in the same order.
5155 // * The EVL operand is promoted from i32 to i64 on RV64.
5156 // * Fixed-length vectors are converted to their scalable-vector container
5157 //   types.
5158 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5159                                        unsigned RISCVISDOpc) const {
5160   SDLoc DL(Op);
5161   MVT VT = Op.getSimpleValueType();
5162   SmallVector<SDValue, 4> Ops;
5163 
5164   for (const auto &OpIdx : enumerate(Op->ops())) {
5165     SDValue V = OpIdx.value();
5166     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5167     // Pass through operands which aren't fixed-length vectors.
5168     if (!V.getValueType().isFixedLengthVector()) {
5169       Ops.push_back(V);
5170       continue;
5171     }
5172     // "cast" fixed length vector to a scalable vector.
5173     MVT OpVT = V.getSimpleValueType();
5174     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5175     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5176            "Only fixed length vectors are supported!");
5177     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5178   }
5179 
5180   if (!VT.isFixedLengthVector())
5181     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5182 
5183   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5184 
5185   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5186 
5187   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5188 }
5189 
5190 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5191 // matched to a RVV indexed load. The RVV indexed load instructions only
5192 // support the "unsigned unscaled" addressing mode; indices are implicitly
5193 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5194 // signed or scaled indexing is extended to the XLEN value type and scaled
5195 // accordingly.
5196 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5197                                                SelectionDAG &DAG) const {
5198   SDLoc DL(Op);
5199   MVT VT = Op.getSimpleValueType();
5200 
5201   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5202   EVT MemVT = MemSD->getMemoryVT();
5203   MachineMemOperand *MMO = MemSD->getMemOperand();
5204   SDValue Chain = MemSD->getChain();
5205   SDValue BasePtr = MemSD->getBasePtr();
5206 
5207   ISD::LoadExtType LoadExtType;
5208   SDValue Index, Mask, PassThru, VL;
5209 
5210   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5211     Index = VPGN->getIndex();
5212     Mask = VPGN->getMask();
5213     PassThru = DAG.getUNDEF(VT);
5214     VL = VPGN->getVectorLength();
5215     // VP doesn't support extending loads.
5216     LoadExtType = ISD::NON_EXTLOAD;
5217   } else {
5218     // Else it must be a MGATHER.
5219     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5220     Index = MGN->getIndex();
5221     Mask = MGN->getMask();
5222     PassThru = MGN->getPassThru();
5223     LoadExtType = MGN->getExtensionType();
5224   }
5225 
5226   MVT IndexVT = Index.getSimpleValueType();
5227   MVT XLenVT = Subtarget.getXLenVT();
5228 
5229   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5230          "Unexpected VTs!");
5231   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5232   // Targets have to explicitly opt-in for extending vector loads.
5233   assert(LoadExtType == ISD::NON_EXTLOAD &&
5234          "Unexpected extending MGATHER/VP_GATHER");
5235   (void)LoadExtType;
5236 
5237   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5238   // the selection of the masked intrinsics doesn't do this for us.
5239   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5240 
5241   MVT ContainerVT = VT;
5242   if (VT.isFixedLengthVector()) {
5243     // We need to use the larger of the result and index type to determine the
5244     // scalable type to use so we don't increase LMUL for any operand/result.
5245     if (VT.bitsGE(IndexVT)) {
5246       ContainerVT = getContainerForFixedLengthVector(VT);
5247       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5248                                  ContainerVT.getVectorElementCount());
5249     } else {
5250       IndexVT = getContainerForFixedLengthVector(IndexVT);
5251       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5252                                      IndexVT.getVectorElementCount());
5253     }
5254 
5255     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5256 
5257     if (!IsUnmasked) {
5258       MVT MaskVT =
5259           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5260       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5261       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5262     }
5263   }
5264 
5265   if (!VL)
5266     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5267 
5268   unsigned IntID =
5269       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5270   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5271   if (!IsUnmasked)
5272     Ops.push_back(PassThru);
5273   Ops.push_back(BasePtr);
5274   Ops.push_back(Index);
5275   if (!IsUnmasked)
5276     Ops.push_back(Mask);
5277   Ops.push_back(VL);
5278   if (!IsUnmasked)
5279     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5280 
5281   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5282   SDValue Result =
5283       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5284   Chain = Result.getValue(1);
5285 
5286   if (VT.isFixedLengthVector())
5287     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5288 
5289   return DAG.getMergeValues({Result, Chain}, DL);
5290 }
5291 
5292 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5293 // matched to a RVV indexed store. The RVV indexed store instructions only
5294 // support the "unsigned unscaled" addressing mode; indices are implicitly
5295 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5296 // signed or scaled indexing is extended to the XLEN value type and scaled
5297 // accordingly.
5298 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5299                                                 SelectionDAG &DAG) const {
5300   SDLoc DL(Op);
5301   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5302   EVT MemVT = MemSD->getMemoryVT();
5303   MachineMemOperand *MMO = MemSD->getMemOperand();
5304   SDValue Chain = MemSD->getChain();
5305   SDValue BasePtr = MemSD->getBasePtr();
5306 
5307   bool IsTruncatingStore = false;
5308   SDValue Index, Mask, Val, VL;
5309 
5310   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5311     Index = VPSN->getIndex();
5312     Mask = VPSN->getMask();
5313     Val = VPSN->getValue();
5314     VL = VPSN->getVectorLength();
5315     // VP doesn't support truncating stores.
5316     IsTruncatingStore = false;
5317   } else {
5318     // Else it must be a MSCATTER.
5319     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5320     Index = MSN->getIndex();
5321     Mask = MSN->getMask();
5322     Val = MSN->getValue();
5323     IsTruncatingStore = MSN->isTruncatingStore();
5324   }
5325 
5326   MVT VT = Val.getSimpleValueType();
5327   MVT IndexVT = Index.getSimpleValueType();
5328   MVT XLenVT = Subtarget.getXLenVT();
5329 
5330   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5331          "Unexpected VTs!");
5332   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5333   // Targets have to explicitly opt-in for extending vector loads and
5334   // truncating vector stores.
5335   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5336   (void)IsTruncatingStore;
5337 
5338   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5339   // the selection of the masked intrinsics doesn't do this for us.
5340   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5341 
5342   MVT ContainerVT = VT;
5343   if (VT.isFixedLengthVector()) {
5344     // We need to use the larger of the value and index type to determine the
5345     // scalable type to use so we don't increase LMUL for any operand/result.
5346     if (VT.bitsGE(IndexVT)) {
5347       ContainerVT = getContainerForFixedLengthVector(VT);
5348       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5349                                  ContainerVT.getVectorElementCount());
5350     } else {
5351       IndexVT = getContainerForFixedLengthVector(IndexVT);
5352       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5353                                      IndexVT.getVectorElementCount());
5354     }
5355 
5356     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5357     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5358 
5359     if (!IsUnmasked) {
5360       MVT MaskVT =
5361           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5362       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5363     }
5364   }
5365 
5366   if (!VL)
5367     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5368 
5369   unsigned IntID =
5370       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5371   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5372   Ops.push_back(Val);
5373   Ops.push_back(BasePtr);
5374   Ops.push_back(Index);
5375   if (!IsUnmasked)
5376     Ops.push_back(Mask);
5377   Ops.push_back(VL);
5378 
5379   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5380                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5381 }
5382 
5383 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5384                                                SelectionDAG &DAG) const {
5385   const MVT XLenVT = Subtarget.getXLenVT();
5386   SDLoc DL(Op);
5387   SDValue Chain = Op->getOperand(0);
5388   SDValue SysRegNo = DAG.getTargetConstant(
5389       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5390   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5391   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5392 
5393   // Encoding used for rounding mode in RISCV differs from that used in
5394   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5395   // table, which consists of a sequence of 4-bit fields, each representing
5396   // corresponding FLT_ROUNDS mode.
5397   static const int Table =
5398       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5399       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5400       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5401       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5402       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5403 
5404   SDValue Shift =
5405       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5406   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5407                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5408   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5409                                DAG.getConstant(7, DL, XLenVT));
5410 
5411   return DAG.getMergeValues({Masked, Chain}, DL);
5412 }
5413 
5414 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5415                                                SelectionDAG &DAG) const {
5416   const MVT XLenVT = Subtarget.getXLenVT();
5417   SDLoc DL(Op);
5418   SDValue Chain = Op->getOperand(0);
5419   SDValue RMValue = Op->getOperand(1);
5420   SDValue SysRegNo = DAG.getTargetConstant(
5421       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5422 
5423   // Encoding used for rounding mode in RISCV differs from that used in
5424   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5425   // a table, which consists of a sequence of 4-bit fields, each representing
5426   // corresponding RISCV mode.
5427   static const unsigned Table =
5428       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5429       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5430       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5431       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5432       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5433 
5434   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5435                               DAG.getConstant(2, DL, XLenVT));
5436   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5437                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5438   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5439                         DAG.getConstant(0x7, DL, XLenVT));
5440   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5441                      RMValue);
5442 }
5443 
5444 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5445 // form of the given Opcode.
5446 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5447   switch (Opcode) {
5448   default:
5449     llvm_unreachable("Unexpected opcode");
5450   case ISD::SHL:
5451     return RISCVISD::SLLW;
5452   case ISD::SRA:
5453     return RISCVISD::SRAW;
5454   case ISD::SRL:
5455     return RISCVISD::SRLW;
5456   case ISD::SDIV:
5457     return RISCVISD::DIVW;
5458   case ISD::UDIV:
5459     return RISCVISD::DIVUW;
5460   case ISD::UREM:
5461     return RISCVISD::REMUW;
5462   case ISD::ROTL:
5463     return RISCVISD::ROLW;
5464   case ISD::ROTR:
5465     return RISCVISD::RORW;
5466   case RISCVISD::GREV:
5467     return RISCVISD::GREVW;
5468   case RISCVISD::GORC:
5469     return RISCVISD::GORCW;
5470   }
5471 }
5472 
5473 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5474 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5475 // otherwise be promoted to i64, making it difficult to select the
5476 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5477 // type i8/i16/i32 is lost.
5478 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5479                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5480   SDLoc DL(N);
5481   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5482   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5483   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5484   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5485   // ReplaceNodeResults requires we maintain the same type for the return value.
5486   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5487 }
5488 
5489 // Converts the given 32-bit operation to a i64 operation with signed extension
5490 // semantic to reduce the signed extension instructions.
5491 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5492   SDLoc DL(N);
5493   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5494   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5495   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5496   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5497                                DAG.getValueType(MVT::i32));
5498   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5499 }
5500 
5501 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5502                                              SmallVectorImpl<SDValue> &Results,
5503                                              SelectionDAG &DAG) const {
5504   SDLoc DL(N);
5505   switch (N->getOpcode()) {
5506   default:
5507     llvm_unreachable("Don't know how to custom type legalize this operation!");
5508   case ISD::STRICT_FP_TO_SINT:
5509   case ISD::STRICT_FP_TO_UINT:
5510   case ISD::FP_TO_SINT:
5511   case ISD::FP_TO_UINT: {
5512     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5513            "Unexpected custom legalisation");
5514     bool IsStrict = N->isStrictFPOpcode();
5515     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5516                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5517     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5518     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5519         TargetLowering::TypeSoftenFloat) {
5520       // FIXME: Support strict FP.
5521       if (IsStrict)
5522         return;
5523       if (!isTypeLegal(Op0.getValueType()))
5524         return;
5525       unsigned Opc =
5526           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5527       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5528       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5529       return;
5530     }
5531     // If the FP type needs to be softened, emit a library call using the 'si'
5532     // version. If we left it to default legalization we'd end up with 'di'. If
5533     // the FP type doesn't need to be softened just let generic type
5534     // legalization promote the result type.
5535     RTLIB::Libcall LC;
5536     if (IsSigned)
5537       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5538     else
5539       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5540     MakeLibCallOptions CallOptions;
5541     EVT OpVT = Op0.getValueType();
5542     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5543     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5544     SDValue Result;
5545     std::tie(Result, Chain) =
5546         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5547     Results.push_back(Result);
5548     if (IsStrict)
5549       Results.push_back(Chain);
5550     break;
5551   }
5552   case ISD::READCYCLECOUNTER: {
5553     assert(!Subtarget.is64Bit() &&
5554            "READCYCLECOUNTER only has custom type legalization on riscv32");
5555 
5556     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5557     SDValue RCW =
5558         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5559 
5560     Results.push_back(
5561         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5562     Results.push_back(RCW.getValue(2));
5563     break;
5564   }
5565   case ISD::MUL: {
5566     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5567     unsigned XLen = Subtarget.getXLen();
5568     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5569     if (Size > XLen) {
5570       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5571       SDValue LHS = N->getOperand(0);
5572       SDValue RHS = N->getOperand(1);
5573       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5574 
5575       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5576       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5577       // We need exactly one side to be unsigned.
5578       if (LHSIsU == RHSIsU)
5579         return;
5580 
5581       auto MakeMULPair = [&](SDValue S, SDValue U) {
5582         MVT XLenVT = Subtarget.getXLenVT();
5583         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5584         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5585         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5586         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5587         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5588       };
5589 
5590       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5591       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5592 
5593       // The other operand should be signed, but still prefer MULH when
5594       // possible.
5595       if (RHSIsU && LHSIsS && !RHSIsS)
5596         Results.push_back(MakeMULPair(LHS, RHS));
5597       else if (LHSIsU && RHSIsS && !LHSIsS)
5598         Results.push_back(MakeMULPair(RHS, LHS));
5599 
5600       return;
5601     }
5602     LLVM_FALLTHROUGH;
5603   }
5604   case ISD::ADD:
5605   case ISD::SUB:
5606     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5607            "Unexpected custom legalisation");
5608     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5609     break;
5610   case ISD::SHL:
5611   case ISD::SRA:
5612   case ISD::SRL:
5613     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5614            "Unexpected custom legalisation");
5615     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5616       Results.push_back(customLegalizeToWOp(N, DAG));
5617       break;
5618     }
5619 
5620     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5621     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5622     // shift amount.
5623     if (N->getOpcode() == ISD::SHL) {
5624       SDLoc DL(N);
5625       SDValue NewOp0 =
5626           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5627       SDValue NewOp1 =
5628           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5629       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5630       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5631                                    DAG.getValueType(MVT::i32));
5632       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5633     }
5634 
5635     break;
5636   case ISD::ROTL:
5637   case ISD::ROTR:
5638     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5639            "Unexpected custom legalisation");
5640     Results.push_back(customLegalizeToWOp(N, DAG));
5641     break;
5642   case ISD::CTTZ:
5643   case ISD::CTTZ_ZERO_UNDEF:
5644   case ISD::CTLZ:
5645   case ISD::CTLZ_ZERO_UNDEF: {
5646     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5647            "Unexpected custom legalisation");
5648 
5649     SDValue NewOp0 =
5650         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5651     bool IsCTZ =
5652         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5653     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5654     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5655     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5656     return;
5657   }
5658   case ISD::SDIV:
5659   case ISD::UDIV:
5660   case ISD::UREM: {
5661     MVT VT = N->getSimpleValueType(0);
5662     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5663            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5664            "Unexpected custom legalisation");
5665     // Don't promote division/remainder by constant since we should expand those
5666     // to multiply by magic constant.
5667     // FIXME: What if the expansion is disabled for minsize.
5668     if (N->getOperand(1).getOpcode() == ISD::Constant)
5669       return;
5670 
5671     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5672     // the upper 32 bits. For other types we need to sign or zero extend
5673     // based on the opcode.
5674     unsigned ExtOpc = ISD::ANY_EXTEND;
5675     if (VT != MVT::i32)
5676       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5677                                            : ISD::ZERO_EXTEND;
5678 
5679     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5680     break;
5681   }
5682   case ISD::UADDO:
5683   case ISD::USUBO: {
5684     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5685            "Unexpected custom legalisation");
5686     bool IsAdd = N->getOpcode() == ISD::UADDO;
5687     // Create an ADDW or SUBW.
5688     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5689     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5690     SDValue Res =
5691         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5692     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5693                       DAG.getValueType(MVT::i32));
5694 
5695     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5696     // Since the inputs are sign extended from i32, this is equivalent to
5697     // comparing the lower 32 bits.
5698     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5699     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5700                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5701 
5702     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5703     Results.push_back(Overflow);
5704     return;
5705   }
5706   case ISD::UADDSAT:
5707   case ISD::USUBSAT: {
5708     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5709            "Unexpected custom legalisation");
5710     if (Subtarget.hasStdExtZbb()) {
5711       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5712       // sign extend allows overflow of the lower 32 bits to be detected on
5713       // the promoted size.
5714       SDValue LHS =
5715           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5716       SDValue RHS =
5717           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5718       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5719       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5720       return;
5721     }
5722 
5723     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5724     // promotion for UADDO/USUBO.
5725     Results.push_back(expandAddSubSat(N, DAG));
5726     return;
5727   }
5728   case ISD::BITCAST: {
5729     EVT VT = N->getValueType(0);
5730     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5731     SDValue Op0 = N->getOperand(0);
5732     EVT Op0VT = Op0.getValueType();
5733     MVT XLenVT = Subtarget.getXLenVT();
5734     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5735       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5736       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5737     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5738                Subtarget.hasStdExtF()) {
5739       SDValue FPConv =
5740           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5741       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5742     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5743                isTypeLegal(Op0VT)) {
5744       // Custom-legalize bitcasts from fixed-length vector types to illegal
5745       // scalar types in order to improve codegen. Bitcast the vector to a
5746       // one-element vector type whose element type is the same as the result
5747       // type, and extract the first element.
5748       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
5749       if (isTypeLegal(BVT)) {
5750         SDValue BVec = DAG.getBitcast(BVT, Op0);
5751         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5752                                       DAG.getConstant(0, DL, XLenVT)));
5753       }
5754     }
5755     break;
5756   }
5757   case RISCVISD::GREV:
5758   case RISCVISD::GORC: {
5759     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5760            "Unexpected custom legalisation");
5761     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5762     // This is similar to customLegalizeToWOp, except that we pass the second
5763     // operand (a TargetConstant) straight through: it is already of type
5764     // XLenVT.
5765     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5766     SDValue NewOp0 =
5767         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5768     SDValue NewOp1 =
5769         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5770     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5771     // ReplaceNodeResults requires we maintain the same type for the return
5772     // value.
5773     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5774     break;
5775   }
5776   case RISCVISD::SHFL: {
5777     // There is no SHFLIW instruction, but we can just promote the operation.
5778     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5779            "Unexpected custom legalisation");
5780     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5781     SDValue NewOp0 =
5782         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5783     SDValue NewOp1 =
5784         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5785     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5786     // ReplaceNodeResults requires we maintain the same type for the return
5787     // value.
5788     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5789     break;
5790   }
5791   case ISD::BSWAP:
5792   case ISD::BITREVERSE: {
5793     MVT VT = N->getSimpleValueType(0);
5794     MVT XLenVT = Subtarget.getXLenVT();
5795     assert((VT == MVT::i8 || VT == MVT::i16 ||
5796             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5797            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5798     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5799     unsigned Imm = VT.getSizeInBits() - 1;
5800     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5801     if (N->getOpcode() == ISD::BSWAP)
5802       Imm &= ~0x7U;
5803     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5804     SDValue GREVI =
5805         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5806     // ReplaceNodeResults requires we maintain the same type for the return
5807     // value.
5808     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5809     break;
5810   }
5811   case ISD::FSHL:
5812   case ISD::FSHR: {
5813     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5814            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5815     SDValue NewOp0 =
5816         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5817     SDValue NewOp1 =
5818         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5819     SDValue NewOp2 =
5820         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5821     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5822     // Mask the shift amount to 5 bits.
5823     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5824                          DAG.getConstant(0x1f, DL, MVT::i64));
5825     unsigned Opc =
5826         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5827     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5828     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5829     break;
5830   }
5831   case ISD::EXTRACT_VECTOR_ELT: {
5832     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5833     // type is illegal (currently only vXi64 RV32).
5834     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5835     // transferred to the destination register. We issue two of these from the
5836     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5837     // first element.
5838     SDValue Vec = N->getOperand(0);
5839     SDValue Idx = N->getOperand(1);
5840 
5841     // The vector type hasn't been legalized yet so we can't issue target
5842     // specific nodes if it needs legalization.
5843     // FIXME: We would manually legalize if it's important.
5844     if (!isTypeLegal(Vec.getValueType()))
5845       return;
5846 
5847     MVT VecVT = Vec.getSimpleValueType();
5848 
5849     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5850            VecVT.getVectorElementType() == MVT::i64 &&
5851            "Unexpected EXTRACT_VECTOR_ELT legalization");
5852 
5853     // If this is a fixed vector, we need to convert it to a scalable vector.
5854     MVT ContainerVT = VecVT;
5855     if (VecVT.isFixedLengthVector()) {
5856       ContainerVT = getContainerForFixedLengthVector(VecVT);
5857       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5858     }
5859 
5860     MVT XLenVT = Subtarget.getXLenVT();
5861 
5862     // Use a VL of 1 to avoid processing more elements than we need.
5863     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5864     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5865     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5866 
5867     // Unless the index is known to be 0, we must slide the vector down to get
5868     // the desired element into index 0.
5869     if (!isNullConstant(Idx)) {
5870       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5871                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5872     }
5873 
5874     // Extract the lower XLEN bits of the correct vector element.
5875     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5876 
5877     // To extract the upper XLEN bits of the vector element, shift the first
5878     // element right by 32 bits and re-extract the lower XLEN bits.
5879     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5880                                      DAG.getConstant(32, DL, XLenVT), VL);
5881     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5882                                  ThirtyTwoV, Mask, VL);
5883 
5884     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5885 
5886     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5887     break;
5888   }
5889   case ISD::INTRINSIC_WO_CHAIN: {
5890     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5891     switch (IntNo) {
5892     default:
5893       llvm_unreachable(
5894           "Don't know how to custom type legalize this intrinsic!");
5895     case Intrinsic::riscv_orc_b: {
5896       // Lower to the GORCI encoding for orc.b with the operand extended.
5897       SDValue NewOp =
5898           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5899       // If Zbp is enabled, use GORCIW which will sign extend the result.
5900       unsigned Opc =
5901           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5902       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5903                                 DAG.getConstant(7, DL, MVT::i64));
5904       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5905       return;
5906     }
5907     case Intrinsic::riscv_grev:
5908     case Intrinsic::riscv_gorc: {
5909       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5910              "Unexpected custom legalisation");
5911       SDValue NewOp1 =
5912           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5913       SDValue NewOp2 =
5914           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5915       unsigned Opc =
5916           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5917       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5918       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5919       break;
5920     }
5921     case Intrinsic::riscv_shfl:
5922     case Intrinsic::riscv_unshfl: {
5923       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5924              "Unexpected custom legalisation");
5925       SDValue NewOp1 =
5926           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5927       SDValue NewOp2 =
5928           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5929       unsigned Opc =
5930           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5931       if (isa<ConstantSDNode>(N->getOperand(2))) {
5932         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5933                              DAG.getConstant(0xf, DL, MVT::i64));
5934         Opc =
5935             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5936       }
5937       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5938       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5939       break;
5940     }
5941     case Intrinsic::riscv_bcompress:
5942     case Intrinsic::riscv_bdecompress: {
5943       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5944              "Unexpected custom legalisation");
5945       SDValue NewOp1 =
5946           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5947       SDValue NewOp2 =
5948           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5949       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5950                          ? RISCVISD::BCOMPRESSW
5951                          : RISCVISD::BDECOMPRESSW;
5952       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5953       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5954       break;
5955     }
5956     case Intrinsic::riscv_vmv_x_s: {
5957       EVT VT = N->getValueType(0);
5958       MVT XLenVT = Subtarget.getXLenVT();
5959       if (VT.bitsLT(XLenVT)) {
5960         // Simple case just extract using vmv.x.s and truncate.
5961         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5962                                       Subtarget.getXLenVT(), N->getOperand(1));
5963         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5964         return;
5965       }
5966 
5967       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5968              "Unexpected custom legalization");
5969 
5970       // We need to do the move in two steps.
5971       SDValue Vec = N->getOperand(1);
5972       MVT VecVT = Vec.getSimpleValueType();
5973 
5974       // First extract the lower XLEN bits of the element.
5975       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5976 
5977       // To extract the upper XLEN bits of the vector element, shift the first
5978       // element right by 32 bits and re-extract the lower XLEN bits.
5979       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5980       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5981       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5982       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5983                                        DAG.getConstant(32, DL, XLenVT), VL);
5984       SDValue LShr32 =
5985           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5986       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5987 
5988       Results.push_back(
5989           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5990       break;
5991     }
5992     }
5993     break;
5994   }
5995   case ISD::VECREDUCE_ADD:
5996   case ISD::VECREDUCE_AND:
5997   case ISD::VECREDUCE_OR:
5998   case ISD::VECREDUCE_XOR:
5999   case ISD::VECREDUCE_SMAX:
6000   case ISD::VECREDUCE_UMAX:
6001   case ISD::VECREDUCE_SMIN:
6002   case ISD::VECREDUCE_UMIN:
6003     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6004       Results.push_back(V);
6005     break;
6006   case ISD::VP_REDUCE_ADD:
6007   case ISD::VP_REDUCE_AND:
6008   case ISD::VP_REDUCE_OR:
6009   case ISD::VP_REDUCE_XOR:
6010   case ISD::VP_REDUCE_SMAX:
6011   case ISD::VP_REDUCE_UMAX:
6012   case ISD::VP_REDUCE_SMIN:
6013   case ISD::VP_REDUCE_UMIN:
6014     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6015       Results.push_back(V);
6016     break;
6017   case ISD::FLT_ROUNDS_: {
6018     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6019     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6020     Results.push_back(Res.getValue(0));
6021     Results.push_back(Res.getValue(1));
6022     break;
6023   }
6024   }
6025 }
6026 
6027 // A structure to hold one of the bit-manipulation patterns below. Together, a
6028 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6029 //   (or (and (shl x, 1), 0xAAAAAAAA),
6030 //       (and (srl x, 1), 0x55555555))
6031 struct RISCVBitmanipPat {
6032   SDValue Op;
6033   unsigned ShAmt;
6034   bool IsSHL;
6035 
6036   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6037     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6038   }
6039 };
6040 
6041 // Matches patterns of the form
6042 //   (and (shl x, C2), (C1 << C2))
6043 //   (and (srl x, C2), C1)
6044 //   (shl (and x, C1), C2)
6045 //   (srl (and x, (C1 << C2)), C2)
6046 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6047 // The expected masks for each shift amount are specified in BitmanipMasks where
6048 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6049 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6050 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6051 // XLen is 64.
6052 static Optional<RISCVBitmanipPat>
6053 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6054   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6055          "Unexpected number of masks");
6056   Optional<uint64_t> Mask;
6057   // Optionally consume a mask around the shift operation.
6058   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6059     Mask = Op.getConstantOperandVal(1);
6060     Op = Op.getOperand(0);
6061   }
6062   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6063     return None;
6064   bool IsSHL = Op.getOpcode() == ISD::SHL;
6065 
6066   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6067     return None;
6068   uint64_t ShAmt = Op.getConstantOperandVal(1);
6069 
6070   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6071   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6072     return None;
6073   // If we don't have enough masks for 64 bit, then we must be trying to
6074   // match SHFL so we're only allowed to shift 1/4 of the width.
6075   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6076     return None;
6077 
6078   SDValue Src = Op.getOperand(0);
6079 
6080   // The expected mask is shifted left when the AND is found around SHL
6081   // patterns.
6082   //   ((x >> 1) & 0x55555555)
6083   //   ((x << 1) & 0xAAAAAAAA)
6084   bool SHLExpMask = IsSHL;
6085 
6086   if (!Mask) {
6087     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6088     // the mask is all ones: consume that now.
6089     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6090       Mask = Src.getConstantOperandVal(1);
6091       Src = Src.getOperand(0);
6092       // The expected mask is now in fact shifted left for SRL, so reverse the
6093       // decision.
6094       //   ((x & 0xAAAAAAAA) >> 1)
6095       //   ((x & 0x55555555) << 1)
6096       SHLExpMask = !SHLExpMask;
6097     } else {
6098       // Use a default shifted mask of all-ones if there's no AND, truncated
6099       // down to the expected width. This simplifies the logic later on.
6100       Mask = maskTrailingOnes<uint64_t>(Width);
6101       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6102     }
6103   }
6104 
6105   unsigned MaskIdx = Log2_32(ShAmt);
6106   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6107 
6108   if (SHLExpMask)
6109     ExpMask <<= ShAmt;
6110 
6111   if (Mask != ExpMask)
6112     return None;
6113 
6114   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6115 }
6116 
6117 // Matches any of the following bit-manipulation patterns:
6118 //   (and (shl x, 1), (0x55555555 << 1))
6119 //   (and (srl x, 1), 0x55555555)
6120 //   (shl (and x, 0x55555555), 1)
6121 //   (srl (and x, (0x55555555 << 1)), 1)
6122 // where the shift amount and mask may vary thus:
6123 //   [1]  = 0x55555555 / 0xAAAAAAAA
6124 //   [2]  = 0x33333333 / 0xCCCCCCCC
6125 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6126 //   [8]  = 0x00FF00FF / 0xFF00FF00
6127 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6128 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6129 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6130   // These are the unshifted masks which we use to match bit-manipulation
6131   // patterns. They may be shifted left in certain circumstances.
6132   static const uint64_t BitmanipMasks[] = {
6133       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6134       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6135 
6136   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6137 }
6138 
6139 // Match the following pattern as a GREVI(W) operation
6140 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6141 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6142                                const RISCVSubtarget &Subtarget) {
6143   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6144   EVT VT = Op.getValueType();
6145 
6146   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6147     auto LHS = matchGREVIPat(Op.getOperand(0));
6148     auto RHS = matchGREVIPat(Op.getOperand(1));
6149     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6150       SDLoc DL(Op);
6151       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6152                          DAG.getConstant(LHS->ShAmt, DL, VT));
6153     }
6154   }
6155   return SDValue();
6156 }
6157 
6158 // Matches any the following pattern as a GORCI(W) operation
6159 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6160 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6161 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6162 // Note that with the variant of 3.,
6163 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6164 // the inner pattern will first be matched as GREVI and then the outer
6165 // pattern will be matched to GORC via the first rule above.
6166 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6167 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6168                                const RISCVSubtarget &Subtarget) {
6169   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6170   EVT VT = Op.getValueType();
6171 
6172   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6173     SDLoc DL(Op);
6174     SDValue Op0 = Op.getOperand(0);
6175     SDValue Op1 = Op.getOperand(1);
6176 
6177     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6178       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6179           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6180           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6181         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6182       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6183       if ((Reverse.getOpcode() == ISD::ROTL ||
6184            Reverse.getOpcode() == ISD::ROTR) &&
6185           Reverse.getOperand(0) == X &&
6186           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6187         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6188         if (RotAmt == (VT.getSizeInBits() / 2))
6189           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6190                              DAG.getConstant(RotAmt, DL, VT));
6191       }
6192       return SDValue();
6193     };
6194 
6195     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6196     if (SDValue V = MatchOROfReverse(Op0, Op1))
6197       return V;
6198     if (SDValue V = MatchOROfReverse(Op1, Op0))
6199       return V;
6200 
6201     // OR is commutable so canonicalize its OR operand to the left
6202     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6203       std::swap(Op0, Op1);
6204     if (Op0.getOpcode() != ISD::OR)
6205       return SDValue();
6206     SDValue OrOp0 = Op0.getOperand(0);
6207     SDValue OrOp1 = Op0.getOperand(1);
6208     auto LHS = matchGREVIPat(OrOp0);
6209     // OR is commutable so swap the operands and try again: x might have been
6210     // on the left
6211     if (!LHS) {
6212       std::swap(OrOp0, OrOp1);
6213       LHS = matchGREVIPat(OrOp0);
6214     }
6215     auto RHS = matchGREVIPat(Op1);
6216     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6217       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6218                          DAG.getConstant(LHS->ShAmt, DL, VT));
6219     }
6220   }
6221   return SDValue();
6222 }
6223 
6224 // Matches any of the following bit-manipulation patterns:
6225 //   (and (shl x, 1), (0x22222222 << 1))
6226 //   (and (srl x, 1), 0x22222222)
6227 //   (shl (and x, 0x22222222), 1)
6228 //   (srl (and x, (0x22222222 << 1)), 1)
6229 // where the shift amount and mask may vary thus:
6230 //   [1]  = 0x22222222 / 0x44444444
6231 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6232 //   [4]  = 0x00F000F0 / 0x0F000F00
6233 //   [8]  = 0x0000FF00 / 0x00FF0000
6234 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6235 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6236   // These are the unshifted masks which we use to match bit-manipulation
6237   // patterns. They may be shifted left in certain circumstances.
6238   static const uint64_t BitmanipMasks[] = {
6239       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6240       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6241 
6242   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6243 }
6244 
6245 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6246 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6247                                const RISCVSubtarget &Subtarget) {
6248   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6249   EVT VT = Op.getValueType();
6250 
6251   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6252     return SDValue();
6253 
6254   SDValue Op0 = Op.getOperand(0);
6255   SDValue Op1 = Op.getOperand(1);
6256 
6257   // Or is commutable so canonicalize the second OR to the LHS.
6258   if (Op0.getOpcode() != ISD::OR)
6259     std::swap(Op0, Op1);
6260   if (Op0.getOpcode() != ISD::OR)
6261     return SDValue();
6262 
6263   // We found an inner OR, so our operands are the operands of the inner OR
6264   // and the other operand of the outer OR.
6265   SDValue A = Op0.getOperand(0);
6266   SDValue B = Op0.getOperand(1);
6267   SDValue C = Op1;
6268 
6269   auto Match1 = matchSHFLPat(A);
6270   auto Match2 = matchSHFLPat(B);
6271 
6272   // If neither matched, we failed.
6273   if (!Match1 && !Match2)
6274     return SDValue();
6275 
6276   // We had at least one match. if one failed, try the remaining C operand.
6277   if (!Match1) {
6278     std::swap(A, C);
6279     Match1 = matchSHFLPat(A);
6280     if (!Match1)
6281       return SDValue();
6282   } else if (!Match2) {
6283     std::swap(B, C);
6284     Match2 = matchSHFLPat(B);
6285     if (!Match2)
6286       return SDValue();
6287   }
6288   assert(Match1 && Match2);
6289 
6290   // Make sure our matches pair up.
6291   if (!Match1->formsPairWith(*Match2))
6292     return SDValue();
6293 
6294   // All the remains is to make sure C is an AND with the same input, that masks
6295   // out the bits that are being shuffled.
6296   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6297       C.getOperand(0) != Match1->Op)
6298     return SDValue();
6299 
6300   uint64_t Mask = C.getConstantOperandVal(1);
6301 
6302   static const uint64_t BitmanipMasks[] = {
6303       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6304       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6305   };
6306 
6307   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6308   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6309   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6310 
6311   if (Mask != ExpMask)
6312     return SDValue();
6313 
6314   SDLoc DL(Op);
6315   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6316                      DAG.getConstant(Match1->ShAmt, DL, VT));
6317 }
6318 
6319 // Optimize (add (shl x, c0), (shl y, c1)) ->
6320 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6321 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6322                                   const RISCVSubtarget &Subtarget) {
6323   // Perform this optimization only in the zba extension.
6324   if (!Subtarget.hasStdExtZba())
6325     return SDValue();
6326 
6327   // Skip for vector types and larger types.
6328   EVT VT = N->getValueType(0);
6329   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6330     return SDValue();
6331 
6332   // The two operand nodes must be SHL and have no other use.
6333   SDValue N0 = N->getOperand(0);
6334   SDValue N1 = N->getOperand(1);
6335   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6336       !N0->hasOneUse() || !N1->hasOneUse())
6337     return SDValue();
6338 
6339   // Check c0 and c1.
6340   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6341   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6342   if (!N0C || !N1C)
6343     return SDValue();
6344   int64_t C0 = N0C->getSExtValue();
6345   int64_t C1 = N1C->getSExtValue();
6346   if (C0 <= 0 || C1 <= 0)
6347     return SDValue();
6348 
6349   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6350   int64_t Bits = std::min(C0, C1);
6351   int64_t Diff = std::abs(C0 - C1);
6352   if (Diff != 1 && Diff != 2 && Diff != 3)
6353     return SDValue();
6354 
6355   // Build nodes.
6356   SDLoc DL(N);
6357   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6358   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6359   SDValue NA0 =
6360       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6361   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6362   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6363 }
6364 
6365 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6366 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6367 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6368 // not undo itself, but they are redundant.
6369 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6370   SDValue Src = N->getOperand(0);
6371 
6372   if (Src.getOpcode() != N->getOpcode())
6373     return SDValue();
6374 
6375   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6376       !isa<ConstantSDNode>(Src.getOperand(1)))
6377     return SDValue();
6378 
6379   unsigned ShAmt1 = N->getConstantOperandVal(1);
6380   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6381   Src = Src.getOperand(0);
6382 
6383   unsigned CombinedShAmt;
6384   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6385     CombinedShAmt = ShAmt1 | ShAmt2;
6386   else
6387     CombinedShAmt = ShAmt1 ^ ShAmt2;
6388 
6389   if (CombinedShAmt == 0)
6390     return Src;
6391 
6392   SDLoc DL(N);
6393   return DAG.getNode(
6394       N->getOpcode(), DL, N->getValueType(0), Src,
6395       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6396 }
6397 
6398 // Combine a constant select operand into its use:
6399 //
6400 // (and (select cond, -1, c), x)
6401 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6402 // (or  (select cond, 0, c), x)
6403 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6404 // (xor (select cond, 0, c), x)
6405 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6406 // (add (select cond, 0, c), x)
6407 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6408 // (sub x, (select cond, 0, c))
6409 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6410 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6411                                    SelectionDAG &DAG, bool AllOnes) {
6412   EVT VT = N->getValueType(0);
6413 
6414   // Skip vectors.
6415   if (VT.isVector())
6416     return SDValue();
6417 
6418   if ((Slct.getOpcode() != ISD::SELECT &&
6419        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6420       !Slct.hasOneUse())
6421     return SDValue();
6422 
6423   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6424     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6425   };
6426 
6427   bool SwapSelectOps;
6428   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6429   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6430   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6431   SDValue NonConstantVal;
6432   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6433     SwapSelectOps = false;
6434     NonConstantVal = FalseVal;
6435   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6436     SwapSelectOps = true;
6437     NonConstantVal = TrueVal;
6438   } else
6439     return SDValue();
6440 
6441   // Slct is now know to be the desired identity constant when CC is true.
6442   TrueVal = OtherOp;
6443   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6444   // Unless SwapSelectOps says the condition should be false.
6445   if (SwapSelectOps)
6446     std::swap(TrueVal, FalseVal);
6447 
6448   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6449     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6450                        {Slct.getOperand(0), Slct.getOperand(1),
6451                         Slct.getOperand(2), TrueVal, FalseVal});
6452 
6453   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6454                      {Slct.getOperand(0), TrueVal, FalseVal});
6455 }
6456 
6457 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6458 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6459                                               bool AllOnes) {
6460   SDValue N0 = N->getOperand(0);
6461   SDValue N1 = N->getOperand(1);
6462   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6463     return Result;
6464   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6465     return Result;
6466   return SDValue();
6467 }
6468 
6469 // Transform (add (mul x, c0), c1) ->
6470 //           (add (mul (add x, c1/c0), c0), c1%c0).
6471 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6472 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6473 // to an infinite loop in DAGCombine if transformed.
6474 // Or transform (add (mul x, c0), c1) ->
6475 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6476 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6477 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6478 // lead to an infinite loop in DAGCombine if transformed.
6479 // Or transform (add (mul x, c0), c1) ->
6480 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6481 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6482 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6483 // lead to an infinite loop in DAGCombine if transformed.
6484 // Or transform (add (mul x, c0), c1) ->
6485 //              (mul (add x, c1/c0), c0).
6486 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6487 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6488                                      const RISCVSubtarget &Subtarget) {
6489   // Skip for vector types and larger types.
6490   EVT VT = N->getValueType(0);
6491   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6492     return SDValue();
6493   // The first operand node must be a MUL and has no other use.
6494   SDValue N0 = N->getOperand(0);
6495   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6496     return SDValue();
6497   // Check if c0 and c1 match above conditions.
6498   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6499   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6500   if (!N0C || !N1C)
6501     return SDValue();
6502   int64_t C0 = N0C->getSExtValue();
6503   int64_t C1 = N1C->getSExtValue();
6504   int64_t CA, CB;
6505   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6506     return SDValue();
6507   // Search for proper CA (non-zero) and CB that both are simm12.
6508   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6509       !isInt<12>(C0 * (C1 / C0))) {
6510     CA = C1 / C0;
6511     CB = C1 % C0;
6512   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6513              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6514     CA = C1 / C0 + 1;
6515     CB = C1 % C0 - C0;
6516   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6517              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6518     CA = C1 / C0 - 1;
6519     CB = C1 % C0 + C0;
6520   } else
6521     return SDValue();
6522   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6523   SDLoc DL(N);
6524   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6525                              DAG.getConstant(CA, DL, VT));
6526   SDValue New1 =
6527       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6528   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6529 }
6530 
6531 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6532                                  const RISCVSubtarget &Subtarget) {
6533   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6534     return V;
6535   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6536     return V;
6537   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6538   //      (select lhs, rhs, cc, x, (add x, y))
6539   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6540 }
6541 
6542 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6543   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6544   //      (select lhs, rhs, cc, x, (sub x, y))
6545   SDValue N0 = N->getOperand(0);
6546   SDValue N1 = N->getOperand(1);
6547   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6548 }
6549 
6550 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6551   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6552   //      (select lhs, rhs, cc, x, (and x, y))
6553   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6554 }
6555 
6556 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6557                                 const RISCVSubtarget &Subtarget) {
6558   if (Subtarget.hasStdExtZbp()) {
6559     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6560       return GREV;
6561     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6562       return GORC;
6563     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6564       return SHFL;
6565   }
6566 
6567   // fold (or (select cond, 0, y), x) ->
6568   //      (select cond, x, (or x, y))
6569   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6570 }
6571 
6572 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6573   // fold (xor (select cond, 0, y), x) ->
6574   //      (select cond, x, (xor x, y))
6575   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6576 }
6577 
6578 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6579 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6580 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6581 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6582 // ADDW/SUBW/MULW.
6583 static SDValue performANY_EXTENDCombine(SDNode *N,
6584                                         TargetLowering::DAGCombinerInfo &DCI,
6585                                         const RISCVSubtarget &Subtarget) {
6586   if (!Subtarget.is64Bit())
6587     return SDValue();
6588 
6589   SelectionDAG &DAG = DCI.DAG;
6590 
6591   SDValue Src = N->getOperand(0);
6592   EVT VT = N->getValueType(0);
6593   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6594     return SDValue();
6595 
6596   // The opcode must be one that can implicitly sign_extend.
6597   // FIXME: Additional opcodes.
6598   switch (Src.getOpcode()) {
6599   default:
6600     return SDValue();
6601   case ISD::MUL:
6602     if (!Subtarget.hasStdExtM())
6603       return SDValue();
6604     LLVM_FALLTHROUGH;
6605   case ISD::ADD:
6606   case ISD::SUB:
6607     break;
6608   }
6609 
6610   // Only handle cases where the result is used by a CopyToReg. That likely
6611   // means the value is a liveout of the basic block. This helps prevent
6612   // infinite combine loops like PR51206.
6613   if (none_of(N->uses(),
6614               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6615     return SDValue();
6616 
6617   SmallVector<SDNode *, 4> SetCCs;
6618   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6619                             UE = Src.getNode()->use_end();
6620        UI != UE; ++UI) {
6621     SDNode *User = *UI;
6622     if (User == N)
6623       continue;
6624     if (UI.getUse().getResNo() != Src.getResNo())
6625       continue;
6626     // All i32 setccs are legalized by sign extending operands.
6627     if (User->getOpcode() == ISD::SETCC) {
6628       SetCCs.push_back(User);
6629       continue;
6630     }
6631     // We don't know if we can extend this user.
6632     break;
6633   }
6634 
6635   // If we don't have any SetCCs, this isn't worthwhile.
6636   if (SetCCs.empty())
6637     return SDValue();
6638 
6639   SDLoc DL(N);
6640   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6641   DCI.CombineTo(N, SExt);
6642 
6643   // Promote all the setccs.
6644   for (SDNode *SetCC : SetCCs) {
6645     SmallVector<SDValue, 4> Ops;
6646 
6647     for (unsigned j = 0; j != 2; ++j) {
6648       SDValue SOp = SetCC->getOperand(j);
6649       if (SOp == Src)
6650         Ops.push_back(SExt);
6651       else
6652         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6653     }
6654 
6655     Ops.push_back(SetCC->getOperand(2));
6656     DCI.CombineTo(SetCC,
6657                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6658   }
6659   return SDValue(N, 0);
6660 }
6661 
6662 // Try to form VWMUL or VWMULU.
6663 // FIXME: Support VWMULSU.
6664 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6665                                     SelectionDAG &DAG) {
6666   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6667   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6668   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6669   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6670     return SDValue();
6671 
6672   SDValue Mask = N->getOperand(2);
6673   SDValue VL = N->getOperand(3);
6674 
6675   // Make sure the mask and VL match.
6676   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6677     return SDValue();
6678 
6679   MVT VT = N->getSimpleValueType(0);
6680 
6681   // Determine the narrow size for a widening multiply.
6682   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6683   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6684                                   VT.getVectorElementCount());
6685 
6686   SDLoc DL(N);
6687 
6688   // See if the other operand is the same opcode.
6689   if (Op0.getOpcode() == Op1.getOpcode()) {
6690     if (!Op1.hasOneUse())
6691       return SDValue();
6692 
6693     // Make sure the mask and VL match.
6694     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6695       return SDValue();
6696 
6697     Op1 = Op1.getOperand(0);
6698   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6699     // The operand is a splat of a scalar.
6700 
6701     // The VL must be the same.
6702     if (Op1.getOperand(1) != VL)
6703       return SDValue();
6704 
6705     // Get the scalar value.
6706     Op1 = Op1.getOperand(0);
6707 
6708     // See if have enough sign bits or zero bits in the scalar to use a
6709     // widening multiply by splatting to smaller element size.
6710     unsigned EltBits = VT.getScalarSizeInBits();
6711     unsigned ScalarBits = Op1.getValueSizeInBits();
6712     // Make sure we're getting all element bits from the scalar register.
6713     // FIXME: Support implicit sign extension of vmv.v.x?
6714     if (ScalarBits < EltBits)
6715       return SDValue();
6716 
6717     if (IsSignExt) {
6718       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6719         return SDValue();
6720     } else {
6721       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
6722       if (!DAG.MaskedValueIsZero(Op1, Mask))
6723         return SDValue();
6724     }
6725 
6726     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
6727   } else
6728     return SDValue();
6729 
6730   Op0 = Op0.getOperand(0);
6731 
6732   // Re-introduce narrower extends if needed.
6733   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6734   if (Op0.getValueType() != NarrowVT)
6735     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6736   if (Op1.getValueType() != NarrowVT)
6737     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6738 
6739   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6740   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6741 }
6742 
6743 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6744                                                DAGCombinerInfo &DCI) const {
6745   SelectionDAG &DAG = DCI.DAG;
6746 
6747   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6748   // bits are demanded. N will be added to the Worklist if it was not deleted.
6749   // Caller should return SDValue(N, 0) if this returns true.
6750   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6751     SDValue Op = N->getOperand(OpNo);
6752     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6753     if (!SimplifyDemandedBits(Op, Mask, DCI))
6754       return false;
6755 
6756     if (N->getOpcode() != ISD::DELETED_NODE)
6757       DCI.AddToWorklist(N);
6758     return true;
6759   };
6760 
6761   switch (N->getOpcode()) {
6762   default:
6763     break;
6764   case RISCVISD::SplitF64: {
6765     SDValue Op0 = N->getOperand(0);
6766     // If the input to SplitF64 is just BuildPairF64 then the operation is
6767     // redundant. Instead, use BuildPairF64's operands directly.
6768     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6769       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6770 
6771     SDLoc DL(N);
6772 
6773     // It's cheaper to materialise two 32-bit integers than to load a double
6774     // from the constant pool and transfer it to integer registers through the
6775     // stack.
6776     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6777       APInt V = C->getValueAPF().bitcastToAPInt();
6778       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6779       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6780       return DCI.CombineTo(N, Lo, Hi);
6781     }
6782 
6783     // This is a target-specific version of a DAGCombine performed in
6784     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6785     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6786     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6787     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6788         !Op0.getNode()->hasOneUse())
6789       break;
6790     SDValue NewSplitF64 =
6791         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6792                     Op0.getOperand(0));
6793     SDValue Lo = NewSplitF64.getValue(0);
6794     SDValue Hi = NewSplitF64.getValue(1);
6795     APInt SignBit = APInt::getSignMask(32);
6796     if (Op0.getOpcode() == ISD::FNEG) {
6797       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6798                                   DAG.getConstant(SignBit, DL, MVT::i32));
6799       return DCI.CombineTo(N, Lo, NewHi);
6800     }
6801     assert(Op0.getOpcode() == ISD::FABS);
6802     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6803                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6804     return DCI.CombineTo(N, Lo, NewHi);
6805   }
6806   case RISCVISD::SLLW:
6807   case RISCVISD::SRAW:
6808   case RISCVISD::SRLW:
6809   case RISCVISD::ROLW:
6810   case RISCVISD::RORW: {
6811     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6812     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6813         SimplifyDemandedLowBitsHelper(1, 5))
6814       return SDValue(N, 0);
6815     break;
6816   }
6817   case RISCVISD::CLZW:
6818   case RISCVISD::CTZW: {
6819     // Only the lower 32 bits of the first operand are read
6820     if (SimplifyDemandedLowBitsHelper(0, 32))
6821       return SDValue(N, 0);
6822     break;
6823   }
6824   case RISCVISD::FSL:
6825   case RISCVISD::FSR: {
6826     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6827     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6828     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6829     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6830       return SDValue(N, 0);
6831     break;
6832   }
6833   case RISCVISD::FSLW:
6834   case RISCVISD::FSRW: {
6835     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6836     // read.
6837     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6838         SimplifyDemandedLowBitsHelper(1, 32) ||
6839         SimplifyDemandedLowBitsHelper(2, 6))
6840       return SDValue(N, 0);
6841     break;
6842   }
6843   case RISCVISD::GREV:
6844   case RISCVISD::GORC: {
6845     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6846     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6847     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6848     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6849       return SDValue(N, 0);
6850 
6851     return combineGREVI_GORCI(N, DCI.DAG);
6852   }
6853   case RISCVISD::GREVW:
6854   case RISCVISD::GORCW: {
6855     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6856     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6857         SimplifyDemandedLowBitsHelper(1, 5))
6858       return SDValue(N, 0);
6859 
6860     return combineGREVI_GORCI(N, DCI.DAG);
6861   }
6862   case RISCVISD::SHFL:
6863   case RISCVISD::UNSHFL: {
6864     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6865     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6866     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6867     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6868       return SDValue(N, 0);
6869 
6870     break;
6871   }
6872   case RISCVISD::SHFLW:
6873   case RISCVISD::UNSHFLW: {
6874     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6875     SDValue LHS = N->getOperand(0);
6876     SDValue RHS = N->getOperand(1);
6877     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6878     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6879     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6880         SimplifyDemandedLowBitsHelper(1, 4))
6881       return SDValue(N, 0);
6882 
6883     break;
6884   }
6885   case RISCVISD::BCOMPRESSW:
6886   case RISCVISD::BDECOMPRESSW: {
6887     // Only the lower 32 bits of LHS and RHS are read.
6888     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6889         SimplifyDemandedLowBitsHelper(1, 32))
6890       return SDValue(N, 0);
6891 
6892     break;
6893   }
6894   case RISCVISD::FMV_X_ANYEXTH:
6895   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6896     SDLoc DL(N);
6897     SDValue Op0 = N->getOperand(0);
6898     MVT VT = N->getSimpleValueType(0);
6899     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6900     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6901     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6902     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6903          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6904         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6905          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6906       assert(Op0.getOperand(0).getValueType() == VT &&
6907              "Unexpected value type!");
6908       return Op0.getOperand(0);
6909     }
6910 
6911     // This is a target-specific version of a DAGCombine performed in
6912     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6913     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6914     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6915     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6916         !Op0.getNode()->hasOneUse())
6917       break;
6918     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6919     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6920     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6921     if (Op0.getOpcode() == ISD::FNEG)
6922       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6923                          DAG.getConstant(SignBit, DL, VT));
6924 
6925     assert(Op0.getOpcode() == ISD::FABS);
6926     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6927                        DAG.getConstant(~SignBit, DL, VT));
6928   }
6929   case ISD::ADD:
6930     return performADDCombine(N, DAG, Subtarget);
6931   case ISD::SUB:
6932     return performSUBCombine(N, DAG);
6933   case ISD::AND:
6934     return performANDCombine(N, DAG);
6935   case ISD::OR:
6936     return performORCombine(N, DAG, Subtarget);
6937   case ISD::XOR:
6938     return performXORCombine(N, DAG);
6939   case ISD::ANY_EXTEND:
6940     return performANY_EXTENDCombine(N, DCI, Subtarget);
6941   case ISD::ZERO_EXTEND:
6942     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6943     // type legalization. This is safe because fp_to_uint produces poison if
6944     // it overflows.
6945     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6946         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6947         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6948       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6949                          N->getOperand(0).getOperand(0));
6950     return SDValue();
6951   case RISCVISD::SELECT_CC: {
6952     // Transform
6953     SDValue LHS = N->getOperand(0);
6954     SDValue RHS = N->getOperand(1);
6955     SDValue TrueV = N->getOperand(3);
6956     SDValue FalseV = N->getOperand(4);
6957 
6958     // If the True and False values are the same, we don't need a select_cc.
6959     if (TrueV == FalseV)
6960       return TrueV;
6961 
6962     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6963     if (!ISD::isIntEqualitySetCC(CCVal))
6964       break;
6965 
6966     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6967     //      (select_cc X, Y, lt, trueV, falseV)
6968     // Sometimes the setcc is introduced after select_cc has been formed.
6969     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6970         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6971       // If we're looking for eq 0 instead of ne 0, we need to invert the
6972       // condition.
6973       bool Invert = CCVal == ISD::SETEQ;
6974       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6975       if (Invert)
6976         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6977 
6978       SDLoc DL(N);
6979       RHS = LHS.getOperand(1);
6980       LHS = LHS.getOperand(0);
6981       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6982 
6983       SDValue TargetCC = DAG.getCondCode(CCVal);
6984       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6985                          {LHS, RHS, TargetCC, TrueV, FalseV});
6986     }
6987 
6988     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6989     //      (select_cc X, Y, eq/ne, trueV, falseV)
6990     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6991       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6992                          {LHS.getOperand(0), LHS.getOperand(1),
6993                           N->getOperand(2), TrueV, FalseV});
6994     // (select_cc X, 1, setne, trueV, falseV) ->
6995     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6996     // This can occur when legalizing some floating point comparisons.
6997     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6998     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6999       SDLoc DL(N);
7000       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7001       SDValue TargetCC = DAG.getCondCode(CCVal);
7002       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7003       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7004                          {LHS, RHS, TargetCC, TrueV, FalseV});
7005     }
7006 
7007     break;
7008   }
7009   case RISCVISD::BR_CC: {
7010     SDValue LHS = N->getOperand(1);
7011     SDValue RHS = N->getOperand(2);
7012     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7013     if (!ISD::isIntEqualitySetCC(CCVal))
7014       break;
7015 
7016     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7017     //      (br_cc X, Y, lt, dest)
7018     // Sometimes the setcc is introduced after br_cc has been formed.
7019     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7020         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7021       // If we're looking for eq 0 instead of ne 0, we need to invert the
7022       // condition.
7023       bool Invert = CCVal == ISD::SETEQ;
7024       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7025       if (Invert)
7026         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7027 
7028       SDLoc DL(N);
7029       RHS = LHS.getOperand(1);
7030       LHS = LHS.getOperand(0);
7031       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7032 
7033       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7034                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7035                          N->getOperand(4));
7036     }
7037 
7038     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7039     //      (br_cc X, Y, eq/ne, trueV, falseV)
7040     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7041       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7042                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7043                          N->getOperand(3), N->getOperand(4));
7044 
7045     // (br_cc X, 1, setne, br_cc) ->
7046     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7047     // This can occur when legalizing some floating point comparisons.
7048     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7049     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7050       SDLoc DL(N);
7051       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7052       SDValue TargetCC = DAG.getCondCode(CCVal);
7053       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7054       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7055                          N->getOperand(0), LHS, RHS, TargetCC,
7056                          N->getOperand(4));
7057     }
7058     break;
7059   }
7060   case ISD::FCOPYSIGN: {
7061     EVT VT = N->getValueType(0);
7062     if (!VT.isVector())
7063       break;
7064     // There is a form of VFSGNJ which injects the negated sign of its second
7065     // operand. Try and bubble any FNEG up after the extend/round to produce
7066     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7067     // TRUNC=1.
7068     SDValue In2 = N->getOperand(1);
7069     // Avoid cases where the extend/round has multiple uses, as duplicating
7070     // those is typically more expensive than removing a fneg.
7071     if (!In2.hasOneUse())
7072       break;
7073     if (In2.getOpcode() != ISD::FP_EXTEND &&
7074         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7075       break;
7076     In2 = In2.getOperand(0);
7077     if (In2.getOpcode() != ISD::FNEG)
7078       break;
7079     SDLoc DL(N);
7080     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7081     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7082                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7083   }
7084   case ISD::MGATHER:
7085   case ISD::MSCATTER:
7086   case ISD::VP_GATHER:
7087   case ISD::VP_SCATTER: {
7088     if (!DCI.isBeforeLegalize())
7089       break;
7090     SDValue Index, ScaleOp;
7091     bool IsIndexScaled = false;
7092     bool IsIndexSigned = false;
7093     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7094       Index = VPGSN->getIndex();
7095       ScaleOp = VPGSN->getScale();
7096       IsIndexScaled = VPGSN->isIndexScaled();
7097       IsIndexSigned = VPGSN->isIndexSigned();
7098     } else {
7099       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7100       Index = MGSN->getIndex();
7101       ScaleOp = MGSN->getScale();
7102       IsIndexScaled = MGSN->isIndexScaled();
7103       IsIndexSigned = MGSN->isIndexSigned();
7104     }
7105     EVT IndexVT = Index.getValueType();
7106     MVT XLenVT = Subtarget.getXLenVT();
7107     // RISCV indexed loads only support the "unsigned unscaled" addressing
7108     // mode, so anything else must be manually legalized.
7109     bool NeedsIdxLegalization =
7110         IsIndexScaled ||
7111         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7112     if (!NeedsIdxLegalization)
7113       break;
7114 
7115     SDLoc DL(N);
7116 
7117     // Any index legalization should first promote to XLenVT, so we don't lose
7118     // bits when scaling. This may create an illegal index type so we let
7119     // LLVM's legalization take care of the splitting.
7120     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7121     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7122       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7123       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7124                           DL, IndexVT, Index);
7125     }
7126 
7127     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7128     if (IsIndexScaled && Scale != 1) {
7129       // Manually scale the indices by the element size.
7130       // TODO: Sanitize the scale operand here?
7131       // TODO: For VP nodes, should we use VP_SHL here?
7132       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7133       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7134       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7135     }
7136 
7137     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7138     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7139       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7140                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7141                               VPGN->getScale(), VPGN->getMask(),
7142                               VPGN->getVectorLength()},
7143                              VPGN->getMemOperand(), NewIndexTy);
7144     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7145       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7146                               {VPSN->getChain(), VPSN->getValue(),
7147                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7148                                VPSN->getMask(), VPSN->getVectorLength()},
7149                               VPSN->getMemOperand(), NewIndexTy);
7150     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7151       return DAG.getMaskedGather(
7152           N->getVTList(), MGN->getMemoryVT(), DL,
7153           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7154            MGN->getBasePtr(), Index, MGN->getScale()},
7155           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7156     const auto *MSN = cast<MaskedScatterSDNode>(N);
7157     return DAG.getMaskedScatter(
7158         N->getVTList(), MSN->getMemoryVT(), DL,
7159         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7160          Index, MSN->getScale()},
7161         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7162   }
7163   case RISCVISD::SRA_VL:
7164   case RISCVISD::SRL_VL:
7165   case RISCVISD::SHL_VL: {
7166     SDValue ShAmt = N->getOperand(1);
7167     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7168       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7169       SDLoc DL(N);
7170       SDValue VL = N->getOperand(3);
7171       EVT VT = N->getValueType(0);
7172       ShAmt =
7173           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7174       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7175                          N->getOperand(2), N->getOperand(3));
7176     }
7177     break;
7178   }
7179   case ISD::SRA:
7180   case ISD::SRL:
7181   case ISD::SHL: {
7182     SDValue ShAmt = N->getOperand(1);
7183     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7184       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7185       SDLoc DL(N);
7186       EVT VT = N->getValueType(0);
7187       ShAmt =
7188           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7189       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7190     }
7191     break;
7192   }
7193   case RISCVISD::MUL_VL: {
7194     SDValue Op0 = N->getOperand(0);
7195     SDValue Op1 = N->getOperand(1);
7196     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7197       return V;
7198     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7199       return V;
7200     return SDValue();
7201   }
7202   case ISD::STORE: {
7203     auto *Store = cast<StoreSDNode>(N);
7204     SDValue Val = Store->getValue();
7205     // Combine store of vmv.x.s to vse with VL of 1.
7206     // FIXME: Support FP.
7207     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7208       SDValue Src = Val.getOperand(0);
7209       EVT VecVT = Src.getValueType();
7210       EVT MemVT = Store->getMemoryVT();
7211       // The memory VT and the element type must match.
7212       if (VecVT.getVectorElementType() == MemVT) {
7213         SDLoc DL(N);
7214         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7215         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7216                               DAG.getConstant(1, DL, MaskVT),
7217                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7218                               Store->getPointerInfo(),
7219                               Store->getOriginalAlign(),
7220                               Store->getMemOperand()->getFlags());
7221       }
7222     }
7223 
7224     break;
7225   }
7226   }
7227 
7228   return SDValue();
7229 }
7230 
7231 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7232     const SDNode *N, CombineLevel Level) const {
7233   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7234   // materialised in fewer instructions than `(OP _, c1)`:
7235   //
7236   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7237   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7238   SDValue N0 = N->getOperand(0);
7239   EVT Ty = N0.getValueType();
7240   if (Ty.isScalarInteger() &&
7241       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7242     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7243     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7244     if (C1 && C2) {
7245       const APInt &C1Int = C1->getAPIntValue();
7246       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7247 
7248       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7249       // and the combine should happen, to potentially allow further combines
7250       // later.
7251       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7252           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7253         return true;
7254 
7255       // We can materialise `c1` in an add immediate, so it's "free", and the
7256       // combine should be prevented.
7257       if (C1Int.getMinSignedBits() <= 64 &&
7258           isLegalAddImmediate(C1Int.getSExtValue()))
7259         return false;
7260 
7261       // Neither constant will fit into an immediate, so find materialisation
7262       // costs.
7263       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7264                                               Subtarget.getFeatureBits(),
7265                                               /*CompressionCost*/true);
7266       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7267           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7268           /*CompressionCost*/true);
7269 
7270       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7271       // combine should be prevented.
7272       if (C1Cost < ShiftedC1Cost)
7273         return false;
7274     }
7275   }
7276   return true;
7277 }
7278 
7279 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7280     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7281     TargetLoweringOpt &TLO) const {
7282   // Delay this optimization as late as possible.
7283   if (!TLO.LegalOps)
7284     return false;
7285 
7286   EVT VT = Op.getValueType();
7287   if (VT.isVector())
7288     return false;
7289 
7290   // Only handle AND for now.
7291   if (Op.getOpcode() != ISD::AND)
7292     return false;
7293 
7294   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7295   if (!C)
7296     return false;
7297 
7298   const APInt &Mask = C->getAPIntValue();
7299 
7300   // Clear all non-demanded bits initially.
7301   APInt ShrunkMask = Mask & DemandedBits;
7302 
7303   // Try to make a smaller immediate by setting undemanded bits.
7304 
7305   APInt ExpandedMask = Mask | ~DemandedBits;
7306 
7307   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7308     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7309   };
7310   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7311     if (NewMask == Mask)
7312       return true;
7313     SDLoc DL(Op);
7314     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7315     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7316     return TLO.CombineTo(Op, NewOp);
7317   };
7318 
7319   // If the shrunk mask fits in sign extended 12 bits, let the target
7320   // independent code apply it.
7321   if (ShrunkMask.isSignedIntN(12))
7322     return false;
7323 
7324   // Preserve (and X, 0xffff) when zext.h is supported.
7325   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7326     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7327     if (IsLegalMask(NewMask))
7328       return UseMask(NewMask);
7329   }
7330 
7331   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7332   if (VT == MVT::i64) {
7333     APInt NewMask = APInt(64, 0xffffffff);
7334     if (IsLegalMask(NewMask))
7335       return UseMask(NewMask);
7336   }
7337 
7338   // For the remaining optimizations, we need to be able to make a negative
7339   // number through a combination of mask and undemanded bits.
7340   if (!ExpandedMask.isNegative())
7341     return false;
7342 
7343   // What is the fewest number of bits we need to represent the negative number.
7344   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7345 
7346   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7347   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7348   APInt NewMask = ShrunkMask;
7349   if (MinSignedBits <= 12)
7350     NewMask.setBitsFrom(11);
7351   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7352     NewMask.setBitsFrom(31);
7353   else
7354     return false;
7355 
7356   // Sanity check that our new mask is a subset of the demanded mask.
7357   assert(IsLegalMask(NewMask));
7358   return UseMask(NewMask);
7359 }
7360 
7361 static void computeGREV(APInt &Src, unsigned ShAmt) {
7362   ShAmt &= Src.getBitWidth() - 1;
7363   uint64_t x = Src.getZExtValue();
7364   if (ShAmt & 1)
7365     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7366   if (ShAmt & 2)
7367     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7368   if (ShAmt & 4)
7369     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7370   if (ShAmt & 8)
7371     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7372   if (ShAmt & 16)
7373     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7374   if (ShAmt & 32)
7375     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7376   Src = x;
7377 }
7378 
7379 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7380                                                         KnownBits &Known,
7381                                                         const APInt &DemandedElts,
7382                                                         const SelectionDAG &DAG,
7383                                                         unsigned Depth) const {
7384   unsigned BitWidth = Known.getBitWidth();
7385   unsigned Opc = Op.getOpcode();
7386   assert((Opc >= ISD::BUILTIN_OP_END ||
7387           Opc == ISD::INTRINSIC_WO_CHAIN ||
7388           Opc == ISD::INTRINSIC_W_CHAIN ||
7389           Opc == ISD::INTRINSIC_VOID) &&
7390          "Should use MaskedValueIsZero if you don't know whether Op"
7391          " is a target node!");
7392 
7393   Known.resetAll();
7394   switch (Opc) {
7395   default: break;
7396   case RISCVISD::SELECT_CC: {
7397     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7398     // If we don't know any bits, early out.
7399     if (Known.isUnknown())
7400       break;
7401     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7402 
7403     // Only known if known in both the LHS and RHS.
7404     Known = KnownBits::commonBits(Known, Known2);
7405     break;
7406   }
7407   case RISCVISD::REMUW: {
7408     KnownBits Known2;
7409     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7410     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7411     // We only care about the lower 32 bits.
7412     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7413     // Restore the original width by sign extending.
7414     Known = Known.sext(BitWidth);
7415     break;
7416   }
7417   case RISCVISD::DIVUW: {
7418     KnownBits Known2;
7419     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7420     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7421     // We only care about the lower 32 bits.
7422     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7423     // Restore the original width by sign extending.
7424     Known = Known.sext(BitWidth);
7425     break;
7426   }
7427   case RISCVISD::CTZW: {
7428     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7429     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7430     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7431     Known.Zero.setBitsFrom(LowBits);
7432     break;
7433   }
7434   case RISCVISD::CLZW: {
7435     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7436     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7437     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7438     Known.Zero.setBitsFrom(LowBits);
7439     break;
7440   }
7441   case RISCVISD::GREV:
7442   case RISCVISD::GREVW: {
7443     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7444       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7445       if (Opc == RISCVISD::GREVW)
7446         Known = Known.trunc(32);
7447       unsigned ShAmt = C->getZExtValue();
7448       computeGREV(Known.Zero, ShAmt);
7449       computeGREV(Known.One, ShAmt);
7450       if (Opc == RISCVISD::GREVW)
7451         Known = Known.sext(BitWidth);
7452     }
7453     break;
7454   }
7455   case RISCVISD::READ_VLENB:
7456     // We assume VLENB is at least 16 bytes.
7457     Known.Zero.setLowBits(4);
7458     // We assume VLENB is no more than 65536 / 8 bytes.
7459     Known.Zero.setBitsFrom(14);
7460     break;
7461   case ISD::INTRINSIC_W_CHAIN: {
7462     unsigned IntNo = Op.getConstantOperandVal(1);
7463     switch (IntNo) {
7464     default:
7465       // We can't do anything for most intrinsics.
7466       break;
7467     case Intrinsic::riscv_vsetvli:
7468     case Intrinsic::riscv_vsetvlimax:
7469       // Assume that VL output is positive and would fit in an int32_t.
7470       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7471       if (BitWidth >= 32)
7472         Known.Zero.setBitsFrom(31);
7473       break;
7474     }
7475     break;
7476   }
7477   }
7478 }
7479 
7480 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7481     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7482     unsigned Depth) const {
7483   switch (Op.getOpcode()) {
7484   default:
7485     break;
7486   case RISCVISD::SELECT_CC: {
7487     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7488     if (Tmp == 1) return 1;  // Early out.
7489     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7490     return std::min(Tmp, Tmp2);
7491   }
7492   case RISCVISD::SLLW:
7493   case RISCVISD::SRAW:
7494   case RISCVISD::SRLW:
7495   case RISCVISD::DIVW:
7496   case RISCVISD::DIVUW:
7497   case RISCVISD::REMUW:
7498   case RISCVISD::ROLW:
7499   case RISCVISD::RORW:
7500   case RISCVISD::GREVW:
7501   case RISCVISD::GORCW:
7502   case RISCVISD::FSLW:
7503   case RISCVISD::FSRW:
7504   case RISCVISD::SHFLW:
7505   case RISCVISD::UNSHFLW:
7506   case RISCVISD::BCOMPRESSW:
7507   case RISCVISD::BDECOMPRESSW:
7508   case RISCVISD::FCVT_W_RTZ_RV64:
7509   case RISCVISD::FCVT_WU_RTZ_RV64:
7510     // TODO: As the result is sign-extended, this is conservatively correct. A
7511     // more precise answer could be calculated for SRAW depending on known
7512     // bits in the shift amount.
7513     return 33;
7514   case RISCVISD::SHFL:
7515   case RISCVISD::UNSHFL: {
7516     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7517     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7518     // will stay within the upper 32 bits. If there were more than 32 sign bits
7519     // before there will be at least 33 sign bits after.
7520     if (Op.getValueType() == MVT::i64 &&
7521         isa<ConstantSDNode>(Op.getOperand(1)) &&
7522         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7523       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7524       if (Tmp > 32)
7525         return 33;
7526     }
7527     break;
7528   }
7529   case RISCVISD::VMV_X_S:
7530     // The number of sign bits of the scalar result is computed by obtaining the
7531     // element type of the input vector operand, subtracting its width from the
7532     // XLEN, and then adding one (sign bit within the element type). If the
7533     // element type is wider than XLen, the least-significant XLEN bits are
7534     // taken.
7535     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7536       return 1;
7537     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7538   }
7539 
7540   return 1;
7541 }
7542 
7543 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7544                                                   MachineBasicBlock *BB) {
7545   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7546 
7547   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7548   // Should the count have wrapped while it was being read, we need to try
7549   // again.
7550   // ...
7551   // read:
7552   // rdcycleh x3 # load high word of cycle
7553   // rdcycle  x2 # load low word of cycle
7554   // rdcycleh x4 # load high word of cycle
7555   // bne x3, x4, read # check if high word reads match, otherwise try again
7556   // ...
7557 
7558   MachineFunction &MF = *BB->getParent();
7559   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7560   MachineFunction::iterator It = ++BB->getIterator();
7561 
7562   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7563   MF.insert(It, LoopMBB);
7564 
7565   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7566   MF.insert(It, DoneMBB);
7567 
7568   // Transfer the remainder of BB and its successor edges to DoneMBB.
7569   DoneMBB->splice(DoneMBB->begin(), BB,
7570                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7571   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7572 
7573   BB->addSuccessor(LoopMBB);
7574 
7575   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7576   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7577   Register LoReg = MI.getOperand(0).getReg();
7578   Register HiReg = MI.getOperand(1).getReg();
7579   DebugLoc DL = MI.getDebugLoc();
7580 
7581   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7582   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7583       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7584       .addReg(RISCV::X0);
7585   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7586       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7587       .addReg(RISCV::X0);
7588   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7589       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7590       .addReg(RISCV::X0);
7591 
7592   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7593       .addReg(HiReg)
7594       .addReg(ReadAgainReg)
7595       .addMBB(LoopMBB);
7596 
7597   LoopMBB->addSuccessor(LoopMBB);
7598   LoopMBB->addSuccessor(DoneMBB);
7599 
7600   MI.eraseFromParent();
7601 
7602   return DoneMBB;
7603 }
7604 
7605 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7606                                              MachineBasicBlock *BB) {
7607   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7608 
7609   MachineFunction &MF = *BB->getParent();
7610   DebugLoc DL = MI.getDebugLoc();
7611   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7612   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7613   Register LoReg = MI.getOperand(0).getReg();
7614   Register HiReg = MI.getOperand(1).getReg();
7615   Register SrcReg = MI.getOperand(2).getReg();
7616   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7617   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7618 
7619   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7620                           RI);
7621   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7622   MachineMemOperand *MMOLo =
7623       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7624   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7625       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7626   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7627       .addFrameIndex(FI)
7628       .addImm(0)
7629       .addMemOperand(MMOLo);
7630   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7631       .addFrameIndex(FI)
7632       .addImm(4)
7633       .addMemOperand(MMOHi);
7634   MI.eraseFromParent(); // The pseudo instruction is gone now.
7635   return BB;
7636 }
7637 
7638 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7639                                                  MachineBasicBlock *BB) {
7640   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7641          "Unexpected instruction");
7642 
7643   MachineFunction &MF = *BB->getParent();
7644   DebugLoc DL = MI.getDebugLoc();
7645   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7646   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7647   Register DstReg = MI.getOperand(0).getReg();
7648   Register LoReg = MI.getOperand(1).getReg();
7649   Register HiReg = MI.getOperand(2).getReg();
7650   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7651   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7652 
7653   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7654   MachineMemOperand *MMOLo =
7655       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7656   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7657       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7658   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7659       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7660       .addFrameIndex(FI)
7661       .addImm(0)
7662       .addMemOperand(MMOLo);
7663   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7664       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7665       .addFrameIndex(FI)
7666       .addImm(4)
7667       .addMemOperand(MMOHi);
7668   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7669   MI.eraseFromParent(); // The pseudo instruction is gone now.
7670   return BB;
7671 }
7672 
7673 static bool isSelectPseudo(MachineInstr &MI) {
7674   switch (MI.getOpcode()) {
7675   default:
7676     return false;
7677   case RISCV::Select_GPR_Using_CC_GPR:
7678   case RISCV::Select_FPR16_Using_CC_GPR:
7679   case RISCV::Select_FPR32_Using_CC_GPR:
7680   case RISCV::Select_FPR64_Using_CC_GPR:
7681     return true;
7682   }
7683 }
7684 
7685 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7686                                            MachineBasicBlock *BB,
7687                                            const RISCVSubtarget &Subtarget) {
7688   // To "insert" Select_* instructions, we actually have to insert the triangle
7689   // control-flow pattern.  The incoming instructions know the destination vreg
7690   // to set, the condition code register to branch on, the true/false values to
7691   // select between, and the condcode to use to select the appropriate branch.
7692   //
7693   // We produce the following control flow:
7694   //     HeadMBB
7695   //     |  \
7696   //     |  IfFalseMBB
7697   //     | /
7698   //    TailMBB
7699   //
7700   // When we find a sequence of selects we attempt to optimize their emission
7701   // by sharing the control flow. Currently we only handle cases where we have
7702   // multiple selects with the exact same condition (same LHS, RHS and CC).
7703   // The selects may be interleaved with other instructions if the other
7704   // instructions meet some requirements we deem safe:
7705   // - They are debug instructions. Otherwise,
7706   // - They do not have side-effects, do not access memory and their inputs do
7707   //   not depend on the results of the select pseudo-instructions.
7708   // The TrueV/FalseV operands of the selects cannot depend on the result of
7709   // previous selects in the sequence.
7710   // These conditions could be further relaxed. See the X86 target for a
7711   // related approach and more information.
7712   Register LHS = MI.getOperand(1).getReg();
7713   Register RHS = MI.getOperand(2).getReg();
7714   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7715 
7716   SmallVector<MachineInstr *, 4> SelectDebugValues;
7717   SmallSet<Register, 4> SelectDests;
7718   SelectDests.insert(MI.getOperand(0).getReg());
7719 
7720   MachineInstr *LastSelectPseudo = &MI;
7721 
7722   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7723        SequenceMBBI != E; ++SequenceMBBI) {
7724     if (SequenceMBBI->isDebugInstr())
7725       continue;
7726     else if (isSelectPseudo(*SequenceMBBI)) {
7727       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7728           SequenceMBBI->getOperand(2).getReg() != RHS ||
7729           SequenceMBBI->getOperand(3).getImm() != CC ||
7730           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7731           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7732         break;
7733       LastSelectPseudo = &*SequenceMBBI;
7734       SequenceMBBI->collectDebugValues(SelectDebugValues);
7735       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7736     } else {
7737       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7738           SequenceMBBI->mayLoadOrStore())
7739         break;
7740       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7741             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7742           }))
7743         break;
7744     }
7745   }
7746 
7747   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7748   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7749   DebugLoc DL = MI.getDebugLoc();
7750   MachineFunction::iterator I = ++BB->getIterator();
7751 
7752   MachineBasicBlock *HeadMBB = BB;
7753   MachineFunction *F = BB->getParent();
7754   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7755   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7756 
7757   F->insert(I, IfFalseMBB);
7758   F->insert(I, TailMBB);
7759 
7760   // Transfer debug instructions associated with the selects to TailMBB.
7761   for (MachineInstr *DebugInstr : SelectDebugValues) {
7762     TailMBB->push_back(DebugInstr->removeFromParent());
7763   }
7764 
7765   // Move all instructions after the sequence to TailMBB.
7766   TailMBB->splice(TailMBB->end(), HeadMBB,
7767                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7768   // Update machine-CFG edges by transferring all successors of the current
7769   // block to the new block which will contain the Phi nodes for the selects.
7770   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7771   // Set the successors for HeadMBB.
7772   HeadMBB->addSuccessor(IfFalseMBB);
7773   HeadMBB->addSuccessor(TailMBB);
7774 
7775   // Insert appropriate branch.
7776   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7777     .addReg(LHS)
7778     .addReg(RHS)
7779     .addMBB(TailMBB);
7780 
7781   // IfFalseMBB just falls through to TailMBB.
7782   IfFalseMBB->addSuccessor(TailMBB);
7783 
7784   // Create PHIs for all of the select pseudo-instructions.
7785   auto SelectMBBI = MI.getIterator();
7786   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7787   auto InsertionPoint = TailMBB->begin();
7788   while (SelectMBBI != SelectEnd) {
7789     auto Next = std::next(SelectMBBI);
7790     if (isSelectPseudo(*SelectMBBI)) {
7791       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7792       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7793               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7794           .addReg(SelectMBBI->getOperand(4).getReg())
7795           .addMBB(HeadMBB)
7796           .addReg(SelectMBBI->getOperand(5).getReg())
7797           .addMBB(IfFalseMBB);
7798       SelectMBBI->eraseFromParent();
7799     }
7800     SelectMBBI = Next;
7801   }
7802 
7803   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7804   return TailMBB;
7805 }
7806 
7807 MachineBasicBlock *
7808 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7809                                                  MachineBasicBlock *BB) const {
7810   switch (MI.getOpcode()) {
7811   default:
7812     llvm_unreachable("Unexpected instr type to insert");
7813   case RISCV::ReadCycleWide:
7814     assert(!Subtarget.is64Bit() &&
7815            "ReadCycleWrite is only to be used on riscv32");
7816     return emitReadCycleWidePseudo(MI, BB);
7817   case RISCV::Select_GPR_Using_CC_GPR:
7818   case RISCV::Select_FPR16_Using_CC_GPR:
7819   case RISCV::Select_FPR32_Using_CC_GPR:
7820   case RISCV::Select_FPR64_Using_CC_GPR:
7821     return emitSelectPseudo(MI, BB, Subtarget);
7822   case RISCV::BuildPairF64Pseudo:
7823     return emitBuildPairF64Pseudo(MI, BB);
7824   case RISCV::SplitF64Pseudo:
7825     return emitSplitF64Pseudo(MI, BB);
7826   }
7827 }
7828 
7829 // Calling Convention Implementation.
7830 // The expectations for frontend ABI lowering vary from target to target.
7831 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7832 // details, but this is a longer term goal. For now, we simply try to keep the
7833 // role of the frontend as simple and well-defined as possible. The rules can
7834 // be summarised as:
7835 // * Never split up large scalar arguments. We handle them here.
7836 // * If a hardfloat calling convention is being used, and the struct may be
7837 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7838 // available, then pass as two separate arguments. If either the GPRs or FPRs
7839 // are exhausted, then pass according to the rule below.
7840 // * If a struct could never be passed in registers or directly in a stack
7841 // slot (as it is larger than 2*XLEN and the floating point rules don't
7842 // apply), then pass it using a pointer with the byval attribute.
7843 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7844 // word-sized array or a 2*XLEN scalar (depending on alignment).
7845 // * The frontend can determine whether a struct is returned by reference or
7846 // not based on its size and fields. If it will be returned by reference, the
7847 // frontend must modify the prototype so a pointer with the sret annotation is
7848 // passed as the first argument. This is not necessary for large scalar
7849 // returns.
7850 // * Struct return values and varargs should be coerced to structs containing
7851 // register-size fields in the same situations they would be for fixed
7852 // arguments.
7853 
7854 static const MCPhysReg ArgGPRs[] = {
7855   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7856   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7857 };
7858 static const MCPhysReg ArgFPR16s[] = {
7859   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7860   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7861 };
7862 static const MCPhysReg ArgFPR32s[] = {
7863   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7864   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7865 };
7866 static const MCPhysReg ArgFPR64s[] = {
7867   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7868   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7869 };
7870 // This is an interim calling convention and it may be changed in the future.
7871 static const MCPhysReg ArgVRs[] = {
7872     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7873     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7874     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7875 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7876                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7877                                      RISCV::V20M2, RISCV::V22M2};
7878 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7879                                      RISCV::V20M4};
7880 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7881 
7882 // Pass a 2*XLEN argument that has been split into two XLEN values through
7883 // registers or the stack as necessary.
7884 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7885                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7886                                 MVT ValVT2, MVT LocVT2,
7887                                 ISD::ArgFlagsTy ArgFlags2) {
7888   unsigned XLenInBytes = XLen / 8;
7889   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7890     // At least one half can be passed via register.
7891     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7892                                      VA1.getLocVT(), CCValAssign::Full));
7893   } else {
7894     // Both halves must be passed on the stack, with proper alignment.
7895     Align StackAlign =
7896         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7897     State.addLoc(
7898         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7899                             State.AllocateStack(XLenInBytes, StackAlign),
7900                             VA1.getLocVT(), CCValAssign::Full));
7901     State.addLoc(CCValAssign::getMem(
7902         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7903         LocVT2, CCValAssign::Full));
7904     return false;
7905   }
7906 
7907   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7908     // The second half can also be passed via register.
7909     State.addLoc(
7910         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7911   } else {
7912     // The second half is passed via the stack, without additional alignment.
7913     State.addLoc(CCValAssign::getMem(
7914         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7915         LocVT2, CCValAssign::Full));
7916   }
7917 
7918   return false;
7919 }
7920 
7921 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7922                                Optional<unsigned> FirstMaskArgument,
7923                                CCState &State, const RISCVTargetLowering &TLI) {
7924   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7925   if (RC == &RISCV::VRRegClass) {
7926     // Assign the first mask argument to V0.
7927     // This is an interim calling convention and it may be changed in the
7928     // future.
7929     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7930       return State.AllocateReg(RISCV::V0);
7931     return State.AllocateReg(ArgVRs);
7932   }
7933   if (RC == &RISCV::VRM2RegClass)
7934     return State.AllocateReg(ArgVRM2s);
7935   if (RC == &RISCV::VRM4RegClass)
7936     return State.AllocateReg(ArgVRM4s);
7937   if (RC == &RISCV::VRM8RegClass)
7938     return State.AllocateReg(ArgVRM8s);
7939   llvm_unreachable("Unhandled register class for ValueType");
7940 }
7941 
7942 // Implements the RISC-V calling convention. Returns true upon failure.
7943 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7944                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7945                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7946                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7947                      Optional<unsigned> FirstMaskArgument) {
7948   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7949   assert(XLen == 32 || XLen == 64);
7950   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7951 
7952   // Any return value split in to more than two values can't be returned
7953   // directly. Vectors are returned via the available vector registers.
7954   if (!LocVT.isVector() && IsRet && ValNo > 1)
7955     return true;
7956 
7957   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7958   // variadic argument, or if no F16/F32 argument registers are available.
7959   bool UseGPRForF16_F32 = true;
7960   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7961   // variadic argument, or if no F64 argument registers are available.
7962   bool UseGPRForF64 = true;
7963 
7964   switch (ABI) {
7965   default:
7966     llvm_unreachable("Unexpected ABI");
7967   case RISCVABI::ABI_ILP32:
7968   case RISCVABI::ABI_LP64:
7969     break;
7970   case RISCVABI::ABI_ILP32F:
7971   case RISCVABI::ABI_LP64F:
7972     UseGPRForF16_F32 = !IsFixed;
7973     break;
7974   case RISCVABI::ABI_ILP32D:
7975   case RISCVABI::ABI_LP64D:
7976     UseGPRForF16_F32 = !IsFixed;
7977     UseGPRForF64 = !IsFixed;
7978     break;
7979   }
7980 
7981   // FPR16, FPR32, and FPR64 alias each other.
7982   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7983     UseGPRForF16_F32 = true;
7984     UseGPRForF64 = true;
7985   }
7986 
7987   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7988   // similar local variables rather than directly checking against the target
7989   // ABI.
7990 
7991   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7992     LocVT = XLenVT;
7993     LocInfo = CCValAssign::BCvt;
7994   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7995     LocVT = MVT::i64;
7996     LocInfo = CCValAssign::BCvt;
7997   }
7998 
7999   // If this is a variadic argument, the RISC-V calling convention requires
8000   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8001   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8002   // be used regardless of whether the original argument was split during
8003   // legalisation or not. The argument will not be passed by registers if the
8004   // original type is larger than 2*XLEN, so the register alignment rule does
8005   // not apply.
8006   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8007   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8008       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8009     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8010     // Skip 'odd' register if necessary.
8011     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8012       State.AllocateReg(ArgGPRs);
8013   }
8014 
8015   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8016   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8017       State.getPendingArgFlags();
8018 
8019   assert(PendingLocs.size() == PendingArgFlags.size() &&
8020          "PendingLocs and PendingArgFlags out of sync");
8021 
8022   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8023   // registers are exhausted.
8024   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8025     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8026            "Can't lower f64 if it is split");
8027     // Depending on available argument GPRS, f64 may be passed in a pair of
8028     // GPRs, split between a GPR and the stack, or passed completely on the
8029     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8030     // cases.
8031     Register Reg = State.AllocateReg(ArgGPRs);
8032     LocVT = MVT::i32;
8033     if (!Reg) {
8034       unsigned StackOffset = State.AllocateStack(8, Align(8));
8035       State.addLoc(
8036           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8037       return false;
8038     }
8039     if (!State.AllocateReg(ArgGPRs))
8040       State.AllocateStack(4, Align(4));
8041     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8042     return false;
8043   }
8044 
8045   // Fixed-length vectors are located in the corresponding scalable-vector
8046   // container types.
8047   if (ValVT.isFixedLengthVector())
8048     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8049 
8050   // Split arguments might be passed indirectly, so keep track of the pending
8051   // values. Split vectors are passed via a mix of registers and indirectly, so
8052   // treat them as we would any other argument.
8053   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8054     LocVT = XLenVT;
8055     LocInfo = CCValAssign::Indirect;
8056     PendingLocs.push_back(
8057         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8058     PendingArgFlags.push_back(ArgFlags);
8059     if (!ArgFlags.isSplitEnd()) {
8060       return false;
8061     }
8062   }
8063 
8064   // If the split argument only had two elements, it should be passed directly
8065   // in registers or on the stack.
8066   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8067       PendingLocs.size() <= 2) {
8068     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8069     // Apply the normal calling convention rules to the first half of the
8070     // split argument.
8071     CCValAssign VA = PendingLocs[0];
8072     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8073     PendingLocs.clear();
8074     PendingArgFlags.clear();
8075     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8076                                ArgFlags);
8077   }
8078 
8079   // Allocate to a register if possible, or else a stack slot.
8080   Register Reg;
8081   unsigned StoreSizeBytes = XLen / 8;
8082   Align StackAlign = Align(XLen / 8);
8083 
8084   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8085     Reg = State.AllocateReg(ArgFPR16s);
8086   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8087     Reg = State.AllocateReg(ArgFPR32s);
8088   else if (ValVT == MVT::f64 && !UseGPRForF64)
8089     Reg = State.AllocateReg(ArgFPR64s);
8090   else if (ValVT.isVector()) {
8091     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8092     if (!Reg) {
8093       // For return values, the vector must be passed fully via registers or
8094       // via the stack.
8095       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8096       // but we're using all of them.
8097       if (IsRet)
8098         return true;
8099       // Try using a GPR to pass the address
8100       if ((Reg = State.AllocateReg(ArgGPRs))) {
8101         LocVT = XLenVT;
8102         LocInfo = CCValAssign::Indirect;
8103       } else if (ValVT.isScalableVector()) {
8104         report_fatal_error("Unable to pass scalable vector types on the stack");
8105       } else {
8106         // Pass fixed-length vectors on the stack.
8107         LocVT = ValVT;
8108         StoreSizeBytes = ValVT.getStoreSize();
8109         // Align vectors to their element sizes, being careful for vXi1
8110         // vectors.
8111         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8112       }
8113     }
8114   } else {
8115     Reg = State.AllocateReg(ArgGPRs);
8116   }
8117 
8118   unsigned StackOffset =
8119       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8120 
8121   // If we reach this point and PendingLocs is non-empty, we must be at the
8122   // end of a split argument that must be passed indirectly.
8123   if (!PendingLocs.empty()) {
8124     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8125     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8126 
8127     for (auto &It : PendingLocs) {
8128       if (Reg)
8129         It.convertToReg(Reg);
8130       else
8131         It.convertToMem(StackOffset);
8132       State.addLoc(It);
8133     }
8134     PendingLocs.clear();
8135     PendingArgFlags.clear();
8136     return false;
8137   }
8138 
8139   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8140           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8141          "Expected an XLenVT or vector types at this stage");
8142 
8143   if (Reg) {
8144     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8145     return false;
8146   }
8147 
8148   // When a floating-point value is passed on the stack, no bit-conversion is
8149   // needed.
8150   if (ValVT.isFloatingPoint()) {
8151     LocVT = ValVT;
8152     LocInfo = CCValAssign::Full;
8153   }
8154   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8155   return false;
8156 }
8157 
8158 template <typename ArgTy>
8159 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8160   for (const auto &ArgIdx : enumerate(Args)) {
8161     MVT ArgVT = ArgIdx.value().VT;
8162     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8163       return ArgIdx.index();
8164   }
8165   return None;
8166 }
8167 
8168 void RISCVTargetLowering::analyzeInputArgs(
8169     MachineFunction &MF, CCState &CCInfo,
8170     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8171     RISCVCCAssignFn Fn) const {
8172   unsigned NumArgs = Ins.size();
8173   FunctionType *FType = MF.getFunction().getFunctionType();
8174 
8175   Optional<unsigned> FirstMaskArgument;
8176   if (Subtarget.hasVInstructions())
8177     FirstMaskArgument = preAssignMask(Ins);
8178 
8179   for (unsigned i = 0; i != NumArgs; ++i) {
8180     MVT ArgVT = Ins[i].VT;
8181     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8182 
8183     Type *ArgTy = nullptr;
8184     if (IsRet)
8185       ArgTy = FType->getReturnType();
8186     else if (Ins[i].isOrigArg())
8187       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8188 
8189     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8190     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8191            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8192            FirstMaskArgument)) {
8193       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8194                         << EVT(ArgVT).getEVTString() << '\n');
8195       llvm_unreachable(nullptr);
8196     }
8197   }
8198 }
8199 
8200 void RISCVTargetLowering::analyzeOutputArgs(
8201     MachineFunction &MF, CCState &CCInfo,
8202     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8203     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8204   unsigned NumArgs = Outs.size();
8205 
8206   Optional<unsigned> FirstMaskArgument;
8207   if (Subtarget.hasVInstructions())
8208     FirstMaskArgument = preAssignMask(Outs);
8209 
8210   for (unsigned i = 0; i != NumArgs; i++) {
8211     MVT ArgVT = Outs[i].VT;
8212     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8213     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8214 
8215     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8216     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8217            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8218            FirstMaskArgument)) {
8219       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8220                         << EVT(ArgVT).getEVTString() << "\n");
8221       llvm_unreachable(nullptr);
8222     }
8223   }
8224 }
8225 
8226 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8227 // values.
8228 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8229                                    const CCValAssign &VA, const SDLoc &DL,
8230                                    const RISCVSubtarget &Subtarget) {
8231   switch (VA.getLocInfo()) {
8232   default:
8233     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8234   case CCValAssign::Full:
8235     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8236       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8237     break;
8238   case CCValAssign::BCvt:
8239     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8240       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8241     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8242       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8243     else
8244       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8245     break;
8246   }
8247   return Val;
8248 }
8249 
8250 // The caller is responsible for loading the full value if the argument is
8251 // passed with CCValAssign::Indirect.
8252 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8253                                 const CCValAssign &VA, const SDLoc &DL,
8254                                 const RISCVTargetLowering &TLI) {
8255   MachineFunction &MF = DAG.getMachineFunction();
8256   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8257   EVT LocVT = VA.getLocVT();
8258   SDValue Val;
8259   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8260   Register VReg = RegInfo.createVirtualRegister(RC);
8261   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8262   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8263 
8264   if (VA.getLocInfo() == CCValAssign::Indirect)
8265     return Val;
8266 
8267   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8268 }
8269 
8270 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8271                                    const CCValAssign &VA, const SDLoc &DL,
8272                                    const RISCVSubtarget &Subtarget) {
8273   EVT LocVT = VA.getLocVT();
8274 
8275   switch (VA.getLocInfo()) {
8276   default:
8277     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8278   case CCValAssign::Full:
8279     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8280       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8281     break;
8282   case CCValAssign::BCvt:
8283     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8284       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8285     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8286       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8287     else
8288       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8289     break;
8290   }
8291   return Val;
8292 }
8293 
8294 // The caller is responsible for loading the full value if the argument is
8295 // passed with CCValAssign::Indirect.
8296 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8297                                 const CCValAssign &VA, const SDLoc &DL) {
8298   MachineFunction &MF = DAG.getMachineFunction();
8299   MachineFrameInfo &MFI = MF.getFrameInfo();
8300   EVT LocVT = VA.getLocVT();
8301   EVT ValVT = VA.getValVT();
8302   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8303   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8304                                  /*Immutable=*/true);
8305   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8306   SDValue Val;
8307 
8308   ISD::LoadExtType ExtType;
8309   switch (VA.getLocInfo()) {
8310   default:
8311     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8312   case CCValAssign::Full:
8313   case CCValAssign::Indirect:
8314   case CCValAssign::BCvt:
8315     ExtType = ISD::NON_EXTLOAD;
8316     break;
8317   }
8318   Val = DAG.getExtLoad(
8319       ExtType, DL, LocVT, Chain, FIN,
8320       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8321   return Val;
8322 }
8323 
8324 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8325                                        const CCValAssign &VA, const SDLoc &DL) {
8326   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8327          "Unexpected VA");
8328   MachineFunction &MF = DAG.getMachineFunction();
8329   MachineFrameInfo &MFI = MF.getFrameInfo();
8330   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8331 
8332   if (VA.isMemLoc()) {
8333     // f64 is passed on the stack.
8334     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8335     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8336     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8337                        MachinePointerInfo::getFixedStack(MF, FI));
8338   }
8339 
8340   assert(VA.isRegLoc() && "Expected register VA assignment");
8341 
8342   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8343   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8344   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8345   SDValue Hi;
8346   if (VA.getLocReg() == RISCV::X17) {
8347     // Second half of f64 is passed on the stack.
8348     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8349     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8350     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8351                      MachinePointerInfo::getFixedStack(MF, FI));
8352   } else {
8353     // Second half of f64 is passed in another GPR.
8354     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8355     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8356     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8357   }
8358   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8359 }
8360 
8361 // FastCC has less than 1% performance improvement for some particular
8362 // benchmark. But theoretically, it may has benenfit for some cases.
8363 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8364                             unsigned ValNo, MVT ValVT, MVT LocVT,
8365                             CCValAssign::LocInfo LocInfo,
8366                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8367                             bool IsFixed, bool IsRet, Type *OrigTy,
8368                             const RISCVTargetLowering &TLI,
8369                             Optional<unsigned> FirstMaskArgument) {
8370 
8371   // X5 and X6 might be used for save-restore libcall.
8372   static const MCPhysReg GPRList[] = {
8373       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8374       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8375       RISCV::X29, RISCV::X30, RISCV::X31};
8376 
8377   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8378     if (unsigned Reg = State.AllocateReg(GPRList)) {
8379       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8380       return false;
8381     }
8382   }
8383 
8384   if (LocVT == MVT::f16) {
8385     static const MCPhysReg FPR16List[] = {
8386         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8387         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8388         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8389         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8390     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8391       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8392       return false;
8393     }
8394   }
8395 
8396   if (LocVT == MVT::f32) {
8397     static const MCPhysReg FPR32List[] = {
8398         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8399         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8400         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8401         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8402     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8403       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8404       return false;
8405     }
8406   }
8407 
8408   if (LocVT == MVT::f64) {
8409     static const MCPhysReg FPR64List[] = {
8410         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8411         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8412         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8413         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8414     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8415       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8416       return false;
8417     }
8418   }
8419 
8420   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8421     unsigned Offset4 = State.AllocateStack(4, Align(4));
8422     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8423     return false;
8424   }
8425 
8426   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8427     unsigned Offset5 = State.AllocateStack(8, Align(8));
8428     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8429     return false;
8430   }
8431 
8432   if (LocVT.isVector()) {
8433     if (unsigned Reg =
8434             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8435       // Fixed-length vectors are located in the corresponding scalable-vector
8436       // container types.
8437       if (ValVT.isFixedLengthVector())
8438         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8439       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8440     } else {
8441       // Try and pass the address via a "fast" GPR.
8442       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8443         LocInfo = CCValAssign::Indirect;
8444         LocVT = TLI.getSubtarget().getXLenVT();
8445         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8446       } else if (ValVT.isFixedLengthVector()) {
8447         auto StackAlign =
8448             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8449         unsigned StackOffset =
8450             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8451         State.addLoc(
8452             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8453       } else {
8454         // Can't pass scalable vectors on the stack.
8455         return true;
8456       }
8457     }
8458 
8459     return false;
8460   }
8461 
8462   return true; // CC didn't match.
8463 }
8464 
8465 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8466                          CCValAssign::LocInfo LocInfo,
8467                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8468 
8469   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8470     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8471     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8472     static const MCPhysReg GPRList[] = {
8473         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8474         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8475     if (unsigned Reg = State.AllocateReg(GPRList)) {
8476       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8477       return false;
8478     }
8479   }
8480 
8481   if (LocVT == MVT::f32) {
8482     // Pass in STG registers: F1, ..., F6
8483     //                        fs0 ... fs5
8484     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8485                                           RISCV::F18_F, RISCV::F19_F,
8486                                           RISCV::F20_F, RISCV::F21_F};
8487     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8488       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8489       return false;
8490     }
8491   }
8492 
8493   if (LocVT == MVT::f64) {
8494     // Pass in STG registers: D1, ..., D6
8495     //                        fs6 ... fs11
8496     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8497                                           RISCV::F24_D, RISCV::F25_D,
8498                                           RISCV::F26_D, RISCV::F27_D};
8499     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8500       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8501       return false;
8502     }
8503   }
8504 
8505   report_fatal_error("No registers left in GHC calling convention");
8506   return true;
8507 }
8508 
8509 // Transform physical registers into virtual registers.
8510 SDValue RISCVTargetLowering::LowerFormalArguments(
8511     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8512     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8513     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8514 
8515   MachineFunction &MF = DAG.getMachineFunction();
8516 
8517   switch (CallConv) {
8518   default:
8519     report_fatal_error("Unsupported calling convention");
8520   case CallingConv::C:
8521   case CallingConv::Fast:
8522     break;
8523   case CallingConv::GHC:
8524     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8525         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8526       report_fatal_error(
8527         "GHC calling convention requires the F and D instruction set extensions");
8528   }
8529 
8530   const Function &Func = MF.getFunction();
8531   if (Func.hasFnAttribute("interrupt")) {
8532     if (!Func.arg_empty())
8533       report_fatal_error(
8534         "Functions with the interrupt attribute cannot have arguments!");
8535 
8536     StringRef Kind =
8537       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8538 
8539     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8540       report_fatal_error(
8541         "Function interrupt attribute argument not supported!");
8542   }
8543 
8544   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8545   MVT XLenVT = Subtarget.getXLenVT();
8546   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8547   // Used with vargs to acumulate store chains.
8548   std::vector<SDValue> OutChains;
8549 
8550   // Assign locations to all of the incoming arguments.
8551   SmallVector<CCValAssign, 16> ArgLocs;
8552   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8553 
8554   if (CallConv == CallingConv::GHC)
8555     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8556   else
8557     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8558                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8559                                                    : CC_RISCV);
8560 
8561   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8562     CCValAssign &VA = ArgLocs[i];
8563     SDValue ArgValue;
8564     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8565     // case.
8566     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8567       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8568     else if (VA.isRegLoc())
8569       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8570     else
8571       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8572 
8573     if (VA.getLocInfo() == CCValAssign::Indirect) {
8574       // If the original argument was split and passed by reference (e.g. i128
8575       // on RV32), we need to load all parts of it here (using the same
8576       // address). Vectors may be partly split to registers and partly to the
8577       // stack, in which case the base address is partly offset and subsequent
8578       // stores are relative to that.
8579       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8580                                    MachinePointerInfo()));
8581       unsigned ArgIndex = Ins[i].OrigArgIndex;
8582       unsigned ArgPartOffset = Ins[i].PartOffset;
8583       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8584       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8585         CCValAssign &PartVA = ArgLocs[i + 1];
8586         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8587         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8588         if (PartVA.getValVT().isScalableVector())
8589           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8590         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8591         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8592                                      MachinePointerInfo()));
8593         ++i;
8594       }
8595       continue;
8596     }
8597     InVals.push_back(ArgValue);
8598   }
8599 
8600   if (IsVarArg) {
8601     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8602     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8603     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8604     MachineFrameInfo &MFI = MF.getFrameInfo();
8605     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8606     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8607 
8608     // Offset of the first variable argument from stack pointer, and size of
8609     // the vararg save area. For now, the varargs save area is either zero or
8610     // large enough to hold a0-a7.
8611     int VaArgOffset, VarArgsSaveSize;
8612 
8613     // If all registers are allocated, then all varargs must be passed on the
8614     // stack and we don't need to save any argregs.
8615     if (ArgRegs.size() == Idx) {
8616       VaArgOffset = CCInfo.getNextStackOffset();
8617       VarArgsSaveSize = 0;
8618     } else {
8619       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8620       VaArgOffset = -VarArgsSaveSize;
8621     }
8622 
8623     // Record the frame index of the first variable argument
8624     // which is a value necessary to VASTART.
8625     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8626     RVFI->setVarArgsFrameIndex(FI);
8627 
8628     // If saving an odd number of registers then create an extra stack slot to
8629     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8630     // offsets to even-numbered registered remain 2*XLEN-aligned.
8631     if (Idx % 2) {
8632       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8633       VarArgsSaveSize += XLenInBytes;
8634     }
8635 
8636     // Copy the integer registers that may have been used for passing varargs
8637     // to the vararg save area.
8638     for (unsigned I = Idx; I < ArgRegs.size();
8639          ++I, VaArgOffset += XLenInBytes) {
8640       const Register Reg = RegInfo.createVirtualRegister(RC);
8641       RegInfo.addLiveIn(ArgRegs[I], Reg);
8642       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8643       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8644       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8645       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8646                                    MachinePointerInfo::getFixedStack(MF, FI));
8647       cast<StoreSDNode>(Store.getNode())
8648           ->getMemOperand()
8649           ->setValue((Value *)nullptr);
8650       OutChains.push_back(Store);
8651     }
8652     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8653   }
8654 
8655   // All stores are grouped in one node to allow the matching between
8656   // the size of Ins and InVals. This only happens for vararg functions.
8657   if (!OutChains.empty()) {
8658     OutChains.push_back(Chain);
8659     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8660   }
8661 
8662   return Chain;
8663 }
8664 
8665 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8666 /// for tail call optimization.
8667 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8668 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8669     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8670     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8671 
8672   auto &Callee = CLI.Callee;
8673   auto CalleeCC = CLI.CallConv;
8674   auto &Outs = CLI.Outs;
8675   auto &Caller = MF.getFunction();
8676   auto CallerCC = Caller.getCallingConv();
8677 
8678   // Exception-handling functions need a special set of instructions to
8679   // indicate a return to the hardware. Tail-calling another function would
8680   // probably break this.
8681   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8682   // should be expanded as new function attributes are introduced.
8683   if (Caller.hasFnAttribute("interrupt"))
8684     return false;
8685 
8686   // Do not tail call opt if the stack is used to pass parameters.
8687   if (CCInfo.getNextStackOffset() != 0)
8688     return false;
8689 
8690   // Do not tail call opt if any parameters need to be passed indirectly.
8691   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8692   // passed indirectly. So the address of the value will be passed in a
8693   // register, or if not available, then the address is put on the stack. In
8694   // order to pass indirectly, space on the stack often needs to be allocated
8695   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8696   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8697   // are passed CCValAssign::Indirect.
8698   for (auto &VA : ArgLocs)
8699     if (VA.getLocInfo() == CCValAssign::Indirect)
8700       return false;
8701 
8702   // Do not tail call opt if either caller or callee uses struct return
8703   // semantics.
8704   auto IsCallerStructRet = Caller.hasStructRetAttr();
8705   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8706   if (IsCallerStructRet || IsCalleeStructRet)
8707     return false;
8708 
8709   // Externally-defined functions with weak linkage should not be
8710   // tail-called. The behaviour of branch instructions in this situation (as
8711   // used for tail calls) is implementation-defined, so we cannot rely on the
8712   // linker replacing the tail call with a return.
8713   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8714     const GlobalValue *GV = G->getGlobal();
8715     if (GV->hasExternalWeakLinkage())
8716       return false;
8717   }
8718 
8719   // The callee has to preserve all registers the caller needs to preserve.
8720   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8721   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8722   if (CalleeCC != CallerCC) {
8723     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8724     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8725       return false;
8726   }
8727 
8728   // Byval parameters hand the function a pointer directly into the stack area
8729   // we want to reuse during a tail call. Working around this *is* possible
8730   // but less efficient and uglier in LowerCall.
8731   for (auto &Arg : Outs)
8732     if (Arg.Flags.isByVal())
8733       return false;
8734 
8735   return true;
8736 }
8737 
8738 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8739   return DAG.getDataLayout().getPrefTypeAlign(
8740       VT.getTypeForEVT(*DAG.getContext()));
8741 }
8742 
8743 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8744 // and output parameter nodes.
8745 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8746                                        SmallVectorImpl<SDValue> &InVals) const {
8747   SelectionDAG &DAG = CLI.DAG;
8748   SDLoc &DL = CLI.DL;
8749   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8750   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8751   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8752   SDValue Chain = CLI.Chain;
8753   SDValue Callee = CLI.Callee;
8754   bool &IsTailCall = CLI.IsTailCall;
8755   CallingConv::ID CallConv = CLI.CallConv;
8756   bool IsVarArg = CLI.IsVarArg;
8757   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8758   MVT XLenVT = Subtarget.getXLenVT();
8759 
8760   MachineFunction &MF = DAG.getMachineFunction();
8761 
8762   // Analyze the operands of the call, assigning locations to each operand.
8763   SmallVector<CCValAssign, 16> ArgLocs;
8764   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8765 
8766   if (CallConv == CallingConv::GHC)
8767     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8768   else
8769     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8770                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8771                                                     : CC_RISCV);
8772 
8773   // Check if it's really possible to do a tail call.
8774   if (IsTailCall)
8775     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8776 
8777   if (IsTailCall)
8778     ++NumTailCalls;
8779   else if (CLI.CB && CLI.CB->isMustTailCall())
8780     report_fatal_error("failed to perform tail call elimination on a call "
8781                        "site marked musttail");
8782 
8783   // Get a count of how many bytes are to be pushed on the stack.
8784   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8785 
8786   // Create local copies for byval args
8787   SmallVector<SDValue, 8> ByValArgs;
8788   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8789     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8790     if (!Flags.isByVal())
8791       continue;
8792 
8793     SDValue Arg = OutVals[i];
8794     unsigned Size = Flags.getByValSize();
8795     Align Alignment = Flags.getNonZeroByValAlign();
8796 
8797     int FI =
8798         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8799     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8800     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8801 
8802     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8803                           /*IsVolatile=*/false,
8804                           /*AlwaysInline=*/false, IsTailCall,
8805                           MachinePointerInfo(), MachinePointerInfo());
8806     ByValArgs.push_back(FIPtr);
8807   }
8808 
8809   if (!IsTailCall)
8810     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8811 
8812   // Copy argument values to their designated locations.
8813   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8814   SmallVector<SDValue, 8> MemOpChains;
8815   SDValue StackPtr;
8816   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8817     CCValAssign &VA = ArgLocs[i];
8818     SDValue ArgValue = OutVals[i];
8819     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8820 
8821     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8822     bool IsF64OnRV32DSoftABI =
8823         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8824     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8825       SDValue SplitF64 = DAG.getNode(
8826           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8827       SDValue Lo = SplitF64.getValue(0);
8828       SDValue Hi = SplitF64.getValue(1);
8829 
8830       Register RegLo = VA.getLocReg();
8831       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8832 
8833       if (RegLo == RISCV::X17) {
8834         // Second half of f64 is passed on the stack.
8835         // Work out the address of the stack slot.
8836         if (!StackPtr.getNode())
8837           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8838         // Emit the store.
8839         MemOpChains.push_back(
8840             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8841       } else {
8842         // Second half of f64 is passed in another GPR.
8843         assert(RegLo < RISCV::X31 && "Invalid register pair");
8844         Register RegHigh = RegLo + 1;
8845         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8846       }
8847       continue;
8848     }
8849 
8850     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8851     // as any other MemLoc.
8852 
8853     // Promote the value if needed.
8854     // For now, only handle fully promoted and indirect arguments.
8855     if (VA.getLocInfo() == CCValAssign::Indirect) {
8856       // Store the argument in a stack slot and pass its address.
8857       Align StackAlign =
8858           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8859                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8860       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8861       // If the original argument was split (e.g. i128), we need
8862       // to store the required parts of it here (and pass just one address).
8863       // Vectors may be partly split to registers and partly to the stack, in
8864       // which case the base address is partly offset and subsequent stores are
8865       // relative to that.
8866       unsigned ArgIndex = Outs[i].OrigArgIndex;
8867       unsigned ArgPartOffset = Outs[i].PartOffset;
8868       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8869       // Calculate the total size to store. We don't have access to what we're
8870       // actually storing other than performing the loop and collecting the
8871       // info.
8872       SmallVector<std::pair<SDValue, SDValue>> Parts;
8873       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8874         SDValue PartValue = OutVals[i + 1];
8875         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8876         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8877         EVT PartVT = PartValue.getValueType();
8878         if (PartVT.isScalableVector())
8879           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8880         StoredSize += PartVT.getStoreSize();
8881         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8882         Parts.push_back(std::make_pair(PartValue, Offset));
8883         ++i;
8884       }
8885       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8886       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8887       MemOpChains.push_back(
8888           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8889                        MachinePointerInfo::getFixedStack(MF, FI)));
8890       for (const auto &Part : Parts) {
8891         SDValue PartValue = Part.first;
8892         SDValue PartOffset = Part.second;
8893         SDValue Address =
8894             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8895         MemOpChains.push_back(
8896             DAG.getStore(Chain, DL, PartValue, Address,
8897                          MachinePointerInfo::getFixedStack(MF, FI)));
8898       }
8899       ArgValue = SpillSlot;
8900     } else {
8901       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8902     }
8903 
8904     // Use local copy if it is a byval arg.
8905     if (Flags.isByVal())
8906       ArgValue = ByValArgs[j++];
8907 
8908     if (VA.isRegLoc()) {
8909       // Queue up the argument copies and emit them at the end.
8910       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8911     } else {
8912       assert(VA.isMemLoc() && "Argument not register or memory");
8913       assert(!IsTailCall && "Tail call not allowed if stack is used "
8914                             "for passing parameters");
8915 
8916       // Work out the address of the stack slot.
8917       if (!StackPtr.getNode())
8918         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8919       SDValue Address =
8920           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8921                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8922 
8923       // Emit the store.
8924       MemOpChains.push_back(
8925           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8926     }
8927   }
8928 
8929   // Join the stores, which are independent of one another.
8930   if (!MemOpChains.empty())
8931     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8932 
8933   SDValue Glue;
8934 
8935   // Build a sequence of copy-to-reg nodes, chained and glued together.
8936   for (auto &Reg : RegsToPass) {
8937     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8938     Glue = Chain.getValue(1);
8939   }
8940 
8941   // Validate that none of the argument registers have been marked as
8942   // reserved, if so report an error. Do the same for the return address if this
8943   // is not a tailcall.
8944   validateCCReservedRegs(RegsToPass, MF);
8945   if (!IsTailCall &&
8946       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8947     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8948         MF.getFunction(),
8949         "Return address register required, but has been reserved."});
8950 
8951   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8952   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8953   // split it and then direct call can be matched by PseudoCALL.
8954   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8955     const GlobalValue *GV = S->getGlobal();
8956 
8957     unsigned OpFlags = RISCVII::MO_CALL;
8958     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8959       OpFlags = RISCVII::MO_PLT;
8960 
8961     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8962   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8963     unsigned OpFlags = RISCVII::MO_CALL;
8964 
8965     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8966                                                  nullptr))
8967       OpFlags = RISCVII::MO_PLT;
8968 
8969     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8970   }
8971 
8972   // The first call operand is the chain and the second is the target address.
8973   SmallVector<SDValue, 8> Ops;
8974   Ops.push_back(Chain);
8975   Ops.push_back(Callee);
8976 
8977   // Add argument registers to the end of the list so that they are
8978   // known live into the call.
8979   for (auto &Reg : RegsToPass)
8980     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8981 
8982   if (!IsTailCall) {
8983     // Add a register mask operand representing the call-preserved registers.
8984     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8985     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8986     assert(Mask && "Missing call preserved mask for calling convention");
8987     Ops.push_back(DAG.getRegisterMask(Mask));
8988   }
8989 
8990   // Glue the call to the argument copies, if any.
8991   if (Glue.getNode())
8992     Ops.push_back(Glue);
8993 
8994   // Emit the call.
8995   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8996 
8997   if (IsTailCall) {
8998     MF.getFrameInfo().setHasTailCall();
8999     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9000   }
9001 
9002   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9003   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9004   Glue = Chain.getValue(1);
9005 
9006   // Mark the end of the call, which is glued to the call itself.
9007   Chain = DAG.getCALLSEQ_END(Chain,
9008                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9009                              DAG.getConstant(0, DL, PtrVT, true),
9010                              Glue, DL);
9011   Glue = Chain.getValue(1);
9012 
9013   // Assign locations to each value returned by this call.
9014   SmallVector<CCValAssign, 16> RVLocs;
9015   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9016   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9017 
9018   // Copy all of the result registers out of their specified physreg.
9019   for (auto &VA : RVLocs) {
9020     // Copy the value out
9021     SDValue RetValue =
9022         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9023     // Glue the RetValue to the end of the call sequence
9024     Chain = RetValue.getValue(1);
9025     Glue = RetValue.getValue(2);
9026 
9027     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9028       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9029       SDValue RetValue2 =
9030           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9031       Chain = RetValue2.getValue(1);
9032       Glue = RetValue2.getValue(2);
9033       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9034                              RetValue2);
9035     }
9036 
9037     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9038 
9039     InVals.push_back(RetValue);
9040   }
9041 
9042   return Chain;
9043 }
9044 
9045 bool RISCVTargetLowering::CanLowerReturn(
9046     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9047     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9048   SmallVector<CCValAssign, 16> RVLocs;
9049   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9050 
9051   Optional<unsigned> FirstMaskArgument;
9052   if (Subtarget.hasVInstructions())
9053     FirstMaskArgument = preAssignMask(Outs);
9054 
9055   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9056     MVT VT = Outs[i].VT;
9057     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9058     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9059     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9060                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9061                  *this, FirstMaskArgument))
9062       return false;
9063   }
9064   return true;
9065 }
9066 
9067 SDValue
9068 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9069                                  bool IsVarArg,
9070                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9071                                  const SmallVectorImpl<SDValue> &OutVals,
9072                                  const SDLoc &DL, SelectionDAG &DAG) const {
9073   const MachineFunction &MF = DAG.getMachineFunction();
9074   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9075 
9076   // Stores the assignment of the return value to a location.
9077   SmallVector<CCValAssign, 16> RVLocs;
9078 
9079   // Info about the registers and stack slot.
9080   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9081                  *DAG.getContext());
9082 
9083   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9084                     nullptr, CC_RISCV);
9085 
9086   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9087     report_fatal_error("GHC functions return void only");
9088 
9089   SDValue Glue;
9090   SmallVector<SDValue, 4> RetOps(1, Chain);
9091 
9092   // Copy the result values into the output registers.
9093   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9094     SDValue Val = OutVals[i];
9095     CCValAssign &VA = RVLocs[i];
9096     assert(VA.isRegLoc() && "Can only return in registers!");
9097 
9098     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9099       // Handle returning f64 on RV32D with a soft float ABI.
9100       assert(VA.isRegLoc() && "Expected return via registers");
9101       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9102                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9103       SDValue Lo = SplitF64.getValue(0);
9104       SDValue Hi = SplitF64.getValue(1);
9105       Register RegLo = VA.getLocReg();
9106       assert(RegLo < RISCV::X31 && "Invalid register pair");
9107       Register RegHi = RegLo + 1;
9108 
9109       if (STI.isRegisterReservedByUser(RegLo) ||
9110           STI.isRegisterReservedByUser(RegHi))
9111         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9112             MF.getFunction(),
9113             "Return value register required, but has been reserved."});
9114 
9115       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9116       Glue = Chain.getValue(1);
9117       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9118       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9119       Glue = Chain.getValue(1);
9120       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9121     } else {
9122       // Handle a 'normal' return.
9123       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9124       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9125 
9126       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9127         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9128             MF.getFunction(),
9129             "Return value register required, but has been reserved."});
9130 
9131       // Guarantee that all emitted copies are stuck together.
9132       Glue = Chain.getValue(1);
9133       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9134     }
9135   }
9136 
9137   RetOps[0] = Chain; // Update chain.
9138 
9139   // Add the glue node if we have it.
9140   if (Glue.getNode()) {
9141     RetOps.push_back(Glue);
9142   }
9143 
9144   unsigned RetOpc = RISCVISD::RET_FLAG;
9145   // Interrupt service routines use different return instructions.
9146   const Function &Func = DAG.getMachineFunction().getFunction();
9147   if (Func.hasFnAttribute("interrupt")) {
9148     if (!Func.getReturnType()->isVoidTy())
9149       report_fatal_error(
9150           "Functions with the interrupt attribute must have void return type!");
9151 
9152     MachineFunction &MF = DAG.getMachineFunction();
9153     StringRef Kind =
9154       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9155 
9156     if (Kind == "user")
9157       RetOpc = RISCVISD::URET_FLAG;
9158     else if (Kind == "supervisor")
9159       RetOpc = RISCVISD::SRET_FLAG;
9160     else
9161       RetOpc = RISCVISD::MRET_FLAG;
9162   }
9163 
9164   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9165 }
9166 
9167 void RISCVTargetLowering::validateCCReservedRegs(
9168     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9169     MachineFunction &MF) const {
9170   const Function &F = MF.getFunction();
9171   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9172 
9173   if (llvm::any_of(Regs, [&STI](auto Reg) {
9174         return STI.isRegisterReservedByUser(Reg.first);
9175       }))
9176     F.getContext().diagnose(DiagnosticInfoUnsupported{
9177         F, "Argument register required, but has been reserved."});
9178 }
9179 
9180 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9181   return CI->isTailCall();
9182 }
9183 
9184 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9185 #define NODE_NAME_CASE(NODE)                                                   \
9186   case RISCVISD::NODE:                                                         \
9187     return "RISCVISD::" #NODE;
9188   // clang-format off
9189   switch ((RISCVISD::NodeType)Opcode) {
9190   case RISCVISD::FIRST_NUMBER:
9191     break;
9192   NODE_NAME_CASE(RET_FLAG)
9193   NODE_NAME_CASE(URET_FLAG)
9194   NODE_NAME_CASE(SRET_FLAG)
9195   NODE_NAME_CASE(MRET_FLAG)
9196   NODE_NAME_CASE(CALL)
9197   NODE_NAME_CASE(SELECT_CC)
9198   NODE_NAME_CASE(BR_CC)
9199   NODE_NAME_CASE(BuildPairF64)
9200   NODE_NAME_CASE(SplitF64)
9201   NODE_NAME_CASE(TAIL)
9202   NODE_NAME_CASE(MULHSU)
9203   NODE_NAME_CASE(SLLW)
9204   NODE_NAME_CASE(SRAW)
9205   NODE_NAME_CASE(SRLW)
9206   NODE_NAME_CASE(DIVW)
9207   NODE_NAME_CASE(DIVUW)
9208   NODE_NAME_CASE(REMUW)
9209   NODE_NAME_CASE(ROLW)
9210   NODE_NAME_CASE(RORW)
9211   NODE_NAME_CASE(CLZW)
9212   NODE_NAME_CASE(CTZW)
9213   NODE_NAME_CASE(FSLW)
9214   NODE_NAME_CASE(FSRW)
9215   NODE_NAME_CASE(FSL)
9216   NODE_NAME_CASE(FSR)
9217   NODE_NAME_CASE(FMV_H_X)
9218   NODE_NAME_CASE(FMV_X_ANYEXTH)
9219   NODE_NAME_CASE(FMV_W_X_RV64)
9220   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9221   NODE_NAME_CASE(FCVT_X_RTZ)
9222   NODE_NAME_CASE(FCVT_XU_RTZ)
9223   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9224   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9225   NODE_NAME_CASE(READ_CYCLE_WIDE)
9226   NODE_NAME_CASE(GREV)
9227   NODE_NAME_CASE(GREVW)
9228   NODE_NAME_CASE(GORC)
9229   NODE_NAME_CASE(GORCW)
9230   NODE_NAME_CASE(SHFL)
9231   NODE_NAME_CASE(SHFLW)
9232   NODE_NAME_CASE(UNSHFL)
9233   NODE_NAME_CASE(UNSHFLW)
9234   NODE_NAME_CASE(BCOMPRESS)
9235   NODE_NAME_CASE(BCOMPRESSW)
9236   NODE_NAME_CASE(BDECOMPRESS)
9237   NODE_NAME_CASE(BDECOMPRESSW)
9238   NODE_NAME_CASE(VMV_V_X_VL)
9239   NODE_NAME_CASE(VFMV_V_F_VL)
9240   NODE_NAME_CASE(VMV_X_S)
9241   NODE_NAME_CASE(VMV_S_X_VL)
9242   NODE_NAME_CASE(VFMV_S_F_VL)
9243   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9244   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9245   NODE_NAME_CASE(READ_VLENB)
9246   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9247   NODE_NAME_CASE(VSLIDEUP_VL)
9248   NODE_NAME_CASE(VSLIDE1UP_VL)
9249   NODE_NAME_CASE(VSLIDEDOWN_VL)
9250   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9251   NODE_NAME_CASE(VID_VL)
9252   NODE_NAME_CASE(VFNCVT_ROD_VL)
9253   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9254   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9255   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9256   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9257   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9258   NODE_NAME_CASE(VECREDUCE_AND_VL)
9259   NODE_NAME_CASE(VECREDUCE_OR_VL)
9260   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9261   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9262   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9263   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9264   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9265   NODE_NAME_CASE(ADD_VL)
9266   NODE_NAME_CASE(AND_VL)
9267   NODE_NAME_CASE(MUL_VL)
9268   NODE_NAME_CASE(OR_VL)
9269   NODE_NAME_CASE(SDIV_VL)
9270   NODE_NAME_CASE(SHL_VL)
9271   NODE_NAME_CASE(SREM_VL)
9272   NODE_NAME_CASE(SRA_VL)
9273   NODE_NAME_CASE(SRL_VL)
9274   NODE_NAME_CASE(SUB_VL)
9275   NODE_NAME_CASE(UDIV_VL)
9276   NODE_NAME_CASE(UREM_VL)
9277   NODE_NAME_CASE(XOR_VL)
9278   NODE_NAME_CASE(SADDSAT_VL)
9279   NODE_NAME_CASE(UADDSAT_VL)
9280   NODE_NAME_CASE(SSUBSAT_VL)
9281   NODE_NAME_CASE(USUBSAT_VL)
9282   NODE_NAME_CASE(FADD_VL)
9283   NODE_NAME_CASE(FSUB_VL)
9284   NODE_NAME_CASE(FMUL_VL)
9285   NODE_NAME_CASE(FDIV_VL)
9286   NODE_NAME_CASE(FNEG_VL)
9287   NODE_NAME_CASE(FABS_VL)
9288   NODE_NAME_CASE(FSQRT_VL)
9289   NODE_NAME_CASE(FMA_VL)
9290   NODE_NAME_CASE(FCOPYSIGN_VL)
9291   NODE_NAME_CASE(SMIN_VL)
9292   NODE_NAME_CASE(SMAX_VL)
9293   NODE_NAME_CASE(UMIN_VL)
9294   NODE_NAME_CASE(UMAX_VL)
9295   NODE_NAME_CASE(FMINNUM_VL)
9296   NODE_NAME_CASE(FMAXNUM_VL)
9297   NODE_NAME_CASE(MULHS_VL)
9298   NODE_NAME_CASE(MULHU_VL)
9299   NODE_NAME_CASE(FP_TO_SINT_VL)
9300   NODE_NAME_CASE(FP_TO_UINT_VL)
9301   NODE_NAME_CASE(SINT_TO_FP_VL)
9302   NODE_NAME_CASE(UINT_TO_FP_VL)
9303   NODE_NAME_CASE(FP_EXTEND_VL)
9304   NODE_NAME_CASE(FP_ROUND_VL)
9305   NODE_NAME_CASE(VWMUL_VL)
9306   NODE_NAME_CASE(VWMULU_VL)
9307   NODE_NAME_CASE(SETCC_VL)
9308   NODE_NAME_CASE(VSELECT_VL)
9309   NODE_NAME_CASE(VMAND_VL)
9310   NODE_NAME_CASE(VMOR_VL)
9311   NODE_NAME_CASE(VMXOR_VL)
9312   NODE_NAME_CASE(VMCLR_VL)
9313   NODE_NAME_CASE(VMSET_VL)
9314   NODE_NAME_CASE(VRGATHER_VX_VL)
9315   NODE_NAME_CASE(VRGATHER_VV_VL)
9316   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9317   NODE_NAME_CASE(VSEXT_VL)
9318   NODE_NAME_CASE(VZEXT_VL)
9319   NODE_NAME_CASE(VCPOP_VL)
9320   NODE_NAME_CASE(VLE_VL)
9321   NODE_NAME_CASE(VSE_VL)
9322   NODE_NAME_CASE(READ_CSR)
9323   NODE_NAME_CASE(WRITE_CSR)
9324   NODE_NAME_CASE(SWAP_CSR)
9325   }
9326   // clang-format on
9327   return nullptr;
9328 #undef NODE_NAME_CASE
9329 }
9330 
9331 /// getConstraintType - Given a constraint letter, return the type of
9332 /// constraint it is for this target.
9333 RISCVTargetLowering::ConstraintType
9334 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9335   if (Constraint.size() == 1) {
9336     switch (Constraint[0]) {
9337     default:
9338       break;
9339     case 'f':
9340       return C_RegisterClass;
9341     case 'I':
9342     case 'J':
9343     case 'K':
9344       return C_Immediate;
9345     case 'A':
9346       return C_Memory;
9347     case 'S': // A symbolic address
9348       return C_Other;
9349     }
9350   } else {
9351     if (Constraint == "vr" || Constraint == "vm")
9352       return C_RegisterClass;
9353   }
9354   return TargetLowering::getConstraintType(Constraint);
9355 }
9356 
9357 std::pair<unsigned, const TargetRegisterClass *>
9358 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9359                                                   StringRef Constraint,
9360                                                   MVT VT) const {
9361   // First, see if this is a constraint that directly corresponds to a
9362   // RISCV register class.
9363   if (Constraint.size() == 1) {
9364     switch (Constraint[0]) {
9365     case 'r':
9366       return std::make_pair(0U, &RISCV::GPRRegClass);
9367     case 'f':
9368       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9369         return std::make_pair(0U, &RISCV::FPR16RegClass);
9370       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9371         return std::make_pair(0U, &RISCV::FPR32RegClass);
9372       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9373         return std::make_pair(0U, &RISCV::FPR64RegClass);
9374       break;
9375     default:
9376       break;
9377     }
9378   } else {
9379     if (Constraint == "vr") {
9380       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9381                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9382         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9383           return std::make_pair(0U, RC);
9384       }
9385     } else if (Constraint == "vm") {
9386       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9387         return std::make_pair(0U, &RISCV::VMRegClass);
9388     }
9389   }
9390 
9391   // Clang will correctly decode the usage of register name aliases into their
9392   // official names. However, other frontends like `rustc` do not. This allows
9393   // users of these frontends to use the ABI names for registers in LLVM-style
9394   // register constraints.
9395   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9396                                .Case("{zero}", RISCV::X0)
9397                                .Case("{ra}", RISCV::X1)
9398                                .Case("{sp}", RISCV::X2)
9399                                .Case("{gp}", RISCV::X3)
9400                                .Case("{tp}", RISCV::X4)
9401                                .Case("{t0}", RISCV::X5)
9402                                .Case("{t1}", RISCV::X6)
9403                                .Case("{t2}", RISCV::X7)
9404                                .Cases("{s0}", "{fp}", RISCV::X8)
9405                                .Case("{s1}", RISCV::X9)
9406                                .Case("{a0}", RISCV::X10)
9407                                .Case("{a1}", RISCV::X11)
9408                                .Case("{a2}", RISCV::X12)
9409                                .Case("{a3}", RISCV::X13)
9410                                .Case("{a4}", RISCV::X14)
9411                                .Case("{a5}", RISCV::X15)
9412                                .Case("{a6}", RISCV::X16)
9413                                .Case("{a7}", RISCV::X17)
9414                                .Case("{s2}", RISCV::X18)
9415                                .Case("{s3}", RISCV::X19)
9416                                .Case("{s4}", RISCV::X20)
9417                                .Case("{s5}", RISCV::X21)
9418                                .Case("{s6}", RISCV::X22)
9419                                .Case("{s7}", RISCV::X23)
9420                                .Case("{s8}", RISCV::X24)
9421                                .Case("{s9}", RISCV::X25)
9422                                .Case("{s10}", RISCV::X26)
9423                                .Case("{s11}", RISCV::X27)
9424                                .Case("{t3}", RISCV::X28)
9425                                .Case("{t4}", RISCV::X29)
9426                                .Case("{t5}", RISCV::X30)
9427                                .Case("{t6}", RISCV::X31)
9428                                .Default(RISCV::NoRegister);
9429   if (XRegFromAlias != RISCV::NoRegister)
9430     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9431 
9432   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9433   // TableGen record rather than the AsmName to choose registers for InlineAsm
9434   // constraints, plus we want to match those names to the widest floating point
9435   // register type available, manually select floating point registers here.
9436   //
9437   // The second case is the ABI name of the register, so that frontends can also
9438   // use the ABI names in register constraint lists.
9439   if (Subtarget.hasStdExtF()) {
9440     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9441                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9442                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9443                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9444                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9445                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9446                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9447                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9448                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9449                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9450                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9451                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9452                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9453                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9454                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9455                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9456                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9457                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9458                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9459                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9460                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9461                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9462                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9463                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9464                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9465                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9466                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9467                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9468                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9469                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9470                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9471                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9472                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9473                         .Default(RISCV::NoRegister);
9474     if (FReg != RISCV::NoRegister) {
9475       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9476       if (Subtarget.hasStdExtD()) {
9477         unsigned RegNo = FReg - RISCV::F0_F;
9478         unsigned DReg = RISCV::F0_D + RegNo;
9479         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9480       }
9481       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9482     }
9483   }
9484 
9485   if (Subtarget.hasVInstructions()) {
9486     Register VReg = StringSwitch<Register>(Constraint.lower())
9487                         .Case("{v0}", RISCV::V0)
9488                         .Case("{v1}", RISCV::V1)
9489                         .Case("{v2}", RISCV::V2)
9490                         .Case("{v3}", RISCV::V3)
9491                         .Case("{v4}", RISCV::V4)
9492                         .Case("{v5}", RISCV::V5)
9493                         .Case("{v6}", RISCV::V6)
9494                         .Case("{v7}", RISCV::V7)
9495                         .Case("{v8}", RISCV::V8)
9496                         .Case("{v9}", RISCV::V9)
9497                         .Case("{v10}", RISCV::V10)
9498                         .Case("{v11}", RISCV::V11)
9499                         .Case("{v12}", RISCV::V12)
9500                         .Case("{v13}", RISCV::V13)
9501                         .Case("{v14}", RISCV::V14)
9502                         .Case("{v15}", RISCV::V15)
9503                         .Case("{v16}", RISCV::V16)
9504                         .Case("{v17}", RISCV::V17)
9505                         .Case("{v18}", RISCV::V18)
9506                         .Case("{v19}", RISCV::V19)
9507                         .Case("{v20}", RISCV::V20)
9508                         .Case("{v21}", RISCV::V21)
9509                         .Case("{v22}", RISCV::V22)
9510                         .Case("{v23}", RISCV::V23)
9511                         .Case("{v24}", RISCV::V24)
9512                         .Case("{v25}", RISCV::V25)
9513                         .Case("{v26}", RISCV::V26)
9514                         .Case("{v27}", RISCV::V27)
9515                         .Case("{v28}", RISCV::V28)
9516                         .Case("{v29}", RISCV::V29)
9517                         .Case("{v30}", RISCV::V30)
9518                         .Case("{v31}", RISCV::V31)
9519                         .Default(RISCV::NoRegister);
9520     if (VReg != RISCV::NoRegister) {
9521       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9522         return std::make_pair(VReg, &RISCV::VMRegClass);
9523       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9524         return std::make_pair(VReg, &RISCV::VRRegClass);
9525       for (const auto *RC :
9526            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9527         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9528           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9529           return std::make_pair(VReg, RC);
9530         }
9531       }
9532     }
9533   }
9534 
9535   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9536 }
9537 
9538 unsigned
9539 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9540   // Currently only support length 1 constraints.
9541   if (ConstraintCode.size() == 1) {
9542     switch (ConstraintCode[0]) {
9543     case 'A':
9544       return InlineAsm::Constraint_A;
9545     default:
9546       break;
9547     }
9548   }
9549 
9550   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9551 }
9552 
9553 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9554     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9555     SelectionDAG &DAG) const {
9556   // Currently only support length 1 constraints.
9557   if (Constraint.length() == 1) {
9558     switch (Constraint[0]) {
9559     case 'I':
9560       // Validate & create a 12-bit signed immediate operand.
9561       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9562         uint64_t CVal = C->getSExtValue();
9563         if (isInt<12>(CVal))
9564           Ops.push_back(
9565               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9566       }
9567       return;
9568     case 'J':
9569       // Validate & create an integer zero operand.
9570       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9571         if (C->getZExtValue() == 0)
9572           Ops.push_back(
9573               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9574       return;
9575     case 'K':
9576       // Validate & create a 5-bit unsigned immediate operand.
9577       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9578         uint64_t CVal = C->getZExtValue();
9579         if (isUInt<5>(CVal))
9580           Ops.push_back(
9581               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9582       }
9583       return;
9584     case 'S':
9585       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9586         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9587                                                  GA->getValueType(0)));
9588       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9589         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9590                                                 BA->getValueType(0)));
9591       }
9592       return;
9593     default:
9594       break;
9595     }
9596   }
9597   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9598 }
9599 
9600 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9601                                                    Instruction *Inst,
9602                                                    AtomicOrdering Ord) const {
9603   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9604     return Builder.CreateFence(Ord);
9605   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9606     return Builder.CreateFence(AtomicOrdering::Release);
9607   return nullptr;
9608 }
9609 
9610 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9611                                                     Instruction *Inst,
9612                                                     AtomicOrdering Ord) const {
9613   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9614     return Builder.CreateFence(AtomicOrdering::Acquire);
9615   return nullptr;
9616 }
9617 
9618 TargetLowering::AtomicExpansionKind
9619 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9620   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9621   // point operations can't be used in an lr/sc sequence without breaking the
9622   // forward-progress guarantee.
9623   if (AI->isFloatingPointOperation())
9624     return AtomicExpansionKind::CmpXChg;
9625 
9626   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9627   if (Size == 8 || Size == 16)
9628     return AtomicExpansionKind::MaskedIntrinsic;
9629   return AtomicExpansionKind::None;
9630 }
9631 
9632 static Intrinsic::ID
9633 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9634   if (XLen == 32) {
9635     switch (BinOp) {
9636     default:
9637       llvm_unreachable("Unexpected AtomicRMW BinOp");
9638     case AtomicRMWInst::Xchg:
9639       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9640     case AtomicRMWInst::Add:
9641       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9642     case AtomicRMWInst::Sub:
9643       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9644     case AtomicRMWInst::Nand:
9645       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9646     case AtomicRMWInst::Max:
9647       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9648     case AtomicRMWInst::Min:
9649       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9650     case AtomicRMWInst::UMax:
9651       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9652     case AtomicRMWInst::UMin:
9653       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9654     }
9655   }
9656 
9657   if (XLen == 64) {
9658     switch (BinOp) {
9659     default:
9660       llvm_unreachable("Unexpected AtomicRMW BinOp");
9661     case AtomicRMWInst::Xchg:
9662       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9663     case AtomicRMWInst::Add:
9664       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9665     case AtomicRMWInst::Sub:
9666       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9667     case AtomicRMWInst::Nand:
9668       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9669     case AtomicRMWInst::Max:
9670       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9671     case AtomicRMWInst::Min:
9672       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9673     case AtomicRMWInst::UMax:
9674       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9675     case AtomicRMWInst::UMin:
9676       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9677     }
9678   }
9679 
9680   llvm_unreachable("Unexpected XLen\n");
9681 }
9682 
9683 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9684     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9685     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9686   unsigned XLen = Subtarget.getXLen();
9687   Value *Ordering =
9688       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9689   Type *Tys[] = {AlignedAddr->getType()};
9690   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9691       AI->getModule(),
9692       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9693 
9694   if (XLen == 64) {
9695     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9696     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9697     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9698   }
9699 
9700   Value *Result;
9701 
9702   // Must pass the shift amount needed to sign extend the loaded value prior
9703   // to performing a signed comparison for min/max. ShiftAmt is the number of
9704   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9705   // is the number of bits to left+right shift the value in order to
9706   // sign-extend.
9707   if (AI->getOperation() == AtomicRMWInst::Min ||
9708       AI->getOperation() == AtomicRMWInst::Max) {
9709     const DataLayout &DL = AI->getModule()->getDataLayout();
9710     unsigned ValWidth =
9711         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9712     Value *SextShamt =
9713         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9714     Result = Builder.CreateCall(LrwOpScwLoop,
9715                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9716   } else {
9717     Result =
9718         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9719   }
9720 
9721   if (XLen == 64)
9722     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9723   return Result;
9724 }
9725 
9726 TargetLowering::AtomicExpansionKind
9727 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9728     AtomicCmpXchgInst *CI) const {
9729   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9730   if (Size == 8 || Size == 16)
9731     return AtomicExpansionKind::MaskedIntrinsic;
9732   return AtomicExpansionKind::None;
9733 }
9734 
9735 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9736     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9737     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9738   unsigned XLen = Subtarget.getXLen();
9739   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9740   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9741   if (XLen == 64) {
9742     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9743     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9744     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9745     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9746   }
9747   Type *Tys[] = {AlignedAddr->getType()};
9748   Function *MaskedCmpXchg =
9749       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9750   Value *Result = Builder.CreateCall(
9751       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9752   if (XLen == 64)
9753     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9754   return Result;
9755 }
9756 
9757 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9758   return false;
9759 }
9760 
9761 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9762                                                      EVT VT) const {
9763   VT = VT.getScalarType();
9764 
9765   if (!VT.isSimple())
9766     return false;
9767 
9768   switch (VT.getSimpleVT().SimpleTy) {
9769   case MVT::f16:
9770     return Subtarget.hasStdExtZfh();
9771   case MVT::f32:
9772     return Subtarget.hasStdExtF();
9773   case MVT::f64:
9774     return Subtarget.hasStdExtD();
9775   default:
9776     break;
9777   }
9778 
9779   return false;
9780 }
9781 
9782 Register RISCVTargetLowering::getExceptionPointerRegister(
9783     const Constant *PersonalityFn) const {
9784   return RISCV::X10;
9785 }
9786 
9787 Register RISCVTargetLowering::getExceptionSelectorRegister(
9788     const Constant *PersonalityFn) const {
9789   return RISCV::X11;
9790 }
9791 
9792 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9793   // Return false to suppress the unnecessary extensions if the LibCall
9794   // arguments or return value is f32 type for LP64 ABI.
9795   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9796   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9797     return false;
9798 
9799   return true;
9800 }
9801 
9802 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9803   if (Subtarget.is64Bit() && Type == MVT::i32)
9804     return true;
9805 
9806   return IsSigned;
9807 }
9808 
9809 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9810                                                  SDValue C) const {
9811   // Check integral scalar types.
9812   if (VT.isScalarInteger()) {
9813     // Omit the optimization if the sub target has the M extension and the data
9814     // size exceeds XLen.
9815     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9816       return false;
9817     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9818       // Break the MUL to a SLLI and an ADD/SUB.
9819       const APInt &Imm = ConstNode->getAPIntValue();
9820       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9821           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9822         return true;
9823       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9824       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9825           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9826            (Imm - 8).isPowerOf2()))
9827         return true;
9828       // Omit the following optimization if the sub target has the M extension
9829       // and the data size >= XLen.
9830       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9831         return false;
9832       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9833       // a pair of LUI/ADDI.
9834       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9835         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9836         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9837             (1 - ImmS).isPowerOf2())
9838         return true;
9839       }
9840     }
9841   }
9842 
9843   return false;
9844 }
9845 
9846 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9847     const SDValue &AddNode, const SDValue &ConstNode) const {
9848   // Let the DAGCombiner decide for vectors.
9849   EVT VT = AddNode.getValueType();
9850   if (VT.isVector())
9851     return true;
9852 
9853   // Let the DAGCombiner decide for larger types.
9854   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9855     return true;
9856 
9857   // It is worse if c1 is simm12 while c1*c2 is not.
9858   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9859   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9860   const APInt &C1 = C1Node->getAPIntValue();
9861   const APInt &C2 = C2Node->getAPIntValue();
9862   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9863     return false;
9864 
9865   // Default to true and let the DAGCombiner decide.
9866   return true;
9867 }
9868 
9869 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9870     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9871     bool *Fast) const {
9872   if (!VT.isVector())
9873     return false;
9874 
9875   EVT ElemVT = VT.getVectorElementType();
9876   if (Alignment >= ElemVT.getStoreSize()) {
9877     if (Fast)
9878       *Fast = true;
9879     return true;
9880   }
9881 
9882   return false;
9883 }
9884 
9885 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9886     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9887     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9888   bool IsABIRegCopy = CC.hasValue();
9889   EVT ValueVT = Val.getValueType();
9890   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9891     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9892     // and cast to f32.
9893     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9894     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9895     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9896                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9897     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9898     Parts[0] = Val;
9899     return true;
9900   }
9901 
9902   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9903     LLVMContext &Context = *DAG.getContext();
9904     EVT ValueEltVT = ValueVT.getVectorElementType();
9905     EVT PartEltVT = PartVT.getVectorElementType();
9906     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9907     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9908     if (PartVTBitSize % ValueVTBitSize == 0) {
9909       // If the element types are different, bitcast to the same element type of
9910       // PartVT first.
9911       if (ValueEltVT != PartEltVT) {
9912         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9913         assert(Count != 0 && "The number of element should not be zero.");
9914         EVT SameEltTypeVT =
9915             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9916         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9917       }
9918       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9919                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9920       Parts[0] = Val;
9921       return true;
9922     }
9923   }
9924   return false;
9925 }
9926 
9927 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9928     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9929     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9930   bool IsABIRegCopy = CC.hasValue();
9931   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9932     SDValue Val = Parts[0];
9933 
9934     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9935     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9936     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9937     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9938     return Val;
9939   }
9940 
9941   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9942     LLVMContext &Context = *DAG.getContext();
9943     SDValue Val = Parts[0];
9944     EVT ValueEltVT = ValueVT.getVectorElementType();
9945     EVT PartEltVT = PartVT.getVectorElementType();
9946     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9947     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9948     if (PartVTBitSize % ValueVTBitSize == 0) {
9949       EVT SameEltTypeVT = ValueVT;
9950       // If the element types are different, convert it to the same element type
9951       // of PartVT.
9952       if (ValueEltVT != PartEltVT) {
9953         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9954         assert(Count != 0 && "The number of element should not be zero.");
9955         SameEltTypeVT =
9956             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9957       }
9958       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9959                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9960       if (ValueEltVT != PartEltVT)
9961         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9962       return Val;
9963     }
9964   }
9965   return SDValue();
9966 }
9967 
9968 #define GET_REGISTER_MATCHER
9969 #include "RISCVGenAsmMatcher.inc"
9970 
9971 Register
9972 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9973                                        const MachineFunction &MF) const {
9974   Register Reg = MatchRegisterAltName(RegName);
9975   if (Reg == RISCV::NoRegister)
9976     Reg = MatchRegisterName(RegName);
9977   if (Reg == RISCV::NoRegister)
9978     report_fatal_error(
9979         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9980   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9981   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9982     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9983                              StringRef(RegName) + "\"."));
9984   return Reg;
9985 }
9986 
9987 namespace llvm {
9988 namespace RISCVVIntrinsicsTable {
9989 
9990 #define GET_RISCVVIntrinsicsTable_IMPL
9991 #include "RISCVGenSearchableTables.inc"
9992 
9993 } // namespace RISCVVIntrinsicsTable
9994 
9995 } // namespace llvm
9996