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 
342   if (Subtarget.hasStdExtF()) {
343     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
344     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
345     setOperationAction(ISD::LRINT, MVT::f32, Legal);
346     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
347     setOperationAction(ISD::LROUND, MVT::f32, Legal);
348     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
349     for (auto CC : FPCCToExpand)
350       setCondCodeAction(CC, MVT::f32, Expand);
351     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
352     setOperationAction(ISD::SELECT, MVT::f32, Custom);
353     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
354     for (auto Op : FPOpToExpand)
355       setOperationAction(Op, MVT::f32, Expand);
356     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
357     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
358   }
359 
360   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
361     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
362 
363   if (Subtarget.hasStdExtD()) {
364     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
365     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
366     setOperationAction(ISD::LRINT, MVT::f64, Legal);
367     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
368     setOperationAction(ISD::LROUND, MVT::f64, Legal);
369     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
370     for (auto CC : FPCCToExpand)
371       setCondCodeAction(CC, MVT::f64, Expand);
372     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
373     setOperationAction(ISD::SELECT, MVT::f64, Custom);
374     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
375     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
376     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
377     for (auto Op : FPOpToExpand)
378       setOperationAction(Op, MVT::f64, Expand);
379     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   }
382 
383   if (Subtarget.is64Bit()) {
384     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
385     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
386     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
387     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
388   }
389 
390   if (Subtarget.hasStdExtF()) {
391     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
392     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
393 
394     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
395     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
396   }
397 
398   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
399   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
400   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
401   setOperationAction(ISD::JumpTable, XLenVT, Custom);
402 
403   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
404 
405   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
406   // Unfortunately this can't be determined just from the ISA naming string.
407   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
408                      Subtarget.is64Bit() ? Legal : Custom);
409 
410   setOperationAction(ISD::TRAP, MVT::Other, Legal);
411   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
412   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
413   if (Subtarget.is64Bit())
414     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
415 
416   if (Subtarget.hasStdExtA()) {
417     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
418     setMinCmpXchgSizeInBits(32);
419   } else {
420     setMaxAtomicSizeInBitsSupported(0);
421   }
422 
423   setBooleanContents(ZeroOrOneBooleanContent);
424 
425   if (Subtarget.hasVInstructions()) {
426     setBooleanVectorContents(ZeroOrOneBooleanContent);
427 
428     setOperationAction(ISD::VSCALE, XLenVT, Custom);
429 
430     // RVV intrinsics may have illegal operands.
431     // We also need to custom legalize vmv.x.s.
432     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
433     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
434     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
435     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
436     if (Subtarget.is64Bit()) {
437       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
438     } else {
439       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
440       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
441     }
442 
443     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
444     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
445 
446     static const unsigned IntegerVPOps[] = {
447         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
448         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
449         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
450         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
451         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
452         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
453         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN};
454 
455     static const unsigned FloatingPointVPOps[] = {
456         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
457         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
458         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX};
459 
460     if (!Subtarget.is64Bit()) {
461       // We must custom-lower certain vXi64 operations on RV32 due to the vector
462       // element type being illegal.
463       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
464       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
465 
466       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
467       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
468       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
469       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
470       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
471       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
472       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
473       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
474 
475       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
476       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
477       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
478       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
479       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
480       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
481       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
482       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
483     }
484 
485     for (MVT VT : BoolVecVTs) {
486       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
487 
488       // Mask VTs are custom-expanded into a series of standard nodes
489       setOperationAction(ISD::TRUNCATE, VT, Custom);
490       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
491       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
492       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
493 
494       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
495       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
496 
497       setOperationAction(ISD::SELECT, VT, Custom);
498       setOperationAction(ISD::SELECT_CC, VT, Expand);
499       setOperationAction(ISD::VSELECT, VT, Expand);
500 
501       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
502       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
503       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
504 
505       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
506       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
507       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
508 
509       // RVV has native int->float & float->int conversions where the
510       // element type sizes are within one power-of-two of each other. Any
511       // wider distances between type sizes have to be lowered as sequences
512       // which progressively narrow the gap in stages.
513       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
514       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
515       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
516       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
517 
518       // Expand all extending loads to types larger than this, and truncating
519       // stores from types larger than this.
520       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
521         setTruncStoreAction(OtherVT, VT, Expand);
522         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
523         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
524         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
525       }
526     }
527 
528     for (MVT VT : IntVecVTs) {
529       if (VT.getVectorElementType() == MVT::i64 &&
530           !Subtarget.hasVInstructionsI64())
531         continue;
532 
533       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
534       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
535 
536       // Vectors implement MULHS/MULHU.
537       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
538       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
539 
540       setOperationAction(ISD::SMIN, VT, Legal);
541       setOperationAction(ISD::SMAX, VT, Legal);
542       setOperationAction(ISD::UMIN, VT, Legal);
543       setOperationAction(ISD::UMAX, VT, Legal);
544 
545       setOperationAction(ISD::ROTL, VT, Expand);
546       setOperationAction(ISD::ROTR, VT, Expand);
547 
548       setOperationAction(ISD::CTTZ, VT, Expand);
549       setOperationAction(ISD::CTLZ, VT, Expand);
550       setOperationAction(ISD::CTPOP, VT, Expand);
551 
552       setOperationAction(ISD::BSWAP, VT, Expand);
553 
554       // Custom-lower extensions and truncations from/to mask types.
555       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
556       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
557       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
558 
559       // RVV has native int->float & float->int conversions where the
560       // element type sizes are within one power-of-two of each other. Any
561       // wider distances between type sizes have to be lowered as sequences
562       // which progressively narrow the gap in stages.
563       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
564       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
565       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
566       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
567 
568       setOperationAction(ISD::SADDSAT, VT, Legal);
569       setOperationAction(ISD::UADDSAT, VT, Legal);
570       setOperationAction(ISD::SSUBSAT, VT, Legal);
571       setOperationAction(ISD::USUBSAT, VT, Legal);
572 
573       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
574       // nodes which truncate by one power of two at a time.
575       setOperationAction(ISD::TRUNCATE, VT, Custom);
576 
577       // Custom-lower insert/extract operations to simplify patterns.
578       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
579       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
580 
581       // Custom-lower reduction operations to set up the corresponding custom
582       // nodes' operands.
583       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
584       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
585       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
586       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
587       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
588       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
589       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
590       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
591 
592       for (unsigned VPOpc : IntegerVPOps)
593         setOperationAction(VPOpc, VT, Custom);
594 
595       setOperationAction(ISD::LOAD, VT, Custom);
596       setOperationAction(ISD::STORE, VT, Custom);
597 
598       setOperationAction(ISD::MLOAD, VT, Custom);
599       setOperationAction(ISD::MSTORE, VT, Custom);
600       setOperationAction(ISD::MGATHER, VT, Custom);
601       setOperationAction(ISD::MSCATTER, VT, Custom);
602 
603       setOperationAction(ISD::VP_LOAD, VT, Custom);
604       setOperationAction(ISD::VP_STORE, VT, Custom);
605       setOperationAction(ISD::VP_GATHER, VT, Custom);
606       setOperationAction(ISD::VP_SCATTER, VT, Custom);
607 
608       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
609       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
610       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
611 
612       setOperationAction(ISD::SELECT, VT, Custom);
613       setOperationAction(ISD::SELECT_CC, VT, Expand);
614 
615       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
616       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
617 
618       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
619         setTruncStoreAction(VT, OtherVT, Expand);
620         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
621         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
622         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
623       }
624     }
625 
626     // Expand various CCs to best match the RVV ISA, which natively supports UNE
627     // but no other unordered comparisons, and supports all ordered comparisons
628     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
629     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
630     // and we pattern-match those back to the "original", swapping operands once
631     // more. This way we catch both operations and both "vf" and "fv" forms with
632     // fewer patterns.
633     static const ISD::CondCode VFPCCToExpand[] = {
634         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
635         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
636         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
637     };
638 
639     // Sets common operation actions on RVV floating-point vector types.
640     const auto SetCommonVFPActions = [&](MVT VT) {
641       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
642       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
643       // sizes are within one power-of-two of each other. Therefore conversions
644       // between vXf16 and vXf64 must be lowered as sequences which convert via
645       // vXf32.
646       setOperationAction(ISD::FP_ROUND, VT, Custom);
647       setOperationAction(ISD::FP_EXTEND, VT, Custom);
648       // Custom-lower insert/extract operations to simplify patterns.
649       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
650       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
651       // Expand various condition codes (explained above).
652       for (auto CC : VFPCCToExpand)
653         setCondCodeAction(CC, VT, Expand);
654 
655       setOperationAction(ISD::FMINNUM, VT, Legal);
656       setOperationAction(ISD::FMAXNUM, VT, Legal);
657 
658       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
659       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
660       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
661       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
662 
663       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
664 
665       setOperationAction(ISD::LOAD, VT, Custom);
666       setOperationAction(ISD::STORE, VT, Custom);
667 
668       setOperationAction(ISD::MLOAD, VT, Custom);
669       setOperationAction(ISD::MSTORE, VT, Custom);
670       setOperationAction(ISD::MGATHER, VT, Custom);
671       setOperationAction(ISD::MSCATTER, VT, Custom);
672 
673       setOperationAction(ISD::VP_LOAD, VT, Custom);
674       setOperationAction(ISD::VP_STORE, VT, Custom);
675       setOperationAction(ISD::VP_GATHER, VT, Custom);
676       setOperationAction(ISD::VP_SCATTER, VT, Custom);
677 
678       setOperationAction(ISD::SELECT, VT, Custom);
679       setOperationAction(ISD::SELECT_CC, VT, Expand);
680 
681       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
682       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
683       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
684 
685       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
686 
687       for (unsigned VPOpc : FloatingPointVPOps)
688         setOperationAction(VPOpc, VT, Custom);
689     };
690 
691     // Sets common extload/truncstore actions on RVV floating-point vector
692     // types.
693     const auto SetCommonVFPExtLoadTruncStoreActions =
694         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
695           for (auto SmallVT : SmallerVTs) {
696             setTruncStoreAction(VT, SmallVT, Expand);
697             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
698           }
699         };
700 
701     if (Subtarget.hasVInstructionsF16())
702       for (MVT VT : F16VecVTs)
703         SetCommonVFPActions(VT);
704 
705     for (MVT VT : F32VecVTs) {
706       if (Subtarget.hasVInstructionsF32())
707         SetCommonVFPActions(VT);
708       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
709     }
710 
711     for (MVT VT : F64VecVTs) {
712       if (Subtarget.hasVInstructionsF64())
713         SetCommonVFPActions(VT);
714       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
715       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
716     }
717 
718     if (Subtarget.useRVVForFixedLengthVectors()) {
719       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
720         if (!useRVVForFixedLengthVectorVT(VT))
721           continue;
722 
723         // By default everything must be expanded.
724         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
725           setOperationAction(Op, VT, Expand);
726         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
727           setTruncStoreAction(VT, OtherVT, Expand);
728           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
729           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
730           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
731         }
732 
733         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
734         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
735         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
736 
737         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
738         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
739 
740         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
741         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
742 
743         setOperationAction(ISD::LOAD, VT, Custom);
744         setOperationAction(ISD::STORE, VT, Custom);
745 
746         setOperationAction(ISD::SETCC, VT, Custom);
747 
748         setOperationAction(ISD::SELECT, VT, Custom);
749 
750         setOperationAction(ISD::TRUNCATE, VT, Custom);
751 
752         setOperationAction(ISD::BITCAST, VT, Custom);
753 
754         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
755         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
756         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
757 
758         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
759         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
760         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
761 
762         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
763         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
764         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
765         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
766 
767         // Operations below are different for between masks and other vectors.
768         if (VT.getVectorElementType() == MVT::i1) {
769           setOperationAction(ISD::AND, VT, Custom);
770           setOperationAction(ISD::OR, VT, Custom);
771           setOperationAction(ISD::XOR, VT, Custom);
772           continue;
773         }
774 
775         // Use SPLAT_VECTOR to prevent type legalization from destroying the
776         // splats when type legalizing i64 scalar on RV32.
777         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
778         // improvements first.
779         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
780           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
781           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
782         }
783 
784         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
785         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
786 
787         setOperationAction(ISD::MLOAD, VT, Custom);
788         setOperationAction(ISD::MSTORE, VT, Custom);
789         setOperationAction(ISD::MGATHER, VT, Custom);
790         setOperationAction(ISD::MSCATTER, VT, Custom);
791 
792         setOperationAction(ISD::VP_LOAD, VT, Custom);
793         setOperationAction(ISD::VP_STORE, VT, Custom);
794         setOperationAction(ISD::VP_GATHER, VT, Custom);
795         setOperationAction(ISD::VP_SCATTER, VT, Custom);
796 
797         setOperationAction(ISD::ADD, VT, Custom);
798         setOperationAction(ISD::MUL, VT, Custom);
799         setOperationAction(ISD::SUB, VT, Custom);
800         setOperationAction(ISD::AND, VT, Custom);
801         setOperationAction(ISD::OR, VT, Custom);
802         setOperationAction(ISD::XOR, VT, Custom);
803         setOperationAction(ISD::SDIV, VT, Custom);
804         setOperationAction(ISD::SREM, VT, Custom);
805         setOperationAction(ISD::UDIV, VT, Custom);
806         setOperationAction(ISD::UREM, VT, Custom);
807         setOperationAction(ISD::SHL, VT, Custom);
808         setOperationAction(ISD::SRA, VT, Custom);
809         setOperationAction(ISD::SRL, VT, Custom);
810 
811         setOperationAction(ISD::SMIN, VT, Custom);
812         setOperationAction(ISD::SMAX, VT, Custom);
813         setOperationAction(ISD::UMIN, VT, Custom);
814         setOperationAction(ISD::UMAX, VT, Custom);
815         setOperationAction(ISD::ABS,  VT, Custom);
816 
817         setOperationAction(ISD::MULHS, VT, Custom);
818         setOperationAction(ISD::MULHU, VT, Custom);
819 
820         setOperationAction(ISD::SADDSAT, VT, Custom);
821         setOperationAction(ISD::UADDSAT, VT, Custom);
822         setOperationAction(ISD::SSUBSAT, VT, Custom);
823         setOperationAction(ISD::USUBSAT, VT, Custom);
824 
825         setOperationAction(ISD::VSELECT, VT, Custom);
826         setOperationAction(ISD::SELECT_CC, VT, Expand);
827 
828         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
829         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
830         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
831 
832         // Custom-lower reduction operations to set up the corresponding custom
833         // nodes' operands.
834         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
835         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
836         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
837         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
838         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
839 
840         for (unsigned VPOpc : IntegerVPOps)
841           setOperationAction(VPOpc, VT, Custom);
842       }
843 
844       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
845         if (!useRVVForFixedLengthVectorVT(VT))
846           continue;
847 
848         // By default everything must be expanded.
849         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
850           setOperationAction(Op, VT, Expand);
851         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
852           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
853           setTruncStoreAction(VT, OtherVT, Expand);
854         }
855 
856         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
857         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
858         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
859 
860         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
861         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
862         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
863         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
864         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
865 
866         setOperationAction(ISD::LOAD, VT, Custom);
867         setOperationAction(ISD::STORE, VT, Custom);
868         setOperationAction(ISD::MLOAD, VT, Custom);
869         setOperationAction(ISD::MSTORE, VT, Custom);
870         setOperationAction(ISD::MGATHER, VT, Custom);
871         setOperationAction(ISD::MSCATTER, VT, Custom);
872 
873         setOperationAction(ISD::VP_LOAD, VT, Custom);
874         setOperationAction(ISD::VP_STORE, VT, Custom);
875         setOperationAction(ISD::VP_GATHER, VT, Custom);
876         setOperationAction(ISD::VP_SCATTER, VT, Custom);
877 
878         setOperationAction(ISD::FADD, VT, Custom);
879         setOperationAction(ISD::FSUB, VT, Custom);
880         setOperationAction(ISD::FMUL, VT, Custom);
881         setOperationAction(ISD::FDIV, VT, Custom);
882         setOperationAction(ISD::FNEG, VT, Custom);
883         setOperationAction(ISD::FABS, VT, Custom);
884         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
885         setOperationAction(ISD::FSQRT, VT, Custom);
886         setOperationAction(ISD::FMA, VT, Custom);
887         setOperationAction(ISD::FMINNUM, VT, Custom);
888         setOperationAction(ISD::FMAXNUM, VT, Custom);
889 
890         setOperationAction(ISD::FP_ROUND, VT, Custom);
891         setOperationAction(ISD::FP_EXTEND, VT, Custom);
892 
893         for (auto CC : VFPCCToExpand)
894           setCondCodeAction(CC, VT, Expand);
895 
896         setOperationAction(ISD::VSELECT, VT, Custom);
897         setOperationAction(ISD::SELECT, VT, Custom);
898         setOperationAction(ISD::SELECT_CC, VT, Expand);
899 
900         setOperationAction(ISD::BITCAST, VT, Custom);
901 
902         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
903         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
904         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
905         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
906 
907         for (unsigned VPOpc : FloatingPointVPOps)
908           setOperationAction(VPOpc, VT, Custom);
909       }
910 
911       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
912       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
913       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
914       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
915       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
916       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
917       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
918       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
919     }
920   }
921 
922   // Function alignments.
923   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
924   setMinFunctionAlignment(FunctionAlignment);
925   setPrefFunctionAlignment(FunctionAlignment);
926 
927   setMinimumJumpTableEntries(5);
928 
929   // Jumps are expensive, compared to logic
930   setJumpIsExpensive();
931 
932   // We can use any register for comparisons
933   setHasMultipleConditionRegisters();
934 
935   setTargetDAGCombine(ISD::ADD);
936   setTargetDAGCombine(ISD::SUB);
937   setTargetDAGCombine(ISD::AND);
938   setTargetDAGCombine(ISD::OR);
939   setTargetDAGCombine(ISD::XOR);
940   setTargetDAGCombine(ISD::ANY_EXTEND);
941   setTargetDAGCombine(ISD::ZERO_EXTEND);
942   if (Subtarget.hasVInstructions()) {
943     setTargetDAGCombine(ISD::FCOPYSIGN);
944     setTargetDAGCombine(ISD::MGATHER);
945     setTargetDAGCombine(ISD::MSCATTER);
946     setTargetDAGCombine(ISD::VP_GATHER);
947     setTargetDAGCombine(ISD::VP_SCATTER);
948     setTargetDAGCombine(ISD::SRA);
949     setTargetDAGCombine(ISD::SRL);
950     setTargetDAGCombine(ISD::SHL);
951     setTargetDAGCombine(ISD::STORE);
952   }
953 }
954 
955 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
956                                             LLVMContext &Context,
957                                             EVT VT) const {
958   if (!VT.isVector())
959     return getPointerTy(DL);
960   if (Subtarget.hasVInstructions() &&
961       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
962     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
963   return VT.changeVectorElementTypeToInteger();
964 }
965 
966 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
967   return Subtarget.getXLenVT();
968 }
969 
970 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
971                                              const CallInst &I,
972                                              MachineFunction &MF,
973                                              unsigned Intrinsic) const {
974   auto &DL = I.getModule()->getDataLayout();
975   switch (Intrinsic) {
976   default:
977     return false;
978   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
979   case Intrinsic::riscv_masked_atomicrmw_add_i32:
980   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
981   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
982   case Intrinsic::riscv_masked_atomicrmw_max_i32:
983   case Intrinsic::riscv_masked_atomicrmw_min_i32:
984   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
985   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
986   case Intrinsic::riscv_masked_cmpxchg_i32: {
987     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
988     Info.opc = ISD::INTRINSIC_W_CHAIN;
989     Info.memVT = MVT::getVT(PtrTy->getElementType());
990     Info.ptrVal = I.getArgOperand(0);
991     Info.offset = 0;
992     Info.align = Align(4);
993     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
994                  MachineMemOperand::MOVolatile;
995     return true;
996   }
997   case Intrinsic::riscv_masked_strided_load:
998     Info.opc = ISD::INTRINSIC_W_CHAIN;
999     Info.ptrVal = I.getArgOperand(1);
1000     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1001     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1002     Info.size = MemoryLocation::UnknownSize;
1003     Info.flags |= MachineMemOperand::MOLoad;
1004     return true;
1005   case Intrinsic::riscv_masked_strided_store:
1006     Info.opc = ISD::INTRINSIC_VOID;
1007     Info.ptrVal = I.getArgOperand(1);
1008     Info.memVT =
1009         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1010     Info.align = Align(
1011         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1012         8);
1013     Info.size = MemoryLocation::UnknownSize;
1014     Info.flags |= MachineMemOperand::MOStore;
1015     return true;
1016   }
1017 }
1018 
1019 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1020                                                 const AddrMode &AM, Type *Ty,
1021                                                 unsigned AS,
1022                                                 Instruction *I) const {
1023   // No global is ever allowed as a base.
1024   if (AM.BaseGV)
1025     return false;
1026 
1027   // Require a 12-bit signed offset.
1028   if (!isInt<12>(AM.BaseOffs))
1029     return false;
1030 
1031   switch (AM.Scale) {
1032   case 0: // "r+i" or just "i", depending on HasBaseReg.
1033     break;
1034   case 1:
1035     if (!AM.HasBaseReg) // allow "r+i".
1036       break;
1037     return false; // disallow "r+r" or "r+r+i".
1038   default:
1039     return false;
1040   }
1041 
1042   return true;
1043 }
1044 
1045 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1046   return isInt<12>(Imm);
1047 }
1048 
1049 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1050   return isInt<12>(Imm);
1051 }
1052 
1053 // On RV32, 64-bit integers are split into their high and low parts and held
1054 // in two different registers, so the trunc is free since the low register can
1055 // just be used.
1056 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1057   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1058     return false;
1059   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1060   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1061   return (SrcBits == 64 && DestBits == 32);
1062 }
1063 
1064 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1065   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1066       !SrcVT.isInteger() || !DstVT.isInteger())
1067     return false;
1068   unsigned SrcBits = SrcVT.getSizeInBits();
1069   unsigned DestBits = DstVT.getSizeInBits();
1070   return (SrcBits == 64 && DestBits == 32);
1071 }
1072 
1073 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1074   // Zexts are free if they can be combined with a load.
1075   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1076     EVT MemVT = LD->getMemoryVT();
1077     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1078          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1079         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1080          LD->getExtensionType() == ISD::ZEXTLOAD))
1081       return true;
1082   }
1083 
1084   return TargetLowering::isZExtFree(Val, VT2);
1085 }
1086 
1087 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1088   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1089 }
1090 
1091 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1092   return Subtarget.hasStdExtZbb();
1093 }
1094 
1095 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1096   return Subtarget.hasStdExtZbb();
1097 }
1098 
1099 /// Check if sinking \p I's operands to I's basic block is profitable, because
1100 /// the operands can be folded into a target instruction, e.g.
1101 /// splats of scalars can fold into vector instructions.
1102 bool RISCVTargetLowering::shouldSinkOperands(
1103     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1104   using namespace llvm::PatternMatch;
1105 
1106   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1107     return false;
1108 
1109   auto IsSinker = [&](Instruction *I, int Operand) {
1110     switch (I->getOpcode()) {
1111     case Instruction::Add:
1112     case Instruction::Sub:
1113     case Instruction::Mul:
1114     case Instruction::And:
1115     case Instruction::Or:
1116     case Instruction::Xor:
1117     case Instruction::FAdd:
1118     case Instruction::FSub:
1119     case Instruction::FMul:
1120     case Instruction::FDiv:
1121     case Instruction::ICmp:
1122     case Instruction::FCmp:
1123       return true;
1124     case Instruction::Shl:
1125     case Instruction::LShr:
1126     case Instruction::AShr:
1127       return Operand == 1;
1128     case Instruction::Call:
1129       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1130         switch (II->getIntrinsicID()) {
1131         case Intrinsic::fma:
1132           return Operand == 0 || Operand == 1;
1133         default:
1134           return false;
1135         }
1136       }
1137       return false;
1138     default:
1139       return false;
1140     }
1141   };
1142 
1143   for (auto OpIdx : enumerate(I->operands())) {
1144     if (!IsSinker(I, OpIdx.index()))
1145       continue;
1146 
1147     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1148     // Make sure we are not already sinking this operand
1149     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1150       continue;
1151 
1152     // We are looking for a splat that can be sunk.
1153     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1154                              m_Undef(), m_ZeroMask())))
1155       continue;
1156 
1157     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1158     // and vector registers
1159     for (Use &U : Op->uses()) {
1160       Instruction *Insn = cast<Instruction>(U.getUser());
1161       if (!IsSinker(Insn, U.getOperandNo()))
1162         return false;
1163     }
1164 
1165     Ops.push_back(&Op->getOperandUse(0));
1166     Ops.push_back(&OpIdx.value());
1167   }
1168   return true;
1169 }
1170 
1171 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1172                                        bool ForCodeSize) const {
1173   if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin())
1174     return false;
1175   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1176     return false;
1177   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1178     return false;
1179   if (Imm.isNegZero())
1180     return false;
1181   return Imm.isZero();
1182 }
1183 
1184 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1185   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1186          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1187          (VT == MVT::f64 && Subtarget.hasStdExtD());
1188 }
1189 
1190 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1191                                                       CallingConv::ID CC,
1192                                                       EVT VT) const {
1193   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1194   // We might still end up using a GPR but that will be decided based on ABI.
1195   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1196     return MVT::f32;
1197 
1198   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1199 }
1200 
1201 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1202                                                            CallingConv::ID CC,
1203                                                            EVT VT) const {
1204   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1205   // We might still end up using a GPR but that will be decided based on ABI.
1206   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1207     return 1;
1208 
1209   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1210 }
1211 
1212 // Changes the condition code and swaps operands if necessary, so the SetCC
1213 // operation matches one of the comparisons supported directly by branches
1214 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1215 // with 1/-1.
1216 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1217                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1218   // Convert X > -1 to X >= 0.
1219   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1220     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1221     CC = ISD::SETGE;
1222     return;
1223   }
1224   // Convert X < 1 to 0 >= X.
1225   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1226     RHS = LHS;
1227     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1228     CC = ISD::SETGE;
1229     return;
1230   }
1231 
1232   switch (CC) {
1233   default:
1234     break;
1235   case ISD::SETGT:
1236   case ISD::SETLE:
1237   case ISD::SETUGT:
1238   case ISD::SETULE:
1239     CC = ISD::getSetCCSwappedOperands(CC);
1240     std::swap(LHS, RHS);
1241     break;
1242   }
1243 }
1244 
1245 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1246   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1247   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1248   if (VT.getVectorElementType() == MVT::i1)
1249     KnownSize *= 8;
1250 
1251   switch (KnownSize) {
1252   default:
1253     llvm_unreachable("Invalid LMUL.");
1254   case 8:
1255     return RISCVII::VLMUL::LMUL_F8;
1256   case 16:
1257     return RISCVII::VLMUL::LMUL_F4;
1258   case 32:
1259     return RISCVII::VLMUL::LMUL_F2;
1260   case 64:
1261     return RISCVII::VLMUL::LMUL_1;
1262   case 128:
1263     return RISCVII::VLMUL::LMUL_2;
1264   case 256:
1265     return RISCVII::VLMUL::LMUL_4;
1266   case 512:
1267     return RISCVII::VLMUL::LMUL_8;
1268   }
1269 }
1270 
1271 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1272   switch (LMul) {
1273   default:
1274     llvm_unreachable("Invalid LMUL.");
1275   case RISCVII::VLMUL::LMUL_F8:
1276   case RISCVII::VLMUL::LMUL_F4:
1277   case RISCVII::VLMUL::LMUL_F2:
1278   case RISCVII::VLMUL::LMUL_1:
1279     return RISCV::VRRegClassID;
1280   case RISCVII::VLMUL::LMUL_2:
1281     return RISCV::VRM2RegClassID;
1282   case RISCVII::VLMUL::LMUL_4:
1283     return RISCV::VRM4RegClassID;
1284   case RISCVII::VLMUL::LMUL_8:
1285     return RISCV::VRM8RegClassID;
1286   }
1287 }
1288 
1289 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1290   RISCVII::VLMUL LMUL = getLMUL(VT);
1291   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1292       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1293       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1294       LMUL == RISCVII::VLMUL::LMUL_1) {
1295     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1296                   "Unexpected subreg numbering");
1297     return RISCV::sub_vrm1_0 + Index;
1298   }
1299   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1300     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1301                   "Unexpected subreg numbering");
1302     return RISCV::sub_vrm2_0 + Index;
1303   }
1304   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1305     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1306                   "Unexpected subreg numbering");
1307     return RISCV::sub_vrm4_0 + Index;
1308   }
1309   llvm_unreachable("Invalid vector type.");
1310 }
1311 
1312 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1313   if (VT.getVectorElementType() == MVT::i1)
1314     return RISCV::VRRegClassID;
1315   return getRegClassIDForLMUL(getLMUL(VT));
1316 }
1317 
1318 // Attempt to decompose a subvector insert/extract between VecVT and
1319 // SubVecVT via subregister indices. Returns the subregister index that
1320 // can perform the subvector insert/extract with the given element index, as
1321 // well as the index corresponding to any leftover subvectors that must be
1322 // further inserted/extracted within the register class for SubVecVT.
1323 std::pair<unsigned, unsigned>
1324 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1325     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1326     const RISCVRegisterInfo *TRI) {
1327   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1328                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1329                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1330                 "Register classes not ordered");
1331   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1332   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1333   // Try to compose a subregister index that takes us from the incoming
1334   // LMUL>1 register class down to the outgoing one. At each step we half
1335   // the LMUL:
1336   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1337   // Note that this is not guaranteed to find a subregister index, such as
1338   // when we are extracting from one VR type to another.
1339   unsigned SubRegIdx = RISCV::NoSubRegister;
1340   for (const unsigned RCID :
1341        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1342     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1343       VecVT = VecVT.getHalfNumVectorElementsVT();
1344       bool IsHi =
1345           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1346       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1347                                             getSubregIndexByMVT(VecVT, IsHi));
1348       if (IsHi)
1349         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1350     }
1351   return {SubRegIdx, InsertExtractIdx};
1352 }
1353 
1354 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1355 // stores for those types.
1356 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1357   return !Subtarget.useRVVForFixedLengthVectors() ||
1358          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1359 }
1360 
1361 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1362   if (ScalarTy->isPointerTy())
1363     return true;
1364 
1365   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1366       ScalarTy->isIntegerTy(32))
1367     return true;
1368 
1369   if (ScalarTy->isIntegerTy(64))
1370     return Subtarget.hasVInstructionsI64();
1371 
1372   if (ScalarTy->isHalfTy())
1373     return Subtarget.hasVInstructionsF16();
1374   if (ScalarTy->isFloatTy())
1375     return Subtarget.hasVInstructionsF32();
1376   if (ScalarTy->isDoubleTy())
1377     return Subtarget.hasVInstructionsF64();
1378 
1379   return false;
1380 }
1381 
1382 static bool useRVVForFixedLengthVectorVT(MVT VT,
1383                                          const RISCVSubtarget &Subtarget) {
1384   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1385   if (!Subtarget.useRVVForFixedLengthVectors())
1386     return false;
1387 
1388   // We only support a set of vector types with a consistent maximum fixed size
1389   // across all supported vector element types to avoid legalization issues.
1390   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1391   // fixed-length vector type we support is 1024 bytes.
1392   if (VT.getFixedSizeInBits() > 1024 * 8)
1393     return false;
1394 
1395   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1396 
1397   MVT EltVT = VT.getVectorElementType();
1398 
1399   // Don't use RVV for vectors we cannot scalarize if required.
1400   switch (EltVT.SimpleTy) {
1401   // i1 is supported but has different rules.
1402   default:
1403     return false;
1404   case MVT::i1:
1405     // Masks can only use a single register.
1406     if (VT.getVectorNumElements() > MinVLen)
1407       return false;
1408     MinVLen /= 8;
1409     break;
1410   case MVT::i8:
1411   case MVT::i16:
1412   case MVT::i32:
1413     break;
1414   case MVT::i64:
1415     if (!Subtarget.hasVInstructionsI64())
1416       return false;
1417     break;
1418   case MVT::f16:
1419     if (!Subtarget.hasVInstructionsF16())
1420       return false;
1421     break;
1422   case MVT::f32:
1423     if (!Subtarget.hasVInstructionsF32())
1424       return false;
1425     break;
1426   case MVT::f64:
1427     if (!Subtarget.hasVInstructionsF64())
1428       return false;
1429     break;
1430   }
1431 
1432   // Reject elements larger than ELEN.
1433   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1434     return false;
1435 
1436   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1437   // Don't use RVV for types that don't fit.
1438   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1439     return false;
1440 
1441   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1442   // the base fixed length RVV support in place.
1443   if (!VT.isPow2VectorType())
1444     return false;
1445 
1446   return true;
1447 }
1448 
1449 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1450   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1451 }
1452 
1453 // Return the largest legal scalable vector type that matches VT's element type.
1454 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1455                                             const RISCVSubtarget &Subtarget) {
1456   // This may be called before legal types are setup.
1457   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1458           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1459          "Expected legal fixed length vector!");
1460 
1461   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1462   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1463 
1464   MVT EltVT = VT.getVectorElementType();
1465   switch (EltVT.SimpleTy) {
1466   default:
1467     llvm_unreachable("unexpected element type for RVV container");
1468   case MVT::i1:
1469   case MVT::i8:
1470   case MVT::i16:
1471   case MVT::i32:
1472   case MVT::i64:
1473   case MVT::f16:
1474   case MVT::f32:
1475   case MVT::f64: {
1476     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1477     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1478     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1479     unsigned NumElts =
1480         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1481     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1482     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1483     return MVT::getScalableVectorVT(EltVT, NumElts);
1484   }
1485   }
1486 }
1487 
1488 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1489                                             const RISCVSubtarget &Subtarget) {
1490   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1491                                           Subtarget);
1492 }
1493 
1494 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1495   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1496 }
1497 
1498 // Grow V to consume an entire RVV register.
1499 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1500                                        const RISCVSubtarget &Subtarget) {
1501   assert(VT.isScalableVector() &&
1502          "Expected to convert into a scalable vector!");
1503   assert(V.getValueType().isFixedLengthVector() &&
1504          "Expected a fixed length vector operand!");
1505   SDLoc DL(V);
1506   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1507   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1508 }
1509 
1510 // Shrink V so it's just big enough to maintain a VT's worth of data.
1511 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1512                                          const RISCVSubtarget &Subtarget) {
1513   assert(VT.isFixedLengthVector() &&
1514          "Expected to convert into a fixed length vector!");
1515   assert(V.getValueType().isScalableVector() &&
1516          "Expected a scalable vector operand!");
1517   SDLoc DL(V);
1518   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1519   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1520 }
1521 
1522 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1523 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1524 // the vector type that it is contained in.
1525 static std::pair<SDValue, SDValue>
1526 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1527                 const RISCVSubtarget &Subtarget) {
1528   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1529   MVT XLenVT = Subtarget.getXLenVT();
1530   SDValue VL = VecVT.isFixedLengthVector()
1531                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1532                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1533   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1534   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1535   return {Mask, VL};
1536 }
1537 
1538 // As above but assuming the given type is a scalable vector type.
1539 static std::pair<SDValue, SDValue>
1540 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1541                         const RISCVSubtarget &Subtarget) {
1542   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1543   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1544 }
1545 
1546 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1547 // of either is (currently) supported. This can get us into an infinite loop
1548 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1549 // as a ..., etc.
1550 // Until either (or both) of these can reliably lower any node, reporting that
1551 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1552 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1553 // which is not desirable.
1554 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1555     EVT VT, unsigned DefinedValues) const {
1556   return false;
1557 }
1558 
1559 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1560   // Only splats are currently supported.
1561   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1562     return true;
1563 
1564   return false;
1565 }
1566 
1567 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1568   // RISCV FP-to-int conversions saturate to the destination register size, but
1569   // don't produce 0 for nan. We can use a conversion instruction and fix the
1570   // nan case with a compare and a select.
1571   SDValue Src = Op.getOperand(0);
1572 
1573   EVT DstVT = Op.getValueType();
1574   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1575 
1576   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1577   unsigned Opc;
1578   if (SatVT == DstVT)
1579     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1580   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1581     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1582   else
1583     return SDValue();
1584   // FIXME: Support other SatVTs by clamping before or after the conversion.
1585 
1586   SDLoc DL(Op);
1587   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1588 
1589   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1590   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1591 }
1592 
1593 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1594                                  const RISCVSubtarget &Subtarget) {
1595   MVT VT = Op.getSimpleValueType();
1596   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1597 
1598   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1599 
1600   SDLoc DL(Op);
1601   SDValue Mask, VL;
1602   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1603 
1604   unsigned Opc =
1605       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1606   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1607   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1608 }
1609 
1610 struct VIDSequence {
1611   int64_t StepNumerator;
1612   unsigned StepDenominator;
1613   int64_t Addend;
1614 };
1615 
1616 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1617 // to the (non-zero) step S and start value X. This can be then lowered as the
1618 // RVV sequence (VID * S) + X, for example.
1619 // The step S is represented as an integer numerator divided by a positive
1620 // denominator. Note that the implementation currently only identifies
1621 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1622 // cannot detect 2/3, for example.
1623 // Note that this method will also match potentially unappealing index
1624 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1625 // determine whether this is worth generating code for.
1626 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1627   unsigned NumElts = Op.getNumOperands();
1628   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1629   if (!Op.getValueType().isInteger())
1630     return None;
1631 
1632   Optional<unsigned> SeqStepDenom;
1633   Optional<int64_t> SeqStepNum, SeqAddend;
1634   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1635   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1636   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1637     // Assume undef elements match the sequence; we just have to be careful
1638     // when interpolating across them.
1639     if (Op.getOperand(Idx).isUndef())
1640       continue;
1641     // The BUILD_VECTOR must be all constants.
1642     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1643       return None;
1644 
1645     uint64_t Val = Op.getConstantOperandVal(Idx) &
1646                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1647 
1648     if (PrevElt) {
1649       // Calculate the step since the last non-undef element, and ensure
1650       // it's consistent across the entire sequence.
1651       unsigned IdxDiff = Idx - PrevElt->second;
1652       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1653 
1654       // A zero-value value difference means that we're somewhere in the middle
1655       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1656       // step change before evaluating the sequence.
1657       if (ValDiff != 0) {
1658         int64_t Remainder = ValDiff % IdxDiff;
1659         // Normalize the step if it's greater than 1.
1660         if (Remainder != ValDiff) {
1661           // The difference must cleanly divide the element span.
1662           if (Remainder != 0)
1663             return None;
1664           ValDiff /= IdxDiff;
1665           IdxDiff = 1;
1666         }
1667 
1668         if (!SeqStepNum)
1669           SeqStepNum = ValDiff;
1670         else if (ValDiff != SeqStepNum)
1671           return None;
1672 
1673         if (!SeqStepDenom)
1674           SeqStepDenom = IdxDiff;
1675         else if (IdxDiff != *SeqStepDenom)
1676           return None;
1677       }
1678     }
1679 
1680     // Record and/or check any addend.
1681     if (SeqStepNum && SeqStepDenom) {
1682       uint64_t ExpectedVal =
1683           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1684       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1685       if (!SeqAddend)
1686         SeqAddend = Addend;
1687       else if (SeqAddend != Addend)
1688         return None;
1689     }
1690 
1691     // Record this non-undef element for later.
1692     if (!PrevElt || PrevElt->first != Val)
1693       PrevElt = std::make_pair(Val, Idx);
1694   }
1695   // We need to have logged both a step and an addend for this to count as
1696   // a legal index sequence.
1697   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1698     return None;
1699 
1700   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1701 }
1702 
1703 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1704                                  const RISCVSubtarget &Subtarget) {
1705   MVT VT = Op.getSimpleValueType();
1706   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1707 
1708   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1709 
1710   SDLoc DL(Op);
1711   SDValue Mask, VL;
1712   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1713 
1714   MVT XLenVT = Subtarget.getXLenVT();
1715   unsigned NumElts = Op.getNumOperands();
1716 
1717   if (VT.getVectorElementType() == MVT::i1) {
1718     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1719       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1720       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1721     }
1722 
1723     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1724       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1725       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1726     }
1727 
1728     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1729     // scalar integer chunks whose bit-width depends on the number of mask
1730     // bits and XLEN.
1731     // First, determine the most appropriate scalar integer type to use. This
1732     // is at most XLenVT, but may be shrunk to a smaller vector element type
1733     // according to the size of the final vector - use i8 chunks rather than
1734     // XLenVT if we're producing a v8i1. This results in more consistent
1735     // codegen across RV32 and RV64.
1736     unsigned NumViaIntegerBits =
1737         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1738     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1739       // If we have to use more than one INSERT_VECTOR_ELT then this
1740       // optimization is likely to increase code size; avoid peforming it in
1741       // such a case. We can use a load from a constant pool in this case.
1742       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1743         return SDValue();
1744       // Now we can create our integer vector type. Note that it may be larger
1745       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1746       MVT IntegerViaVecVT =
1747           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1748                            divideCeil(NumElts, NumViaIntegerBits));
1749 
1750       uint64_t Bits = 0;
1751       unsigned BitPos = 0, IntegerEltIdx = 0;
1752       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1753 
1754       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1755         // Once we accumulate enough bits to fill our scalar type, insert into
1756         // our vector and clear our accumulated data.
1757         if (I != 0 && I % NumViaIntegerBits == 0) {
1758           if (NumViaIntegerBits <= 32)
1759             Bits = SignExtend64(Bits, 32);
1760           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1761           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1762                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1763           Bits = 0;
1764           BitPos = 0;
1765           IntegerEltIdx++;
1766         }
1767         SDValue V = Op.getOperand(I);
1768         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1769         Bits |= ((uint64_t)BitValue << BitPos);
1770       }
1771 
1772       // Insert the (remaining) scalar value into position in our integer
1773       // vector type.
1774       if (NumViaIntegerBits <= 32)
1775         Bits = SignExtend64(Bits, 32);
1776       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1777       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1778                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1779 
1780       if (NumElts < NumViaIntegerBits) {
1781         // If we're producing a smaller vector than our minimum legal integer
1782         // type, bitcast to the equivalent (known-legal) mask type, and extract
1783         // our final mask.
1784         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1785         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1786         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1787                           DAG.getConstant(0, DL, XLenVT));
1788       } else {
1789         // Else we must have produced an integer type with the same size as the
1790         // mask type; bitcast for the final result.
1791         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1792         Vec = DAG.getBitcast(VT, Vec);
1793       }
1794 
1795       return Vec;
1796     }
1797 
1798     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1799     // vector type, we have a legal equivalently-sized i8 type, so we can use
1800     // that.
1801     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1802     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1803 
1804     SDValue WideVec;
1805     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1806       // For a splat, perform a scalar truncate before creating the wider
1807       // vector.
1808       assert(Splat.getValueType() == XLenVT &&
1809              "Unexpected type for i1 splat value");
1810       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1811                           DAG.getConstant(1, DL, XLenVT));
1812       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1813     } else {
1814       SmallVector<SDValue, 8> Ops(Op->op_values());
1815       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1816       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1817       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1818     }
1819 
1820     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1821   }
1822 
1823   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1824     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1825                                         : RISCVISD::VMV_V_X_VL;
1826     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1827     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1828   }
1829 
1830   // Try and match index sequences, which we can lower to the vid instruction
1831   // with optional modifications. An all-undef vector is matched by
1832   // getSplatValue, above.
1833   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1834     int64_t StepNumerator = SimpleVID->StepNumerator;
1835     unsigned StepDenominator = SimpleVID->StepDenominator;
1836     int64_t Addend = SimpleVID->Addend;
1837     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1838     // threshold since it's the immediate value many RVV instructions accept.
1839     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1840         isInt<5>(Addend)) {
1841       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1842       // Convert right out of the scalable type so we can use standard ISD
1843       // nodes for the rest of the computation. If we used scalable types with
1844       // these, we'd lose the fixed-length vector info and generate worse
1845       // vsetvli code.
1846       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1847       assert(StepNumerator != 0 && "Invalid step");
1848       bool Negate = false;
1849       if (StepNumerator != 1) {
1850         int64_t SplatStepVal = StepNumerator;
1851         unsigned Opcode = ISD::MUL;
1852         if (isPowerOf2_64(std::abs(StepNumerator))) {
1853           Negate = StepNumerator < 0;
1854           Opcode = ISD::SHL;
1855           SplatStepVal = Log2_64(std::abs(StepNumerator));
1856         }
1857         SDValue SplatStep = DAG.getSplatVector(
1858             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1859         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1860       }
1861       if (StepDenominator != 1) {
1862         SDValue SplatStep = DAG.getSplatVector(
1863             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1864         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1865       }
1866       if (Addend != 0 || Negate) {
1867         SDValue SplatAddend =
1868             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1869         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1870       }
1871       return VID;
1872     }
1873   }
1874 
1875   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1876   // when re-interpreted as a vector with a larger element type. For example,
1877   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1878   // could be instead splat as
1879   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1880   // TODO: This optimization could also work on non-constant splats, but it
1881   // would require bit-manipulation instructions to construct the splat value.
1882   SmallVector<SDValue> Sequence;
1883   unsigned EltBitSize = VT.getScalarSizeInBits();
1884   const auto *BV = cast<BuildVectorSDNode>(Op);
1885   if (VT.isInteger() && EltBitSize < 64 &&
1886       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1887       BV->getRepeatedSequence(Sequence) &&
1888       (Sequence.size() * EltBitSize) <= 64) {
1889     unsigned SeqLen = Sequence.size();
1890     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1891     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1892     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1893             ViaIntVT == MVT::i64) &&
1894            "Unexpected sequence type");
1895 
1896     unsigned EltIdx = 0;
1897     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1898     uint64_t SplatValue = 0;
1899     // Construct the amalgamated value which can be splatted as this larger
1900     // vector type.
1901     for (const auto &SeqV : Sequence) {
1902       if (!SeqV.isUndef())
1903         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1904                        << (EltIdx * EltBitSize));
1905       EltIdx++;
1906     }
1907 
1908     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1909     // achieve better constant materializion.
1910     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1911       SplatValue = SignExtend64(SplatValue, 32);
1912 
1913     // Since we can't introduce illegal i64 types at this stage, we can only
1914     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1915     // way we can use RVV instructions to splat.
1916     assert((ViaIntVT.bitsLE(XLenVT) ||
1917             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1918            "Unexpected bitcast sequence");
1919     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1920       SDValue ViaVL =
1921           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1922       MVT ViaContainerVT =
1923           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
1924       SDValue Splat =
1925           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1926                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1927       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1928       return DAG.getBitcast(VT, Splat);
1929     }
1930   }
1931 
1932   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1933   // which constitute a large proportion of the elements. In such cases we can
1934   // splat a vector with the dominant element and make up the shortfall with
1935   // INSERT_VECTOR_ELTs.
1936   // Note that this includes vectors of 2 elements by association. The
1937   // upper-most element is the "dominant" one, allowing us to use a splat to
1938   // "insert" the upper element, and an insert of the lower element at position
1939   // 0, which improves codegen.
1940   SDValue DominantValue;
1941   unsigned MostCommonCount = 0;
1942   DenseMap<SDValue, unsigned> ValueCounts;
1943   unsigned NumUndefElts =
1944       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1945 
1946   // Track the number of scalar loads we know we'd be inserting, estimated as
1947   // any non-zero floating-point constant. Other kinds of element are either
1948   // already in registers or are materialized on demand. The threshold at which
1949   // a vector load is more desirable than several scalar materializion and
1950   // vector-insertion instructions is not known.
1951   unsigned NumScalarLoads = 0;
1952 
1953   for (SDValue V : Op->op_values()) {
1954     if (V.isUndef())
1955       continue;
1956 
1957     ValueCounts.insert(std::make_pair(V, 0));
1958     unsigned &Count = ValueCounts[V];
1959 
1960     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
1961       NumScalarLoads += !CFP->isExactlyValue(+0.0);
1962 
1963     // Is this value dominant? In case of a tie, prefer the highest element as
1964     // it's cheaper to insert near the beginning of a vector than it is at the
1965     // end.
1966     if (++Count >= MostCommonCount) {
1967       DominantValue = V;
1968       MostCommonCount = Count;
1969     }
1970   }
1971 
1972   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1973   unsigned NumDefElts = NumElts - NumUndefElts;
1974   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1975 
1976   // Don't perform this optimization when optimizing for size, since
1977   // materializing elements and inserting them tends to cause code bloat.
1978   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
1979       ((MostCommonCount > DominantValueCountThreshold) ||
1980        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
1981     // Start by splatting the most common element.
1982     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
1983 
1984     DenseSet<SDValue> Processed{DominantValue};
1985     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
1986     for (const auto &OpIdx : enumerate(Op->ops())) {
1987       const SDValue &V = OpIdx.value();
1988       if (V.isUndef() || !Processed.insert(V).second)
1989         continue;
1990       if (ValueCounts[V] == 1) {
1991         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
1992                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
1993       } else {
1994         // Blend in all instances of this value using a VSELECT, using a
1995         // mask where each bit signals whether that element is the one
1996         // we're after.
1997         SmallVector<SDValue> Ops;
1998         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
1999           return DAG.getConstant(V == V1, DL, XLenVT);
2000         });
2001         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2002                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2003                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2004       }
2005     }
2006 
2007     return Vec;
2008   }
2009 
2010   return SDValue();
2011 }
2012 
2013 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2014                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2015   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2016     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2017     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2018     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2019     // node in order to try and match RVV vector/scalar instructions.
2020     if ((LoC >> 31) == HiC)
2021       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2022   }
2023 
2024   // Fall back to a stack store and stride x0 vector load.
2025   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2026 }
2027 
2028 // Called by type legalization to handle splat of i64 on RV32.
2029 // FIXME: We can optimize this when the type has sign or zero bits in one
2030 // of the halves.
2031 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2032                                    SDValue VL, SelectionDAG &DAG) {
2033   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2034   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2035                            DAG.getConstant(0, DL, MVT::i32));
2036   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2037                            DAG.getConstant(1, DL, MVT::i32));
2038   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2039 }
2040 
2041 // This function lowers a splat of a scalar operand Splat with the vector
2042 // length VL. It ensures the final sequence is type legal, which is useful when
2043 // lowering a splat after type legalization.
2044 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2045                                 SelectionDAG &DAG,
2046                                 const RISCVSubtarget &Subtarget) {
2047   if (VT.isFloatingPoint())
2048     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2049 
2050   MVT XLenVT = Subtarget.getXLenVT();
2051 
2052   // Simplest case is that the operand needs to be promoted to XLenVT.
2053   if (Scalar.getValueType().bitsLE(XLenVT)) {
2054     // If the operand is a constant, sign extend to increase our chances
2055     // of being able to use a .vi instruction. ANY_EXTEND would become a
2056     // a zero extend and the simm5 check in isel would fail.
2057     // FIXME: Should we ignore the upper bits in isel instead?
2058     unsigned ExtOpc =
2059         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2060     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2061     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2062   }
2063 
2064   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2065          "Unexpected scalar for splat lowering!");
2066 
2067   // Otherwise use the more complicated splatting algorithm.
2068   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2069 }
2070 
2071 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2072                                    const RISCVSubtarget &Subtarget) {
2073   SDValue V1 = Op.getOperand(0);
2074   SDValue V2 = Op.getOperand(1);
2075   SDLoc DL(Op);
2076   MVT XLenVT = Subtarget.getXLenVT();
2077   MVT VT = Op.getSimpleValueType();
2078   unsigned NumElts = VT.getVectorNumElements();
2079   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2080 
2081   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2082 
2083   SDValue TrueMask, VL;
2084   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2085 
2086   if (SVN->isSplat()) {
2087     const int Lane = SVN->getSplatIndex();
2088     if (Lane >= 0) {
2089       MVT SVT = VT.getVectorElementType();
2090 
2091       // Turn splatted vector load into a strided load with an X0 stride.
2092       SDValue V = V1;
2093       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2094       // with undef.
2095       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2096       int Offset = Lane;
2097       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2098         int OpElements =
2099             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2100         V = V.getOperand(Offset / OpElements);
2101         Offset %= OpElements;
2102       }
2103 
2104       // We need to ensure the load isn't atomic or volatile.
2105       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2106         auto *Ld = cast<LoadSDNode>(V);
2107         Offset *= SVT.getStoreSize();
2108         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2109                                                    TypeSize::Fixed(Offset), DL);
2110 
2111         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2112         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2113           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2114           SDValue IntID =
2115               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2116           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2117                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2118           SDValue NewLoad = DAG.getMemIntrinsicNode(
2119               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2120               DAG.getMachineFunction().getMachineMemOperand(
2121                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2122           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2123           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2124         }
2125 
2126         // Otherwise use a scalar load and splat. This will give the best
2127         // opportunity to fold a splat into the operation. ISel can turn it into
2128         // the x0 strided load if we aren't able to fold away the select.
2129         if (SVT.isFloatingPoint())
2130           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2131                           Ld->getPointerInfo().getWithOffset(Offset),
2132                           Ld->getOriginalAlign(),
2133                           Ld->getMemOperand()->getFlags());
2134         else
2135           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2136                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2137                              Ld->getOriginalAlign(),
2138                              Ld->getMemOperand()->getFlags());
2139         DAG.makeEquivalentMemoryOrdering(Ld, V);
2140 
2141         unsigned Opc =
2142             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2143         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2144         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2145       }
2146 
2147       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2148       assert(Lane < (int)NumElts && "Unexpected lane!");
2149       SDValue Gather =
2150           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2151                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2152       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2153     }
2154   }
2155 
2156   // Detect shuffles which can be re-expressed as vector selects; these are
2157   // shuffles in which each element in the destination is taken from an element
2158   // at the corresponding index in either source vectors.
2159   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2160     int MaskIndex = MaskIdx.value();
2161     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2162   });
2163 
2164   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2165 
2166   SmallVector<SDValue> MaskVals;
2167   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2168   // merged with a second vrgather.
2169   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2170 
2171   // By default we preserve the original operand order, and use a mask to
2172   // select LHS as true and RHS as false. However, since RVV vector selects may
2173   // feature splats but only on the LHS, we may choose to invert our mask and
2174   // instead select between RHS and LHS.
2175   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2176   bool InvertMask = IsSelect == SwapOps;
2177 
2178   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2179   // half.
2180   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2181 
2182   // Now construct the mask that will be used by the vselect or blended
2183   // vrgather operation. For vrgathers, construct the appropriate indices into
2184   // each vector.
2185   for (int MaskIndex : SVN->getMask()) {
2186     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2187     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2188     if (!IsSelect) {
2189       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2190       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2191                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2192                                      : DAG.getUNDEF(XLenVT));
2193       GatherIndicesRHS.push_back(
2194           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2195                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2196       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2197         ++LHSIndexCounts[MaskIndex];
2198       if (!IsLHSOrUndefIndex)
2199         ++RHSIndexCounts[MaskIndex - NumElts];
2200     }
2201   }
2202 
2203   if (SwapOps) {
2204     std::swap(V1, V2);
2205     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2206   }
2207 
2208   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2209   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2210   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2211 
2212   if (IsSelect)
2213     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2214 
2215   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2216     // On such a large vector we're unable to use i8 as the index type.
2217     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2218     // may involve vector splitting if we're already at LMUL=8, or our
2219     // user-supplied maximum fixed-length LMUL.
2220     return SDValue();
2221   }
2222 
2223   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2224   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2225   MVT IndexVT = VT.changeTypeToInteger();
2226   // Since we can't introduce illegal index types at this stage, use i16 and
2227   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2228   // than XLenVT.
2229   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2230     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2231     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2232   }
2233 
2234   MVT IndexContainerVT =
2235       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2236 
2237   SDValue Gather;
2238   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2239   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2240   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2241     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2242   } else {
2243     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2244     // If only one index is used, we can use a "splat" vrgather.
2245     // TODO: We can splat the most-common index and fix-up any stragglers, if
2246     // that's beneficial.
2247     if (LHSIndexCounts.size() == 1) {
2248       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2249       Gather =
2250           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2251                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2252     } else {
2253       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2254       LHSIndices =
2255           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2256 
2257       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2258                            TrueMask, VL);
2259     }
2260   }
2261 
2262   // If a second vector operand is used by this shuffle, blend it in with an
2263   // additional vrgather.
2264   if (!V2.isUndef()) {
2265     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2266     // If only one index is used, we can use a "splat" vrgather.
2267     // TODO: We can splat the most-common index and fix-up any stragglers, if
2268     // that's beneficial.
2269     if (RHSIndexCounts.size() == 1) {
2270       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2271       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2272                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2273     } else {
2274       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2275       RHSIndices =
2276           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2277       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2278                        VL);
2279     }
2280 
2281     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2282     SelectMask =
2283         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2284 
2285     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2286                          Gather, VL);
2287   }
2288 
2289   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2290 }
2291 
2292 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2293                                      SDLoc DL, SelectionDAG &DAG,
2294                                      const RISCVSubtarget &Subtarget) {
2295   if (VT.isScalableVector())
2296     return DAG.getFPExtendOrRound(Op, DL, VT);
2297   assert(VT.isFixedLengthVector() &&
2298          "Unexpected value type for RVV FP extend/round lowering");
2299   SDValue Mask, VL;
2300   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2301   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2302                         ? RISCVISD::FP_EXTEND_VL
2303                         : RISCVISD::FP_ROUND_VL;
2304   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2305 }
2306 
2307 // While RVV has alignment restrictions, we should always be able to load as a
2308 // legal equivalently-sized byte-typed vector instead. This method is
2309 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2310 // the load is already correctly-aligned, it returns SDValue().
2311 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2312                                                     SelectionDAG &DAG) const {
2313   auto *Load = cast<LoadSDNode>(Op);
2314   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2315 
2316   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2317                                      Load->getMemoryVT(),
2318                                      *Load->getMemOperand()))
2319     return SDValue();
2320 
2321   SDLoc DL(Op);
2322   MVT VT = Op.getSimpleValueType();
2323   unsigned EltSizeBits = VT.getScalarSizeInBits();
2324   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2325          "Unexpected unaligned RVV load type");
2326   MVT NewVT =
2327       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2328   assert(NewVT.isValid() &&
2329          "Expecting equally-sized RVV vector types to be legal");
2330   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2331                           Load->getPointerInfo(), Load->getOriginalAlign(),
2332                           Load->getMemOperand()->getFlags());
2333   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2334 }
2335 
2336 // While RVV has alignment restrictions, we should always be able to store as a
2337 // legal equivalently-sized byte-typed vector instead. This method is
2338 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2339 // returns SDValue() if the store is already correctly aligned.
2340 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2341                                                      SelectionDAG &DAG) const {
2342   auto *Store = cast<StoreSDNode>(Op);
2343   assert(Store && Store->getValue().getValueType().isVector() &&
2344          "Expected vector store");
2345 
2346   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2347                                      Store->getMemoryVT(),
2348                                      *Store->getMemOperand()))
2349     return SDValue();
2350 
2351   SDLoc DL(Op);
2352   SDValue StoredVal = Store->getValue();
2353   MVT VT = StoredVal.getSimpleValueType();
2354   unsigned EltSizeBits = VT.getScalarSizeInBits();
2355   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2356          "Unexpected unaligned RVV store type");
2357   MVT NewVT =
2358       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2359   assert(NewVT.isValid() &&
2360          "Expecting equally-sized RVV vector types to be legal");
2361   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2362   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2363                       Store->getPointerInfo(), Store->getOriginalAlign(),
2364                       Store->getMemOperand()->getFlags());
2365 }
2366 
2367 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2368                                             SelectionDAG &DAG) const {
2369   switch (Op.getOpcode()) {
2370   default:
2371     report_fatal_error("unimplemented operand");
2372   case ISD::GlobalAddress:
2373     return lowerGlobalAddress(Op, DAG);
2374   case ISD::BlockAddress:
2375     return lowerBlockAddress(Op, DAG);
2376   case ISD::ConstantPool:
2377     return lowerConstantPool(Op, DAG);
2378   case ISD::JumpTable:
2379     return lowerJumpTable(Op, DAG);
2380   case ISD::GlobalTLSAddress:
2381     return lowerGlobalTLSAddress(Op, DAG);
2382   case ISD::SELECT:
2383     return lowerSELECT(Op, DAG);
2384   case ISD::BRCOND:
2385     return lowerBRCOND(Op, DAG);
2386   case ISD::VASTART:
2387     return lowerVASTART(Op, DAG);
2388   case ISD::FRAMEADDR:
2389     return lowerFRAMEADDR(Op, DAG);
2390   case ISD::RETURNADDR:
2391     return lowerRETURNADDR(Op, DAG);
2392   case ISD::SHL_PARTS:
2393     return lowerShiftLeftParts(Op, DAG);
2394   case ISD::SRA_PARTS:
2395     return lowerShiftRightParts(Op, DAG, true);
2396   case ISD::SRL_PARTS:
2397     return lowerShiftRightParts(Op, DAG, false);
2398   case ISD::BITCAST: {
2399     SDLoc DL(Op);
2400     EVT VT = Op.getValueType();
2401     SDValue Op0 = Op.getOperand(0);
2402     EVT Op0VT = Op0.getValueType();
2403     MVT XLenVT = Subtarget.getXLenVT();
2404     if (VT.isFixedLengthVector()) {
2405       // We can handle fixed length vector bitcasts with a simple replacement
2406       // in isel.
2407       if (Op0VT.isFixedLengthVector())
2408         return Op;
2409       // When bitcasting from scalar to fixed-length vector, insert the scalar
2410       // into a one-element vector of the result type, and perform a vector
2411       // bitcast.
2412       if (!Op0VT.isVector()) {
2413         auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2414         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2415                                               DAG.getUNDEF(BVT), Op0,
2416                                               DAG.getConstant(0, DL, XLenVT)));
2417       }
2418       return SDValue();
2419     }
2420     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2421     // thus: bitcast the vector to a one-element vector type whose element type
2422     // is the same as the result type, and extract the first element.
2423     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2424       LLVMContext &Context = *DAG.getContext();
2425       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
2426       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2427                          DAG.getConstant(0, DL, XLenVT));
2428     }
2429     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2430       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2431       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2432       return FPConv;
2433     }
2434     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2435         Subtarget.hasStdExtF()) {
2436       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2437       SDValue FPConv =
2438           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2439       return FPConv;
2440     }
2441     return SDValue();
2442   }
2443   case ISD::INTRINSIC_WO_CHAIN:
2444     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2445   case ISD::INTRINSIC_W_CHAIN:
2446     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2447   case ISD::INTRINSIC_VOID:
2448     return LowerINTRINSIC_VOID(Op, DAG);
2449   case ISD::BSWAP:
2450   case ISD::BITREVERSE: {
2451     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2452     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2453     MVT VT = Op.getSimpleValueType();
2454     SDLoc DL(Op);
2455     // Start with the maximum immediate value which is the bitwidth - 1.
2456     unsigned Imm = VT.getSizeInBits() - 1;
2457     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2458     if (Op.getOpcode() == ISD::BSWAP)
2459       Imm &= ~0x7U;
2460     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2461                        DAG.getConstant(Imm, DL, VT));
2462   }
2463   case ISD::FSHL:
2464   case ISD::FSHR: {
2465     MVT VT = Op.getSimpleValueType();
2466     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2467     SDLoc DL(Op);
2468     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2469       return Op;
2470     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2471     // use log(XLen) bits. Mask the shift amount accordingly.
2472     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2473     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2474                                 DAG.getConstant(ShAmtWidth, DL, VT));
2475     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2476     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2477   }
2478   case ISD::TRUNCATE: {
2479     SDLoc DL(Op);
2480     MVT VT = Op.getSimpleValueType();
2481     // Only custom-lower vector truncates
2482     if (!VT.isVector())
2483       return Op;
2484 
2485     // Truncates to mask types are handled differently
2486     if (VT.getVectorElementType() == MVT::i1)
2487       return lowerVectorMaskTrunc(Op, DAG);
2488 
2489     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2490     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2491     // truncate by one power of two at a time.
2492     MVT DstEltVT = VT.getVectorElementType();
2493 
2494     SDValue Src = Op.getOperand(0);
2495     MVT SrcVT = Src.getSimpleValueType();
2496     MVT SrcEltVT = SrcVT.getVectorElementType();
2497 
2498     assert(DstEltVT.bitsLT(SrcEltVT) &&
2499            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2500            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2501            "Unexpected vector truncate lowering");
2502 
2503     MVT ContainerVT = SrcVT;
2504     if (SrcVT.isFixedLengthVector()) {
2505       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2506       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2507     }
2508 
2509     SDValue Result = Src;
2510     SDValue Mask, VL;
2511     std::tie(Mask, VL) =
2512         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2513     LLVMContext &Context = *DAG.getContext();
2514     const ElementCount Count = ContainerVT.getVectorElementCount();
2515     do {
2516       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2517       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2518       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2519                            Mask, VL);
2520     } while (SrcEltVT != DstEltVT);
2521 
2522     if (SrcVT.isFixedLengthVector())
2523       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2524 
2525     return Result;
2526   }
2527   case ISD::ANY_EXTEND:
2528   case ISD::ZERO_EXTEND:
2529     if (Op.getOperand(0).getValueType().isVector() &&
2530         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2531       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2532     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2533   case ISD::SIGN_EXTEND:
2534     if (Op.getOperand(0).getValueType().isVector() &&
2535         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2536       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2537     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2538   case ISD::SPLAT_VECTOR_PARTS:
2539     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2540   case ISD::INSERT_VECTOR_ELT:
2541     return lowerINSERT_VECTOR_ELT(Op, DAG);
2542   case ISD::EXTRACT_VECTOR_ELT:
2543     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2544   case ISD::VSCALE: {
2545     MVT VT = Op.getSimpleValueType();
2546     SDLoc DL(Op);
2547     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2548     // We define our scalable vector types for lmul=1 to use a 64 bit known
2549     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2550     // vscale as VLENB / 8.
2551     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2552     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2553       // We assume VLENB is a multiple of 8. We manually choose the best shift
2554       // here because SimplifyDemandedBits isn't always able to simplify it.
2555       uint64_t Val = Op.getConstantOperandVal(0);
2556       if (isPowerOf2_64(Val)) {
2557         uint64_t Log2 = Log2_64(Val);
2558         if (Log2 < 3)
2559           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2560                              DAG.getConstant(3 - Log2, DL, VT));
2561         if (Log2 > 3)
2562           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2563                              DAG.getConstant(Log2 - 3, DL, VT));
2564         return VLENB;
2565       }
2566       // If the multiplier is a multiple of 8, scale it down to avoid needing
2567       // to shift the VLENB value.
2568       if ((Val % 8) == 0)
2569         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2570                            DAG.getConstant(Val / 8, DL, VT));
2571     }
2572 
2573     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2574                                  DAG.getConstant(3, DL, VT));
2575     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2576   }
2577   case ISD::FP_EXTEND: {
2578     // RVV can only do fp_extend to types double the size as the source. We
2579     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2580     // via f32.
2581     SDLoc DL(Op);
2582     MVT VT = Op.getSimpleValueType();
2583     SDValue Src = Op.getOperand(0);
2584     MVT SrcVT = Src.getSimpleValueType();
2585 
2586     // Prepare any fixed-length vector operands.
2587     MVT ContainerVT = VT;
2588     if (SrcVT.isFixedLengthVector()) {
2589       ContainerVT = getContainerForFixedLengthVector(VT);
2590       MVT SrcContainerVT =
2591           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2592       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2593     }
2594 
2595     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2596         SrcVT.getVectorElementType() != MVT::f16) {
2597       // For scalable vectors, we only need to close the gap between
2598       // vXf16->vXf64.
2599       if (!VT.isFixedLengthVector())
2600         return Op;
2601       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2602       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2603       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2604     }
2605 
2606     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2607     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2608     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2609         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2610 
2611     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2612                                            DL, DAG, Subtarget);
2613     if (VT.isFixedLengthVector())
2614       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2615     return Extend;
2616   }
2617   case ISD::FP_ROUND: {
2618     // RVV can only do fp_round to types half the size as the source. We
2619     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2620     // conversion instruction.
2621     SDLoc DL(Op);
2622     MVT VT = Op.getSimpleValueType();
2623     SDValue Src = Op.getOperand(0);
2624     MVT SrcVT = Src.getSimpleValueType();
2625 
2626     // Prepare any fixed-length vector operands.
2627     MVT ContainerVT = VT;
2628     if (VT.isFixedLengthVector()) {
2629       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2630       ContainerVT =
2631           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2632       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2633     }
2634 
2635     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2636         SrcVT.getVectorElementType() != MVT::f64) {
2637       // For scalable vectors, we only need to close the gap between
2638       // vXf64<->vXf16.
2639       if (!VT.isFixedLengthVector())
2640         return Op;
2641       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2642       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2643       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2644     }
2645 
2646     SDValue Mask, VL;
2647     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2648 
2649     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2650     SDValue IntermediateRound =
2651         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2652     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2653                                           DL, DAG, Subtarget);
2654 
2655     if (VT.isFixedLengthVector())
2656       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2657     return Round;
2658   }
2659   case ISD::FP_TO_SINT:
2660   case ISD::FP_TO_UINT:
2661   case ISD::SINT_TO_FP:
2662   case ISD::UINT_TO_FP: {
2663     // RVV can only do fp<->int conversions to types half/double the size as
2664     // the source. We custom-lower any conversions that do two hops into
2665     // sequences.
2666     MVT VT = Op.getSimpleValueType();
2667     if (!VT.isVector())
2668       return Op;
2669     SDLoc DL(Op);
2670     SDValue Src = Op.getOperand(0);
2671     MVT EltVT = VT.getVectorElementType();
2672     MVT SrcVT = Src.getSimpleValueType();
2673     MVT SrcEltVT = SrcVT.getVectorElementType();
2674     unsigned EltSize = EltVT.getSizeInBits();
2675     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2676     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2677            "Unexpected vector element types");
2678 
2679     bool IsInt2FP = SrcEltVT.isInteger();
2680     // Widening conversions
2681     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2682       if (IsInt2FP) {
2683         // Do a regular integer sign/zero extension then convert to float.
2684         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2685                                       VT.getVectorElementCount());
2686         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2687                                  ? ISD::ZERO_EXTEND
2688                                  : ISD::SIGN_EXTEND;
2689         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2690         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2691       }
2692       // FP2Int
2693       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2694       // Do one doubling fp_extend then complete the operation by converting
2695       // to int.
2696       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2697       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2698       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2699     }
2700 
2701     // Narrowing conversions
2702     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2703       if (IsInt2FP) {
2704         // One narrowing int_to_fp, then an fp_round.
2705         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2706         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2707         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2708         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2709       }
2710       // FP2Int
2711       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2712       // representable by the integer, the result is poison.
2713       MVT IVecVT =
2714           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2715                            VT.getVectorElementCount());
2716       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2717       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2718     }
2719 
2720     // Scalable vectors can exit here. Patterns will handle equally-sized
2721     // conversions halving/doubling ones.
2722     if (!VT.isFixedLengthVector())
2723       return Op;
2724 
2725     // For fixed-length vectors we lower to a custom "VL" node.
2726     unsigned RVVOpc = 0;
2727     switch (Op.getOpcode()) {
2728     default:
2729       llvm_unreachable("Impossible opcode");
2730     case ISD::FP_TO_SINT:
2731       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2732       break;
2733     case ISD::FP_TO_UINT:
2734       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2735       break;
2736     case ISD::SINT_TO_FP:
2737       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2738       break;
2739     case ISD::UINT_TO_FP:
2740       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2741       break;
2742     }
2743 
2744     MVT ContainerVT, SrcContainerVT;
2745     // Derive the reference container type from the larger vector type.
2746     if (SrcEltSize > EltSize) {
2747       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2748       ContainerVT =
2749           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2750     } else {
2751       ContainerVT = getContainerForFixedLengthVector(VT);
2752       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2753     }
2754 
2755     SDValue Mask, VL;
2756     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2757 
2758     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2759     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2760     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2761   }
2762   case ISD::FP_TO_SINT_SAT:
2763   case ISD::FP_TO_UINT_SAT:
2764     return lowerFP_TO_INT_SAT(Op, DAG);
2765   case ISD::VECREDUCE_ADD:
2766   case ISD::VECREDUCE_UMAX:
2767   case ISD::VECREDUCE_SMAX:
2768   case ISD::VECREDUCE_UMIN:
2769   case ISD::VECREDUCE_SMIN:
2770     return lowerVECREDUCE(Op, DAG);
2771   case ISD::VECREDUCE_AND:
2772   case ISD::VECREDUCE_OR:
2773   case ISD::VECREDUCE_XOR:
2774     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2775       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
2776     return lowerVECREDUCE(Op, DAG);
2777   case ISD::VECREDUCE_FADD:
2778   case ISD::VECREDUCE_SEQ_FADD:
2779   case ISD::VECREDUCE_FMIN:
2780   case ISD::VECREDUCE_FMAX:
2781     return lowerFPVECREDUCE(Op, DAG);
2782   case ISD::VP_REDUCE_ADD:
2783   case ISD::VP_REDUCE_UMAX:
2784   case ISD::VP_REDUCE_SMAX:
2785   case ISD::VP_REDUCE_UMIN:
2786   case ISD::VP_REDUCE_SMIN:
2787   case ISD::VP_REDUCE_FADD:
2788   case ISD::VP_REDUCE_SEQ_FADD:
2789   case ISD::VP_REDUCE_FMIN:
2790   case ISD::VP_REDUCE_FMAX:
2791     return lowerVPREDUCE(Op, DAG);
2792   case ISD::VP_REDUCE_AND:
2793   case ISD::VP_REDUCE_OR:
2794   case ISD::VP_REDUCE_XOR:
2795     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
2796       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
2797     return lowerVPREDUCE(Op, DAG);
2798   case ISD::INSERT_SUBVECTOR:
2799     return lowerINSERT_SUBVECTOR(Op, DAG);
2800   case ISD::EXTRACT_SUBVECTOR:
2801     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2802   case ISD::STEP_VECTOR:
2803     return lowerSTEP_VECTOR(Op, DAG);
2804   case ISD::VECTOR_REVERSE:
2805     return lowerVECTOR_REVERSE(Op, DAG);
2806   case ISD::BUILD_VECTOR:
2807     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2808   case ISD::SPLAT_VECTOR:
2809     if (Op.getValueType().getVectorElementType() == MVT::i1)
2810       return lowerVectorMaskSplat(Op, DAG);
2811     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
2812   case ISD::VECTOR_SHUFFLE:
2813     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2814   case ISD::CONCAT_VECTORS: {
2815     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2816     // better than going through the stack, as the default expansion does.
2817     SDLoc DL(Op);
2818     MVT VT = Op.getSimpleValueType();
2819     unsigned NumOpElts =
2820         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2821     SDValue Vec = DAG.getUNDEF(VT);
2822     for (const auto &OpIdx : enumerate(Op->ops()))
2823       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2824                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2825     return Vec;
2826   }
2827   case ISD::LOAD:
2828     if (auto V = expandUnalignedRVVLoad(Op, DAG))
2829       return V;
2830     if (Op.getValueType().isFixedLengthVector())
2831       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2832     return Op;
2833   case ISD::STORE:
2834     if (auto V = expandUnalignedRVVStore(Op, DAG))
2835       return V;
2836     if (Op.getOperand(1).getValueType().isFixedLengthVector())
2837       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2838     return Op;
2839   case ISD::MLOAD:
2840   case ISD::VP_LOAD:
2841     return lowerMaskedLoad(Op, DAG);
2842   case ISD::MSTORE:
2843   case ISD::VP_STORE:
2844     return lowerMaskedStore(Op, DAG);
2845   case ISD::SETCC:
2846     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2847   case ISD::ADD:
2848     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2849   case ISD::SUB:
2850     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2851   case ISD::MUL:
2852     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2853   case ISD::MULHS:
2854     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2855   case ISD::MULHU:
2856     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2857   case ISD::AND:
2858     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2859                                               RISCVISD::AND_VL);
2860   case ISD::OR:
2861     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2862                                               RISCVISD::OR_VL);
2863   case ISD::XOR:
2864     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2865                                               RISCVISD::XOR_VL);
2866   case ISD::SDIV:
2867     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2868   case ISD::SREM:
2869     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2870   case ISD::UDIV:
2871     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2872   case ISD::UREM:
2873     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2874   case ISD::SHL:
2875   case ISD::SRA:
2876   case ISD::SRL:
2877     if (Op.getSimpleValueType().isFixedLengthVector())
2878       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
2879     // This can be called for an i32 shift amount that needs to be promoted.
2880     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
2881            "Unexpected custom legalisation");
2882     return SDValue();
2883   case ISD::SADDSAT:
2884     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
2885   case ISD::UADDSAT:
2886     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
2887   case ISD::SSUBSAT:
2888     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
2889   case ISD::USUBSAT:
2890     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
2891   case ISD::FADD:
2892     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2893   case ISD::FSUB:
2894     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2895   case ISD::FMUL:
2896     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2897   case ISD::FDIV:
2898     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2899   case ISD::FNEG:
2900     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2901   case ISD::FABS:
2902     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2903   case ISD::FSQRT:
2904     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2905   case ISD::FMA:
2906     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2907   case ISD::SMIN:
2908     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2909   case ISD::SMAX:
2910     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2911   case ISD::UMIN:
2912     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2913   case ISD::UMAX:
2914     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2915   case ISD::FMINNUM:
2916     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
2917   case ISD::FMAXNUM:
2918     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
2919   case ISD::ABS:
2920     return lowerABS(Op, DAG);
2921   case ISD::VSELECT:
2922     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2923   case ISD::FCOPYSIGN:
2924     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2925   case ISD::MGATHER:
2926   case ISD::VP_GATHER:
2927     return lowerMaskedGather(Op, DAG);
2928   case ISD::MSCATTER:
2929   case ISD::VP_SCATTER:
2930     return lowerMaskedScatter(Op, DAG);
2931   case ISD::FLT_ROUNDS_:
2932     return lowerGET_ROUNDING(Op, DAG);
2933   case ISD::SET_ROUNDING:
2934     return lowerSET_ROUNDING(Op, DAG);
2935   case ISD::VP_ADD:
2936     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
2937   case ISD::VP_SUB:
2938     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
2939   case ISD::VP_MUL:
2940     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
2941   case ISD::VP_SDIV:
2942     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
2943   case ISD::VP_UDIV:
2944     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
2945   case ISD::VP_SREM:
2946     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
2947   case ISD::VP_UREM:
2948     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
2949   case ISD::VP_AND:
2950     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
2951   case ISD::VP_OR:
2952     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
2953   case ISD::VP_XOR:
2954     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
2955   case ISD::VP_ASHR:
2956     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
2957   case ISD::VP_LSHR:
2958     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
2959   case ISD::VP_SHL:
2960     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
2961   case ISD::VP_FADD:
2962     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
2963   case ISD::VP_FSUB:
2964     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
2965   case ISD::VP_FMUL:
2966     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
2967   case ISD::VP_FDIV:
2968     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
2969   }
2970 }
2971 
2972 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2973                              SelectionDAG &DAG, unsigned Flags) {
2974   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2975 }
2976 
2977 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
2978                              SelectionDAG &DAG, unsigned Flags) {
2979   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
2980                                    Flags);
2981 }
2982 
2983 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
2984                              SelectionDAG &DAG, unsigned Flags) {
2985   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
2986                                    N->getOffset(), Flags);
2987 }
2988 
2989 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
2990                              SelectionDAG &DAG, unsigned Flags) {
2991   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
2992 }
2993 
2994 template <class NodeTy>
2995 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
2996                                      bool IsLocal) const {
2997   SDLoc DL(N);
2998   EVT Ty = getPointerTy(DAG.getDataLayout());
2999 
3000   if (isPositionIndependent()) {
3001     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3002     if (IsLocal)
3003       // Use PC-relative addressing to access the symbol. This generates the
3004       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3005       // %pcrel_lo(auipc)).
3006       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3007 
3008     // Use PC-relative addressing to access the GOT for this symbol, then load
3009     // the address from the GOT. This generates the pattern (PseudoLA sym),
3010     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3011     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3012   }
3013 
3014   switch (getTargetMachine().getCodeModel()) {
3015   default:
3016     report_fatal_error("Unsupported code model for lowering");
3017   case CodeModel::Small: {
3018     // Generate a sequence for accessing addresses within the first 2 GiB of
3019     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3020     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3021     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3022     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3023     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3024   }
3025   case CodeModel::Medium: {
3026     // Generate a sequence for accessing addresses within any 2GiB range within
3027     // the address space. This generates the pattern (PseudoLLA sym), which
3028     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3029     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3030     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3031   }
3032   }
3033 }
3034 
3035 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3036                                                 SelectionDAG &DAG) const {
3037   SDLoc DL(Op);
3038   EVT Ty = Op.getValueType();
3039   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3040   int64_t Offset = N->getOffset();
3041   MVT XLenVT = Subtarget.getXLenVT();
3042 
3043   const GlobalValue *GV = N->getGlobal();
3044   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3045   SDValue Addr = getAddr(N, DAG, IsLocal);
3046 
3047   // In order to maximise the opportunity for common subexpression elimination,
3048   // emit a separate ADD node for the global address offset instead of folding
3049   // it in the global address node. Later peephole optimisations may choose to
3050   // fold it back in when profitable.
3051   if (Offset != 0)
3052     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3053                        DAG.getConstant(Offset, DL, XLenVT));
3054   return Addr;
3055 }
3056 
3057 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3058                                                SelectionDAG &DAG) const {
3059   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3060 
3061   return getAddr(N, DAG);
3062 }
3063 
3064 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3065                                                SelectionDAG &DAG) const {
3066   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3067 
3068   return getAddr(N, DAG);
3069 }
3070 
3071 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3072                                             SelectionDAG &DAG) const {
3073   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3074 
3075   return getAddr(N, DAG);
3076 }
3077 
3078 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3079                                               SelectionDAG &DAG,
3080                                               bool UseGOT) const {
3081   SDLoc DL(N);
3082   EVT Ty = getPointerTy(DAG.getDataLayout());
3083   const GlobalValue *GV = N->getGlobal();
3084   MVT XLenVT = Subtarget.getXLenVT();
3085 
3086   if (UseGOT) {
3087     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3088     // load the address from the GOT and add the thread pointer. This generates
3089     // the pattern (PseudoLA_TLS_IE sym), which expands to
3090     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3091     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3092     SDValue Load =
3093         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3094 
3095     // Add the thread pointer.
3096     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3097     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3098   }
3099 
3100   // Generate a sequence for accessing the address relative to the thread
3101   // pointer, with the appropriate adjustment for the thread pointer offset.
3102   // This generates the pattern
3103   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3104   SDValue AddrHi =
3105       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3106   SDValue AddrAdd =
3107       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3108   SDValue AddrLo =
3109       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3110 
3111   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3112   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3113   SDValue MNAdd = SDValue(
3114       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3115       0);
3116   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3117 }
3118 
3119 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3120                                                SelectionDAG &DAG) const {
3121   SDLoc DL(N);
3122   EVT Ty = getPointerTy(DAG.getDataLayout());
3123   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3124   const GlobalValue *GV = N->getGlobal();
3125 
3126   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3127   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3128   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3129   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3130   SDValue Load =
3131       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3132 
3133   // Prepare argument list to generate call.
3134   ArgListTy Args;
3135   ArgListEntry Entry;
3136   Entry.Node = Load;
3137   Entry.Ty = CallTy;
3138   Args.push_back(Entry);
3139 
3140   // Setup call to __tls_get_addr.
3141   TargetLowering::CallLoweringInfo CLI(DAG);
3142   CLI.setDebugLoc(DL)
3143       .setChain(DAG.getEntryNode())
3144       .setLibCallee(CallingConv::C, CallTy,
3145                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3146                     std::move(Args));
3147 
3148   return LowerCallTo(CLI).first;
3149 }
3150 
3151 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3152                                                    SelectionDAG &DAG) const {
3153   SDLoc DL(Op);
3154   EVT Ty = Op.getValueType();
3155   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3156   int64_t Offset = N->getOffset();
3157   MVT XLenVT = Subtarget.getXLenVT();
3158 
3159   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3160 
3161   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3162       CallingConv::GHC)
3163     report_fatal_error("In GHC calling convention TLS is not supported");
3164 
3165   SDValue Addr;
3166   switch (Model) {
3167   case TLSModel::LocalExec:
3168     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3169     break;
3170   case TLSModel::InitialExec:
3171     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3172     break;
3173   case TLSModel::LocalDynamic:
3174   case TLSModel::GeneralDynamic:
3175     Addr = getDynamicTLSAddr(N, DAG);
3176     break;
3177   }
3178 
3179   // In order to maximise the opportunity for common subexpression elimination,
3180   // emit a separate ADD node for the global address offset instead of folding
3181   // it in the global address node. Later peephole optimisations may choose to
3182   // fold it back in when profitable.
3183   if (Offset != 0)
3184     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3185                        DAG.getConstant(Offset, DL, XLenVT));
3186   return Addr;
3187 }
3188 
3189 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3190   SDValue CondV = Op.getOperand(0);
3191   SDValue TrueV = Op.getOperand(1);
3192   SDValue FalseV = Op.getOperand(2);
3193   SDLoc DL(Op);
3194   MVT VT = Op.getSimpleValueType();
3195   MVT XLenVT = Subtarget.getXLenVT();
3196 
3197   // Lower vector SELECTs to VSELECTs by splatting the condition.
3198   if (VT.isVector()) {
3199     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3200     SDValue CondSplat = VT.isScalableVector()
3201                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3202                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3203     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3204   }
3205 
3206   // If the result type is XLenVT and CondV is the output of a SETCC node
3207   // which also operated on XLenVT inputs, then merge the SETCC node into the
3208   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3209   // compare+branch instructions. i.e.:
3210   // (select (setcc lhs, rhs, cc), truev, falsev)
3211   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3212   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3213       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3214     SDValue LHS = CondV.getOperand(0);
3215     SDValue RHS = CondV.getOperand(1);
3216     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3217     ISD::CondCode CCVal = CC->get();
3218 
3219     // Special case for a select of 2 constants that have a diffence of 1.
3220     // Normally this is done by DAGCombine, but if the select is introduced by
3221     // type legalization or op legalization, we miss it. Restricting to SETLT
3222     // case for now because that is what signed saturating add/sub need.
3223     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3224     // but we would probably want to swap the true/false values if the condition
3225     // is SETGE/SETLE to avoid an XORI.
3226     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3227         CCVal == ISD::SETLT) {
3228       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3229       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3230       if (TrueVal - 1 == FalseVal)
3231         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3232       if (TrueVal + 1 == FalseVal)
3233         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3234     }
3235 
3236     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3237 
3238     SDValue TargetCC = DAG.getCondCode(CCVal);
3239     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3240     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3241   }
3242 
3243   // Otherwise:
3244   // (select condv, truev, falsev)
3245   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3246   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3247   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3248 
3249   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3250 
3251   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3252 }
3253 
3254 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3255   SDValue CondV = Op.getOperand(1);
3256   SDLoc DL(Op);
3257   MVT XLenVT = Subtarget.getXLenVT();
3258 
3259   if (CondV.getOpcode() == ISD::SETCC &&
3260       CondV.getOperand(0).getValueType() == XLenVT) {
3261     SDValue LHS = CondV.getOperand(0);
3262     SDValue RHS = CondV.getOperand(1);
3263     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3264 
3265     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3266 
3267     SDValue TargetCC = DAG.getCondCode(CCVal);
3268     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3269                        LHS, RHS, TargetCC, Op.getOperand(2));
3270   }
3271 
3272   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3273                      CondV, DAG.getConstant(0, DL, XLenVT),
3274                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3275 }
3276 
3277 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3278   MachineFunction &MF = DAG.getMachineFunction();
3279   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3280 
3281   SDLoc DL(Op);
3282   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3283                                  getPointerTy(MF.getDataLayout()));
3284 
3285   // vastart just stores the address of the VarArgsFrameIndex slot into the
3286   // memory location argument.
3287   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3288   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3289                       MachinePointerInfo(SV));
3290 }
3291 
3292 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3293                                             SelectionDAG &DAG) const {
3294   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3295   MachineFunction &MF = DAG.getMachineFunction();
3296   MachineFrameInfo &MFI = MF.getFrameInfo();
3297   MFI.setFrameAddressIsTaken(true);
3298   Register FrameReg = RI.getFrameRegister(MF);
3299   int XLenInBytes = Subtarget.getXLen() / 8;
3300 
3301   EVT VT = Op.getValueType();
3302   SDLoc DL(Op);
3303   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3304   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3305   while (Depth--) {
3306     int Offset = -(XLenInBytes * 2);
3307     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3308                               DAG.getIntPtrConstant(Offset, DL));
3309     FrameAddr =
3310         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3311   }
3312   return FrameAddr;
3313 }
3314 
3315 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3316                                              SelectionDAG &DAG) const {
3317   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3318   MachineFunction &MF = DAG.getMachineFunction();
3319   MachineFrameInfo &MFI = MF.getFrameInfo();
3320   MFI.setReturnAddressIsTaken(true);
3321   MVT XLenVT = Subtarget.getXLenVT();
3322   int XLenInBytes = Subtarget.getXLen() / 8;
3323 
3324   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3325     return SDValue();
3326 
3327   EVT VT = Op.getValueType();
3328   SDLoc DL(Op);
3329   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3330   if (Depth) {
3331     int Off = -XLenInBytes;
3332     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3333     SDValue Offset = DAG.getConstant(Off, DL, VT);
3334     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3335                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3336                        MachinePointerInfo());
3337   }
3338 
3339   // Return the value of the return address register, marking it an implicit
3340   // live-in.
3341   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3342   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3343 }
3344 
3345 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3346                                                  SelectionDAG &DAG) const {
3347   SDLoc DL(Op);
3348   SDValue Lo = Op.getOperand(0);
3349   SDValue Hi = Op.getOperand(1);
3350   SDValue Shamt = Op.getOperand(2);
3351   EVT VT = Lo.getValueType();
3352 
3353   // if Shamt-XLEN < 0: // Shamt < XLEN
3354   //   Lo = Lo << Shamt
3355   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3356   // else:
3357   //   Lo = 0
3358   //   Hi = Lo << (Shamt-XLEN)
3359 
3360   SDValue Zero = DAG.getConstant(0, DL, VT);
3361   SDValue One = DAG.getConstant(1, DL, VT);
3362   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3363   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3364   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3365   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3366 
3367   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3368   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3369   SDValue ShiftRightLo =
3370       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3371   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3372   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3373   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3374 
3375   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3376 
3377   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3378   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3379 
3380   SDValue Parts[2] = {Lo, Hi};
3381   return DAG.getMergeValues(Parts, DL);
3382 }
3383 
3384 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3385                                                   bool IsSRA) const {
3386   SDLoc DL(Op);
3387   SDValue Lo = Op.getOperand(0);
3388   SDValue Hi = Op.getOperand(1);
3389   SDValue Shamt = Op.getOperand(2);
3390   EVT VT = Lo.getValueType();
3391 
3392   // SRA expansion:
3393   //   if Shamt-XLEN < 0: // Shamt < XLEN
3394   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3395   //     Hi = Hi >>s Shamt
3396   //   else:
3397   //     Lo = Hi >>s (Shamt-XLEN);
3398   //     Hi = Hi >>s (XLEN-1)
3399   //
3400   // SRL expansion:
3401   //   if Shamt-XLEN < 0: // Shamt < XLEN
3402   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3403   //     Hi = Hi >>u Shamt
3404   //   else:
3405   //     Lo = Hi >>u (Shamt-XLEN);
3406   //     Hi = 0;
3407 
3408   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3409 
3410   SDValue Zero = DAG.getConstant(0, DL, VT);
3411   SDValue One = DAG.getConstant(1, DL, VT);
3412   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3413   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3414   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3415   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3416 
3417   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3418   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3419   SDValue ShiftLeftHi =
3420       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3421   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3422   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3423   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3424   SDValue HiFalse =
3425       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3426 
3427   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3428 
3429   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3430   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3431 
3432   SDValue Parts[2] = {Lo, Hi};
3433   return DAG.getMergeValues(Parts, DL);
3434 }
3435 
3436 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3437 // legal equivalently-sized i8 type, so we can use that as a go-between.
3438 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3439                                                   SelectionDAG &DAG) const {
3440   SDLoc DL(Op);
3441   MVT VT = Op.getSimpleValueType();
3442   SDValue SplatVal = Op.getOperand(0);
3443   // All-zeros or all-ones splats are handled specially.
3444   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3445     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3446     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3447   }
3448   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3449     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3450     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3451   }
3452   MVT XLenVT = Subtarget.getXLenVT();
3453   assert(SplatVal.getValueType() == XLenVT &&
3454          "Unexpected type for i1 splat value");
3455   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3456   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3457                          DAG.getConstant(1, DL, XLenVT));
3458   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3459   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3460   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3461 }
3462 
3463 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3464 // illegal (currently only vXi64 RV32).
3465 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3466 // them to SPLAT_VECTOR_I64
3467 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3468                                                      SelectionDAG &DAG) const {
3469   SDLoc DL(Op);
3470   MVT VecVT = Op.getSimpleValueType();
3471   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3472          "Unexpected SPLAT_VECTOR_PARTS lowering");
3473 
3474   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3475   SDValue Lo = Op.getOperand(0);
3476   SDValue Hi = Op.getOperand(1);
3477 
3478   if (VecVT.isFixedLengthVector()) {
3479     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3480     SDLoc DL(Op);
3481     SDValue Mask, VL;
3482     std::tie(Mask, VL) =
3483         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3484 
3485     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3486     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3487   }
3488 
3489   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3490     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3491     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3492     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3493     // node in order to try and match RVV vector/scalar instructions.
3494     if ((LoC >> 31) == HiC)
3495       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3496   }
3497 
3498   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3499   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3500       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3501       Hi.getConstantOperandVal(1) == 31)
3502     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3503 
3504   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3505   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3506                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3507 }
3508 
3509 // Custom-lower extensions from mask vectors by using a vselect either with 1
3510 // for zero/any-extension or -1 for sign-extension:
3511 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3512 // Note that any-extension is lowered identically to zero-extension.
3513 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3514                                                 int64_t ExtTrueVal) const {
3515   SDLoc DL(Op);
3516   MVT VecVT = Op.getSimpleValueType();
3517   SDValue Src = Op.getOperand(0);
3518   // Only custom-lower extensions from mask types
3519   assert(Src.getValueType().isVector() &&
3520          Src.getValueType().getVectorElementType() == MVT::i1);
3521 
3522   MVT XLenVT = Subtarget.getXLenVT();
3523   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3524   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3525 
3526   if (VecVT.isScalableVector()) {
3527     // Be careful not to introduce illegal scalar types at this stage, and be
3528     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3529     // illegal and must be expanded. Since we know that the constants are
3530     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3531     bool IsRV32E64 =
3532         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3533 
3534     if (!IsRV32E64) {
3535       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3536       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3537     } else {
3538       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3539       SplatTrueVal =
3540           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3541     }
3542 
3543     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3544   }
3545 
3546   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3547   MVT I1ContainerVT =
3548       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3549 
3550   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3551 
3552   SDValue Mask, VL;
3553   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3554 
3555   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3556   SplatTrueVal =
3557       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3558   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3559                                SplatTrueVal, SplatZero, VL);
3560 
3561   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3562 }
3563 
3564 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3565     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3566   MVT ExtVT = Op.getSimpleValueType();
3567   // Only custom-lower extensions from fixed-length vector types.
3568   if (!ExtVT.isFixedLengthVector())
3569     return Op;
3570   MVT VT = Op.getOperand(0).getSimpleValueType();
3571   // Grab the canonical container type for the extended type. Infer the smaller
3572   // type from that to ensure the same number of vector elements, as we know
3573   // the LMUL will be sufficient to hold the smaller type.
3574   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3575   // Get the extended container type manually to ensure the same number of
3576   // vector elements between source and dest.
3577   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3578                                      ContainerExtVT.getVectorElementCount());
3579 
3580   SDValue Op1 =
3581       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3582 
3583   SDLoc DL(Op);
3584   SDValue Mask, VL;
3585   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3586 
3587   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3588 
3589   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3590 }
3591 
3592 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3593 // setcc operation:
3594 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3595 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3596                                                   SelectionDAG &DAG) const {
3597   SDLoc DL(Op);
3598   EVT MaskVT = Op.getValueType();
3599   // Only expect to custom-lower truncations to mask types
3600   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3601          "Unexpected type for vector mask lowering");
3602   SDValue Src = Op.getOperand(0);
3603   MVT VecVT = Src.getSimpleValueType();
3604 
3605   // If this is a fixed vector, we need to convert it to a scalable vector.
3606   MVT ContainerVT = VecVT;
3607   if (VecVT.isFixedLengthVector()) {
3608     ContainerVT = getContainerForFixedLengthVector(VecVT);
3609     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3610   }
3611 
3612   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3613   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3614 
3615   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3616   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3617 
3618   if (VecVT.isScalableVector()) {
3619     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3620     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3621   }
3622 
3623   SDValue Mask, VL;
3624   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3625 
3626   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3627   SDValue Trunc =
3628       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3629   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3630                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3631   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3632 }
3633 
3634 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3635 // first position of a vector, and that vector is slid up to the insert index.
3636 // By limiting the active vector length to index+1 and merging with the
3637 // original vector (with an undisturbed tail policy for elements >= VL), we
3638 // achieve the desired result of leaving all elements untouched except the one
3639 // at VL-1, which is replaced with the desired value.
3640 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3641                                                     SelectionDAG &DAG) const {
3642   SDLoc DL(Op);
3643   MVT VecVT = Op.getSimpleValueType();
3644   SDValue Vec = Op.getOperand(0);
3645   SDValue Val = Op.getOperand(1);
3646   SDValue Idx = Op.getOperand(2);
3647 
3648   if (VecVT.getVectorElementType() == MVT::i1) {
3649     // FIXME: For now we just promote to an i8 vector and insert into that,
3650     // but this is probably not optimal.
3651     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3652     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3653     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3654     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3655   }
3656 
3657   MVT ContainerVT = VecVT;
3658   // If the operand is a fixed-length vector, convert to a scalable one.
3659   if (VecVT.isFixedLengthVector()) {
3660     ContainerVT = getContainerForFixedLengthVector(VecVT);
3661     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3662   }
3663 
3664   MVT XLenVT = Subtarget.getXLenVT();
3665 
3666   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3667   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3668   // Even i64-element vectors on RV32 can be lowered without scalar
3669   // legalization if the most-significant 32 bits of the value are not affected
3670   // by the sign-extension of the lower 32 bits.
3671   // TODO: We could also catch sign extensions of a 32-bit value.
3672   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3673     const auto *CVal = cast<ConstantSDNode>(Val);
3674     if (isInt<32>(CVal->getSExtValue())) {
3675       IsLegalInsert = true;
3676       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3677     }
3678   }
3679 
3680   SDValue Mask, VL;
3681   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3682 
3683   SDValue ValInVec;
3684 
3685   if (IsLegalInsert) {
3686     unsigned Opc =
3687         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3688     if (isNullConstant(Idx)) {
3689       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3690       if (!VecVT.isFixedLengthVector())
3691         return Vec;
3692       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3693     }
3694     ValInVec =
3695         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3696   } else {
3697     // On RV32, i64-element vectors must be specially handled to place the
3698     // value at element 0, by using two vslide1up instructions in sequence on
3699     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3700     // this.
3701     SDValue One = DAG.getConstant(1, DL, XLenVT);
3702     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3703     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3704     MVT I32ContainerVT =
3705         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3706     SDValue I32Mask =
3707         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3708     // Limit the active VL to two.
3709     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3710     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3711     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3712     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3713                            InsertI64VL);
3714     // First slide in the hi value, then the lo in underneath it.
3715     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3716                            ValHi, I32Mask, InsertI64VL);
3717     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3718                            ValLo, I32Mask, InsertI64VL);
3719     // Bitcast back to the right container type.
3720     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3721   }
3722 
3723   // Now that the value is in a vector, slide it into position.
3724   SDValue InsertVL =
3725       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3726   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3727                                 ValInVec, Idx, Mask, InsertVL);
3728   if (!VecVT.isFixedLengthVector())
3729     return Slideup;
3730   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3731 }
3732 
3733 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3734 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3735 // types this is done using VMV_X_S to allow us to glean information about the
3736 // sign bits of the result.
3737 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3738                                                      SelectionDAG &DAG) const {
3739   SDLoc DL(Op);
3740   SDValue Idx = Op.getOperand(1);
3741   SDValue Vec = Op.getOperand(0);
3742   EVT EltVT = Op.getValueType();
3743   MVT VecVT = Vec.getSimpleValueType();
3744   MVT XLenVT = Subtarget.getXLenVT();
3745 
3746   if (VecVT.getVectorElementType() == MVT::i1) {
3747     // FIXME: For now we just promote to an i8 vector and extract from that,
3748     // but this is probably not optimal.
3749     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3750     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3751     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3752   }
3753 
3754   // If this is a fixed vector, we need to convert it to a scalable vector.
3755   MVT ContainerVT = VecVT;
3756   if (VecVT.isFixedLengthVector()) {
3757     ContainerVT = getContainerForFixedLengthVector(VecVT);
3758     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3759   }
3760 
3761   // If the index is 0, the vector is already in the right position.
3762   if (!isNullConstant(Idx)) {
3763     // Use a VL of 1 to avoid processing more elements than we need.
3764     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3765     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3766     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3767     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3768                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3769   }
3770 
3771   if (!EltVT.isInteger()) {
3772     // Floating-point extracts are handled in TableGen.
3773     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3774                        DAG.getConstant(0, DL, XLenVT));
3775   }
3776 
3777   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3778   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3779 }
3780 
3781 // Some RVV intrinsics may claim that they want an integer operand to be
3782 // promoted or expanded.
3783 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3784                                           const RISCVSubtarget &Subtarget) {
3785   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3786           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3787          "Unexpected opcode");
3788 
3789   if (!Subtarget.hasVInstructions())
3790     return SDValue();
3791 
3792   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3793   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3794   SDLoc DL(Op);
3795 
3796   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
3797       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3798   if (!II || !II->SplatOperand)
3799     return SDValue();
3800 
3801   unsigned SplatOp = II->SplatOperand + HasChain;
3802   assert(SplatOp < Op.getNumOperands());
3803 
3804   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
3805   SDValue &ScalarOp = Operands[SplatOp];
3806   MVT OpVT = ScalarOp.getSimpleValueType();
3807   MVT XLenVT = Subtarget.getXLenVT();
3808 
3809   // If this isn't a scalar, or its type is XLenVT we're done.
3810   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
3811     return SDValue();
3812 
3813   // Simplest case is that the operand needs to be promoted to XLenVT.
3814   if (OpVT.bitsLT(XLenVT)) {
3815     // If the operand is a constant, sign extend to increase our chances
3816     // of being able to use a .vi instruction. ANY_EXTEND would become a
3817     // a zero extend and the simm5 check in isel would fail.
3818     // FIXME: Should we ignore the upper bits in isel instead?
3819     unsigned ExtOpc =
3820         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
3821     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
3822     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3823   }
3824 
3825   // Use the previous operand to get the vXi64 VT. The result might be a mask
3826   // VT for compares. Using the previous operand assumes that the previous
3827   // operand will never have a smaller element size than a scalar operand and
3828   // that a widening operation never uses SEW=64.
3829   // NOTE: If this fails the below assert, we can probably just find the
3830   // element count from any operand or result and use it to construct the VT.
3831   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
3832   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
3833 
3834   // The more complex case is when the scalar is larger than XLenVT.
3835   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3836          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3837 
3838   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3839   // on the instruction to sign-extend since SEW>XLEN.
3840   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3841     if (isInt<32>(CVal->getSExtValue())) {
3842       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3843       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3844     }
3845   }
3846 
3847   // We need to convert the scalar to a splat vector.
3848   // FIXME: Can we implicitly truncate the scalar if it is known to
3849   // be sign extended?
3850   // VL should be the last operand.
3851   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3852   assert(VL.getValueType() == XLenVT);
3853   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3854   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3855 }
3856 
3857 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3858                                                      SelectionDAG &DAG) const {
3859   unsigned IntNo = Op.getConstantOperandVal(0);
3860   SDLoc DL(Op);
3861   MVT XLenVT = Subtarget.getXLenVT();
3862 
3863   switch (IntNo) {
3864   default:
3865     break; // Don't custom lower most intrinsics.
3866   case Intrinsic::thread_pointer: {
3867     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3868     return DAG.getRegister(RISCV::X4, PtrVT);
3869   }
3870   case Intrinsic::riscv_orc_b:
3871     // Lower to the GORCI encoding for orc.b.
3872     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3873                        DAG.getConstant(7, DL, XLenVT));
3874   case Intrinsic::riscv_grev:
3875   case Intrinsic::riscv_gorc: {
3876     unsigned Opc =
3877         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
3878     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3879   }
3880   case Intrinsic::riscv_shfl:
3881   case Intrinsic::riscv_unshfl: {
3882     unsigned Opc =
3883         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
3884     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3885   }
3886   case Intrinsic::riscv_bcompress:
3887   case Intrinsic::riscv_bdecompress: {
3888     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
3889                                                        : RISCVISD::BDECOMPRESS;
3890     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3891   }
3892   case Intrinsic::riscv_vmv_x_s:
3893     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3894     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3895                        Op.getOperand(1));
3896   case Intrinsic::riscv_vmv_v_x:
3897     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3898                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3899   case Intrinsic::riscv_vfmv_v_f:
3900     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3901                        Op.getOperand(1), Op.getOperand(2));
3902   case Intrinsic::riscv_vmv_s_x: {
3903     SDValue Scalar = Op.getOperand(2);
3904 
3905     if (Scalar.getValueType().bitsLE(XLenVT)) {
3906       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3907       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3908                          Op.getOperand(1), Scalar, Op.getOperand(3));
3909     }
3910 
3911     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3912 
3913     // This is an i64 value that lives in two scalar registers. We have to
3914     // insert this in a convoluted way. First we build vXi64 splat containing
3915     // the/ two values that we assemble using some bit math. Next we'll use
3916     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3917     // to merge element 0 from our splat into the source vector.
3918     // FIXME: This is probably not the best way to do this, but it is
3919     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3920     // point.
3921     //   sw lo, (a0)
3922     //   sw hi, 4(a0)
3923     //   vlse vX, (a0)
3924     //
3925     //   vid.v      vVid
3926     //   vmseq.vx   mMask, vVid, 0
3927     //   vmerge.vvm vDest, vSrc, vVal, mMask
3928     MVT VT = Op.getSimpleValueType();
3929     SDValue Vec = Op.getOperand(1);
3930     SDValue VL = Op.getOperand(3);
3931 
3932     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3933     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3934                                       DAG.getConstant(0, DL, MVT::i32), VL);
3935 
3936     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3937     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3938     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3939     SDValue SelectCond =
3940         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3941                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3942     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3943                        Vec, VL);
3944   }
3945   case Intrinsic::riscv_vslide1up:
3946   case Intrinsic::riscv_vslide1down:
3947   case Intrinsic::riscv_vslide1up_mask:
3948   case Intrinsic::riscv_vslide1down_mask: {
3949     // We need to special case these when the scalar is larger than XLen.
3950     unsigned NumOps = Op.getNumOperands();
3951     bool IsMasked = NumOps == 7;
3952     unsigned OpOffset = IsMasked ? 1 : 0;
3953     SDValue Scalar = Op.getOperand(2 + OpOffset);
3954     if (Scalar.getValueType().bitsLE(XLenVT))
3955       break;
3956 
3957     // Splatting a sign extended constant is fine.
3958     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3959       if (isInt<32>(CVal->getSExtValue()))
3960         break;
3961 
3962     MVT VT = Op.getSimpleValueType();
3963     assert(VT.getVectorElementType() == MVT::i64 &&
3964            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3965 
3966     // Convert the vector source to the equivalent nxvXi32 vector.
3967     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3968     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3969 
3970     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3971                                    DAG.getConstant(0, DL, XLenVT));
3972     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3973                                    DAG.getConstant(1, DL, XLenVT));
3974 
3975     // Double the VL since we halved SEW.
3976     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
3977     SDValue I32VL =
3978         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
3979 
3980     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
3981     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
3982 
3983     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
3984     // instructions.
3985     if (IntNo == Intrinsic::riscv_vslide1up ||
3986         IntNo == Intrinsic::riscv_vslide1up_mask) {
3987       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
3988                         I32Mask, I32VL);
3989       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
3990                         I32Mask, I32VL);
3991     } else {
3992       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
3993                         I32Mask, I32VL);
3994       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
3995                         I32Mask, I32VL);
3996     }
3997 
3998     // Convert back to nxvXi64.
3999     Vec = DAG.getBitcast(VT, Vec);
4000 
4001     if (!IsMasked)
4002       return Vec;
4003 
4004     // Apply mask after the operation.
4005     SDValue Mask = Op.getOperand(NumOps - 3);
4006     SDValue MaskedOff = Op.getOperand(1);
4007     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4008   }
4009   }
4010 
4011   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4012 }
4013 
4014 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4015                                                     SelectionDAG &DAG) const {
4016   unsigned IntNo = Op.getConstantOperandVal(1);
4017   switch (IntNo) {
4018   default:
4019     break;
4020   case Intrinsic::riscv_masked_strided_load: {
4021     SDLoc DL(Op);
4022     MVT XLenVT = Subtarget.getXLenVT();
4023 
4024     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4025     // the selection of the masked intrinsics doesn't do this for us.
4026     SDValue Mask = Op.getOperand(5);
4027     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4028 
4029     MVT VT = Op->getSimpleValueType(0);
4030     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4031 
4032     SDValue PassThru = Op.getOperand(2);
4033     if (!IsUnmasked) {
4034       MVT MaskVT =
4035           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4036       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4037       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4038     }
4039 
4040     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4041 
4042     SDValue IntID = DAG.getTargetConstant(
4043         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4044         XLenVT);
4045 
4046     auto *Load = cast<MemIntrinsicSDNode>(Op);
4047     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4048     if (!IsUnmasked)
4049       Ops.push_back(PassThru);
4050     Ops.push_back(Op.getOperand(3)); // Ptr
4051     Ops.push_back(Op.getOperand(4)); // Stride
4052     if (!IsUnmasked)
4053       Ops.push_back(Mask);
4054     Ops.push_back(VL);
4055     if (!IsUnmasked) {
4056       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4057       Ops.push_back(Policy);
4058     }
4059 
4060     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4061     SDValue Result =
4062         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4063                                 Load->getMemoryVT(), Load->getMemOperand());
4064     SDValue Chain = Result.getValue(1);
4065     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4066     return DAG.getMergeValues({Result, Chain}, DL);
4067   }
4068   }
4069 
4070   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4071 }
4072 
4073 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4074                                                  SelectionDAG &DAG) const {
4075   unsigned IntNo = Op.getConstantOperandVal(1);
4076   switch (IntNo) {
4077   default:
4078     break;
4079   case Intrinsic::riscv_masked_strided_store: {
4080     SDLoc DL(Op);
4081     MVT XLenVT = Subtarget.getXLenVT();
4082 
4083     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4084     // the selection of the masked intrinsics doesn't do this for us.
4085     SDValue Mask = Op.getOperand(5);
4086     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4087 
4088     SDValue Val = Op.getOperand(2);
4089     MVT VT = Val.getSimpleValueType();
4090     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4091 
4092     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4093     if (!IsUnmasked) {
4094       MVT MaskVT =
4095           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4096       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4097     }
4098 
4099     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4100 
4101     SDValue IntID = DAG.getTargetConstant(
4102         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4103         XLenVT);
4104 
4105     auto *Store = cast<MemIntrinsicSDNode>(Op);
4106     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4107     Ops.push_back(Val);
4108     Ops.push_back(Op.getOperand(3)); // Ptr
4109     Ops.push_back(Op.getOperand(4)); // Stride
4110     if (!IsUnmasked)
4111       Ops.push_back(Mask);
4112     Ops.push_back(VL);
4113 
4114     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4115                                    Ops, Store->getMemoryVT(),
4116                                    Store->getMemOperand());
4117   }
4118   }
4119 
4120   return SDValue();
4121 }
4122 
4123 static MVT getLMUL1VT(MVT VT) {
4124   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4125          "Unexpected vector MVT");
4126   return MVT::getScalableVectorVT(
4127       VT.getVectorElementType(),
4128       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4129 }
4130 
4131 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4132   switch (ISDOpcode) {
4133   default:
4134     llvm_unreachable("Unhandled reduction");
4135   case ISD::VECREDUCE_ADD:
4136     return RISCVISD::VECREDUCE_ADD_VL;
4137   case ISD::VECREDUCE_UMAX:
4138     return RISCVISD::VECREDUCE_UMAX_VL;
4139   case ISD::VECREDUCE_SMAX:
4140     return RISCVISD::VECREDUCE_SMAX_VL;
4141   case ISD::VECREDUCE_UMIN:
4142     return RISCVISD::VECREDUCE_UMIN_VL;
4143   case ISD::VECREDUCE_SMIN:
4144     return RISCVISD::VECREDUCE_SMIN_VL;
4145   case ISD::VECREDUCE_AND:
4146     return RISCVISD::VECREDUCE_AND_VL;
4147   case ISD::VECREDUCE_OR:
4148     return RISCVISD::VECREDUCE_OR_VL;
4149   case ISD::VECREDUCE_XOR:
4150     return RISCVISD::VECREDUCE_XOR_VL;
4151   }
4152 }
4153 
4154 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4155                                                          SelectionDAG &DAG,
4156                                                          bool IsVP) const {
4157   SDLoc DL(Op);
4158   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4159   MVT VecVT = Vec.getSimpleValueType();
4160   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4161           Op.getOpcode() == ISD::VECREDUCE_OR ||
4162           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4163           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4164           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4165           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4166          "Unexpected reduction lowering");
4167 
4168   MVT XLenVT = Subtarget.getXLenVT();
4169   assert(Op.getValueType() == XLenVT &&
4170          "Expected reduction output to be legalized to XLenVT");
4171 
4172   MVT ContainerVT = VecVT;
4173   if (VecVT.isFixedLengthVector()) {
4174     ContainerVT = getContainerForFixedLengthVector(VecVT);
4175     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4176   }
4177 
4178   SDValue Mask, VL;
4179   if (IsVP) {
4180     Mask = Op.getOperand(2);
4181     VL = Op.getOperand(3);
4182   } else {
4183     std::tie(Mask, VL) =
4184         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4185   }
4186 
4187   unsigned BaseOpc;
4188   ISD::CondCode CC;
4189   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4190 
4191   switch (Op.getOpcode()) {
4192   default:
4193     llvm_unreachable("Unhandled reduction");
4194   case ISD::VECREDUCE_AND:
4195   case ISD::VP_REDUCE_AND: {
4196     // vcpop ~x == 0
4197     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4198     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4199     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4200     CC = ISD::SETEQ;
4201     BaseOpc = ISD::AND;
4202     break;
4203   }
4204   case ISD::VECREDUCE_OR:
4205   case ISD::VP_REDUCE_OR:
4206     // vcpop x != 0
4207     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4208     CC = ISD::SETNE;
4209     BaseOpc = ISD::OR;
4210     break;
4211   case ISD::VECREDUCE_XOR:
4212   case ISD::VP_REDUCE_XOR: {
4213     // ((vcpop x) & 1) != 0
4214     SDValue One = DAG.getConstant(1, DL, XLenVT);
4215     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4216     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4217     CC = ISD::SETNE;
4218     BaseOpc = ISD::XOR;
4219     break;
4220   }
4221   }
4222 
4223   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4224 
4225   if (!IsVP)
4226     return SetCC;
4227 
4228   // Now include the start value in the operation.
4229   // Note that we must return the start value when no elements are operated
4230   // upon. The vcpop instructions we've emitted in each case above will return
4231   // 0 for an inactive vector, and so we've already received the neutral value:
4232   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4233   // can simply include the start value.
4234   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4235 }
4236 
4237 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4238                                             SelectionDAG &DAG) const {
4239   SDLoc DL(Op);
4240   SDValue Vec = Op.getOperand(0);
4241   EVT VecEVT = Vec.getValueType();
4242 
4243   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4244 
4245   // Due to ordering in legalize types we may have a vector type that needs to
4246   // be split. Do that manually so we can get down to a legal type.
4247   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4248          TargetLowering::TypeSplitVector) {
4249     SDValue Lo, Hi;
4250     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4251     VecEVT = Lo.getValueType();
4252     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4253   }
4254 
4255   // TODO: The type may need to be widened rather than split. Or widened before
4256   // it can be split.
4257   if (!isTypeLegal(VecEVT))
4258     return SDValue();
4259 
4260   MVT VecVT = VecEVT.getSimpleVT();
4261   MVT VecEltVT = VecVT.getVectorElementType();
4262   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4263 
4264   MVT ContainerVT = VecVT;
4265   if (VecVT.isFixedLengthVector()) {
4266     ContainerVT = getContainerForFixedLengthVector(VecVT);
4267     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4268   }
4269 
4270   MVT M1VT = getLMUL1VT(ContainerVT);
4271 
4272   SDValue Mask, VL;
4273   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4274 
4275   // FIXME: This is a VLMAX splat which might be too large and can prevent
4276   // vsetvli removal.
4277   SDValue NeutralElem =
4278       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4279   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
4280   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4281                                   IdentitySplat, Mask, VL);
4282   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4283                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4284   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4285 }
4286 
4287 // Given a reduction op, this function returns the matching reduction opcode,
4288 // the vector SDValue and the scalar SDValue required to lower this to a
4289 // RISCVISD node.
4290 static std::tuple<unsigned, SDValue, SDValue>
4291 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4292   SDLoc DL(Op);
4293   auto Flags = Op->getFlags();
4294   unsigned Opcode = Op.getOpcode();
4295   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4296   switch (Opcode) {
4297   default:
4298     llvm_unreachable("Unhandled reduction");
4299   case ISD::VECREDUCE_FADD:
4300     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4301                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4302   case ISD::VECREDUCE_SEQ_FADD:
4303     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4304                            Op.getOperand(0));
4305   case ISD::VECREDUCE_FMIN:
4306     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4307                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4308   case ISD::VECREDUCE_FMAX:
4309     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4310                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4311   }
4312 }
4313 
4314 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4315                                               SelectionDAG &DAG) const {
4316   SDLoc DL(Op);
4317   MVT VecEltVT = Op.getSimpleValueType();
4318 
4319   unsigned RVVOpcode;
4320   SDValue VectorVal, ScalarVal;
4321   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4322       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4323   MVT VecVT = VectorVal.getSimpleValueType();
4324 
4325   MVT ContainerVT = VecVT;
4326   if (VecVT.isFixedLengthVector()) {
4327     ContainerVT = getContainerForFixedLengthVector(VecVT);
4328     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4329   }
4330 
4331   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4332 
4333   SDValue Mask, VL;
4334   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4335 
4336   // FIXME: This is a VLMAX splat which might be too large and can prevent
4337   // vsetvli removal.
4338   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
4339   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4340                                   VectorVal, ScalarSplat, Mask, VL);
4341   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4342                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4343 }
4344 
4345 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4346   switch (ISDOpcode) {
4347   default:
4348     llvm_unreachable("Unhandled reduction");
4349   case ISD::VP_REDUCE_ADD:
4350     return RISCVISD::VECREDUCE_ADD_VL;
4351   case ISD::VP_REDUCE_UMAX:
4352     return RISCVISD::VECREDUCE_UMAX_VL;
4353   case ISD::VP_REDUCE_SMAX:
4354     return RISCVISD::VECREDUCE_SMAX_VL;
4355   case ISD::VP_REDUCE_UMIN:
4356     return RISCVISD::VECREDUCE_UMIN_VL;
4357   case ISD::VP_REDUCE_SMIN:
4358     return RISCVISD::VECREDUCE_SMIN_VL;
4359   case ISD::VP_REDUCE_AND:
4360     return RISCVISD::VECREDUCE_AND_VL;
4361   case ISD::VP_REDUCE_OR:
4362     return RISCVISD::VECREDUCE_OR_VL;
4363   case ISD::VP_REDUCE_XOR:
4364     return RISCVISD::VECREDUCE_XOR_VL;
4365   case ISD::VP_REDUCE_FADD:
4366     return RISCVISD::VECREDUCE_FADD_VL;
4367   case ISD::VP_REDUCE_SEQ_FADD:
4368     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4369   case ISD::VP_REDUCE_FMAX:
4370     return RISCVISD::VECREDUCE_FMAX_VL;
4371   case ISD::VP_REDUCE_FMIN:
4372     return RISCVISD::VECREDUCE_FMIN_VL;
4373   }
4374 }
4375 
4376 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4377                                            SelectionDAG &DAG) const {
4378   SDLoc DL(Op);
4379   SDValue Vec = Op.getOperand(1);
4380   EVT VecEVT = Vec.getValueType();
4381 
4382   // TODO: The type may need to be widened rather than split. Or widened before
4383   // it can be split.
4384   if (!isTypeLegal(VecEVT))
4385     return SDValue();
4386 
4387   MVT VecVT = VecEVT.getSimpleVT();
4388   MVT VecEltVT = VecVT.getVectorElementType();
4389   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4390 
4391   MVT ContainerVT = VecVT;
4392   if (VecVT.isFixedLengthVector()) {
4393     ContainerVT = getContainerForFixedLengthVector(VecVT);
4394     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4395   }
4396 
4397   SDValue VL = Op.getOperand(3);
4398   SDValue Mask = Op.getOperand(2);
4399 
4400   MVT M1VT = getLMUL1VT(ContainerVT);
4401   MVT XLenVT = Subtarget.getXLenVT();
4402   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4403 
4404   // FIXME: This is a VLMAX splat which might be too large and can prevent
4405   // vsetvli removal.
4406   SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0));
4407   SDValue Reduction =
4408       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4409   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4410                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4411   if (!VecVT.isInteger())
4412     return Elt0;
4413   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4414 }
4415 
4416 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4417                                                    SelectionDAG &DAG) const {
4418   SDValue Vec = Op.getOperand(0);
4419   SDValue SubVec = Op.getOperand(1);
4420   MVT VecVT = Vec.getSimpleValueType();
4421   MVT SubVecVT = SubVec.getSimpleValueType();
4422 
4423   SDLoc DL(Op);
4424   MVT XLenVT = Subtarget.getXLenVT();
4425   unsigned OrigIdx = Op.getConstantOperandVal(2);
4426   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4427 
4428   // We don't have the ability to slide mask vectors up indexed by their i1
4429   // elements; the smallest we can do is i8. Often we are able to bitcast to
4430   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4431   // into a scalable one, we might not necessarily have enough scalable
4432   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4433   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4434       (OrigIdx != 0 || !Vec.isUndef())) {
4435     if (VecVT.getVectorMinNumElements() >= 8 &&
4436         SubVecVT.getVectorMinNumElements() >= 8) {
4437       assert(OrigIdx % 8 == 0 && "Invalid index");
4438       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4439              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4440              "Unexpected mask vector lowering");
4441       OrigIdx /= 8;
4442       SubVecVT =
4443           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4444                            SubVecVT.isScalableVector());
4445       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4446                                VecVT.isScalableVector());
4447       Vec = DAG.getBitcast(VecVT, Vec);
4448       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4449     } else {
4450       // We can't slide this mask vector up indexed by its i1 elements.
4451       // This poses a problem when we wish to insert a scalable vector which
4452       // can't be re-expressed as a larger type. Just choose the slow path and
4453       // extend to a larger type, then truncate back down.
4454       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4455       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4456       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4457       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4458       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4459                         Op.getOperand(2));
4460       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4461       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4462     }
4463   }
4464 
4465   // If the subvector vector is a fixed-length type, we cannot use subregister
4466   // manipulation to simplify the codegen; we don't know which register of a
4467   // LMUL group contains the specific subvector as we only know the minimum
4468   // register size. Therefore we must slide the vector group up the full
4469   // amount.
4470   if (SubVecVT.isFixedLengthVector()) {
4471     if (OrigIdx == 0 && Vec.isUndef())
4472       return Op;
4473     MVT ContainerVT = VecVT;
4474     if (VecVT.isFixedLengthVector()) {
4475       ContainerVT = getContainerForFixedLengthVector(VecVT);
4476       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4477     }
4478     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4479                          DAG.getUNDEF(ContainerVT), SubVec,
4480                          DAG.getConstant(0, DL, XLenVT));
4481     SDValue Mask =
4482         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4483     // Set the vector length to only the number of elements we care about. Note
4484     // that for slideup this includes the offset.
4485     SDValue VL =
4486         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4487     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4488     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4489                                   SubVec, SlideupAmt, Mask, VL);
4490     if (VecVT.isFixedLengthVector())
4491       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4492     return DAG.getBitcast(Op.getValueType(), Slideup);
4493   }
4494 
4495   unsigned SubRegIdx, RemIdx;
4496   std::tie(SubRegIdx, RemIdx) =
4497       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4498           VecVT, SubVecVT, OrigIdx, TRI);
4499 
4500   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4501   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4502                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4503                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4504 
4505   // 1. If the Idx has been completely eliminated and this subvector's size is
4506   // a vector register or a multiple thereof, or the surrounding elements are
4507   // undef, then this is a subvector insert which naturally aligns to a vector
4508   // register. These can easily be handled using subregister manipulation.
4509   // 2. If the subvector is smaller than a vector register, then the insertion
4510   // must preserve the undisturbed elements of the register. We do this by
4511   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4512   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4513   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4514   // LMUL=1 type back into the larger vector (resolving to another subregister
4515   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4516   // to avoid allocating a large register group to hold our subvector.
4517   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4518     return Op;
4519 
4520   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4521   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4522   // (in our case undisturbed). This means we can set up a subvector insertion
4523   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4524   // size of the subvector.
4525   MVT InterSubVT = VecVT;
4526   SDValue AlignedExtract = Vec;
4527   unsigned AlignedIdx = OrigIdx - RemIdx;
4528   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4529     InterSubVT = getLMUL1VT(VecVT);
4530     // Extract a subvector equal to the nearest full vector register type. This
4531     // should resolve to a EXTRACT_SUBREG instruction.
4532     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4533                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4534   }
4535 
4536   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4537   // For scalable vectors this must be further multiplied by vscale.
4538   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4539 
4540   SDValue Mask, VL;
4541   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4542 
4543   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4544   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4545   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4546   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4547 
4548   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4549                        DAG.getUNDEF(InterSubVT), SubVec,
4550                        DAG.getConstant(0, DL, XLenVT));
4551 
4552   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4553                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4554 
4555   // If required, insert this subvector back into the correct vector register.
4556   // This should resolve to an INSERT_SUBREG instruction.
4557   if (VecVT.bitsGT(InterSubVT))
4558     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4559                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4560 
4561   // We might have bitcast from a mask type: cast back to the original type if
4562   // required.
4563   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4564 }
4565 
4566 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4567                                                     SelectionDAG &DAG) const {
4568   SDValue Vec = Op.getOperand(0);
4569   MVT SubVecVT = Op.getSimpleValueType();
4570   MVT VecVT = Vec.getSimpleValueType();
4571 
4572   SDLoc DL(Op);
4573   MVT XLenVT = Subtarget.getXLenVT();
4574   unsigned OrigIdx = Op.getConstantOperandVal(1);
4575   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4576 
4577   // We don't have the ability to slide mask vectors down indexed by their i1
4578   // elements; the smallest we can do is i8. Often we are able to bitcast to
4579   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4580   // from a scalable one, we might not necessarily have enough scalable
4581   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4582   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4583     if (VecVT.getVectorMinNumElements() >= 8 &&
4584         SubVecVT.getVectorMinNumElements() >= 8) {
4585       assert(OrigIdx % 8 == 0 && "Invalid index");
4586       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4587              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4588              "Unexpected mask vector lowering");
4589       OrigIdx /= 8;
4590       SubVecVT =
4591           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4592                            SubVecVT.isScalableVector());
4593       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4594                                VecVT.isScalableVector());
4595       Vec = DAG.getBitcast(VecVT, Vec);
4596     } else {
4597       // We can't slide this mask vector down, indexed by its i1 elements.
4598       // This poses a problem when we wish to extract a scalable vector which
4599       // can't be re-expressed as a larger type. Just choose the slow path and
4600       // extend to a larger type, then truncate back down.
4601       // TODO: We could probably improve this when extracting certain fixed
4602       // from fixed, where we can extract as i8 and shift the correct element
4603       // right to reach the desired subvector?
4604       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4605       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4606       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4607       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4608                         Op.getOperand(1));
4609       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4610       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4611     }
4612   }
4613 
4614   // If the subvector vector is a fixed-length type, we cannot use subregister
4615   // manipulation to simplify the codegen; we don't know which register of a
4616   // LMUL group contains the specific subvector as we only know the minimum
4617   // register size. Therefore we must slide the vector group down the full
4618   // amount.
4619   if (SubVecVT.isFixedLengthVector()) {
4620     // With an index of 0 this is a cast-like subvector, which can be performed
4621     // with subregister operations.
4622     if (OrigIdx == 0)
4623       return Op;
4624     MVT ContainerVT = VecVT;
4625     if (VecVT.isFixedLengthVector()) {
4626       ContainerVT = getContainerForFixedLengthVector(VecVT);
4627       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4628     }
4629     SDValue Mask =
4630         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4631     // Set the vector length to only the number of elements we care about. This
4632     // avoids sliding down elements we're going to discard straight away.
4633     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4634     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4635     SDValue Slidedown =
4636         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4637                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4638     // Now we can use a cast-like subvector extract to get the result.
4639     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4640                             DAG.getConstant(0, DL, XLenVT));
4641     return DAG.getBitcast(Op.getValueType(), Slidedown);
4642   }
4643 
4644   unsigned SubRegIdx, RemIdx;
4645   std::tie(SubRegIdx, RemIdx) =
4646       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4647           VecVT, SubVecVT, OrigIdx, TRI);
4648 
4649   // If the Idx has been completely eliminated then this is a subvector extract
4650   // which naturally aligns to a vector register. These can easily be handled
4651   // using subregister manipulation.
4652   if (RemIdx == 0)
4653     return Op;
4654 
4655   // Else we must shift our vector register directly to extract the subvector.
4656   // Do this using VSLIDEDOWN.
4657 
4658   // If the vector type is an LMUL-group type, extract a subvector equal to the
4659   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4660   // instruction.
4661   MVT InterSubVT = VecVT;
4662   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4663     InterSubVT = getLMUL1VT(VecVT);
4664     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4665                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4666   }
4667 
4668   // Slide this vector register down by the desired number of elements in order
4669   // to place the desired subvector starting at element 0.
4670   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4671   // For scalable vectors this must be further multiplied by vscale.
4672   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4673 
4674   SDValue Mask, VL;
4675   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4676   SDValue Slidedown =
4677       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4678                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4679 
4680   // Now the vector is in the right position, extract our final subvector. This
4681   // should resolve to a COPY.
4682   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4683                           DAG.getConstant(0, DL, XLenVT));
4684 
4685   // We might have bitcast from a mask type: cast back to the original type if
4686   // required.
4687   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4688 }
4689 
4690 // Lower step_vector to the vid instruction. Any non-identity step value must
4691 // be accounted for my manual expansion.
4692 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4693                                               SelectionDAG &DAG) const {
4694   SDLoc DL(Op);
4695   MVT VT = Op.getSimpleValueType();
4696   MVT XLenVT = Subtarget.getXLenVT();
4697   SDValue Mask, VL;
4698   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4699   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4700   uint64_t StepValImm = Op.getConstantOperandVal(0);
4701   if (StepValImm != 1) {
4702     if (isPowerOf2_64(StepValImm)) {
4703       SDValue StepVal =
4704           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4705                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4706       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4707     } else {
4708       SDValue StepVal = lowerScalarSplat(
4709           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4710           DL, DAG, Subtarget);
4711       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4712     }
4713   }
4714   return StepVec;
4715 }
4716 
4717 // Implement vector_reverse using vrgather.vv with indices determined by
4718 // subtracting the id of each element from (VLMAX-1). This will convert
4719 // the indices like so:
4720 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4721 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4722 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4723                                                  SelectionDAG &DAG) const {
4724   SDLoc DL(Op);
4725   MVT VecVT = Op.getSimpleValueType();
4726   unsigned EltSize = VecVT.getScalarSizeInBits();
4727   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4728 
4729   unsigned MaxVLMAX = 0;
4730   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4731   if (VectorBitsMax != 0)
4732     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4733 
4734   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4735   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4736 
4737   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4738   // to use vrgatherei16.vv.
4739   // TODO: It's also possible to use vrgatherei16.vv for other types to
4740   // decrease register width for the index calculation.
4741   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4742     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4743     // Reverse each half, then reassemble them in reverse order.
4744     // NOTE: It's also possible that after splitting that VLMAX no longer
4745     // requires vrgatherei16.vv.
4746     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4747       SDValue Lo, Hi;
4748       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4749       EVT LoVT, HiVT;
4750       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4751       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4752       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4753       // Reassemble the low and high pieces reversed.
4754       // FIXME: This is a CONCAT_VECTORS.
4755       SDValue Res =
4756           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4757                       DAG.getIntPtrConstant(0, DL));
4758       return DAG.getNode(
4759           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4760           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4761     }
4762 
4763     // Just promote the int type to i16 which will double the LMUL.
4764     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4765     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4766   }
4767 
4768   MVT XLenVT = Subtarget.getXLenVT();
4769   SDValue Mask, VL;
4770   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4771 
4772   // Calculate VLMAX-1 for the desired SEW.
4773   unsigned MinElts = VecVT.getVectorMinNumElements();
4774   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4775                               DAG.getConstant(MinElts, DL, XLenVT));
4776   SDValue VLMinus1 =
4777       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4778 
4779   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4780   bool IsRV32E64 =
4781       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4782   SDValue SplatVL;
4783   if (!IsRV32E64)
4784     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4785   else
4786     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4787 
4788   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4789   SDValue Indices =
4790       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4791 
4792   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4793 }
4794 
4795 SDValue
4796 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
4797                                                      SelectionDAG &DAG) const {
4798   SDLoc DL(Op);
4799   auto *Load = cast<LoadSDNode>(Op);
4800 
4801   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4802                                         Load->getMemoryVT(),
4803                                         *Load->getMemOperand()) &&
4804          "Expecting a correctly-aligned load");
4805 
4806   MVT VT = Op.getSimpleValueType();
4807   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4808 
4809   SDValue VL =
4810       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4811 
4812   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4813   SDValue NewLoad = DAG.getMemIntrinsicNode(
4814       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
4815       Load->getMemoryVT(), Load->getMemOperand());
4816 
4817   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
4818   return DAG.getMergeValues({Result, Load->getChain()}, DL);
4819 }
4820 
4821 SDValue
4822 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
4823                                                       SelectionDAG &DAG) const {
4824   SDLoc DL(Op);
4825   auto *Store = cast<StoreSDNode>(Op);
4826 
4827   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4828                                         Store->getMemoryVT(),
4829                                         *Store->getMemOperand()) &&
4830          "Expecting a correctly-aligned store");
4831 
4832   SDValue StoreVal = Store->getValue();
4833   MVT VT = StoreVal.getSimpleValueType();
4834 
4835   // If the size less than a byte, we need to pad with zeros to make a byte.
4836   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
4837     VT = MVT::v8i1;
4838     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
4839                            DAG.getConstant(0, DL, VT), StoreVal,
4840                            DAG.getIntPtrConstant(0, DL));
4841   }
4842 
4843   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4844 
4845   SDValue VL =
4846       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4847 
4848   SDValue NewValue =
4849       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
4850   return DAG.getMemIntrinsicNode(
4851       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
4852       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
4853       Store->getMemoryVT(), Store->getMemOperand());
4854 }
4855 
4856 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
4857                                              SelectionDAG &DAG) const {
4858   SDLoc DL(Op);
4859   MVT VT = Op.getSimpleValueType();
4860 
4861   const auto *MemSD = cast<MemSDNode>(Op);
4862   EVT MemVT = MemSD->getMemoryVT();
4863   MachineMemOperand *MMO = MemSD->getMemOperand();
4864   SDValue Chain = MemSD->getChain();
4865   SDValue BasePtr = MemSD->getBasePtr();
4866 
4867   SDValue Mask, PassThru, VL;
4868   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
4869     Mask = VPLoad->getMask();
4870     PassThru = DAG.getUNDEF(VT);
4871     VL = VPLoad->getVectorLength();
4872   } else {
4873     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
4874     Mask = MLoad->getMask();
4875     PassThru = MLoad->getPassThru();
4876   }
4877 
4878   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4879 
4880   MVT XLenVT = Subtarget.getXLenVT();
4881 
4882   MVT ContainerVT = VT;
4883   if (VT.isFixedLengthVector()) {
4884     ContainerVT = getContainerForFixedLengthVector(VT);
4885     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4886     if (!IsUnmasked) {
4887       MVT MaskVT =
4888           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4889       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4890     }
4891   }
4892 
4893   if (!VL)
4894     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4895 
4896   unsigned IntID =
4897       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
4898   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4899   if (!IsUnmasked)
4900     Ops.push_back(PassThru);
4901   Ops.push_back(BasePtr);
4902   if (!IsUnmasked)
4903     Ops.push_back(Mask);
4904   Ops.push_back(VL);
4905   if (!IsUnmasked)
4906     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
4907 
4908   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4909 
4910   SDValue Result =
4911       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
4912   Chain = Result.getValue(1);
4913 
4914   if (VT.isFixedLengthVector())
4915     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4916 
4917   return DAG.getMergeValues({Result, Chain}, DL);
4918 }
4919 
4920 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
4921                                               SelectionDAG &DAG) const {
4922   SDLoc DL(Op);
4923 
4924   const auto *MemSD = cast<MemSDNode>(Op);
4925   EVT MemVT = MemSD->getMemoryVT();
4926   MachineMemOperand *MMO = MemSD->getMemOperand();
4927   SDValue Chain = MemSD->getChain();
4928   SDValue BasePtr = MemSD->getBasePtr();
4929   SDValue Val, Mask, VL;
4930 
4931   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
4932     Val = VPStore->getValue();
4933     Mask = VPStore->getMask();
4934     VL = VPStore->getVectorLength();
4935   } else {
4936     const auto *MStore = cast<MaskedStoreSDNode>(Op);
4937     Val = MStore->getValue();
4938     Mask = MStore->getMask();
4939   }
4940 
4941   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4942 
4943   MVT VT = Val.getSimpleValueType();
4944   MVT XLenVT = Subtarget.getXLenVT();
4945 
4946   MVT ContainerVT = VT;
4947   if (VT.isFixedLengthVector()) {
4948     ContainerVT = getContainerForFixedLengthVector(VT);
4949 
4950     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4951     if (!IsUnmasked) {
4952       MVT MaskVT =
4953           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4954       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4955     }
4956   }
4957 
4958   if (!VL)
4959     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4960 
4961   unsigned IntID =
4962       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
4963   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4964   Ops.push_back(Val);
4965   Ops.push_back(BasePtr);
4966   if (!IsUnmasked)
4967     Ops.push_back(Mask);
4968   Ops.push_back(VL);
4969 
4970   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
4971                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
4972 }
4973 
4974 SDValue
4975 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4976                                                       SelectionDAG &DAG) const {
4977   MVT InVT = Op.getOperand(0).getSimpleValueType();
4978   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
4979 
4980   MVT VT = Op.getSimpleValueType();
4981 
4982   SDValue Op1 =
4983       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4984   SDValue Op2 =
4985       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4986 
4987   SDLoc DL(Op);
4988   SDValue VL =
4989       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4990 
4991   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4992   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4993 
4994   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
4995                             Op.getOperand(2), Mask, VL);
4996 
4997   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
4998 }
4999 
5000 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5001     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5002   MVT VT = Op.getSimpleValueType();
5003 
5004   if (VT.getVectorElementType() == MVT::i1)
5005     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5006 
5007   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5008 }
5009 
5010 SDValue
5011 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5012                                                       SelectionDAG &DAG) const {
5013   unsigned Opc;
5014   switch (Op.getOpcode()) {
5015   default: llvm_unreachable("Unexpected opcode!");
5016   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5017   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5018   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5019   }
5020 
5021   return lowerToScalableOp(Op, DAG, Opc);
5022 }
5023 
5024 // Lower vector ABS to smax(X, sub(0, X)).
5025 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5026   SDLoc DL(Op);
5027   MVT VT = Op.getSimpleValueType();
5028   SDValue X = Op.getOperand(0);
5029 
5030   assert(VT.isFixedLengthVector() && "Unexpected type");
5031 
5032   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5033   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5034 
5035   SDValue Mask, VL;
5036   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5037 
5038   SDValue SplatZero =
5039       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5040                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5041   SDValue NegX =
5042       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5043   SDValue Max =
5044       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5045 
5046   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5047 }
5048 
5049 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5050     SDValue Op, SelectionDAG &DAG) const {
5051   SDLoc DL(Op);
5052   MVT VT = Op.getSimpleValueType();
5053   SDValue Mag = Op.getOperand(0);
5054   SDValue Sign = Op.getOperand(1);
5055   assert(Mag.getValueType() == Sign.getValueType() &&
5056          "Can only handle COPYSIGN with matching types.");
5057 
5058   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5059   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5060   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5061 
5062   SDValue Mask, VL;
5063   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5064 
5065   SDValue CopySign =
5066       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5067 
5068   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5069 }
5070 
5071 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5072     SDValue Op, SelectionDAG &DAG) const {
5073   MVT VT = Op.getSimpleValueType();
5074   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5075 
5076   MVT I1ContainerVT =
5077       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5078 
5079   SDValue CC =
5080       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5081   SDValue Op1 =
5082       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5083   SDValue Op2 =
5084       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5085 
5086   SDLoc DL(Op);
5087   SDValue Mask, VL;
5088   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5089 
5090   SDValue Select =
5091       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5092 
5093   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5094 }
5095 
5096 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5097                                                unsigned NewOpc,
5098                                                bool HasMask) const {
5099   MVT VT = Op.getSimpleValueType();
5100   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5101 
5102   // Create list of operands by converting existing ones to scalable types.
5103   SmallVector<SDValue, 6> Ops;
5104   for (const SDValue &V : Op->op_values()) {
5105     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5106 
5107     // Pass through non-vector operands.
5108     if (!V.getValueType().isVector()) {
5109       Ops.push_back(V);
5110       continue;
5111     }
5112 
5113     // "cast" fixed length vector to a scalable vector.
5114     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5115            "Only fixed length vectors are supported!");
5116     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5117   }
5118 
5119   SDLoc DL(Op);
5120   SDValue Mask, VL;
5121   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5122   if (HasMask)
5123     Ops.push_back(Mask);
5124   Ops.push_back(VL);
5125 
5126   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5127   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5128 }
5129 
5130 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5131 // * Operands of each node are assumed to be in the same order.
5132 // * The EVL operand is promoted from i32 to i64 on RV64.
5133 // * Fixed-length vectors are converted to their scalable-vector container
5134 //   types.
5135 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5136                                        unsigned RISCVISDOpc) const {
5137   SDLoc DL(Op);
5138   MVT VT = Op.getSimpleValueType();
5139   SmallVector<SDValue, 4> Ops;
5140 
5141   for (const auto &OpIdx : enumerate(Op->ops())) {
5142     SDValue V = OpIdx.value();
5143     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5144     // Pass through operands which aren't fixed-length vectors.
5145     if (!V.getValueType().isFixedLengthVector()) {
5146       Ops.push_back(V);
5147       continue;
5148     }
5149     // "cast" fixed length vector to a scalable vector.
5150     MVT OpVT = V.getSimpleValueType();
5151     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5152     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5153            "Only fixed length vectors are supported!");
5154     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5155   }
5156 
5157   if (!VT.isFixedLengthVector())
5158     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5159 
5160   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5161 
5162   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5163 
5164   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5165 }
5166 
5167 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5168 // matched to a RVV indexed load. The RVV indexed load instructions only
5169 // support the "unsigned unscaled" addressing mode; indices are implicitly
5170 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5171 // signed or scaled indexing is extended to the XLEN value type and scaled
5172 // accordingly.
5173 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5174                                                SelectionDAG &DAG) const {
5175   SDLoc DL(Op);
5176   MVT VT = Op.getSimpleValueType();
5177 
5178   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5179   EVT MemVT = MemSD->getMemoryVT();
5180   MachineMemOperand *MMO = MemSD->getMemOperand();
5181   SDValue Chain = MemSD->getChain();
5182   SDValue BasePtr = MemSD->getBasePtr();
5183 
5184   ISD::LoadExtType LoadExtType;
5185   SDValue Index, Mask, PassThru, VL;
5186 
5187   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5188     Index = VPGN->getIndex();
5189     Mask = VPGN->getMask();
5190     PassThru = DAG.getUNDEF(VT);
5191     VL = VPGN->getVectorLength();
5192     // VP doesn't support extending loads.
5193     LoadExtType = ISD::NON_EXTLOAD;
5194   } else {
5195     // Else it must be a MGATHER.
5196     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5197     Index = MGN->getIndex();
5198     Mask = MGN->getMask();
5199     PassThru = MGN->getPassThru();
5200     LoadExtType = MGN->getExtensionType();
5201   }
5202 
5203   MVT IndexVT = Index.getSimpleValueType();
5204   MVT XLenVT = Subtarget.getXLenVT();
5205 
5206   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5207          "Unexpected VTs!");
5208   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5209   // Targets have to explicitly opt-in for extending vector loads.
5210   assert(LoadExtType == ISD::NON_EXTLOAD &&
5211          "Unexpected extending MGATHER/VP_GATHER");
5212   (void)LoadExtType;
5213 
5214   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5215   // the selection of the masked intrinsics doesn't do this for us.
5216   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5217 
5218   MVT ContainerVT = VT;
5219   if (VT.isFixedLengthVector()) {
5220     // We need to use the larger of the result and index type to determine the
5221     // scalable type to use so we don't increase LMUL for any operand/result.
5222     if (VT.bitsGE(IndexVT)) {
5223       ContainerVT = getContainerForFixedLengthVector(VT);
5224       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5225                                  ContainerVT.getVectorElementCount());
5226     } else {
5227       IndexVT = getContainerForFixedLengthVector(IndexVT);
5228       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5229                                      IndexVT.getVectorElementCount());
5230     }
5231 
5232     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5233 
5234     if (!IsUnmasked) {
5235       MVT MaskVT =
5236           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5237       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5238       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5239     }
5240   }
5241 
5242   if (!VL)
5243     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5244 
5245   unsigned IntID =
5246       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5247   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5248   if (!IsUnmasked)
5249     Ops.push_back(PassThru);
5250   Ops.push_back(BasePtr);
5251   Ops.push_back(Index);
5252   if (!IsUnmasked)
5253     Ops.push_back(Mask);
5254   Ops.push_back(VL);
5255   if (!IsUnmasked)
5256     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5257 
5258   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5259   SDValue Result =
5260       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5261   Chain = Result.getValue(1);
5262 
5263   if (VT.isFixedLengthVector())
5264     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5265 
5266   return DAG.getMergeValues({Result, Chain}, DL);
5267 }
5268 
5269 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5270 // matched to a RVV indexed store. The RVV indexed store instructions only
5271 // support the "unsigned unscaled" addressing mode; indices are implicitly
5272 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5273 // signed or scaled indexing is extended to the XLEN value type and scaled
5274 // accordingly.
5275 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5276                                                 SelectionDAG &DAG) const {
5277   SDLoc DL(Op);
5278   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5279   EVT MemVT = MemSD->getMemoryVT();
5280   MachineMemOperand *MMO = MemSD->getMemOperand();
5281   SDValue Chain = MemSD->getChain();
5282   SDValue BasePtr = MemSD->getBasePtr();
5283 
5284   bool IsTruncatingStore = false;
5285   SDValue Index, Mask, Val, VL;
5286 
5287   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5288     Index = VPSN->getIndex();
5289     Mask = VPSN->getMask();
5290     Val = VPSN->getValue();
5291     VL = VPSN->getVectorLength();
5292     // VP doesn't support truncating stores.
5293     IsTruncatingStore = false;
5294   } else {
5295     // Else it must be a MSCATTER.
5296     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5297     Index = MSN->getIndex();
5298     Mask = MSN->getMask();
5299     Val = MSN->getValue();
5300     IsTruncatingStore = MSN->isTruncatingStore();
5301   }
5302 
5303   MVT VT = Val.getSimpleValueType();
5304   MVT IndexVT = Index.getSimpleValueType();
5305   MVT XLenVT = Subtarget.getXLenVT();
5306 
5307   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5308          "Unexpected VTs!");
5309   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5310   // Targets have to explicitly opt-in for extending vector loads and
5311   // truncating vector stores.
5312   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5313   (void)IsTruncatingStore;
5314 
5315   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5316   // the selection of the masked intrinsics doesn't do this for us.
5317   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5318 
5319   MVT ContainerVT = VT;
5320   if (VT.isFixedLengthVector()) {
5321     // We need to use the larger of the value and index type to determine the
5322     // scalable type to use so we don't increase LMUL for any operand/result.
5323     if (VT.bitsGE(IndexVT)) {
5324       ContainerVT = getContainerForFixedLengthVector(VT);
5325       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5326                                  ContainerVT.getVectorElementCount());
5327     } else {
5328       IndexVT = getContainerForFixedLengthVector(IndexVT);
5329       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5330                                      IndexVT.getVectorElementCount());
5331     }
5332 
5333     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5334     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5335 
5336     if (!IsUnmasked) {
5337       MVT MaskVT =
5338           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5339       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5340     }
5341   }
5342 
5343   if (!VL)
5344     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5345 
5346   unsigned IntID =
5347       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5348   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5349   Ops.push_back(Val);
5350   Ops.push_back(BasePtr);
5351   Ops.push_back(Index);
5352   if (!IsUnmasked)
5353     Ops.push_back(Mask);
5354   Ops.push_back(VL);
5355 
5356   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5357                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5358 }
5359 
5360 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5361                                                SelectionDAG &DAG) const {
5362   const MVT XLenVT = Subtarget.getXLenVT();
5363   SDLoc DL(Op);
5364   SDValue Chain = Op->getOperand(0);
5365   SDValue SysRegNo = DAG.getTargetConstant(
5366       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5367   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5368   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5369 
5370   // Encoding used for rounding mode in RISCV differs from that used in
5371   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5372   // table, which consists of a sequence of 4-bit fields, each representing
5373   // corresponding FLT_ROUNDS mode.
5374   static const int Table =
5375       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5376       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5377       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5378       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5379       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5380 
5381   SDValue Shift =
5382       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5383   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5384                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5385   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5386                                DAG.getConstant(7, DL, XLenVT));
5387 
5388   return DAG.getMergeValues({Masked, Chain}, DL);
5389 }
5390 
5391 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5392                                                SelectionDAG &DAG) const {
5393   const MVT XLenVT = Subtarget.getXLenVT();
5394   SDLoc DL(Op);
5395   SDValue Chain = Op->getOperand(0);
5396   SDValue RMValue = Op->getOperand(1);
5397   SDValue SysRegNo = DAG.getTargetConstant(
5398       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5399 
5400   // Encoding used for rounding mode in RISCV differs from that used in
5401   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5402   // a table, which consists of a sequence of 4-bit fields, each representing
5403   // corresponding RISCV mode.
5404   static const unsigned Table =
5405       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5406       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5407       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5408       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5409       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5410 
5411   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5412                               DAG.getConstant(2, DL, XLenVT));
5413   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5414                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5415   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5416                         DAG.getConstant(0x7, DL, XLenVT));
5417   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5418                      RMValue);
5419 }
5420 
5421 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5422 // form of the given Opcode.
5423 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5424   switch (Opcode) {
5425   default:
5426     llvm_unreachable("Unexpected opcode");
5427   case ISD::SHL:
5428     return RISCVISD::SLLW;
5429   case ISD::SRA:
5430     return RISCVISD::SRAW;
5431   case ISD::SRL:
5432     return RISCVISD::SRLW;
5433   case ISD::SDIV:
5434     return RISCVISD::DIVW;
5435   case ISD::UDIV:
5436     return RISCVISD::DIVUW;
5437   case ISD::UREM:
5438     return RISCVISD::REMUW;
5439   case ISD::ROTL:
5440     return RISCVISD::ROLW;
5441   case ISD::ROTR:
5442     return RISCVISD::RORW;
5443   case RISCVISD::GREV:
5444     return RISCVISD::GREVW;
5445   case RISCVISD::GORC:
5446     return RISCVISD::GORCW;
5447   }
5448 }
5449 
5450 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5451 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5452 // otherwise be promoted to i64, making it difficult to select the
5453 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5454 // type i8/i16/i32 is lost.
5455 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5456                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5457   SDLoc DL(N);
5458   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5459   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5460   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5461   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5462   // ReplaceNodeResults requires we maintain the same type for the return value.
5463   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5464 }
5465 
5466 // Converts the given 32-bit operation to a i64 operation with signed extension
5467 // semantic to reduce the signed extension instructions.
5468 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5469   SDLoc DL(N);
5470   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5471   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5472   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5473   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5474                                DAG.getValueType(MVT::i32));
5475   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5476 }
5477 
5478 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5479                                              SmallVectorImpl<SDValue> &Results,
5480                                              SelectionDAG &DAG) const {
5481   SDLoc DL(N);
5482   switch (N->getOpcode()) {
5483   default:
5484     llvm_unreachable("Don't know how to custom type legalize this operation!");
5485   case ISD::STRICT_FP_TO_SINT:
5486   case ISD::STRICT_FP_TO_UINT:
5487   case ISD::FP_TO_SINT:
5488   case ISD::FP_TO_UINT: {
5489     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5490            "Unexpected custom legalisation");
5491     bool IsStrict = N->isStrictFPOpcode();
5492     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5493                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5494     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5495     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5496         TargetLowering::TypeSoftenFloat) {
5497       // FIXME: Support strict FP.
5498       if (IsStrict)
5499         return;
5500       if (!isTypeLegal(Op0.getValueType()))
5501         return;
5502       unsigned Opc =
5503           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5504       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5505       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5506       return;
5507     }
5508     // If the FP type needs to be softened, emit a library call using the 'si'
5509     // version. If we left it to default legalization we'd end up with 'di'. If
5510     // the FP type doesn't need to be softened just let generic type
5511     // legalization promote the result type.
5512     RTLIB::Libcall LC;
5513     if (IsSigned)
5514       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5515     else
5516       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5517     MakeLibCallOptions CallOptions;
5518     EVT OpVT = Op0.getValueType();
5519     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5520     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5521     SDValue Result;
5522     std::tie(Result, Chain) =
5523         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5524     Results.push_back(Result);
5525     if (IsStrict)
5526       Results.push_back(Chain);
5527     break;
5528   }
5529   case ISD::READCYCLECOUNTER: {
5530     assert(!Subtarget.is64Bit() &&
5531            "READCYCLECOUNTER only has custom type legalization on riscv32");
5532 
5533     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5534     SDValue RCW =
5535         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5536 
5537     Results.push_back(
5538         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5539     Results.push_back(RCW.getValue(2));
5540     break;
5541   }
5542   case ISD::MUL: {
5543     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5544     unsigned XLen = Subtarget.getXLen();
5545     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5546     if (Size > XLen) {
5547       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5548       SDValue LHS = N->getOperand(0);
5549       SDValue RHS = N->getOperand(1);
5550       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5551 
5552       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5553       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5554       // We need exactly one side to be unsigned.
5555       if (LHSIsU == RHSIsU)
5556         return;
5557 
5558       auto MakeMULPair = [&](SDValue S, SDValue U) {
5559         MVT XLenVT = Subtarget.getXLenVT();
5560         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5561         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5562         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5563         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5564         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5565       };
5566 
5567       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5568       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5569 
5570       // The other operand should be signed, but still prefer MULH when
5571       // possible.
5572       if (RHSIsU && LHSIsS && !RHSIsS)
5573         Results.push_back(MakeMULPair(LHS, RHS));
5574       else if (LHSIsU && RHSIsS && !LHSIsS)
5575         Results.push_back(MakeMULPair(RHS, LHS));
5576 
5577       return;
5578     }
5579     LLVM_FALLTHROUGH;
5580   }
5581   case ISD::ADD:
5582   case ISD::SUB:
5583     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5584            "Unexpected custom legalisation");
5585     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5586     break;
5587   case ISD::SHL:
5588   case ISD::SRA:
5589   case ISD::SRL:
5590     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5591            "Unexpected custom legalisation");
5592     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5593       Results.push_back(customLegalizeToWOp(N, DAG));
5594       break;
5595     }
5596 
5597     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5598     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5599     // shift amount.
5600     if (N->getOpcode() == ISD::SHL) {
5601       SDLoc DL(N);
5602       SDValue NewOp0 =
5603           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5604       SDValue NewOp1 =
5605           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5606       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5607       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5608                                    DAG.getValueType(MVT::i32));
5609       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5610     }
5611 
5612     break;
5613   case ISD::ROTL:
5614   case ISD::ROTR:
5615     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5616            "Unexpected custom legalisation");
5617     Results.push_back(customLegalizeToWOp(N, DAG));
5618     break;
5619   case ISD::CTTZ:
5620   case ISD::CTTZ_ZERO_UNDEF:
5621   case ISD::CTLZ:
5622   case ISD::CTLZ_ZERO_UNDEF: {
5623     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5624            "Unexpected custom legalisation");
5625 
5626     SDValue NewOp0 =
5627         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5628     bool IsCTZ =
5629         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5630     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5631     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5632     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5633     return;
5634   }
5635   case ISD::SDIV:
5636   case ISD::UDIV:
5637   case ISD::UREM: {
5638     MVT VT = N->getSimpleValueType(0);
5639     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5640            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5641            "Unexpected custom legalisation");
5642     // Don't promote division/remainder by constant since we should expand those
5643     // to multiply by magic constant.
5644     // FIXME: What if the expansion is disabled for minsize.
5645     if (N->getOperand(1).getOpcode() == ISD::Constant)
5646       return;
5647 
5648     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5649     // the upper 32 bits. For other types we need to sign or zero extend
5650     // based on the opcode.
5651     unsigned ExtOpc = ISD::ANY_EXTEND;
5652     if (VT != MVT::i32)
5653       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5654                                            : ISD::ZERO_EXTEND;
5655 
5656     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5657     break;
5658   }
5659   case ISD::UADDO:
5660   case ISD::USUBO: {
5661     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5662            "Unexpected custom legalisation");
5663     bool IsAdd = N->getOpcode() == ISD::UADDO;
5664     // Create an ADDW or SUBW.
5665     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5666     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5667     SDValue Res =
5668         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5669     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5670                       DAG.getValueType(MVT::i32));
5671 
5672     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5673     // Since the inputs are sign extended from i32, this is equivalent to
5674     // comparing the lower 32 bits.
5675     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5676     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5677                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5678 
5679     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5680     Results.push_back(Overflow);
5681     return;
5682   }
5683   case ISD::UADDSAT:
5684   case ISD::USUBSAT: {
5685     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5686            "Unexpected custom legalisation");
5687     if (Subtarget.hasStdExtZbb()) {
5688       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5689       // sign extend allows overflow of the lower 32 bits to be detected on
5690       // the promoted size.
5691       SDValue LHS =
5692           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5693       SDValue RHS =
5694           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5695       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5696       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5697       return;
5698     }
5699 
5700     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5701     // promotion for UADDO/USUBO.
5702     Results.push_back(expandAddSubSat(N, DAG));
5703     return;
5704   }
5705   case ISD::BITCAST: {
5706     EVT VT = N->getValueType(0);
5707     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5708     SDValue Op0 = N->getOperand(0);
5709     EVT Op0VT = Op0.getValueType();
5710     MVT XLenVT = Subtarget.getXLenVT();
5711     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5712       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5713       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5714     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5715                Subtarget.hasStdExtF()) {
5716       SDValue FPConv =
5717           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5718       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5719     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5720                isTypeLegal(Op0VT)) {
5721       // Custom-legalize bitcasts from fixed-length vector types to illegal
5722       // scalar types in order to improve codegen. Bitcast the vector to a
5723       // one-element vector type whose element type is the same as the result
5724       // type, and extract the first element.
5725       LLVMContext &Context = *DAG.getContext();
5726       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5727       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5728                                     DAG.getConstant(0, DL, XLenVT)));
5729     }
5730     break;
5731   }
5732   case RISCVISD::GREV:
5733   case RISCVISD::GORC: {
5734     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5735            "Unexpected custom legalisation");
5736     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5737     // This is similar to customLegalizeToWOp, except that we pass the second
5738     // operand (a TargetConstant) straight through: it is already of type
5739     // XLenVT.
5740     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5741     SDValue NewOp0 =
5742         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5743     SDValue NewOp1 =
5744         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5745     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5746     // ReplaceNodeResults requires we maintain the same type for the return
5747     // value.
5748     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5749     break;
5750   }
5751   case RISCVISD::SHFL: {
5752     // There is no SHFLIW instruction, but we can just promote the operation.
5753     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5754            "Unexpected custom legalisation");
5755     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5756     SDValue NewOp0 =
5757         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5758     SDValue NewOp1 =
5759         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5760     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5761     // ReplaceNodeResults requires we maintain the same type for the return
5762     // value.
5763     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5764     break;
5765   }
5766   case ISD::BSWAP:
5767   case ISD::BITREVERSE: {
5768     MVT VT = N->getSimpleValueType(0);
5769     MVT XLenVT = Subtarget.getXLenVT();
5770     assert((VT == MVT::i8 || VT == MVT::i16 ||
5771             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5772            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5773     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5774     unsigned Imm = VT.getSizeInBits() - 1;
5775     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5776     if (N->getOpcode() == ISD::BSWAP)
5777       Imm &= ~0x7U;
5778     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5779     SDValue GREVI =
5780         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5781     // ReplaceNodeResults requires we maintain the same type for the return
5782     // value.
5783     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5784     break;
5785   }
5786   case ISD::FSHL:
5787   case ISD::FSHR: {
5788     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5789            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5790     SDValue NewOp0 =
5791         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5792     SDValue NewOp1 =
5793         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5794     SDValue NewOp2 =
5795         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5796     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5797     // Mask the shift amount to 5 bits.
5798     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5799                          DAG.getConstant(0x1f, DL, MVT::i64));
5800     unsigned Opc =
5801         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5802     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5803     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5804     break;
5805   }
5806   case ISD::EXTRACT_VECTOR_ELT: {
5807     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5808     // type is illegal (currently only vXi64 RV32).
5809     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5810     // transferred to the destination register. We issue two of these from the
5811     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5812     // first element.
5813     SDValue Vec = N->getOperand(0);
5814     SDValue Idx = N->getOperand(1);
5815 
5816     // The vector type hasn't been legalized yet so we can't issue target
5817     // specific nodes if it needs legalization.
5818     // FIXME: We would manually legalize if it's important.
5819     if (!isTypeLegal(Vec.getValueType()))
5820       return;
5821 
5822     MVT VecVT = Vec.getSimpleValueType();
5823 
5824     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5825            VecVT.getVectorElementType() == MVT::i64 &&
5826            "Unexpected EXTRACT_VECTOR_ELT legalization");
5827 
5828     // If this is a fixed vector, we need to convert it to a scalable vector.
5829     MVT ContainerVT = VecVT;
5830     if (VecVT.isFixedLengthVector()) {
5831       ContainerVT = getContainerForFixedLengthVector(VecVT);
5832       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5833     }
5834 
5835     MVT XLenVT = Subtarget.getXLenVT();
5836 
5837     // Use a VL of 1 to avoid processing more elements than we need.
5838     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5839     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5840     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5841 
5842     // Unless the index is known to be 0, we must slide the vector down to get
5843     // the desired element into index 0.
5844     if (!isNullConstant(Idx)) {
5845       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5846                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5847     }
5848 
5849     // Extract the lower XLEN bits of the correct vector element.
5850     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5851 
5852     // To extract the upper XLEN bits of the vector element, shift the first
5853     // element right by 32 bits and re-extract the lower XLEN bits.
5854     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5855                                      DAG.getConstant(32, DL, XLenVT), VL);
5856     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5857                                  ThirtyTwoV, Mask, VL);
5858 
5859     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5860 
5861     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5862     break;
5863   }
5864   case ISD::INTRINSIC_WO_CHAIN: {
5865     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5866     switch (IntNo) {
5867     default:
5868       llvm_unreachable(
5869           "Don't know how to custom type legalize this intrinsic!");
5870     case Intrinsic::riscv_orc_b: {
5871       // Lower to the GORCI encoding for orc.b with the operand extended.
5872       SDValue NewOp =
5873           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5874       // If Zbp is enabled, use GORCIW which will sign extend the result.
5875       unsigned Opc =
5876           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5877       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5878                                 DAG.getConstant(7, DL, MVT::i64));
5879       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5880       return;
5881     }
5882     case Intrinsic::riscv_grev:
5883     case Intrinsic::riscv_gorc: {
5884       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5885              "Unexpected custom legalisation");
5886       SDValue NewOp1 =
5887           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5888       SDValue NewOp2 =
5889           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5890       unsigned Opc =
5891           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5892       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5893       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5894       break;
5895     }
5896     case Intrinsic::riscv_shfl:
5897     case Intrinsic::riscv_unshfl: {
5898       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5899              "Unexpected custom legalisation");
5900       SDValue NewOp1 =
5901           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5902       SDValue NewOp2 =
5903           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5904       unsigned Opc =
5905           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5906       if (isa<ConstantSDNode>(N->getOperand(2))) {
5907         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5908                              DAG.getConstant(0xf, DL, MVT::i64));
5909         Opc =
5910             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5911       }
5912       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5913       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5914       break;
5915     }
5916     case Intrinsic::riscv_bcompress:
5917     case Intrinsic::riscv_bdecompress: {
5918       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5919              "Unexpected custom legalisation");
5920       SDValue NewOp1 =
5921           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5922       SDValue NewOp2 =
5923           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5924       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5925                          ? RISCVISD::BCOMPRESSW
5926                          : RISCVISD::BDECOMPRESSW;
5927       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5928       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5929       break;
5930     }
5931     case Intrinsic::riscv_vmv_x_s: {
5932       EVT VT = N->getValueType(0);
5933       MVT XLenVT = Subtarget.getXLenVT();
5934       if (VT.bitsLT(XLenVT)) {
5935         // Simple case just extract using vmv.x.s and truncate.
5936         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5937                                       Subtarget.getXLenVT(), N->getOperand(1));
5938         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5939         return;
5940       }
5941 
5942       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5943              "Unexpected custom legalization");
5944 
5945       // We need to do the move in two steps.
5946       SDValue Vec = N->getOperand(1);
5947       MVT VecVT = Vec.getSimpleValueType();
5948 
5949       // First extract the lower XLEN bits of the element.
5950       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5951 
5952       // To extract the upper XLEN bits of the vector element, shift the first
5953       // element right by 32 bits and re-extract the lower XLEN bits.
5954       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5955       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5956       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5957       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5958                                        DAG.getConstant(32, DL, XLenVT), VL);
5959       SDValue LShr32 =
5960           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5961       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5962 
5963       Results.push_back(
5964           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5965       break;
5966     }
5967     }
5968     break;
5969   }
5970   case ISD::VECREDUCE_ADD:
5971   case ISD::VECREDUCE_AND:
5972   case ISD::VECREDUCE_OR:
5973   case ISD::VECREDUCE_XOR:
5974   case ISD::VECREDUCE_SMAX:
5975   case ISD::VECREDUCE_UMAX:
5976   case ISD::VECREDUCE_SMIN:
5977   case ISD::VECREDUCE_UMIN:
5978     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5979       Results.push_back(V);
5980     break;
5981   case ISD::VP_REDUCE_ADD:
5982   case ISD::VP_REDUCE_AND:
5983   case ISD::VP_REDUCE_OR:
5984   case ISD::VP_REDUCE_XOR:
5985   case ISD::VP_REDUCE_SMAX:
5986   case ISD::VP_REDUCE_UMAX:
5987   case ISD::VP_REDUCE_SMIN:
5988   case ISD::VP_REDUCE_UMIN:
5989     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
5990       Results.push_back(V);
5991     break;
5992   case ISD::FLT_ROUNDS_: {
5993     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5994     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5995     Results.push_back(Res.getValue(0));
5996     Results.push_back(Res.getValue(1));
5997     break;
5998   }
5999   }
6000 }
6001 
6002 // A structure to hold one of the bit-manipulation patterns below. Together, a
6003 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6004 //   (or (and (shl x, 1), 0xAAAAAAAA),
6005 //       (and (srl x, 1), 0x55555555))
6006 struct RISCVBitmanipPat {
6007   SDValue Op;
6008   unsigned ShAmt;
6009   bool IsSHL;
6010 
6011   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6012     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6013   }
6014 };
6015 
6016 // Matches patterns of the form
6017 //   (and (shl x, C2), (C1 << C2))
6018 //   (and (srl x, C2), C1)
6019 //   (shl (and x, C1), C2)
6020 //   (srl (and x, (C1 << C2)), C2)
6021 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6022 // The expected masks for each shift amount are specified in BitmanipMasks where
6023 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6024 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6025 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6026 // XLen is 64.
6027 static Optional<RISCVBitmanipPat>
6028 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6029   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6030          "Unexpected number of masks");
6031   Optional<uint64_t> Mask;
6032   // Optionally consume a mask around the shift operation.
6033   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6034     Mask = Op.getConstantOperandVal(1);
6035     Op = Op.getOperand(0);
6036   }
6037   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6038     return None;
6039   bool IsSHL = Op.getOpcode() == ISD::SHL;
6040 
6041   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6042     return None;
6043   uint64_t ShAmt = Op.getConstantOperandVal(1);
6044 
6045   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6046   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6047     return None;
6048   // If we don't have enough masks for 64 bit, then we must be trying to
6049   // match SHFL so we're only allowed to shift 1/4 of the width.
6050   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6051     return None;
6052 
6053   SDValue Src = Op.getOperand(0);
6054 
6055   // The expected mask is shifted left when the AND is found around SHL
6056   // patterns.
6057   //   ((x >> 1) & 0x55555555)
6058   //   ((x << 1) & 0xAAAAAAAA)
6059   bool SHLExpMask = IsSHL;
6060 
6061   if (!Mask) {
6062     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6063     // the mask is all ones: consume that now.
6064     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6065       Mask = Src.getConstantOperandVal(1);
6066       Src = Src.getOperand(0);
6067       // The expected mask is now in fact shifted left for SRL, so reverse the
6068       // decision.
6069       //   ((x & 0xAAAAAAAA) >> 1)
6070       //   ((x & 0x55555555) << 1)
6071       SHLExpMask = !SHLExpMask;
6072     } else {
6073       // Use a default shifted mask of all-ones if there's no AND, truncated
6074       // down to the expected width. This simplifies the logic later on.
6075       Mask = maskTrailingOnes<uint64_t>(Width);
6076       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6077     }
6078   }
6079 
6080   unsigned MaskIdx = Log2_32(ShAmt);
6081   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6082 
6083   if (SHLExpMask)
6084     ExpMask <<= ShAmt;
6085 
6086   if (Mask != ExpMask)
6087     return None;
6088 
6089   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6090 }
6091 
6092 // Matches any of the following bit-manipulation patterns:
6093 //   (and (shl x, 1), (0x55555555 << 1))
6094 //   (and (srl x, 1), 0x55555555)
6095 //   (shl (and x, 0x55555555), 1)
6096 //   (srl (and x, (0x55555555 << 1)), 1)
6097 // where the shift amount and mask may vary thus:
6098 //   [1]  = 0x55555555 / 0xAAAAAAAA
6099 //   [2]  = 0x33333333 / 0xCCCCCCCC
6100 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6101 //   [8]  = 0x00FF00FF / 0xFF00FF00
6102 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6103 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6104 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6105   // These are the unshifted masks which we use to match bit-manipulation
6106   // patterns. They may be shifted left in certain circumstances.
6107   static const uint64_t BitmanipMasks[] = {
6108       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6109       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6110 
6111   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6112 }
6113 
6114 // Match the following pattern as a GREVI(W) operation
6115 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6116 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6117                                const RISCVSubtarget &Subtarget) {
6118   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6119   EVT VT = Op.getValueType();
6120 
6121   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6122     auto LHS = matchGREVIPat(Op.getOperand(0));
6123     auto RHS = matchGREVIPat(Op.getOperand(1));
6124     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6125       SDLoc DL(Op);
6126       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6127                          DAG.getConstant(LHS->ShAmt, DL, VT));
6128     }
6129   }
6130   return SDValue();
6131 }
6132 
6133 // Matches any the following pattern as a GORCI(W) operation
6134 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6135 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6136 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6137 // Note that with the variant of 3.,
6138 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6139 // the inner pattern will first be matched as GREVI and then the outer
6140 // pattern will be matched to GORC via the first rule above.
6141 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6142 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6143                                const RISCVSubtarget &Subtarget) {
6144   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6145   EVT VT = Op.getValueType();
6146 
6147   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6148     SDLoc DL(Op);
6149     SDValue Op0 = Op.getOperand(0);
6150     SDValue Op1 = Op.getOperand(1);
6151 
6152     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6153       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6154           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6155           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6156         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6157       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6158       if ((Reverse.getOpcode() == ISD::ROTL ||
6159            Reverse.getOpcode() == ISD::ROTR) &&
6160           Reverse.getOperand(0) == X &&
6161           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6162         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6163         if (RotAmt == (VT.getSizeInBits() / 2))
6164           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6165                              DAG.getConstant(RotAmt, DL, VT));
6166       }
6167       return SDValue();
6168     };
6169 
6170     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6171     if (SDValue V = MatchOROfReverse(Op0, Op1))
6172       return V;
6173     if (SDValue V = MatchOROfReverse(Op1, Op0))
6174       return V;
6175 
6176     // OR is commutable so canonicalize its OR operand to the left
6177     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6178       std::swap(Op0, Op1);
6179     if (Op0.getOpcode() != ISD::OR)
6180       return SDValue();
6181     SDValue OrOp0 = Op0.getOperand(0);
6182     SDValue OrOp1 = Op0.getOperand(1);
6183     auto LHS = matchGREVIPat(OrOp0);
6184     // OR is commutable so swap the operands and try again: x might have been
6185     // on the left
6186     if (!LHS) {
6187       std::swap(OrOp0, OrOp1);
6188       LHS = matchGREVIPat(OrOp0);
6189     }
6190     auto RHS = matchGREVIPat(Op1);
6191     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6192       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6193                          DAG.getConstant(LHS->ShAmt, DL, VT));
6194     }
6195   }
6196   return SDValue();
6197 }
6198 
6199 // Matches any of the following bit-manipulation patterns:
6200 //   (and (shl x, 1), (0x22222222 << 1))
6201 //   (and (srl x, 1), 0x22222222)
6202 //   (shl (and x, 0x22222222), 1)
6203 //   (srl (and x, (0x22222222 << 1)), 1)
6204 // where the shift amount and mask may vary thus:
6205 //   [1]  = 0x22222222 / 0x44444444
6206 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6207 //   [4]  = 0x00F000F0 / 0x0F000F00
6208 //   [8]  = 0x0000FF00 / 0x00FF0000
6209 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6210 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6211   // These are the unshifted masks which we use to match bit-manipulation
6212   // patterns. They may be shifted left in certain circumstances.
6213   static const uint64_t BitmanipMasks[] = {
6214       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6215       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6216 
6217   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6218 }
6219 
6220 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6221 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6222                                const RISCVSubtarget &Subtarget) {
6223   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6224   EVT VT = Op.getValueType();
6225 
6226   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6227     return SDValue();
6228 
6229   SDValue Op0 = Op.getOperand(0);
6230   SDValue Op1 = Op.getOperand(1);
6231 
6232   // Or is commutable so canonicalize the second OR to the LHS.
6233   if (Op0.getOpcode() != ISD::OR)
6234     std::swap(Op0, Op1);
6235   if (Op0.getOpcode() != ISD::OR)
6236     return SDValue();
6237 
6238   // We found an inner OR, so our operands are the operands of the inner OR
6239   // and the other operand of the outer OR.
6240   SDValue A = Op0.getOperand(0);
6241   SDValue B = Op0.getOperand(1);
6242   SDValue C = Op1;
6243 
6244   auto Match1 = matchSHFLPat(A);
6245   auto Match2 = matchSHFLPat(B);
6246 
6247   // If neither matched, we failed.
6248   if (!Match1 && !Match2)
6249     return SDValue();
6250 
6251   // We had at least one match. if one failed, try the remaining C operand.
6252   if (!Match1) {
6253     std::swap(A, C);
6254     Match1 = matchSHFLPat(A);
6255     if (!Match1)
6256       return SDValue();
6257   } else if (!Match2) {
6258     std::swap(B, C);
6259     Match2 = matchSHFLPat(B);
6260     if (!Match2)
6261       return SDValue();
6262   }
6263   assert(Match1 && Match2);
6264 
6265   // Make sure our matches pair up.
6266   if (!Match1->formsPairWith(*Match2))
6267     return SDValue();
6268 
6269   // All the remains is to make sure C is an AND with the same input, that masks
6270   // out the bits that are being shuffled.
6271   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6272       C.getOperand(0) != Match1->Op)
6273     return SDValue();
6274 
6275   uint64_t Mask = C.getConstantOperandVal(1);
6276 
6277   static const uint64_t BitmanipMasks[] = {
6278       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6279       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6280   };
6281 
6282   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6283   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6284   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6285 
6286   if (Mask != ExpMask)
6287     return SDValue();
6288 
6289   SDLoc DL(Op);
6290   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6291                      DAG.getConstant(Match1->ShAmt, DL, VT));
6292 }
6293 
6294 // Optimize (add (shl x, c0), (shl y, c1)) ->
6295 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6296 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6297                                   const RISCVSubtarget &Subtarget) {
6298   // Perform this optimization only in the zba extension.
6299   if (!Subtarget.hasStdExtZba())
6300     return SDValue();
6301 
6302   // Skip for vector types and larger types.
6303   EVT VT = N->getValueType(0);
6304   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6305     return SDValue();
6306 
6307   // The two operand nodes must be SHL and have no other use.
6308   SDValue N0 = N->getOperand(0);
6309   SDValue N1 = N->getOperand(1);
6310   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6311       !N0->hasOneUse() || !N1->hasOneUse())
6312     return SDValue();
6313 
6314   // Check c0 and c1.
6315   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6316   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6317   if (!N0C || !N1C)
6318     return SDValue();
6319   int64_t C0 = N0C->getSExtValue();
6320   int64_t C1 = N1C->getSExtValue();
6321   if (C0 <= 0 || C1 <= 0)
6322     return SDValue();
6323 
6324   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6325   int64_t Bits = std::min(C0, C1);
6326   int64_t Diff = std::abs(C0 - C1);
6327   if (Diff != 1 && Diff != 2 && Diff != 3)
6328     return SDValue();
6329 
6330   // Build nodes.
6331   SDLoc DL(N);
6332   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6333   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6334   SDValue NA0 =
6335       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6336   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6337   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6338 }
6339 
6340 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6341 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6342 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6343 // not undo itself, but they are redundant.
6344 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6345   SDValue Src = N->getOperand(0);
6346 
6347   if (Src.getOpcode() != N->getOpcode())
6348     return SDValue();
6349 
6350   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6351       !isa<ConstantSDNode>(Src.getOperand(1)))
6352     return SDValue();
6353 
6354   unsigned ShAmt1 = N->getConstantOperandVal(1);
6355   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6356   Src = Src.getOperand(0);
6357 
6358   unsigned CombinedShAmt;
6359   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6360     CombinedShAmt = ShAmt1 | ShAmt2;
6361   else
6362     CombinedShAmt = ShAmt1 ^ ShAmt2;
6363 
6364   if (CombinedShAmt == 0)
6365     return Src;
6366 
6367   SDLoc DL(N);
6368   return DAG.getNode(
6369       N->getOpcode(), DL, N->getValueType(0), Src,
6370       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6371 }
6372 
6373 // Combine a constant select operand into its use:
6374 //
6375 // (and (select cond, -1, c), x)
6376 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6377 // (or  (select cond, 0, c), x)
6378 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6379 // (xor (select cond, 0, c), x)
6380 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6381 // (add (select cond, 0, c), x)
6382 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6383 // (sub x, (select cond, 0, c))
6384 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6385 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6386                                    SelectionDAG &DAG, bool AllOnes) {
6387   EVT VT = N->getValueType(0);
6388 
6389   // Skip vectors.
6390   if (VT.isVector())
6391     return SDValue();
6392 
6393   if ((Slct.getOpcode() != ISD::SELECT &&
6394        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6395       !Slct.hasOneUse())
6396     return SDValue();
6397 
6398   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6399     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6400   };
6401 
6402   bool SwapSelectOps;
6403   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6404   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6405   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6406   SDValue NonConstantVal;
6407   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6408     SwapSelectOps = false;
6409     NonConstantVal = FalseVal;
6410   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6411     SwapSelectOps = true;
6412     NonConstantVal = TrueVal;
6413   } else
6414     return SDValue();
6415 
6416   // Slct is now know to be the desired identity constant when CC is true.
6417   TrueVal = OtherOp;
6418   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6419   // Unless SwapSelectOps says the condition should be false.
6420   if (SwapSelectOps)
6421     std::swap(TrueVal, FalseVal);
6422 
6423   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6424     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6425                        {Slct.getOperand(0), Slct.getOperand(1),
6426                         Slct.getOperand(2), TrueVal, FalseVal});
6427 
6428   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6429                      {Slct.getOperand(0), TrueVal, FalseVal});
6430 }
6431 
6432 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6433 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6434                                               bool AllOnes) {
6435   SDValue N0 = N->getOperand(0);
6436   SDValue N1 = N->getOperand(1);
6437   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6438     return Result;
6439   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6440     return Result;
6441   return SDValue();
6442 }
6443 
6444 // Transform (add (mul x, c0), c1) ->
6445 //           (add (mul (add x, c1/c0), c0), c1%c0).
6446 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6447 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6448 // to an infinite loop in DAGCombine if transformed.
6449 // Or transform (add (mul x, c0), c1) ->
6450 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6451 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6452 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6453 // lead to an infinite loop in DAGCombine if transformed.
6454 // Or transform (add (mul x, c0), c1) ->
6455 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6456 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6457 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6458 // lead to an infinite loop in DAGCombine if transformed.
6459 // Or transform (add (mul x, c0), c1) ->
6460 //              (mul (add x, c1/c0), c0).
6461 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6462 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6463                                      const RISCVSubtarget &Subtarget) {
6464   // Skip for vector types and larger types.
6465   EVT VT = N->getValueType(0);
6466   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6467     return SDValue();
6468   // The first operand node must be a MUL and has no other use.
6469   SDValue N0 = N->getOperand(0);
6470   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6471     return SDValue();
6472   // Check if c0 and c1 match above conditions.
6473   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6474   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6475   if (!N0C || !N1C)
6476     return SDValue();
6477   int64_t C0 = N0C->getSExtValue();
6478   int64_t C1 = N1C->getSExtValue();
6479   int64_t CA, CB;
6480   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6481     return SDValue();
6482   // Search for proper CA (non-zero) and CB that both are simm12.
6483   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6484       !isInt<12>(C0 * (C1 / C0))) {
6485     CA = C1 / C0;
6486     CB = C1 % C0;
6487   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6488              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6489     CA = C1 / C0 + 1;
6490     CB = C1 % C0 - C0;
6491   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6492              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6493     CA = C1 / C0 - 1;
6494     CB = C1 % C0 + C0;
6495   } else
6496     return SDValue();
6497   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6498   SDLoc DL(N);
6499   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6500                              DAG.getConstant(CA, DL, VT));
6501   SDValue New1 =
6502       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6503   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6504 }
6505 
6506 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6507                                  const RISCVSubtarget &Subtarget) {
6508   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6509     return V;
6510   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6511     return V;
6512   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6513   //      (select lhs, rhs, cc, x, (add x, y))
6514   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6515 }
6516 
6517 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6518   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6519   //      (select lhs, rhs, cc, x, (sub x, y))
6520   SDValue N0 = N->getOperand(0);
6521   SDValue N1 = N->getOperand(1);
6522   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6523 }
6524 
6525 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6526   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6527   //      (select lhs, rhs, cc, x, (and x, y))
6528   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6529 }
6530 
6531 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6532                                 const RISCVSubtarget &Subtarget) {
6533   if (Subtarget.hasStdExtZbp()) {
6534     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6535       return GREV;
6536     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6537       return GORC;
6538     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6539       return SHFL;
6540   }
6541 
6542   // fold (or (select cond, 0, y), x) ->
6543   //      (select cond, x, (or x, y))
6544   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6545 }
6546 
6547 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6548   // fold (xor (select cond, 0, y), x) ->
6549   //      (select cond, x, (xor x, y))
6550   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6551 }
6552 
6553 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6554 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6555 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6556 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6557 // ADDW/SUBW/MULW.
6558 static SDValue performANY_EXTENDCombine(SDNode *N,
6559                                         TargetLowering::DAGCombinerInfo &DCI,
6560                                         const RISCVSubtarget &Subtarget) {
6561   if (!Subtarget.is64Bit())
6562     return SDValue();
6563 
6564   SelectionDAG &DAG = DCI.DAG;
6565 
6566   SDValue Src = N->getOperand(0);
6567   EVT VT = N->getValueType(0);
6568   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6569     return SDValue();
6570 
6571   // The opcode must be one that can implicitly sign_extend.
6572   // FIXME: Additional opcodes.
6573   switch (Src.getOpcode()) {
6574   default:
6575     return SDValue();
6576   case ISD::MUL:
6577     if (!Subtarget.hasStdExtM())
6578       return SDValue();
6579     LLVM_FALLTHROUGH;
6580   case ISD::ADD:
6581   case ISD::SUB:
6582     break;
6583   }
6584 
6585   // Only handle cases where the result is used by a CopyToReg. That likely
6586   // means the value is a liveout of the basic block. This helps prevent
6587   // infinite combine loops like PR51206.
6588   if (none_of(N->uses(),
6589               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6590     return SDValue();
6591 
6592   SmallVector<SDNode *, 4> SetCCs;
6593   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6594                             UE = Src.getNode()->use_end();
6595        UI != UE; ++UI) {
6596     SDNode *User = *UI;
6597     if (User == N)
6598       continue;
6599     if (UI.getUse().getResNo() != Src.getResNo())
6600       continue;
6601     // All i32 setccs are legalized by sign extending operands.
6602     if (User->getOpcode() == ISD::SETCC) {
6603       SetCCs.push_back(User);
6604       continue;
6605     }
6606     // We don't know if we can extend this user.
6607     break;
6608   }
6609 
6610   // If we don't have any SetCCs, this isn't worthwhile.
6611   if (SetCCs.empty())
6612     return SDValue();
6613 
6614   SDLoc DL(N);
6615   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6616   DCI.CombineTo(N, SExt);
6617 
6618   // Promote all the setccs.
6619   for (SDNode *SetCC : SetCCs) {
6620     SmallVector<SDValue, 4> Ops;
6621 
6622     for (unsigned j = 0; j != 2; ++j) {
6623       SDValue SOp = SetCC->getOperand(j);
6624       if (SOp == Src)
6625         Ops.push_back(SExt);
6626       else
6627         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6628     }
6629 
6630     Ops.push_back(SetCC->getOperand(2));
6631     DCI.CombineTo(SetCC,
6632                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6633   }
6634   return SDValue(N, 0);
6635 }
6636 
6637 // Try to form VWMUL or VWMULU.
6638 // FIXME: Support VWMULSU.
6639 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6640                                     SelectionDAG &DAG) {
6641   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6642   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6643   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6644   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6645     return SDValue();
6646 
6647   SDValue Mask = N->getOperand(2);
6648   SDValue VL = N->getOperand(3);
6649 
6650   // Make sure the mask and VL match.
6651   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6652     return SDValue();
6653 
6654   MVT VT = N->getSimpleValueType(0);
6655 
6656   // Determine the narrow size for a widening multiply.
6657   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6658   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6659                                   VT.getVectorElementCount());
6660 
6661   SDLoc DL(N);
6662 
6663   // See if the other operand is the same opcode.
6664   if (Op0.getOpcode() == Op1.getOpcode()) {
6665     if (!Op1.hasOneUse())
6666       return SDValue();
6667 
6668     // Make sure the mask and VL match.
6669     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6670       return SDValue();
6671 
6672     Op1 = Op1.getOperand(0);
6673   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6674     // The operand is a splat of a scalar.
6675 
6676     // The VL must be the same.
6677     if (Op1.getOperand(1) != VL)
6678       return SDValue();
6679 
6680     // Get the scalar value.
6681     Op1 = Op1.getOperand(0);
6682 
6683     // See if have enough sign bits or zero bits in the scalar to use a
6684     // widening multiply by splatting to smaller element size.
6685     unsigned EltBits = VT.getScalarSizeInBits();
6686     unsigned ScalarBits = Op1.getValueSizeInBits();
6687     // Make sure we're getting all element bits from the scalar register.
6688     // FIXME: Support implicit sign extension of vmv.v.x?
6689     if (ScalarBits < EltBits)
6690       return SDValue();
6691 
6692     if (IsSignExt) {
6693       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6694         return SDValue();
6695     } else {
6696       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
6697       if (!DAG.MaskedValueIsZero(Op1, Mask))
6698         return SDValue();
6699     }
6700 
6701     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
6702   } else
6703     return SDValue();
6704 
6705   Op0 = Op0.getOperand(0);
6706 
6707   // Re-introduce narrower extends if needed.
6708   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6709   if (Op0.getValueType() != NarrowVT)
6710     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6711   if (Op1.getValueType() != NarrowVT)
6712     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6713 
6714   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6715   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6716 }
6717 
6718 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6719                                                DAGCombinerInfo &DCI) const {
6720   SelectionDAG &DAG = DCI.DAG;
6721 
6722   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6723   // bits are demanded. N will be added to the Worklist if it was not deleted.
6724   // Caller should return SDValue(N, 0) if this returns true.
6725   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6726     SDValue Op = N->getOperand(OpNo);
6727     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6728     if (!SimplifyDemandedBits(Op, Mask, DCI))
6729       return false;
6730 
6731     if (N->getOpcode() != ISD::DELETED_NODE)
6732       DCI.AddToWorklist(N);
6733     return true;
6734   };
6735 
6736   switch (N->getOpcode()) {
6737   default:
6738     break;
6739   case RISCVISD::SplitF64: {
6740     SDValue Op0 = N->getOperand(0);
6741     // If the input to SplitF64 is just BuildPairF64 then the operation is
6742     // redundant. Instead, use BuildPairF64's operands directly.
6743     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6744       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6745 
6746     SDLoc DL(N);
6747 
6748     // It's cheaper to materialise two 32-bit integers than to load a double
6749     // from the constant pool and transfer it to integer registers through the
6750     // stack.
6751     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6752       APInt V = C->getValueAPF().bitcastToAPInt();
6753       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6754       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6755       return DCI.CombineTo(N, Lo, Hi);
6756     }
6757 
6758     // This is a target-specific version of a DAGCombine performed in
6759     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6760     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6761     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6762     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6763         !Op0.getNode()->hasOneUse())
6764       break;
6765     SDValue NewSplitF64 =
6766         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6767                     Op0.getOperand(0));
6768     SDValue Lo = NewSplitF64.getValue(0);
6769     SDValue Hi = NewSplitF64.getValue(1);
6770     APInt SignBit = APInt::getSignMask(32);
6771     if (Op0.getOpcode() == ISD::FNEG) {
6772       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6773                                   DAG.getConstant(SignBit, DL, MVT::i32));
6774       return DCI.CombineTo(N, Lo, NewHi);
6775     }
6776     assert(Op0.getOpcode() == ISD::FABS);
6777     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6778                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6779     return DCI.CombineTo(N, Lo, NewHi);
6780   }
6781   case RISCVISD::SLLW:
6782   case RISCVISD::SRAW:
6783   case RISCVISD::SRLW:
6784   case RISCVISD::ROLW:
6785   case RISCVISD::RORW: {
6786     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6787     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6788         SimplifyDemandedLowBitsHelper(1, 5))
6789       return SDValue(N, 0);
6790     break;
6791   }
6792   case RISCVISD::CLZW:
6793   case RISCVISD::CTZW: {
6794     // Only the lower 32 bits of the first operand are read
6795     if (SimplifyDemandedLowBitsHelper(0, 32))
6796       return SDValue(N, 0);
6797     break;
6798   }
6799   case RISCVISD::FSL:
6800   case RISCVISD::FSR: {
6801     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6802     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6803     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6804     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6805       return SDValue(N, 0);
6806     break;
6807   }
6808   case RISCVISD::FSLW:
6809   case RISCVISD::FSRW: {
6810     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6811     // read.
6812     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6813         SimplifyDemandedLowBitsHelper(1, 32) ||
6814         SimplifyDemandedLowBitsHelper(2, 6))
6815       return SDValue(N, 0);
6816     break;
6817   }
6818   case RISCVISD::GREV:
6819   case RISCVISD::GORC: {
6820     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6821     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6822     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6823     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6824       return SDValue(N, 0);
6825 
6826     return combineGREVI_GORCI(N, DCI.DAG);
6827   }
6828   case RISCVISD::GREVW:
6829   case RISCVISD::GORCW: {
6830     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6831     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6832         SimplifyDemandedLowBitsHelper(1, 5))
6833       return SDValue(N, 0);
6834 
6835     return combineGREVI_GORCI(N, DCI.DAG);
6836   }
6837   case RISCVISD::SHFL:
6838   case RISCVISD::UNSHFL: {
6839     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6840     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6841     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6842     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6843       return SDValue(N, 0);
6844 
6845     break;
6846   }
6847   case RISCVISD::SHFLW:
6848   case RISCVISD::UNSHFLW: {
6849     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6850     SDValue LHS = N->getOperand(0);
6851     SDValue RHS = N->getOperand(1);
6852     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6853     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6854     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6855         SimplifyDemandedLowBitsHelper(1, 4))
6856       return SDValue(N, 0);
6857 
6858     break;
6859   }
6860   case RISCVISD::BCOMPRESSW:
6861   case RISCVISD::BDECOMPRESSW: {
6862     // Only the lower 32 bits of LHS and RHS are read.
6863     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6864         SimplifyDemandedLowBitsHelper(1, 32))
6865       return SDValue(N, 0);
6866 
6867     break;
6868   }
6869   case RISCVISD::FMV_X_ANYEXTH:
6870   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6871     SDLoc DL(N);
6872     SDValue Op0 = N->getOperand(0);
6873     MVT VT = N->getSimpleValueType(0);
6874     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6875     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6876     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6877     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6878          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6879         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6880          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6881       assert(Op0.getOperand(0).getValueType() == VT &&
6882              "Unexpected value type!");
6883       return Op0.getOperand(0);
6884     }
6885 
6886     // This is a target-specific version of a DAGCombine performed in
6887     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6888     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6889     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6890     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6891         !Op0.getNode()->hasOneUse())
6892       break;
6893     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6894     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6895     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6896     if (Op0.getOpcode() == ISD::FNEG)
6897       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6898                          DAG.getConstant(SignBit, DL, VT));
6899 
6900     assert(Op0.getOpcode() == ISD::FABS);
6901     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6902                        DAG.getConstant(~SignBit, DL, VT));
6903   }
6904   case ISD::ADD:
6905     return performADDCombine(N, DAG, Subtarget);
6906   case ISD::SUB:
6907     return performSUBCombine(N, DAG);
6908   case ISD::AND:
6909     return performANDCombine(N, DAG);
6910   case ISD::OR:
6911     return performORCombine(N, DAG, Subtarget);
6912   case ISD::XOR:
6913     return performXORCombine(N, DAG);
6914   case ISD::ANY_EXTEND:
6915     return performANY_EXTENDCombine(N, DCI, Subtarget);
6916   case ISD::ZERO_EXTEND:
6917     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6918     // type legalization. This is safe because fp_to_uint produces poison if
6919     // it overflows.
6920     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6921         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6922         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6923       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6924                          N->getOperand(0).getOperand(0));
6925     return SDValue();
6926   case RISCVISD::SELECT_CC: {
6927     // Transform
6928     SDValue LHS = N->getOperand(0);
6929     SDValue RHS = N->getOperand(1);
6930     SDValue TrueV = N->getOperand(3);
6931     SDValue FalseV = N->getOperand(4);
6932 
6933     // If the True and False values are the same, we don't need a select_cc.
6934     if (TrueV == FalseV)
6935       return TrueV;
6936 
6937     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6938     if (!ISD::isIntEqualitySetCC(CCVal))
6939       break;
6940 
6941     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6942     //      (select_cc X, Y, lt, trueV, falseV)
6943     // Sometimes the setcc is introduced after select_cc has been formed.
6944     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6945         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6946       // If we're looking for eq 0 instead of ne 0, we need to invert the
6947       // condition.
6948       bool Invert = CCVal == ISD::SETEQ;
6949       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6950       if (Invert)
6951         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6952 
6953       SDLoc DL(N);
6954       RHS = LHS.getOperand(1);
6955       LHS = LHS.getOperand(0);
6956       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6957 
6958       SDValue TargetCC = DAG.getCondCode(CCVal);
6959       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6960                          {LHS, RHS, TargetCC, TrueV, FalseV});
6961     }
6962 
6963     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6964     //      (select_cc X, Y, eq/ne, trueV, falseV)
6965     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6966       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6967                          {LHS.getOperand(0), LHS.getOperand(1),
6968                           N->getOperand(2), TrueV, FalseV});
6969     // (select_cc X, 1, setne, trueV, falseV) ->
6970     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6971     // This can occur when legalizing some floating point comparisons.
6972     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6973     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6974       SDLoc DL(N);
6975       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6976       SDValue TargetCC = DAG.getCondCode(CCVal);
6977       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6978       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6979                          {LHS, RHS, TargetCC, TrueV, FalseV});
6980     }
6981 
6982     break;
6983   }
6984   case RISCVISD::BR_CC: {
6985     SDValue LHS = N->getOperand(1);
6986     SDValue RHS = N->getOperand(2);
6987     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6988     if (!ISD::isIntEqualitySetCC(CCVal))
6989       break;
6990 
6991     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6992     //      (br_cc X, Y, lt, dest)
6993     // Sometimes the setcc is introduced after br_cc has been formed.
6994     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6995         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6996       // If we're looking for eq 0 instead of ne 0, we need to invert the
6997       // condition.
6998       bool Invert = CCVal == ISD::SETEQ;
6999       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7000       if (Invert)
7001         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7002 
7003       SDLoc DL(N);
7004       RHS = LHS.getOperand(1);
7005       LHS = LHS.getOperand(0);
7006       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7007 
7008       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7009                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7010                          N->getOperand(4));
7011     }
7012 
7013     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7014     //      (br_cc X, Y, eq/ne, trueV, falseV)
7015     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7016       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7017                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7018                          N->getOperand(3), N->getOperand(4));
7019 
7020     // (br_cc X, 1, setne, br_cc) ->
7021     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7022     // This can occur when legalizing some floating point comparisons.
7023     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7024     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7025       SDLoc DL(N);
7026       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7027       SDValue TargetCC = DAG.getCondCode(CCVal);
7028       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7029       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7030                          N->getOperand(0), LHS, RHS, TargetCC,
7031                          N->getOperand(4));
7032     }
7033     break;
7034   }
7035   case ISD::FCOPYSIGN: {
7036     EVT VT = N->getValueType(0);
7037     if (!VT.isVector())
7038       break;
7039     // There is a form of VFSGNJ which injects the negated sign of its second
7040     // operand. Try and bubble any FNEG up after the extend/round to produce
7041     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7042     // TRUNC=1.
7043     SDValue In2 = N->getOperand(1);
7044     // Avoid cases where the extend/round has multiple uses, as duplicating
7045     // those is typically more expensive than removing a fneg.
7046     if (!In2.hasOneUse())
7047       break;
7048     if (In2.getOpcode() != ISD::FP_EXTEND &&
7049         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7050       break;
7051     In2 = In2.getOperand(0);
7052     if (In2.getOpcode() != ISD::FNEG)
7053       break;
7054     SDLoc DL(N);
7055     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7056     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7057                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7058   }
7059   case ISD::MGATHER:
7060   case ISD::MSCATTER:
7061   case ISD::VP_GATHER:
7062   case ISD::VP_SCATTER: {
7063     if (!DCI.isBeforeLegalize())
7064       break;
7065     SDValue Index, ScaleOp;
7066     bool IsIndexScaled = false;
7067     bool IsIndexSigned = false;
7068     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7069       Index = VPGSN->getIndex();
7070       ScaleOp = VPGSN->getScale();
7071       IsIndexScaled = VPGSN->isIndexScaled();
7072       IsIndexSigned = VPGSN->isIndexSigned();
7073     } else {
7074       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7075       Index = MGSN->getIndex();
7076       ScaleOp = MGSN->getScale();
7077       IsIndexScaled = MGSN->isIndexScaled();
7078       IsIndexSigned = MGSN->isIndexSigned();
7079     }
7080     EVT IndexVT = Index.getValueType();
7081     MVT XLenVT = Subtarget.getXLenVT();
7082     // RISCV indexed loads only support the "unsigned unscaled" addressing
7083     // mode, so anything else must be manually legalized.
7084     bool NeedsIdxLegalization =
7085         IsIndexScaled ||
7086         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7087     if (!NeedsIdxLegalization)
7088       break;
7089 
7090     SDLoc DL(N);
7091 
7092     // Any index legalization should first promote to XLenVT, so we don't lose
7093     // bits when scaling. This may create an illegal index type so we let
7094     // LLVM's legalization take care of the splitting.
7095     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7096     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7097       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7098       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7099                           DL, IndexVT, Index);
7100     }
7101 
7102     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7103     if (IsIndexScaled && Scale != 1) {
7104       // Manually scale the indices by the element size.
7105       // TODO: Sanitize the scale operand here?
7106       // TODO: For VP nodes, should we use VP_SHL here?
7107       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7108       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7109       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7110     }
7111 
7112     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7113     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7114       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7115                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7116                               VPGN->getScale(), VPGN->getMask(),
7117                               VPGN->getVectorLength()},
7118                              VPGN->getMemOperand(), NewIndexTy);
7119     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7120       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7121                               {VPSN->getChain(), VPSN->getValue(),
7122                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7123                                VPSN->getMask(), VPSN->getVectorLength()},
7124                               VPSN->getMemOperand(), NewIndexTy);
7125     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7126       return DAG.getMaskedGather(
7127           N->getVTList(), MGN->getMemoryVT(), DL,
7128           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7129            MGN->getBasePtr(), Index, MGN->getScale()},
7130           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7131     const auto *MSN = cast<MaskedScatterSDNode>(N);
7132     return DAG.getMaskedScatter(
7133         N->getVTList(), MSN->getMemoryVT(), DL,
7134         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7135          Index, MSN->getScale()},
7136         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7137   }
7138   case RISCVISD::SRA_VL:
7139   case RISCVISD::SRL_VL:
7140   case RISCVISD::SHL_VL: {
7141     SDValue ShAmt = N->getOperand(1);
7142     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7143       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7144       SDLoc DL(N);
7145       SDValue VL = N->getOperand(3);
7146       EVT VT = N->getValueType(0);
7147       ShAmt =
7148           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7149       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7150                          N->getOperand(2), N->getOperand(3));
7151     }
7152     break;
7153   }
7154   case ISD::SRA:
7155   case ISD::SRL:
7156   case ISD::SHL: {
7157     SDValue ShAmt = N->getOperand(1);
7158     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7159       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7160       SDLoc DL(N);
7161       EVT VT = N->getValueType(0);
7162       ShAmt =
7163           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7164       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7165     }
7166     break;
7167   }
7168   case RISCVISD::MUL_VL: {
7169     SDValue Op0 = N->getOperand(0);
7170     SDValue Op1 = N->getOperand(1);
7171     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7172       return V;
7173     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7174       return V;
7175     return SDValue();
7176   }
7177   case ISD::STORE: {
7178     auto *Store = cast<StoreSDNode>(N);
7179     SDValue Val = Store->getValue();
7180     // Combine store of vmv.x.s to vse with VL of 1.
7181     // FIXME: Support FP.
7182     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7183       SDValue Src = Val.getOperand(0);
7184       EVT VecVT = Src.getValueType();
7185       EVT MemVT = Store->getMemoryVT();
7186       // The memory VT and the element type must match.
7187       if (VecVT.getVectorElementType() == MemVT) {
7188         SDLoc DL(N);
7189         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7190         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7191                               DAG.getConstant(1, DL, MaskVT),
7192                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7193                               Store->getPointerInfo(),
7194                               Store->getOriginalAlign(),
7195                               Store->getMemOperand()->getFlags());
7196       }
7197     }
7198 
7199     break;
7200   }
7201   }
7202 
7203   return SDValue();
7204 }
7205 
7206 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7207     const SDNode *N, CombineLevel Level) const {
7208   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7209   // materialised in fewer instructions than `(OP _, c1)`:
7210   //
7211   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7212   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7213   SDValue N0 = N->getOperand(0);
7214   EVT Ty = N0.getValueType();
7215   if (Ty.isScalarInteger() &&
7216       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7217     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7218     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7219     if (C1 && C2) {
7220       const APInt &C1Int = C1->getAPIntValue();
7221       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7222 
7223       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7224       // and the combine should happen, to potentially allow further combines
7225       // later.
7226       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7227           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7228         return true;
7229 
7230       // We can materialise `c1` in an add immediate, so it's "free", and the
7231       // combine should be prevented.
7232       if (C1Int.getMinSignedBits() <= 64 &&
7233           isLegalAddImmediate(C1Int.getSExtValue()))
7234         return false;
7235 
7236       // Neither constant will fit into an immediate, so find materialisation
7237       // costs.
7238       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7239                                               Subtarget.getFeatureBits(),
7240                                               /*CompressionCost*/true);
7241       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7242           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7243           /*CompressionCost*/true);
7244 
7245       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7246       // combine should be prevented.
7247       if (C1Cost < ShiftedC1Cost)
7248         return false;
7249     }
7250   }
7251   return true;
7252 }
7253 
7254 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7255     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7256     TargetLoweringOpt &TLO) const {
7257   // Delay this optimization as late as possible.
7258   if (!TLO.LegalOps)
7259     return false;
7260 
7261   EVT VT = Op.getValueType();
7262   if (VT.isVector())
7263     return false;
7264 
7265   // Only handle AND for now.
7266   if (Op.getOpcode() != ISD::AND)
7267     return false;
7268 
7269   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7270   if (!C)
7271     return false;
7272 
7273   const APInt &Mask = C->getAPIntValue();
7274 
7275   // Clear all non-demanded bits initially.
7276   APInt ShrunkMask = Mask & DemandedBits;
7277 
7278   // Try to make a smaller immediate by setting undemanded bits.
7279 
7280   APInt ExpandedMask = Mask | ~DemandedBits;
7281 
7282   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7283     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7284   };
7285   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7286     if (NewMask == Mask)
7287       return true;
7288     SDLoc DL(Op);
7289     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7290     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7291     return TLO.CombineTo(Op, NewOp);
7292   };
7293 
7294   // If the shrunk mask fits in sign extended 12 bits, let the target
7295   // independent code apply it.
7296   if (ShrunkMask.isSignedIntN(12))
7297     return false;
7298 
7299   // Preserve (and X, 0xffff) when zext.h is supported.
7300   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7301     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7302     if (IsLegalMask(NewMask))
7303       return UseMask(NewMask);
7304   }
7305 
7306   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7307   if (VT == MVT::i64) {
7308     APInt NewMask = APInt(64, 0xffffffff);
7309     if (IsLegalMask(NewMask))
7310       return UseMask(NewMask);
7311   }
7312 
7313   // For the remaining optimizations, we need to be able to make a negative
7314   // number through a combination of mask and undemanded bits.
7315   if (!ExpandedMask.isNegative())
7316     return false;
7317 
7318   // What is the fewest number of bits we need to represent the negative number.
7319   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7320 
7321   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7322   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7323   APInt NewMask = ShrunkMask;
7324   if (MinSignedBits <= 12)
7325     NewMask.setBitsFrom(11);
7326   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7327     NewMask.setBitsFrom(31);
7328   else
7329     return false;
7330 
7331   // Sanity check that our new mask is a subset of the demanded mask.
7332   assert(IsLegalMask(NewMask));
7333   return UseMask(NewMask);
7334 }
7335 
7336 static void computeGREV(APInt &Src, unsigned ShAmt) {
7337   ShAmt &= Src.getBitWidth() - 1;
7338   uint64_t x = Src.getZExtValue();
7339   if (ShAmt & 1)
7340     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7341   if (ShAmt & 2)
7342     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7343   if (ShAmt & 4)
7344     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7345   if (ShAmt & 8)
7346     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7347   if (ShAmt & 16)
7348     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7349   if (ShAmt & 32)
7350     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7351   Src = x;
7352 }
7353 
7354 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7355                                                         KnownBits &Known,
7356                                                         const APInt &DemandedElts,
7357                                                         const SelectionDAG &DAG,
7358                                                         unsigned Depth) const {
7359   unsigned BitWidth = Known.getBitWidth();
7360   unsigned Opc = Op.getOpcode();
7361   assert((Opc >= ISD::BUILTIN_OP_END ||
7362           Opc == ISD::INTRINSIC_WO_CHAIN ||
7363           Opc == ISD::INTRINSIC_W_CHAIN ||
7364           Opc == ISD::INTRINSIC_VOID) &&
7365          "Should use MaskedValueIsZero if you don't know whether Op"
7366          " is a target node!");
7367 
7368   Known.resetAll();
7369   switch (Opc) {
7370   default: break;
7371   case RISCVISD::SELECT_CC: {
7372     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7373     // If we don't know any bits, early out.
7374     if (Known.isUnknown())
7375       break;
7376     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7377 
7378     // Only known if known in both the LHS and RHS.
7379     Known = KnownBits::commonBits(Known, Known2);
7380     break;
7381   }
7382   case RISCVISD::REMUW: {
7383     KnownBits Known2;
7384     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7385     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7386     // We only care about the lower 32 bits.
7387     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7388     // Restore the original width by sign extending.
7389     Known = Known.sext(BitWidth);
7390     break;
7391   }
7392   case RISCVISD::DIVUW: {
7393     KnownBits Known2;
7394     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7395     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7396     // We only care about the lower 32 bits.
7397     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7398     // Restore the original width by sign extending.
7399     Known = Known.sext(BitWidth);
7400     break;
7401   }
7402   case RISCVISD::CTZW: {
7403     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7404     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7405     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7406     Known.Zero.setBitsFrom(LowBits);
7407     break;
7408   }
7409   case RISCVISD::CLZW: {
7410     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7411     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7412     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7413     Known.Zero.setBitsFrom(LowBits);
7414     break;
7415   }
7416   case RISCVISD::GREV:
7417   case RISCVISD::GREVW: {
7418     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7419       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7420       if (Opc == RISCVISD::GREVW)
7421         Known = Known.trunc(32);
7422       unsigned ShAmt = C->getZExtValue();
7423       computeGREV(Known.Zero, ShAmt);
7424       computeGREV(Known.One, ShAmt);
7425       if (Opc == RISCVISD::GREVW)
7426         Known = Known.sext(BitWidth);
7427     }
7428     break;
7429   }
7430   case RISCVISD::READ_VLENB:
7431     // We assume VLENB is at least 16 bytes.
7432     Known.Zero.setLowBits(4);
7433     // We assume VLENB is no more than 65536 / 8 bytes.
7434     Known.Zero.setBitsFrom(14);
7435     break;
7436   case ISD::INTRINSIC_W_CHAIN: {
7437     unsigned IntNo = Op.getConstantOperandVal(1);
7438     switch (IntNo) {
7439     default:
7440       // We can't do anything for most intrinsics.
7441       break;
7442     case Intrinsic::riscv_vsetvli:
7443     case Intrinsic::riscv_vsetvlimax:
7444       // Assume that VL output is positive and would fit in an int32_t.
7445       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7446       if (BitWidth >= 32)
7447         Known.Zero.setBitsFrom(31);
7448       break;
7449     }
7450     break;
7451   }
7452   }
7453 }
7454 
7455 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7456     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7457     unsigned Depth) const {
7458   switch (Op.getOpcode()) {
7459   default:
7460     break;
7461   case RISCVISD::SELECT_CC: {
7462     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7463     if (Tmp == 1) return 1;  // Early out.
7464     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7465     return std::min(Tmp, Tmp2);
7466   }
7467   case RISCVISD::SLLW:
7468   case RISCVISD::SRAW:
7469   case RISCVISD::SRLW:
7470   case RISCVISD::DIVW:
7471   case RISCVISD::DIVUW:
7472   case RISCVISD::REMUW:
7473   case RISCVISD::ROLW:
7474   case RISCVISD::RORW:
7475   case RISCVISD::GREVW:
7476   case RISCVISD::GORCW:
7477   case RISCVISD::FSLW:
7478   case RISCVISD::FSRW:
7479   case RISCVISD::SHFLW:
7480   case RISCVISD::UNSHFLW:
7481   case RISCVISD::BCOMPRESSW:
7482   case RISCVISD::BDECOMPRESSW:
7483   case RISCVISD::FCVT_W_RTZ_RV64:
7484   case RISCVISD::FCVT_WU_RTZ_RV64:
7485     // TODO: As the result is sign-extended, this is conservatively correct. A
7486     // more precise answer could be calculated for SRAW depending on known
7487     // bits in the shift amount.
7488     return 33;
7489   case RISCVISD::SHFL:
7490   case RISCVISD::UNSHFL: {
7491     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7492     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7493     // will stay within the upper 32 bits. If there were more than 32 sign bits
7494     // before there will be at least 33 sign bits after.
7495     if (Op.getValueType() == MVT::i64 &&
7496         isa<ConstantSDNode>(Op.getOperand(1)) &&
7497         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7498       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7499       if (Tmp > 32)
7500         return 33;
7501     }
7502     break;
7503   }
7504   case RISCVISD::VMV_X_S:
7505     // The number of sign bits of the scalar result is computed by obtaining the
7506     // element type of the input vector operand, subtracting its width from the
7507     // XLEN, and then adding one (sign bit within the element type). If the
7508     // element type is wider than XLen, the least-significant XLEN bits are
7509     // taken.
7510     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7511       return 1;
7512     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7513   }
7514 
7515   return 1;
7516 }
7517 
7518 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7519                                                   MachineBasicBlock *BB) {
7520   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7521 
7522   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7523   // Should the count have wrapped while it was being read, we need to try
7524   // again.
7525   // ...
7526   // read:
7527   // rdcycleh x3 # load high word of cycle
7528   // rdcycle  x2 # load low word of cycle
7529   // rdcycleh x4 # load high word of cycle
7530   // bne x3, x4, read # check if high word reads match, otherwise try again
7531   // ...
7532 
7533   MachineFunction &MF = *BB->getParent();
7534   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7535   MachineFunction::iterator It = ++BB->getIterator();
7536 
7537   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7538   MF.insert(It, LoopMBB);
7539 
7540   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7541   MF.insert(It, DoneMBB);
7542 
7543   // Transfer the remainder of BB and its successor edges to DoneMBB.
7544   DoneMBB->splice(DoneMBB->begin(), BB,
7545                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7546   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7547 
7548   BB->addSuccessor(LoopMBB);
7549 
7550   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7551   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7552   Register LoReg = MI.getOperand(0).getReg();
7553   Register HiReg = MI.getOperand(1).getReg();
7554   DebugLoc DL = MI.getDebugLoc();
7555 
7556   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7557   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7558       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7559       .addReg(RISCV::X0);
7560   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7561       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7562       .addReg(RISCV::X0);
7563   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7564       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7565       .addReg(RISCV::X0);
7566 
7567   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7568       .addReg(HiReg)
7569       .addReg(ReadAgainReg)
7570       .addMBB(LoopMBB);
7571 
7572   LoopMBB->addSuccessor(LoopMBB);
7573   LoopMBB->addSuccessor(DoneMBB);
7574 
7575   MI.eraseFromParent();
7576 
7577   return DoneMBB;
7578 }
7579 
7580 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7581                                              MachineBasicBlock *BB) {
7582   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7583 
7584   MachineFunction &MF = *BB->getParent();
7585   DebugLoc DL = MI.getDebugLoc();
7586   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7587   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7588   Register LoReg = MI.getOperand(0).getReg();
7589   Register HiReg = MI.getOperand(1).getReg();
7590   Register SrcReg = MI.getOperand(2).getReg();
7591   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7592   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7593 
7594   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7595                           RI);
7596   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7597   MachineMemOperand *MMOLo =
7598       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7599   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7600       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7601   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7602       .addFrameIndex(FI)
7603       .addImm(0)
7604       .addMemOperand(MMOLo);
7605   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7606       .addFrameIndex(FI)
7607       .addImm(4)
7608       .addMemOperand(MMOHi);
7609   MI.eraseFromParent(); // The pseudo instruction is gone now.
7610   return BB;
7611 }
7612 
7613 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7614                                                  MachineBasicBlock *BB) {
7615   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7616          "Unexpected instruction");
7617 
7618   MachineFunction &MF = *BB->getParent();
7619   DebugLoc DL = MI.getDebugLoc();
7620   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7621   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7622   Register DstReg = MI.getOperand(0).getReg();
7623   Register LoReg = MI.getOperand(1).getReg();
7624   Register HiReg = MI.getOperand(2).getReg();
7625   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7626   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7627 
7628   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7629   MachineMemOperand *MMOLo =
7630       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7631   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7632       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7633   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7634       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7635       .addFrameIndex(FI)
7636       .addImm(0)
7637       .addMemOperand(MMOLo);
7638   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7639       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7640       .addFrameIndex(FI)
7641       .addImm(4)
7642       .addMemOperand(MMOHi);
7643   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7644   MI.eraseFromParent(); // The pseudo instruction is gone now.
7645   return BB;
7646 }
7647 
7648 static bool isSelectPseudo(MachineInstr &MI) {
7649   switch (MI.getOpcode()) {
7650   default:
7651     return false;
7652   case RISCV::Select_GPR_Using_CC_GPR:
7653   case RISCV::Select_FPR16_Using_CC_GPR:
7654   case RISCV::Select_FPR32_Using_CC_GPR:
7655   case RISCV::Select_FPR64_Using_CC_GPR:
7656     return true;
7657   }
7658 }
7659 
7660 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7661                                            MachineBasicBlock *BB,
7662                                            const RISCVSubtarget &Subtarget) {
7663   // To "insert" Select_* instructions, we actually have to insert the triangle
7664   // control-flow pattern.  The incoming instructions know the destination vreg
7665   // to set, the condition code register to branch on, the true/false values to
7666   // select between, and the condcode to use to select the appropriate branch.
7667   //
7668   // We produce the following control flow:
7669   //     HeadMBB
7670   //     |  \
7671   //     |  IfFalseMBB
7672   //     | /
7673   //    TailMBB
7674   //
7675   // When we find a sequence of selects we attempt to optimize their emission
7676   // by sharing the control flow. Currently we only handle cases where we have
7677   // multiple selects with the exact same condition (same LHS, RHS and CC).
7678   // The selects may be interleaved with other instructions if the other
7679   // instructions meet some requirements we deem safe:
7680   // - They are debug instructions. Otherwise,
7681   // - They do not have side-effects, do not access memory and their inputs do
7682   //   not depend on the results of the select pseudo-instructions.
7683   // The TrueV/FalseV operands of the selects cannot depend on the result of
7684   // previous selects in the sequence.
7685   // These conditions could be further relaxed. See the X86 target for a
7686   // related approach and more information.
7687   Register LHS = MI.getOperand(1).getReg();
7688   Register RHS = MI.getOperand(2).getReg();
7689   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7690 
7691   SmallVector<MachineInstr *, 4> SelectDebugValues;
7692   SmallSet<Register, 4> SelectDests;
7693   SelectDests.insert(MI.getOperand(0).getReg());
7694 
7695   MachineInstr *LastSelectPseudo = &MI;
7696 
7697   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7698        SequenceMBBI != E; ++SequenceMBBI) {
7699     if (SequenceMBBI->isDebugInstr())
7700       continue;
7701     else if (isSelectPseudo(*SequenceMBBI)) {
7702       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7703           SequenceMBBI->getOperand(2).getReg() != RHS ||
7704           SequenceMBBI->getOperand(3).getImm() != CC ||
7705           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7706           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7707         break;
7708       LastSelectPseudo = &*SequenceMBBI;
7709       SequenceMBBI->collectDebugValues(SelectDebugValues);
7710       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7711     } else {
7712       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7713           SequenceMBBI->mayLoadOrStore())
7714         break;
7715       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7716             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7717           }))
7718         break;
7719     }
7720   }
7721 
7722   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7723   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7724   DebugLoc DL = MI.getDebugLoc();
7725   MachineFunction::iterator I = ++BB->getIterator();
7726 
7727   MachineBasicBlock *HeadMBB = BB;
7728   MachineFunction *F = BB->getParent();
7729   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7730   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7731 
7732   F->insert(I, IfFalseMBB);
7733   F->insert(I, TailMBB);
7734 
7735   // Transfer debug instructions associated with the selects to TailMBB.
7736   for (MachineInstr *DebugInstr : SelectDebugValues) {
7737     TailMBB->push_back(DebugInstr->removeFromParent());
7738   }
7739 
7740   // Move all instructions after the sequence to TailMBB.
7741   TailMBB->splice(TailMBB->end(), HeadMBB,
7742                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7743   // Update machine-CFG edges by transferring all successors of the current
7744   // block to the new block which will contain the Phi nodes for the selects.
7745   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7746   // Set the successors for HeadMBB.
7747   HeadMBB->addSuccessor(IfFalseMBB);
7748   HeadMBB->addSuccessor(TailMBB);
7749 
7750   // Insert appropriate branch.
7751   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7752     .addReg(LHS)
7753     .addReg(RHS)
7754     .addMBB(TailMBB);
7755 
7756   // IfFalseMBB just falls through to TailMBB.
7757   IfFalseMBB->addSuccessor(TailMBB);
7758 
7759   // Create PHIs for all of the select pseudo-instructions.
7760   auto SelectMBBI = MI.getIterator();
7761   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7762   auto InsertionPoint = TailMBB->begin();
7763   while (SelectMBBI != SelectEnd) {
7764     auto Next = std::next(SelectMBBI);
7765     if (isSelectPseudo(*SelectMBBI)) {
7766       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7767       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7768               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7769           .addReg(SelectMBBI->getOperand(4).getReg())
7770           .addMBB(HeadMBB)
7771           .addReg(SelectMBBI->getOperand(5).getReg())
7772           .addMBB(IfFalseMBB);
7773       SelectMBBI->eraseFromParent();
7774     }
7775     SelectMBBI = Next;
7776   }
7777 
7778   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7779   return TailMBB;
7780 }
7781 
7782 MachineBasicBlock *
7783 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7784                                                  MachineBasicBlock *BB) const {
7785   switch (MI.getOpcode()) {
7786   default:
7787     llvm_unreachable("Unexpected instr type to insert");
7788   case RISCV::ReadCycleWide:
7789     assert(!Subtarget.is64Bit() &&
7790            "ReadCycleWrite is only to be used on riscv32");
7791     return emitReadCycleWidePseudo(MI, BB);
7792   case RISCV::Select_GPR_Using_CC_GPR:
7793   case RISCV::Select_FPR16_Using_CC_GPR:
7794   case RISCV::Select_FPR32_Using_CC_GPR:
7795   case RISCV::Select_FPR64_Using_CC_GPR:
7796     return emitSelectPseudo(MI, BB, Subtarget);
7797   case RISCV::BuildPairF64Pseudo:
7798     return emitBuildPairF64Pseudo(MI, BB);
7799   case RISCV::SplitF64Pseudo:
7800     return emitSplitF64Pseudo(MI, BB);
7801   }
7802 }
7803 
7804 // Calling Convention Implementation.
7805 // The expectations for frontend ABI lowering vary from target to target.
7806 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7807 // details, but this is a longer term goal. For now, we simply try to keep the
7808 // role of the frontend as simple and well-defined as possible. The rules can
7809 // be summarised as:
7810 // * Never split up large scalar arguments. We handle them here.
7811 // * If a hardfloat calling convention is being used, and the struct may be
7812 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7813 // available, then pass as two separate arguments. If either the GPRs or FPRs
7814 // are exhausted, then pass according to the rule below.
7815 // * If a struct could never be passed in registers or directly in a stack
7816 // slot (as it is larger than 2*XLEN and the floating point rules don't
7817 // apply), then pass it using a pointer with the byval attribute.
7818 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7819 // word-sized array or a 2*XLEN scalar (depending on alignment).
7820 // * The frontend can determine whether a struct is returned by reference or
7821 // not based on its size and fields. If it will be returned by reference, the
7822 // frontend must modify the prototype so a pointer with the sret annotation is
7823 // passed as the first argument. This is not necessary for large scalar
7824 // returns.
7825 // * Struct return values and varargs should be coerced to structs containing
7826 // register-size fields in the same situations they would be for fixed
7827 // arguments.
7828 
7829 static const MCPhysReg ArgGPRs[] = {
7830   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7831   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7832 };
7833 static const MCPhysReg ArgFPR16s[] = {
7834   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7835   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7836 };
7837 static const MCPhysReg ArgFPR32s[] = {
7838   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7839   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7840 };
7841 static const MCPhysReg ArgFPR64s[] = {
7842   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7843   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7844 };
7845 // This is an interim calling convention and it may be changed in the future.
7846 static const MCPhysReg ArgVRs[] = {
7847     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7848     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7849     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7850 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7851                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7852                                      RISCV::V20M2, RISCV::V22M2};
7853 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7854                                      RISCV::V20M4};
7855 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7856 
7857 // Pass a 2*XLEN argument that has been split into two XLEN values through
7858 // registers or the stack as necessary.
7859 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7860                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7861                                 MVT ValVT2, MVT LocVT2,
7862                                 ISD::ArgFlagsTy ArgFlags2) {
7863   unsigned XLenInBytes = XLen / 8;
7864   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7865     // At least one half can be passed via register.
7866     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7867                                      VA1.getLocVT(), CCValAssign::Full));
7868   } else {
7869     // Both halves must be passed on the stack, with proper alignment.
7870     Align StackAlign =
7871         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7872     State.addLoc(
7873         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7874                             State.AllocateStack(XLenInBytes, StackAlign),
7875                             VA1.getLocVT(), CCValAssign::Full));
7876     State.addLoc(CCValAssign::getMem(
7877         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7878         LocVT2, CCValAssign::Full));
7879     return false;
7880   }
7881 
7882   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7883     // The second half can also be passed via register.
7884     State.addLoc(
7885         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7886   } else {
7887     // The second half is passed via the stack, without additional alignment.
7888     State.addLoc(CCValAssign::getMem(
7889         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7890         LocVT2, CCValAssign::Full));
7891   }
7892 
7893   return false;
7894 }
7895 
7896 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7897                                Optional<unsigned> FirstMaskArgument,
7898                                CCState &State, const RISCVTargetLowering &TLI) {
7899   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7900   if (RC == &RISCV::VRRegClass) {
7901     // Assign the first mask argument to V0.
7902     // This is an interim calling convention and it may be changed in the
7903     // future.
7904     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7905       return State.AllocateReg(RISCV::V0);
7906     return State.AllocateReg(ArgVRs);
7907   }
7908   if (RC == &RISCV::VRM2RegClass)
7909     return State.AllocateReg(ArgVRM2s);
7910   if (RC == &RISCV::VRM4RegClass)
7911     return State.AllocateReg(ArgVRM4s);
7912   if (RC == &RISCV::VRM8RegClass)
7913     return State.AllocateReg(ArgVRM8s);
7914   llvm_unreachable("Unhandled register class for ValueType");
7915 }
7916 
7917 // Implements the RISC-V calling convention. Returns true upon failure.
7918 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7919                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7920                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7921                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7922                      Optional<unsigned> FirstMaskArgument) {
7923   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7924   assert(XLen == 32 || XLen == 64);
7925   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7926 
7927   // Any return value split in to more than two values can't be returned
7928   // directly. Vectors are returned via the available vector registers.
7929   if (!LocVT.isVector() && IsRet && ValNo > 1)
7930     return true;
7931 
7932   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7933   // variadic argument, or if no F16/F32 argument registers are available.
7934   bool UseGPRForF16_F32 = true;
7935   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7936   // variadic argument, or if no F64 argument registers are available.
7937   bool UseGPRForF64 = true;
7938 
7939   switch (ABI) {
7940   default:
7941     llvm_unreachable("Unexpected ABI");
7942   case RISCVABI::ABI_ILP32:
7943   case RISCVABI::ABI_LP64:
7944     break;
7945   case RISCVABI::ABI_ILP32F:
7946   case RISCVABI::ABI_LP64F:
7947     UseGPRForF16_F32 = !IsFixed;
7948     break;
7949   case RISCVABI::ABI_ILP32D:
7950   case RISCVABI::ABI_LP64D:
7951     UseGPRForF16_F32 = !IsFixed;
7952     UseGPRForF64 = !IsFixed;
7953     break;
7954   }
7955 
7956   // FPR16, FPR32, and FPR64 alias each other.
7957   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7958     UseGPRForF16_F32 = true;
7959     UseGPRForF64 = true;
7960   }
7961 
7962   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7963   // similar local variables rather than directly checking against the target
7964   // ABI.
7965 
7966   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7967     LocVT = XLenVT;
7968     LocInfo = CCValAssign::BCvt;
7969   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7970     LocVT = MVT::i64;
7971     LocInfo = CCValAssign::BCvt;
7972   }
7973 
7974   // If this is a variadic argument, the RISC-V calling convention requires
7975   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7976   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7977   // be used regardless of whether the original argument was split during
7978   // legalisation or not. The argument will not be passed by registers if the
7979   // original type is larger than 2*XLEN, so the register alignment rule does
7980   // not apply.
7981   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7982   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7983       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7984     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7985     // Skip 'odd' register if necessary.
7986     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7987       State.AllocateReg(ArgGPRs);
7988   }
7989 
7990   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7991   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7992       State.getPendingArgFlags();
7993 
7994   assert(PendingLocs.size() == PendingArgFlags.size() &&
7995          "PendingLocs and PendingArgFlags out of sync");
7996 
7997   // Handle passing f64 on RV32D with a soft float ABI or when floating point
7998   // registers are exhausted.
7999   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8000     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8001            "Can't lower f64 if it is split");
8002     // Depending on available argument GPRS, f64 may be passed in a pair of
8003     // GPRs, split between a GPR and the stack, or passed completely on the
8004     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8005     // cases.
8006     Register Reg = State.AllocateReg(ArgGPRs);
8007     LocVT = MVT::i32;
8008     if (!Reg) {
8009       unsigned StackOffset = State.AllocateStack(8, Align(8));
8010       State.addLoc(
8011           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8012       return false;
8013     }
8014     if (!State.AllocateReg(ArgGPRs))
8015       State.AllocateStack(4, Align(4));
8016     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8017     return false;
8018   }
8019 
8020   // Fixed-length vectors are located in the corresponding scalable-vector
8021   // container types.
8022   if (ValVT.isFixedLengthVector())
8023     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8024 
8025   // Split arguments might be passed indirectly, so keep track of the pending
8026   // values. Split vectors are passed via a mix of registers and indirectly, so
8027   // treat them as we would any other argument.
8028   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8029     LocVT = XLenVT;
8030     LocInfo = CCValAssign::Indirect;
8031     PendingLocs.push_back(
8032         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8033     PendingArgFlags.push_back(ArgFlags);
8034     if (!ArgFlags.isSplitEnd()) {
8035       return false;
8036     }
8037   }
8038 
8039   // If the split argument only had two elements, it should be passed directly
8040   // in registers or on the stack.
8041   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8042       PendingLocs.size() <= 2) {
8043     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8044     // Apply the normal calling convention rules to the first half of the
8045     // split argument.
8046     CCValAssign VA = PendingLocs[0];
8047     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8048     PendingLocs.clear();
8049     PendingArgFlags.clear();
8050     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8051                                ArgFlags);
8052   }
8053 
8054   // Allocate to a register if possible, or else a stack slot.
8055   Register Reg;
8056   unsigned StoreSizeBytes = XLen / 8;
8057   Align StackAlign = Align(XLen / 8);
8058 
8059   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8060     Reg = State.AllocateReg(ArgFPR16s);
8061   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8062     Reg = State.AllocateReg(ArgFPR32s);
8063   else if (ValVT == MVT::f64 && !UseGPRForF64)
8064     Reg = State.AllocateReg(ArgFPR64s);
8065   else if (ValVT.isVector()) {
8066     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8067     if (!Reg) {
8068       // For return values, the vector must be passed fully via registers or
8069       // via the stack.
8070       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8071       // but we're using all of them.
8072       if (IsRet)
8073         return true;
8074       // Try using a GPR to pass the address
8075       if ((Reg = State.AllocateReg(ArgGPRs))) {
8076         LocVT = XLenVT;
8077         LocInfo = CCValAssign::Indirect;
8078       } else if (ValVT.isScalableVector()) {
8079         report_fatal_error("Unable to pass scalable vector types on the stack");
8080       } else {
8081         // Pass fixed-length vectors on the stack.
8082         LocVT = ValVT;
8083         StoreSizeBytes = ValVT.getStoreSize();
8084         // Align vectors to their element sizes, being careful for vXi1
8085         // vectors.
8086         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8087       }
8088     }
8089   } else {
8090     Reg = State.AllocateReg(ArgGPRs);
8091   }
8092 
8093   unsigned StackOffset =
8094       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8095 
8096   // If we reach this point and PendingLocs is non-empty, we must be at the
8097   // end of a split argument that must be passed indirectly.
8098   if (!PendingLocs.empty()) {
8099     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8100     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8101 
8102     for (auto &It : PendingLocs) {
8103       if (Reg)
8104         It.convertToReg(Reg);
8105       else
8106         It.convertToMem(StackOffset);
8107       State.addLoc(It);
8108     }
8109     PendingLocs.clear();
8110     PendingArgFlags.clear();
8111     return false;
8112   }
8113 
8114   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8115           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8116          "Expected an XLenVT or vector types at this stage");
8117 
8118   if (Reg) {
8119     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8120     return false;
8121   }
8122 
8123   // When a floating-point value is passed on the stack, no bit-conversion is
8124   // needed.
8125   if (ValVT.isFloatingPoint()) {
8126     LocVT = ValVT;
8127     LocInfo = CCValAssign::Full;
8128   }
8129   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8130   return false;
8131 }
8132 
8133 template <typename ArgTy>
8134 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8135   for (const auto &ArgIdx : enumerate(Args)) {
8136     MVT ArgVT = ArgIdx.value().VT;
8137     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8138       return ArgIdx.index();
8139   }
8140   return None;
8141 }
8142 
8143 void RISCVTargetLowering::analyzeInputArgs(
8144     MachineFunction &MF, CCState &CCInfo,
8145     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8146     RISCVCCAssignFn Fn) const {
8147   unsigned NumArgs = Ins.size();
8148   FunctionType *FType = MF.getFunction().getFunctionType();
8149 
8150   Optional<unsigned> FirstMaskArgument;
8151   if (Subtarget.hasVInstructions())
8152     FirstMaskArgument = preAssignMask(Ins);
8153 
8154   for (unsigned i = 0; i != NumArgs; ++i) {
8155     MVT ArgVT = Ins[i].VT;
8156     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8157 
8158     Type *ArgTy = nullptr;
8159     if (IsRet)
8160       ArgTy = FType->getReturnType();
8161     else if (Ins[i].isOrigArg())
8162       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8163 
8164     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8165     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8166            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8167            FirstMaskArgument)) {
8168       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8169                         << EVT(ArgVT).getEVTString() << '\n');
8170       llvm_unreachable(nullptr);
8171     }
8172   }
8173 }
8174 
8175 void RISCVTargetLowering::analyzeOutputArgs(
8176     MachineFunction &MF, CCState &CCInfo,
8177     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8178     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8179   unsigned NumArgs = Outs.size();
8180 
8181   Optional<unsigned> FirstMaskArgument;
8182   if (Subtarget.hasVInstructions())
8183     FirstMaskArgument = preAssignMask(Outs);
8184 
8185   for (unsigned i = 0; i != NumArgs; i++) {
8186     MVT ArgVT = Outs[i].VT;
8187     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8188     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8189 
8190     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8191     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8192            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8193            FirstMaskArgument)) {
8194       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8195                         << EVT(ArgVT).getEVTString() << "\n");
8196       llvm_unreachable(nullptr);
8197     }
8198   }
8199 }
8200 
8201 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8202 // values.
8203 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8204                                    const CCValAssign &VA, const SDLoc &DL,
8205                                    const RISCVSubtarget &Subtarget) {
8206   switch (VA.getLocInfo()) {
8207   default:
8208     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8209   case CCValAssign::Full:
8210     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8211       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8212     break;
8213   case CCValAssign::BCvt:
8214     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8215       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8216     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8217       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8218     else
8219       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8220     break;
8221   }
8222   return Val;
8223 }
8224 
8225 // The caller is responsible for loading the full value if the argument is
8226 // passed with CCValAssign::Indirect.
8227 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8228                                 const CCValAssign &VA, const SDLoc &DL,
8229                                 const RISCVTargetLowering &TLI) {
8230   MachineFunction &MF = DAG.getMachineFunction();
8231   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8232   EVT LocVT = VA.getLocVT();
8233   SDValue Val;
8234   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8235   Register VReg = RegInfo.createVirtualRegister(RC);
8236   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8237   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8238 
8239   if (VA.getLocInfo() == CCValAssign::Indirect)
8240     return Val;
8241 
8242   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8243 }
8244 
8245 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8246                                    const CCValAssign &VA, const SDLoc &DL,
8247                                    const RISCVSubtarget &Subtarget) {
8248   EVT LocVT = VA.getLocVT();
8249 
8250   switch (VA.getLocInfo()) {
8251   default:
8252     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8253   case CCValAssign::Full:
8254     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8255       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8256     break;
8257   case CCValAssign::BCvt:
8258     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8259       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8260     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8261       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8262     else
8263       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8264     break;
8265   }
8266   return Val;
8267 }
8268 
8269 // The caller is responsible for loading the full value if the argument is
8270 // passed with CCValAssign::Indirect.
8271 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8272                                 const CCValAssign &VA, const SDLoc &DL) {
8273   MachineFunction &MF = DAG.getMachineFunction();
8274   MachineFrameInfo &MFI = MF.getFrameInfo();
8275   EVT LocVT = VA.getLocVT();
8276   EVT ValVT = VA.getValVT();
8277   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8278   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8279                                  /*Immutable=*/true);
8280   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8281   SDValue Val;
8282 
8283   ISD::LoadExtType ExtType;
8284   switch (VA.getLocInfo()) {
8285   default:
8286     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8287   case CCValAssign::Full:
8288   case CCValAssign::Indirect:
8289   case CCValAssign::BCvt:
8290     ExtType = ISD::NON_EXTLOAD;
8291     break;
8292   }
8293   Val = DAG.getExtLoad(
8294       ExtType, DL, LocVT, Chain, FIN,
8295       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8296   return Val;
8297 }
8298 
8299 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8300                                        const CCValAssign &VA, const SDLoc &DL) {
8301   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8302          "Unexpected VA");
8303   MachineFunction &MF = DAG.getMachineFunction();
8304   MachineFrameInfo &MFI = MF.getFrameInfo();
8305   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8306 
8307   if (VA.isMemLoc()) {
8308     // f64 is passed on the stack.
8309     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8310     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8311     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8312                        MachinePointerInfo::getFixedStack(MF, FI));
8313   }
8314 
8315   assert(VA.isRegLoc() && "Expected register VA assignment");
8316 
8317   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8318   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8319   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8320   SDValue Hi;
8321   if (VA.getLocReg() == RISCV::X17) {
8322     // Second half of f64 is passed on the stack.
8323     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8324     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8325     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8326                      MachinePointerInfo::getFixedStack(MF, FI));
8327   } else {
8328     // Second half of f64 is passed in another GPR.
8329     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8330     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8331     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8332   }
8333   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8334 }
8335 
8336 // FastCC has less than 1% performance improvement for some particular
8337 // benchmark. But theoretically, it may has benenfit for some cases.
8338 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8339                             unsigned ValNo, MVT ValVT, MVT LocVT,
8340                             CCValAssign::LocInfo LocInfo,
8341                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8342                             bool IsFixed, bool IsRet, Type *OrigTy,
8343                             const RISCVTargetLowering &TLI,
8344                             Optional<unsigned> FirstMaskArgument) {
8345 
8346   // X5 and X6 might be used for save-restore libcall.
8347   static const MCPhysReg GPRList[] = {
8348       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8349       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8350       RISCV::X29, RISCV::X30, RISCV::X31};
8351 
8352   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8353     if (unsigned Reg = State.AllocateReg(GPRList)) {
8354       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8355       return false;
8356     }
8357   }
8358 
8359   if (LocVT == MVT::f16) {
8360     static const MCPhysReg FPR16List[] = {
8361         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8362         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8363         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8364         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8365     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8366       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8367       return false;
8368     }
8369   }
8370 
8371   if (LocVT == MVT::f32) {
8372     static const MCPhysReg FPR32List[] = {
8373         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8374         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8375         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8376         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8377     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8378       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8379       return false;
8380     }
8381   }
8382 
8383   if (LocVT == MVT::f64) {
8384     static const MCPhysReg FPR64List[] = {
8385         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8386         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8387         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8388         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8389     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8390       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8391       return false;
8392     }
8393   }
8394 
8395   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8396     unsigned Offset4 = State.AllocateStack(4, Align(4));
8397     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8398     return false;
8399   }
8400 
8401   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8402     unsigned Offset5 = State.AllocateStack(8, Align(8));
8403     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8404     return false;
8405   }
8406 
8407   if (LocVT.isVector()) {
8408     if (unsigned Reg =
8409             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8410       // Fixed-length vectors are located in the corresponding scalable-vector
8411       // container types.
8412       if (ValVT.isFixedLengthVector())
8413         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8414       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8415     } else {
8416       // Try and pass the address via a "fast" GPR.
8417       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8418         LocInfo = CCValAssign::Indirect;
8419         LocVT = TLI.getSubtarget().getXLenVT();
8420         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8421       } else if (ValVT.isFixedLengthVector()) {
8422         auto StackAlign =
8423             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8424         unsigned StackOffset =
8425             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8426         State.addLoc(
8427             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8428       } else {
8429         // Can't pass scalable vectors on the stack.
8430         return true;
8431       }
8432     }
8433 
8434     return false;
8435   }
8436 
8437   return true; // CC didn't match.
8438 }
8439 
8440 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8441                          CCValAssign::LocInfo LocInfo,
8442                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8443 
8444   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8445     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8446     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8447     static const MCPhysReg GPRList[] = {
8448         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8449         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8450     if (unsigned Reg = State.AllocateReg(GPRList)) {
8451       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8452       return false;
8453     }
8454   }
8455 
8456   if (LocVT == MVT::f32) {
8457     // Pass in STG registers: F1, ..., F6
8458     //                        fs0 ... fs5
8459     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8460                                           RISCV::F18_F, RISCV::F19_F,
8461                                           RISCV::F20_F, RISCV::F21_F};
8462     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8463       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8464       return false;
8465     }
8466   }
8467 
8468   if (LocVT == MVT::f64) {
8469     // Pass in STG registers: D1, ..., D6
8470     //                        fs6 ... fs11
8471     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8472                                           RISCV::F24_D, RISCV::F25_D,
8473                                           RISCV::F26_D, RISCV::F27_D};
8474     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8475       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8476       return false;
8477     }
8478   }
8479 
8480   report_fatal_error("No registers left in GHC calling convention");
8481   return true;
8482 }
8483 
8484 // Transform physical registers into virtual registers.
8485 SDValue RISCVTargetLowering::LowerFormalArguments(
8486     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8487     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8488     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8489 
8490   MachineFunction &MF = DAG.getMachineFunction();
8491 
8492   switch (CallConv) {
8493   default:
8494     report_fatal_error("Unsupported calling convention");
8495   case CallingConv::C:
8496   case CallingConv::Fast:
8497     break;
8498   case CallingConv::GHC:
8499     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8500         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8501       report_fatal_error(
8502         "GHC calling convention requires the F and D instruction set extensions");
8503   }
8504 
8505   const Function &Func = MF.getFunction();
8506   if (Func.hasFnAttribute("interrupt")) {
8507     if (!Func.arg_empty())
8508       report_fatal_error(
8509         "Functions with the interrupt attribute cannot have arguments!");
8510 
8511     StringRef Kind =
8512       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8513 
8514     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8515       report_fatal_error(
8516         "Function interrupt attribute argument not supported!");
8517   }
8518 
8519   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8520   MVT XLenVT = Subtarget.getXLenVT();
8521   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8522   // Used with vargs to acumulate store chains.
8523   std::vector<SDValue> OutChains;
8524 
8525   // Assign locations to all of the incoming arguments.
8526   SmallVector<CCValAssign, 16> ArgLocs;
8527   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8528 
8529   if (CallConv == CallingConv::GHC)
8530     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8531   else
8532     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8533                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8534                                                    : CC_RISCV);
8535 
8536   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8537     CCValAssign &VA = ArgLocs[i];
8538     SDValue ArgValue;
8539     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8540     // case.
8541     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8542       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8543     else if (VA.isRegLoc())
8544       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8545     else
8546       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8547 
8548     if (VA.getLocInfo() == CCValAssign::Indirect) {
8549       // If the original argument was split and passed by reference (e.g. i128
8550       // on RV32), we need to load all parts of it here (using the same
8551       // address). Vectors may be partly split to registers and partly to the
8552       // stack, in which case the base address is partly offset and subsequent
8553       // stores are relative to that.
8554       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8555                                    MachinePointerInfo()));
8556       unsigned ArgIndex = Ins[i].OrigArgIndex;
8557       unsigned ArgPartOffset = Ins[i].PartOffset;
8558       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8559       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8560         CCValAssign &PartVA = ArgLocs[i + 1];
8561         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8562         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8563         if (PartVA.getValVT().isScalableVector())
8564           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8565         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8566         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8567                                      MachinePointerInfo()));
8568         ++i;
8569       }
8570       continue;
8571     }
8572     InVals.push_back(ArgValue);
8573   }
8574 
8575   if (IsVarArg) {
8576     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8577     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8578     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8579     MachineFrameInfo &MFI = MF.getFrameInfo();
8580     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8581     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8582 
8583     // Offset of the first variable argument from stack pointer, and size of
8584     // the vararg save area. For now, the varargs save area is either zero or
8585     // large enough to hold a0-a7.
8586     int VaArgOffset, VarArgsSaveSize;
8587 
8588     // If all registers are allocated, then all varargs must be passed on the
8589     // stack and we don't need to save any argregs.
8590     if (ArgRegs.size() == Idx) {
8591       VaArgOffset = CCInfo.getNextStackOffset();
8592       VarArgsSaveSize = 0;
8593     } else {
8594       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8595       VaArgOffset = -VarArgsSaveSize;
8596     }
8597 
8598     // Record the frame index of the first variable argument
8599     // which is a value necessary to VASTART.
8600     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8601     RVFI->setVarArgsFrameIndex(FI);
8602 
8603     // If saving an odd number of registers then create an extra stack slot to
8604     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8605     // offsets to even-numbered registered remain 2*XLEN-aligned.
8606     if (Idx % 2) {
8607       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8608       VarArgsSaveSize += XLenInBytes;
8609     }
8610 
8611     // Copy the integer registers that may have been used for passing varargs
8612     // to the vararg save area.
8613     for (unsigned I = Idx; I < ArgRegs.size();
8614          ++I, VaArgOffset += XLenInBytes) {
8615       const Register Reg = RegInfo.createVirtualRegister(RC);
8616       RegInfo.addLiveIn(ArgRegs[I], Reg);
8617       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8618       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8619       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8620       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8621                                    MachinePointerInfo::getFixedStack(MF, FI));
8622       cast<StoreSDNode>(Store.getNode())
8623           ->getMemOperand()
8624           ->setValue((Value *)nullptr);
8625       OutChains.push_back(Store);
8626     }
8627     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8628   }
8629 
8630   // All stores are grouped in one node to allow the matching between
8631   // the size of Ins and InVals. This only happens for vararg functions.
8632   if (!OutChains.empty()) {
8633     OutChains.push_back(Chain);
8634     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8635   }
8636 
8637   return Chain;
8638 }
8639 
8640 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8641 /// for tail call optimization.
8642 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8643 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8644     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8645     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8646 
8647   auto &Callee = CLI.Callee;
8648   auto CalleeCC = CLI.CallConv;
8649   auto &Outs = CLI.Outs;
8650   auto &Caller = MF.getFunction();
8651   auto CallerCC = Caller.getCallingConv();
8652 
8653   // Exception-handling functions need a special set of instructions to
8654   // indicate a return to the hardware. Tail-calling another function would
8655   // probably break this.
8656   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8657   // should be expanded as new function attributes are introduced.
8658   if (Caller.hasFnAttribute("interrupt"))
8659     return false;
8660 
8661   // Do not tail call opt if the stack is used to pass parameters.
8662   if (CCInfo.getNextStackOffset() != 0)
8663     return false;
8664 
8665   // Do not tail call opt if any parameters need to be passed indirectly.
8666   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8667   // passed indirectly. So the address of the value will be passed in a
8668   // register, or if not available, then the address is put on the stack. In
8669   // order to pass indirectly, space on the stack often needs to be allocated
8670   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8671   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8672   // are passed CCValAssign::Indirect.
8673   for (auto &VA : ArgLocs)
8674     if (VA.getLocInfo() == CCValAssign::Indirect)
8675       return false;
8676 
8677   // Do not tail call opt if either caller or callee uses struct return
8678   // semantics.
8679   auto IsCallerStructRet = Caller.hasStructRetAttr();
8680   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8681   if (IsCallerStructRet || IsCalleeStructRet)
8682     return false;
8683 
8684   // Externally-defined functions with weak linkage should not be
8685   // tail-called. The behaviour of branch instructions in this situation (as
8686   // used for tail calls) is implementation-defined, so we cannot rely on the
8687   // linker replacing the tail call with a return.
8688   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8689     const GlobalValue *GV = G->getGlobal();
8690     if (GV->hasExternalWeakLinkage())
8691       return false;
8692   }
8693 
8694   // The callee has to preserve all registers the caller needs to preserve.
8695   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8696   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8697   if (CalleeCC != CallerCC) {
8698     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8699     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8700       return false;
8701   }
8702 
8703   // Byval parameters hand the function a pointer directly into the stack area
8704   // we want to reuse during a tail call. Working around this *is* possible
8705   // but less efficient and uglier in LowerCall.
8706   for (auto &Arg : Outs)
8707     if (Arg.Flags.isByVal())
8708       return false;
8709 
8710   return true;
8711 }
8712 
8713 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8714   return DAG.getDataLayout().getPrefTypeAlign(
8715       VT.getTypeForEVT(*DAG.getContext()));
8716 }
8717 
8718 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8719 // and output parameter nodes.
8720 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8721                                        SmallVectorImpl<SDValue> &InVals) const {
8722   SelectionDAG &DAG = CLI.DAG;
8723   SDLoc &DL = CLI.DL;
8724   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8725   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8726   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8727   SDValue Chain = CLI.Chain;
8728   SDValue Callee = CLI.Callee;
8729   bool &IsTailCall = CLI.IsTailCall;
8730   CallingConv::ID CallConv = CLI.CallConv;
8731   bool IsVarArg = CLI.IsVarArg;
8732   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8733   MVT XLenVT = Subtarget.getXLenVT();
8734 
8735   MachineFunction &MF = DAG.getMachineFunction();
8736 
8737   // Analyze the operands of the call, assigning locations to each operand.
8738   SmallVector<CCValAssign, 16> ArgLocs;
8739   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8740 
8741   if (CallConv == CallingConv::GHC)
8742     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8743   else
8744     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8745                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8746                                                     : CC_RISCV);
8747 
8748   // Check if it's really possible to do a tail call.
8749   if (IsTailCall)
8750     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8751 
8752   if (IsTailCall)
8753     ++NumTailCalls;
8754   else if (CLI.CB && CLI.CB->isMustTailCall())
8755     report_fatal_error("failed to perform tail call elimination on a call "
8756                        "site marked musttail");
8757 
8758   // Get a count of how many bytes are to be pushed on the stack.
8759   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8760 
8761   // Create local copies for byval args
8762   SmallVector<SDValue, 8> ByValArgs;
8763   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8764     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8765     if (!Flags.isByVal())
8766       continue;
8767 
8768     SDValue Arg = OutVals[i];
8769     unsigned Size = Flags.getByValSize();
8770     Align Alignment = Flags.getNonZeroByValAlign();
8771 
8772     int FI =
8773         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8774     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8775     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8776 
8777     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8778                           /*IsVolatile=*/false,
8779                           /*AlwaysInline=*/false, IsTailCall,
8780                           MachinePointerInfo(), MachinePointerInfo());
8781     ByValArgs.push_back(FIPtr);
8782   }
8783 
8784   if (!IsTailCall)
8785     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8786 
8787   // Copy argument values to their designated locations.
8788   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8789   SmallVector<SDValue, 8> MemOpChains;
8790   SDValue StackPtr;
8791   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8792     CCValAssign &VA = ArgLocs[i];
8793     SDValue ArgValue = OutVals[i];
8794     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8795 
8796     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8797     bool IsF64OnRV32DSoftABI =
8798         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8799     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8800       SDValue SplitF64 = DAG.getNode(
8801           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8802       SDValue Lo = SplitF64.getValue(0);
8803       SDValue Hi = SplitF64.getValue(1);
8804 
8805       Register RegLo = VA.getLocReg();
8806       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8807 
8808       if (RegLo == RISCV::X17) {
8809         // Second half of f64 is passed on the stack.
8810         // Work out the address of the stack slot.
8811         if (!StackPtr.getNode())
8812           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8813         // Emit the store.
8814         MemOpChains.push_back(
8815             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8816       } else {
8817         // Second half of f64 is passed in another GPR.
8818         assert(RegLo < RISCV::X31 && "Invalid register pair");
8819         Register RegHigh = RegLo + 1;
8820         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8821       }
8822       continue;
8823     }
8824 
8825     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8826     // as any other MemLoc.
8827 
8828     // Promote the value if needed.
8829     // For now, only handle fully promoted and indirect arguments.
8830     if (VA.getLocInfo() == CCValAssign::Indirect) {
8831       // Store the argument in a stack slot and pass its address.
8832       Align StackAlign =
8833           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8834                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8835       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8836       // If the original argument was split (e.g. i128), we need
8837       // to store the required parts of it here (and pass just one address).
8838       // Vectors may be partly split to registers and partly to the stack, in
8839       // which case the base address is partly offset and subsequent stores are
8840       // relative to that.
8841       unsigned ArgIndex = Outs[i].OrigArgIndex;
8842       unsigned ArgPartOffset = Outs[i].PartOffset;
8843       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8844       // Calculate the total size to store. We don't have access to what we're
8845       // actually storing other than performing the loop and collecting the
8846       // info.
8847       SmallVector<std::pair<SDValue, SDValue>> Parts;
8848       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8849         SDValue PartValue = OutVals[i + 1];
8850         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8851         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8852         EVT PartVT = PartValue.getValueType();
8853         if (PartVT.isScalableVector())
8854           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8855         StoredSize += PartVT.getStoreSize();
8856         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8857         Parts.push_back(std::make_pair(PartValue, Offset));
8858         ++i;
8859       }
8860       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8861       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8862       MemOpChains.push_back(
8863           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8864                        MachinePointerInfo::getFixedStack(MF, FI)));
8865       for (const auto &Part : Parts) {
8866         SDValue PartValue = Part.first;
8867         SDValue PartOffset = Part.second;
8868         SDValue Address =
8869             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8870         MemOpChains.push_back(
8871             DAG.getStore(Chain, DL, PartValue, Address,
8872                          MachinePointerInfo::getFixedStack(MF, FI)));
8873       }
8874       ArgValue = SpillSlot;
8875     } else {
8876       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8877     }
8878 
8879     // Use local copy if it is a byval arg.
8880     if (Flags.isByVal())
8881       ArgValue = ByValArgs[j++];
8882 
8883     if (VA.isRegLoc()) {
8884       // Queue up the argument copies and emit them at the end.
8885       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8886     } else {
8887       assert(VA.isMemLoc() && "Argument not register or memory");
8888       assert(!IsTailCall && "Tail call not allowed if stack is used "
8889                             "for passing parameters");
8890 
8891       // Work out the address of the stack slot.
8892       if (!StackPtr.getNode())
8893         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8894       SDValue Address =
8895           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8896                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8897 
8898       // Emit the store.
8899       MemOpChains.push_back(
8900           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8901     }
8902   }
8903 
8904   // Join the stores, which are independent of one another.
8905   if (!MemOpChains.empty())
8906     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8907 
8908   SDValue Glue;
8909 
8910   // Build a sequence of copy-to-reg nodes, chained and glued together.
8911   for (auto &Reg : RegsToPass) {
8912     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8913     Glue = Chain.getValue(1);
8914   }
8915 
8916   // Validate that none of the argument registers have been marked as
8917   // reserved, if so report an error. Do the same for the return address if this
8918   // is not a tailcall.
8919   validateCCReservedRegs(RegsToPass, MF);
8920   if (!IsTailCall &&
8921       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8922     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8923         MF.getFunction(),
8924         "Return address register required, but has been reserved."});
8925 
8926   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8927   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8928   // split it and then direct call can be matched by PseudoCALL.
8929   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8930     const GlobalValue *GV = S->getGlobal();
8931 
8932     unsigned OpFlags = RISCVII::MO_CALL;
8933     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8934       OpFlags = RISCVII::MO_PLT;
8935 
8936     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8937   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8938     unsigned OpFlags = RISCVII::MO_CALL;
8939 
8940     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8941                                                  nullptr))
8942       OpFlags = RISCVII::MO_PLT;
8943 
8944     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8945   }
8946 
8947   // The first call operand is the chain and the second is the target address.
8948   SmallVector<SDValue, 8> Ops;
8949   Ops.push_back(Chain);
8950   Ops.push_back(Callee);
8951 
8952   // Add argument registers to the end of the list so that they are
8953   // known live into the call.
8954   for (auto &Reg : RegsToPass)
8955     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8956 
8957   if (!IsTailCall) {
8958     // Add a register mask operand representing the call-preserved registers.
8959     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8960     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8961     assert(Mask && "Missing call preserved mask for calling convention");
8962     Ops.push_back(DAG.getRegisterMask(Mask));
8963   }
8964 
8965   // Glue the call to the argument copies, if any.
8966   if (Glue.getNode())
8967     Ops.push_back(Glue);
8968 
8969   // Emit the call.
8970   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8971 
8972   if (IsTailCall) {
8973     MF.getFrameInfo().setHasTailCall();
8974     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8975   }
8976 
8977   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8978   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8979   Glue = Chain.getValue(1);
8980 
8981   // Mark the end of the call, which is glued to the call itself.
8982   Chain = DAG.getCALLSEQ_END(Chain,
8983                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8984                              DAG.getConstant(0, DL, PtrVT, true),
8985                              Glue, DL);
8986   Glue = Chain.getValue(1);
8987 
8988   // Assign locations to each value returned by this call.
8989   SmallVector<CCValAssign, 16> RVLocs;
8990   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8991   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8992 
8993   // Copy all of the result registers out of their specified physreg.
8994   for (auto &VA : RVLocs) {
8995     // Copy the value out
8996     SDValue RetValue =
8997         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
8998     // Glue the RetValue to the end of the call sequence
8999     Chain = RetValue.getValue(1);
9000     Glue = RetValue.getValue(2);
9001 
9002     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9003       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9004       SDValue RetValue2 =
9005           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9006       Chain = RetValue2.getValue(1);
9007       Glue = RetValue2.getValue(2);
9008       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9009                              RetValue2);
9010     }
9011 
9012     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9013 
9014     InVals.push_back(RetValue);
9015   }
9016 
9017   return Chain;
9018 }
9019 
9020 bool RISCVTargetLowering::CanLowerReturn(
9021     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9022     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9023   SmallVector<CCValAssign, 16> RVLocs;
9024   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9025 
9026   Optional<unsigned> FirstMaskArgument;
9027   if (Subtarget.hasVInstructions())
9028     FirstMaskArgument = preAssignMask(Outs);
9029 
9030   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9031     MVT VT = Outs[i].VT;
9032     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9033     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9034     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9035                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9036                  *this, FirstMaskArgument))
9037       return false;
9038   }
9039   return true;
9040 }
9041 
9042 SDValue
9043 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9044                                  bool IsVarArg,
9045                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9046                                  const SmallVectorImpl<SDValue> &OutVals,
9047                                  const SDLoc &DL, SelectionDAG &DAG) const {
9048   const MachineFunction &MF = DAG.getMachineFunction();
9049   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9050 
9051   // Stores the assignment of the return value to a location.
9052   SmallVector<CCValAssign, 16> RVLocs;
9053 
9054   // Info about the registers and stack slot.
9055   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9056                  *DAG.getContext());
9057 
9058   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9059                     nullptr, CC_RISCV);
9060 
9061   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9062     report_fatal_error("GHC functions return void only");
9063 
9064   SDValue Glue;
9065   SmallVector<SDValue, 4> RetOps(1, Chain);
9066 
9067   // Copy the result values into the output registers.
9068   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9069     SDValue Val = OutVals[i];
9070     CCValAssign &VA = RVLocs[i];
9071     assert(VA.isRegLoc() && "Can only return in registers!");
9072 
9073     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9074       // Handle returning f64 on RV32D with a soft float ABI.
9075       assert(VA.isRegLoc() && "Expected return via registers");
9076       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9077                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9078       SDValue Lo = SplitF64.getValue(0);
9079       SDValue Hi = SplitF64.getValue(1);
9080       Register RegLo = VA.getLocReg();
9081       assert(RegLo < RISCV::X31 && "Invalid register pair");
9082       Register RegHi = RegLo + 1;
9083 
9084       if (STI.isRegisterReservedByUser(RegLo) ||
9085           STI.isRegisterReservedByUser(RegHi))
9086         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9087             MF.getFunction(),
9088             "Return value register required, but has been reserved."});
9089 
9090       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9091       Glue = Chain.getValue(1);
9092       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9093       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9094       Glue = Chain.getValue(1);
9095       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9096     } else {
9097       // Handle a 'normal' return.
9098       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9099       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9100 
9101       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9102         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9103             MF.getFunction(),
9104             "Return value register required, but has been reserved."});
9105 
9106       // Guarantee that all emitted copies are stuck together.
9107       Glue = Chain.getValue(1);
9108       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9109     }
9110   }
9111 
9112   RetOps[0] = Chain; // Update chain.
9113 
9114   // Add the glue node if we have it.
9115   if (Glue.getNode()) {
9116     RetOps.push_back(Glue);
9117   }
9118 
9119   unsigned RetOpc = RISCVISD::RET_FLAG;
9120   // Interrupt service routines use different return instructions.
9121   const Function &Func = DAG.getMachineFunction().getFunction();
9122   if (Func.hasFnAttribute("interrupt")) {
9123     if (!Func.getReturnType()->isVoidTy())
9124       report_fatal_error(
9125           "Functions with the interrupt attribute must have void return type!");
9126 
9127     MachineFunction &MF = DAG.getMachineFunction();
9128     StringRef Kind =
9129       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9130 
9131     if (Kind == "user")
9132       RetOpc = RISCVISD::URET_FLAG;
9133     else if (Kind == "supervisor")
9134       RetOpc = RISCVISD::SRET_FLAG;
9135     else
9136       RetOpc = RISCVISD::MRET_FLAG;
9137   }
9138 
9139   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9140 }
9141 
9142 void RISCVTargetLowering::validateCCReservedRegs(
9143     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9144     MachineFunction &MF) const {
9145   const Function &F = MF.getFunction();
9146   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9147 
9148   if (llvm::any_of(Regs, [&STI](auto Reg) {
9149         return STI.isRegisterReservedByUser(Reg.first);
9150       }))
9151     F.getContext().diagnose(DiagnosticInfoUnsupported{
9152         F, "Argument register required, but has been reserved."});
9153 }
9154 
9155 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9156   return CI->isTailCall();
9157 }
9158 
9159 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9160 #define NODE_NAME_CASE(NODE)                                                   \
9161   case RISCVISD::NODE:                                                         \
9162     return "RISCVISD::" #NODE;
9163   // clang-format off
9164   switch ((RISCVISD::NodeType)Opcode) {
9165   case RISCVISD::FIRST_NUMBER:
9166     break;
9167   NODE_NAME_CASE(RET_FLAG)
9168   NODE_NAME_CASE(URET_FLAG)
9169   NODE_NAME_CASE(SRET_FLAG)
9170   NODE_NAME_CASE(MRET_FLAG)
9171   NODE_NAME_CASE(CALL)
9172   NODE_NAME_CASE(SELECT_CC)
9173   NODE_NAME_CASE(BR_CC)
9174   NODE_NAME_CASE(BuildPairF64)
9175   NODE_NAME_CASE(SplitF64)
9176   NODE_NAME_CASE(TAIL)
9177   NODE_NAME_CASE(MULHSU)
9178   NODE_NAME_CASE(SLLW)
9179   NODE_NAME_CASE(SRAW)
9180   NODE_NAME_CASE(SRLW)
9181   NODE_NAME_CASE(DIVW)
9182   NODE_NAME_CASE(DIVUW)
9183   NODE_NAME_CASE(REMUW)
9184   NODE_NAME_CASE(ROLW)
9185   NODE_NAME_CASE(RORW)
9186   NODE_NAME_CASE(CLZW)
9187   NODE_NAME_CASE(CTZW)
9188   NODE_NAME_CASE(FSLW)
9189   NODE_NAME_CASE(FSRW)
9190   NODE_NAME_CASE(FSL)
9191   NODE_NAME_CASE(FSR)
9192   NODE_NAME_CASE(FMV_H_X)
9193   NODE_NAME_CASE(FMV_X_ANYEXTH)
9194   NODE_NAME_CASE(FMV_W_X_RV64)
9195   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9196   NODE_NAME_CASE(FCVT_X_RTZ)
9197   NODE_NAME_CASE(FCVT_XU_RTZ)
9198   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9199   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9200   NODE_NAME_CASE(READ_CYCLE_WIDE)
9201   NODE_NAME_CASE(GREV)
9202   NODE_NAME_CASE(GREVW)
9203   NODE_NAME_CASE(GORC)
9204   NODE_NAME_CASE(GORCW)
9205   NODE_NAME_CASE(SHFL)
9206   NODE_NAME_CASE(SHFLW)
9207   NODE_NAME_CASE(UNSHFL)
9208   NODE_NAME_CASE(UNSHFLW)
9209   NODE_NAME_CASE(BCOMPRESS)
9210   NODE_NAME_CASE(BCOMPRESSW)
9211   NODE_NAME_CASE(BDECOMPRESS)
9212   NODE_NAME_CASE(BDECOMPRESSW)
9213   NODE_NAME_CASE(VMV_V_X_VL)
9214   NODE_NAME_CASE(VFMV_V_F_VL)
9215   NODE_NAME_CASE(VMV_X_S)
9216   NODE_NAME_CASE(VMV_S_X_VL)
9217   NODE_NAME_CASE(VFMV_S_F_VL)
9218   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9219   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9220   NODE_NAME_CASE(READ_VLENB)
9221   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9222   NODE_NAME_CASE(VSLIDEUP_VL)
9223   NODE_NAME_CASE(VSLIDE1UP_VL)
9224   NODE_NAME_CASE(VSLIDEDOWN_VL)
9225   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9226   NODE_NAME_CASE(VID_VL)
9227   NODE_NAME_CASE(VFNCVT_ROD_VL)
9228   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9229   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9230   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9231   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9232   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9233   NODE_NAME_CASE(VECREDUCE_AND_VL)
9234   NODE_NAME_CASE(VECREDUCE_OR_VL)
9235   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9236   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9237   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9238   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9239   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9240   NODE_NAME_CASE(ADD_VL)
9241   NODE_NAME_CASE(AND_VL)
9242   NODE_NAME_CASE(MUL_VL)
9243   NODE_NAME_CASE(OR_VL)
9244   NODE_NAME_CASE(SDIV_VL)
9245   NODE_NAME_CASE(SHL_VL)
9246   NODE_NAME_CASE(SREM_VL)
9247   NODE_NAME_CASE(SRA_VL)
9248   NODE_NAME_CASE(SRL_VL)
9249   NODE_NAME_CASE(SUB_VL)
9250   NODE_NAME_CASE(UDIV_VL)
9251   NODE_NAME_CASE(UREM_VL)
9252   NODE_NAME_CASE(XOR_VL)
9253   NODE_NAME_CASE(SADDSAT_VL)
9254   NODE_NAME_CASE(UADDSAT_VL)
9255   NODE_NAME_CASE(SSUBSAT_VL)
9256   NODE_NAME_CASE(USUBSAT_VL)
9257   NODE_NAME_CASE(FADD_VL)
9258   NODE_NAME_CASE(FSUB_VL)
9259   NODE_NAME_CASE(FMUL_VL)
9260   NODE_NAME_CASE(FDIV_VL)
9261   NODE_NAME_CASE(FNEG_VL)
9262   NODE_NAME_CASE(FABS_VL)
9263   NODE_NAME_CASE(FSQRT_VL)
9264   NODE_NAME_CASE(FMA_VL)
9265   NODE_NAME_CASE(FCOPYSIGN_VL)
9266   NODE_NAME_CASE(SMIN_VL)
9267   NODE_NAME_CASE(SMAX_VL)
9268   NODE_NAME_CASE(UMIN_VL)
9269   NODE_NAME_CASE(UMAX_VL)
9270   NODE_NAME_CASE(FMINNUM_VL)
9271   NODE_NAME_CASE(FMAXNUM_VL)
9272   NODE_NAME_CASE(MULHS_VL)
9273   NODE_NAME_CASE(MULHU_VL)
9274   NODE_NAME_CASE(FP_TO_SINT_VL)
9275   NODE_NAME_CASE(FP_TO_UINT_VL)
9276   NODE_NAME_CASE(SINT_TO_FP_VL)
9277   NODE_NAME_CASE(UINT_TO_FP_VL)
9278   NODE_NAME_CASE(FP_EXTEND_VL)
9279   NODE_NAME_CASE(FP_ROUND_VL)
9280   NODE_NAME_CASE(VWMUL_VL)
9281   NODE_NAME_CASE(VWMULU_VL)
9282   NODE_NAME_CASE(SETCC_VL)
9283   NODE_NAME_CASE(VSELECT_VL)
9284   NODE_NAME_CASE(VMAND_VL)
9285   NODE_NAME_CASE(VMOR_VL)
9286   NODE_NAME_CASE(VMXOR_VL)
9287   NODE_NAME_CASE(VMCLR_VL)
9288   NODE_NAME_CASE(VMSET_VL)
9289   NODE_NAME_CASE(VRGATHER_VX_VL)
9290   NODE_NAME_CASE(VRGATHER_VV_VL)
9291   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9292   NODE_NAME_CASE(VSEXT_VL)
9293   NODE_NAME_CASE(VZEXT_VL)
9294   NODE_NAME_CASE(VCPOP_VL)
9295   NODE_NAME_CASE(VLE_VL)
9296   NODE_NAME_CASE(VSE_VL)
9297   NODE_NAME_CASE(READ_CSR)
9298   NODE_NAME_CASE(WRITE_CSR)
9299   NODE_NAME_CASE(SWAP_CSR)
9300   }
9301   // clang-format on
9302   return nullptr;
9303 #undef NODE_NAME_CASE
9304 }
9305 
9306 /// getConstraintType - Given a constraint letter, return the type of
9307 /// constraint it is for this target.
9308 RISCVTargetLowering::ConstraintType
9309 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9310   if (Constraint.size() == 1) {
9311     switch (Constraint[0]) {
9312     default:
9313       break;
9314     case 'f':
9315       return C_RegisterClass;
9316     case 'I':
9317     case 'J':
9318     case 'K':
9319       return C_Immediate;
9320     case 'A':
9321       return C_Memory;
9322     case 'S': // A symbolic address
9323       return C_Other;
9324     }
9325   } else {
9326     if (Constraint == "vr" || Constraint == "vm")
9327       return C_RegisterClass;
9328   }
9329   return TargetLowering::getConstraintType(Constraint);
9330 }
9331 
9332 std::pair<unsigned, const TargetRegisterClass *>
9333 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9334                                                   StringRef Constraint,
9335                                                   MVT VT) const {
9336   // First, see if this is a constraint that directly corresponds to a
9337   // RISCV register class.
9338   if (Constraint.size() == 1) {
9339     switch (Constraint[0]) {
9340     case 'r':
9341       return std::make_pair(0U, &RISCV::GPRRegClass);
9342     case 'f':
9343       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9344         return std::make_pair(0U, &RISCV::FPR16RegClass);
9345       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9346         return std::make_pair(0U, &RISCV::FPR32RegClass);
9347       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9348         return std::make_pair(0U, &RISCV::FPR64RegClass);
9349       break;
9350     default:
9351       break;
9352     }
9353   } else {
9354     if (Constraint == "vr") {
9355       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9356                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9357         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9358           return std::make_pair(0U, RC);
9359       }
9360     } else if (Constraint == "vm") {
9361       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9362         return std::make_pair(0U, &RISCV::VMRegClass);
9363     }
9364   }
9365 
9366   // Clang will correctly decode the usage of register name aliases into their
9367   // official names. However, other frontends like `rustc` do not. This allows
9368   // users of these frontends to use the ABI names for registers in LLVM-style
9369   // register constraints.
9370   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9371                                .Case("{zero}", RISCV::X0)
9372                                .Case("{ra}", RISCV::X1)
9373                                .Case("{sp}", RISCV::X2)
9374                                .Case("{gp}", RISCV::X3)
9375                                .Case("{tp}", RISCV::X4)
9376                                .Case("{t0}", RISCV::X5)
9377                                .Case("{t1}", RISCV::X6)
9378                                .Case("{t2}", RISCV::X7)
9379                                .Cases("{s0}", "{fp}", RISCV::X8)
9380                                .Case("{s1}", RISCV::X9)
9381                                .Case("{a0}", RISCV::X10)
9382                                .Case("{a1}", RISCV::X11)
9383                                .Case("{a2}", RISCV::X12)
9384                                .Case("{a3}", RISCV::X13)
9385                                .Case("{a4}", RISCV::X14)
9386                                .Case("{a5}", RISCV::X15)
9387                                .Case("{a6}", RISCV::X16)
9388                                .Case("{a7}", RISCV::X17)
9389                                .Case("{s2}", RISCV::X18)
9390                                .Case("{s3}", RISCV::X19)
9391                                .Case("{s4}", RISCV::X20)
9392                                .Case("{s5}", RISCV::X21)
9393                                .Case("{s6}", RISCV::X22)
9394                                .Case("{s7}", RISCV::X23)
9395                                .Case("{s8}", RISCV::X24)
9396                                .Case("{s9}", RISCV::X25)
9397                                .Case("{s10}", RISCV::X26)
9398                                .Case("{s11}", RISCV::X27)
9399                                .Case("{t3}", RISCV::X28)
9400                                .Case("{t4}", RISCV::X29)
9401                                .Case("{t5}", RISCV::X30)
9402                                .Case("{t6}", RISCV::X31)
9403                                .Default(RISCV::NoRegister);
9404   if (XRegFromAlias != RISCV::NoRegister)
9405     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9406 
9407   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9408   // TableGen record rather than the AsmName to choose registers for InlineAsm
9409   // constraints, plus we want to match those names to the widest floating point
9410   // register type available, manually select floating point registers here.
9411   //
9412   // The second case is the ABI name of the register, so that frontends can also
9413   // use the ABI names in register constraint lists.
9414   if (Subtarget.hasStdExtF()) {
9415     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9416                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9417                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9418                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9419                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9420                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9421                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9422                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9423                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9424                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9425                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9426                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9427                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9428                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9429                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9430                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9431                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9432                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9433                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9434                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9435                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9436                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9437                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9438                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9439                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9440                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9441                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9442                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9443                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9444                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9445                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9446                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9447                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9448                         .Default(RISCV::NoRegister);
9449     if (FReg != RISCV::NoRegister) {
9450       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9451       if (Subtarget.hasStdExtD()) {
9452         unsigned RegNo = FReg - RISCV::F0_F;
9453         unsigned DReg = RISCV::F0_D + RegNo;
9454         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9455       }
9456       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9457     }
9458   }
9459 
9460   if (Subtarget.hasVInstructions()) {
9461     Register VReg = StringSwitch<Register>(Constraint.lower())
9462                         .Case("{v0}", RISCV::V0)
9463                         .Case("{v1}", RISCV::V1)
9464                         .Case("{v2}", RISCV::V2)
9465                         .Case("{v3}", RISCV::V3)
9466                         .Case("{v4}", RISCV::V4)
9467                         .Case("{v5}", RISCV::V5)
9468                         .Case("{v6}", RISCV::V6)
9469                         .Case("{v7}", RISCV::V7)
9470                         .Case("{v8}", RISCV::V8)
9471                         .Case("{v9}", RISCV::V9)
9472                         .Case("{v10}", RISCV::V10)
9473                         .Case("{v11}", RISCV::V11)
9474                         .Case("{v12}", RISCV::V12)
9475                         .Case("{v13}", RISCV::V13)
9476                         .Case("{v14}", RISCV::V14)
9477                         .Case("{v15}", RISCV::V15)
9478                         .Case("{v16}", RISCV::V16)
9479                         .Case("{v17}", RISCV::V17)
9480                         .Case("{v18}", RISCV::V18)
9481                         .Case("{v19}", RISCV::V19)
9482                         .Case("{v20}", RISCV::V20)
9483                         .Case("{v21}", RISCV::V21)
9484                         .Case("{v22}", RISCV::V22)
9485                         .Case("{v23}", RISCV::V23)
9486                         .Case("{v24}", RISCV::V24)
9487                         .Case("{v25}", RISCV::V25)
9488                         .Case("{v26}", RISCV::V26)
9489                         .Case("{v27}", RISCV::V27)
9490                         .Case("{v28}", RISCV::V28)
9491                         .Case("{v29}", RISCV::V29)
9492                         .Case("{v30}", RISCV::V30)
9493                         .Case("{v31}", RISCV::V31)
9494                         .Default(RISCV::NoRegister);
9495     if (VReg != RISCV::NoRegister) {
9496       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9497         return std::make_pair(VReg, &RISCV::VMRegClass);
9498       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9499         return std::make_pair(VReg, &RISCV::VRRegClass);
9500       for (const auto *RC :
9501            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9502         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9503           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9504           return std::make_pair(VReg, RC);
9505         }
9506       }
9507     }
9508   }
9509 
9510   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9511 }
9512 
9513 unsigned
9514 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9515   // Currently only support length 1 constraints.
9516   if (ConstraintCode.size() == 1) {
9517     switch (ConstraintCode[0]) {
9518     case 'A':
9519       return InlineAsm::Constraint_A;
9520     default:
9521       break;
9522     }
9523   }
9524 
9525   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9526 }
9527 
9528 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9529     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9530     SelectionDAG &DAG) const {
9531   // Currently only support length 1 constraints.
9532   if (Constraint.length() == 1) {
9533     switch (Constraint[0]) {
9534     case 'I':
9535       // Validate & create a 12-bit signed immediate operand.
9536       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9537         uint64_t CVal = C->getSExtValue();
9538         if (isInt<12>(CVal))
9539           Ops.push_back(
9540               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9541       }
9542       return;
9543     case 'J':
9544       // Validate & create an integer zero operand.
9545       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9546         if (C->getZExtValue() == 0)
9547           Ops.push_back(
9548               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9549       return;
9550     case 'K':
9551       // Validate & create a 5-bit unsigned immediate operand.
9552       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9553         uint64_t CVal = C->getZExtValue();
9554         if (isUInt<5>(CVal))
9555           Ops.push_back(
9556               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9557       }
9558       return;
9559     case 'S':
9560       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9561         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9562                                                  GA->getValueType(0)));
9563       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9564         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9565                                                 BA->getValueType(0)));
9566       }
9567       return;
9568     default:
9569       break;
9570     }
9571   }
9572   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9573 }
9574 
9575 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9576                                                    Instruction *Inst,
9577                                                    AtomicOrdering Ord) const {
9578   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9579     return Builder.CreateFence(Ord);
9580   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9581     return Builder.CreateFence(AtomicOrdering::Release);
9582   return nullptr;
9583 }
9584 
9585 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9586                                                     Instruction *Inst,
9587                                                     AtomicOrdering Ord) const {
9588   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9589     return Builder.CreateFence(AtomicOrdering::Acquire);
9590   return nullptr;
9591 }
9592 
9593 TargetLowering::AtomicExpansionKind
9594 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9595   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9596   // point operations can't be used in an lr/sc sequence without breaking the
9597   // forward-progress guarantee.
9598   if (AI->isFloatingPointOperation())
9599     return AtomicExpansionKind::CmpXChg;
9600 
9601   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9602   if (Size == 8 || Size == 16)
9603     return AtomicExpansionKind::MaskedIntrinsic;
9604   return AtomicExpansionKind::None;
9605 }
9606 
9607 static Intrinsic::ID
9608 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9609   if (XLen == 32) {
9610     switch (BinOp) {
9611     default:
9612       llvm_unreachable("Unexpected AtomicRMW BinOp");
9613     case AtomicRMWInst::Xchg:
9614       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9615     case AtomicRMWInst::Add:
9616       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9617     case AtomicRMWInst::Sub:
9618       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9619     case AtomicRMWInst::Nand:
9620       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9621     case AtomicRMWInst::Max:
9622       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9623     case AtomicRMWInst::Min:
9624       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9625     case AtomicRMWInst::UMax:
9626       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9627     case AtomicRMWInst::UMin:
9628       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9629     }
9630   }
9631 
9632   if (XLen == 64) {
9633     switch (BinOp) {
9634     default:
9635       llvm_unreachable("Unexpected AtomicRMW BinOp");
9636     case AtomicRMWInst::Xchg:
9637       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9638     case AtomicRMWInst::Add:
9639       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9640     case AtomicRMWInst::Sub:
9641       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9642     case AtomicRMWInst::Nand:
9643       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9644     case AtomicRMWInst::Max:
9645       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9646     case AtomicRMWInst::Min:
9647       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9648     case AtomicRMWInst::UMax:
9649       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9650     case AtomicRMWInst::UMin:
9651       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9652     }
9653   }
9654 
9655   llvm_unreachable("Unexpected XLen\n");
9656 }
9657 
9658 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9659     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9660     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9661   unsigned XLen = Subtarget.getXLen();
9662   Value *Ordering =
9663       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9664   Type *Tys[] = {AlignedAddr->getType()};
9665   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9666       AI->getModule(),
9667       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9668 
9669   if (XLen == 64) {
9670     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9671     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9672     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9673   }
9674 
9675   Value *Result;
9676 
9677   // Must pass the shift amount needed to sign extend the loaded value prior
9678   // to performing a signed comparison for min/max. ShiftAmt is the number of
9679   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9680   // is the number of bits to left+right shift the value in order to
9681   // sign-extend.
9682   if (AI->getOperation() == AtomicRMWInst::Min ||
9683       AI->getOperation() == AtomicRMWInst::Max) {
9684     const DataLayout &DL = AI->getModule()->getDataLayout();
9685     unsigned ValWidth =
9686         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9687     Value *SextShamt =
9688         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9689     Result = Builder.CreateCall(LrwOpScwLoop,
9690                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9691   } else {
9692     Result =
9693         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9694   }
9695 
9696   if (XLen == 64)
9697     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9698   return Result;
9699 }
9700 
9701 TargetLowering::AtomicExpansionKind
9702 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9703     AtomicCmpXchgInst *CI) const {
9704   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9705   if (Size == 8 || Size == 16)
9706     return AtomicExpansionKind::MaskedIntrinsic;
9707   return AtomicExpansionKind::None;
9708 }
9709 
9710 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9711     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9712     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9713   unsigned XLen = Subtarget.getXLen();
9714   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9715   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9716   if (XLen == 64) {
9717     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9718     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9719     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9720     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9721   }
9722   Type *Tys[] = {AlignedAddr->getType()};
9723   Function *MaskedCmpXchg =
9724       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9725   Value *Result = Builder.CreateCall(
9726       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9727   if (XLen == 64)
9728     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9729   return Result;
9730 }
9731 
9732 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9733   return false;
9734 }
9735 
9736 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9737                                                      EVT VT) const {
9738   VT = VT.getScalarType();
9739 
9740   if (!VT.isSimple())
9741     return false;
9742 
9743   switch (VT.getSimpleVT().SimpleTy) {
9744   case MVT::f16:
9745     return Subtarget.hasStdExtZfh();
9746   case MVT::f32:
9747     return Subtarget.hasStdExtF();
9748   case MVT::f64:
9749     return Subtarget.hasStdExtD();
9750   default:
9751     break;
9752   }
9753 
9754   return false;
9755 }
9756 
9757 Register RISCVTargetLowering::getExceptionPointerRegister(
9758     const Constant *PersonalityFn) const {
9759   return RISCV::X10;
9760 }
9761 
9762 Register RISCVTargetLowering::getExceptionSelectorRegister(
9763     const Constant *PersonalityFn) const {
9764   return RISCV::X11;
9765 }
9766 
9767 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9768   // Return false to suppress the unnecessary extensions if the LibCall
9769   // arguments or return value is f32 type for LP64 ABI.
9770   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9771   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9772     return false;
9773 
9774   return true;
9775 }
9776 
9777 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9778   if (Subtarget.is64Bit() && Type == MVT::i32)
9779     return true;
9780 
9781   return IsSigned;
9782 }
9783 
9784 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9785                                                  SDValue C) const {
9786   // Check integral scalar types.
9787   if (VT.isScalarInteger()) {
9788     // Omit the optimization if the sub target has the M extension and the data
9789     // size exceeds XLen.
9790     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9791       return false;
9792     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9793       // Break the MUL to a SLLI and an ADD/SUB.
9794       const APInt &Imm = ConstNode->getAPIntValue();
9795       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9796           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9797         return true;
9798       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9799       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9800           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9801            (Imm - 8).isPowerOf2()))
9802         return true;
9803       // Omit the following optimization if the sub target has the M extension
9804       // and the data size >= XLen.
9805       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9806         return false;
9807       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9808       // a pair of LUI/ADDI.
9809       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9810         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9811         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9812             (1 - ImmS).isPowerOf2())
9813         return true;
9814       }
9815     }
9816   }
9817 
9818   return false;
9819 }
9820 
9821 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9822     const SDValue &AddNode, const SDValue &ConstNode) const {
9823   // Let the DAGCombiner decide for vectors.
9824   EVT VT = AddNode.getValueType();
9825   if (VT.isVector())
9826     return true;
9827 
9828   // Let the DAGCombiner decide for larger types.
9829   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9830     return true;
9831 
9832   // It is worse if c1 is simm12 while c1*c2 is not.
9833   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9834   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9835   const APInt &C1 = C1Node->getAPIntValue();
9836   const APInt &C2 = C2Node->getAPIntValue();
9837   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9838     return false;
9839 
9840   // Default to true and let the DAGCombiner decide.
9841   return true;
9842 }
9843 
9844 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9845     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9846     bool *Fast) const {
9847   if (!VT.isVector())
9848     return false;
9849 
9850   EVT ElemVT = VT.getVectorElementType();
9851   if (Alignment >= ElemVT.getStoreSize()) {
9852     if (Fast)
9853       *Fast = true;
9854     return true;
9855   }
9856 
9857   return false;
9858 }
9859 
9860 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9861     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9862     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9863   bool IsABIRegCopy = CC.hasValue();
9864   EVT ValueVT = Val.getValueType();
9865   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9866     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9867     // and cast to f32.
9868     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9869     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9870     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9871                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9872     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9873     Parts[0] = Val;
9874     return true;
9875   }
9876 
9877   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9878     LLVMContext &Context = *DAG.getContext();
9879     EVT ValueEltVT = ValueVT.getVectorElementType();
9880     EVT PartEltVT = PartVT.getVectorElementType();
9881     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9882     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9883     if (PartVTBitSize % ValueVTBitSize == 0) {
9884       // If the element types are different, bitcast to the same element type of
9885       // PartVT first.
9886       if (ValueEltVT != PartEltVT) {
9887         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9888         assert(Count != 0 && "The number of element should not be zero.");
9889         EVT SameEltTypeVT =
9890             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9891         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9892       }
9893       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9894                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9895       Parts[0] = Val;
9896       return true;
9897     }
9898   }
9899   return false;
9900 }
9901 
9902 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9903     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9904     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9905   bool IsABIRegCopy = CC.hasValue();
9906   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9907     SDValue Val = Parts[0];
9908 
9909     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9910     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9911     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9912     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9913     return Val;
9914   }
9915 
9916   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9917     LLVMContext &Context = *DAG.getContext();
9918     SDValue Val = Parts[0];
9919     EVT ValueEltVT = ValueVT.getVectorElementType();
9920     EVT PartEltVT = PartVT.getVectorElementType();
9921     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9922     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9923     if (PartVTBitSize % ValueVTBitSize == 0) {
9924       EVT SameEltTypeVT = ValueVT;
9925       // If the element types are different, convert it to the same element type
9926       // of PartVT.
9927       if (ValueEltVT != PartEltVT) {
9928         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9929         assert(Count != 0 && "The number of element should not be zero.");
9930         SameEltTypeVT =
9931             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9932       }
9933       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9934                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9935       if (ValueEltVT != PartEltVT)
9936         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9937       return Val;
9938     }
9939   }
9940   return SDValue();
9941 }
9942 
9943 #define GET_REGISTER_MATCHER
9944 #include "RISCVGenAsmMatcher.inc"
9945 
9946 Register
9947 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9948                                        const MachineFunction &MF) const {
9949   Register Reg = MatchRegisterAltName(RegName);
9950   if (Reg == RISCV::NoRegister)
9951     Reg = MatchRegisterName(RegName);
9952   if (Reg == RISCV::NoRegister)
9953     report_fatal_error(
9954         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9955   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9956   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9957     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9958                              StringRef(RegName) + "\"."));
9959   return Reg;
9960 }
9961 
9962 namespace llvm {
9963 namespace RISCVVIntrinsicsTable {
9964 
9965 #define GET_RISCVVIntrinsicsTable_IMPL
9966 #include "RISCVGenSearchableTables.inc"
9967 
9968 } // namespace RISCVVIntrinsicsTable
9969 
9970 } // namespace llvm
9971