1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
174     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
185   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction(ISD::VAARG, MVT::Other, Expand);
189   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190   setOperationAction(ISD::VAEND, MVT::Other, Expand);
191 
192   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193   if (!Subtarget.hasStdExtZbb()) {
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
195     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
196   }
197 
198   if (Subtarget.is64Bit()) {
199     setOperationAction(ISD::ADD, MVT::i32, Custom);
200     setOperationAction(ISD::SUB, MVT::i32, Custom);
201     setOperationAction(ISD::SHL, MVT::i32, Custom);
202     setOperationAction(ISD::SRA, MVT::i32, Custom);
203     setOperationAction(ISD::SRL, MVT::i32, Custom);
204 
205     setOperationAction(ISD::UADDO, MVT::i32, Custom);
206     setOperationAction(ISD::USUBO, MVT::i32, Custom);
207     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
208     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
209   } else {
210     setLibcallName(RTLIB::SHL_I128, nullptr);
211     setLibcallName(RTLIB::SRL_I128, nullptr);
212     setLibcallName(RTLIB::SRA_I128, nullptr);
213     setLibcallName(RTLIB::MUL_I128, nullptr);
214     setLibcallName(RTLIB::MULO_I64, nullptr);
215   }
216 
217   if (!Subtarget.hasStdExtM()) {
218     setOperationAction(ISD::MUL, XLenVT, Expand);
219     setOperationAction(ISD::MULHS, XLenVT, Expand);
220     setOperationAction(ISD::MULHU, XLenVT, Expand);
221     setOperationAction(ISD::SDIV, XLenVT, Expand);
222     setOperationAction(ISD::UDIV, XLenVT, Expand);
223     setOperationAction(ISD::SREM, XLenVT, Expand);
224     setOperationAction(ISD::UREM, XLenVT, Expand);
225   } else {
226     if (Subtarget.is64Bit()) {
227       setOperationAction(ISD::MUL, MVT::i32, Custom);
228       setOperationAction(ISD::MUL, MVT::i128, Custom);
229 
230       setOperationAction(ISD::SDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UDIV, MVT::i8, Custom);
232       setOperationAction(ISD::UREM, MVT::i8, Custom);
233       setOperationAction(ISD::SDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UDIV, MVT::i16, Custom);
235       setOperationAction(ISD::UREM, MVT::i16, Custom);
236       setOperationAction(ISD::SDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UDIV, MVT::i32, Custom);
238       setOperationAction(ISD::UREM, MVT::i32, Custom);
239     } else {
240       setOperationAction(ISD::MUL, MVT::i64, Custom);
241     }
242   }
243 
244   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
246   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
247   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
248 
249   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
251   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
252 
253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
254       Subtarget.hasStdExtZbkb()) {
255     if (Subtarget.is64Bit()) {
256       setOperationAction(ISD::ROTL, MVT::i32, Custom);
257       setOperationAction(ISD::ROTR, MVT::i32, Custom);
258     }
259   } else {
260     setOperationAction(ISD::ROTL, XLenVT, Expand);
261     setOperationAction(ISD::ROTR, XLenVT, Expand);
262   }
263 
264   if (Subtarget.hasStdExtZbp()) {
265     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
266     // more combining.
267     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
268     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
269     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
270     // BSWAP i8 doesn't exist.
271     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
272     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
273 
274     if (Subtarget.is64Bit()) {
275       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
276       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
277     }
278   } else {
279     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
280     // pattern match it directly in isel.
281     setOperationAction(ISD::BSWAP, XLenVT,
282                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
283                            ? Legal
284                            : Expand);
285     // Zbkb can use rev8+brev8 to implement bitreverse.
286     setOperationAction(ISD::BITREVERSE, XLenVT,
287                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
288   }
289 
290   if (Subtarget.hasStdExtZbb()) {
291     setOperationAction(ISD::SMIN, XLenVT, Legal);
292     setOperationAction(ISD::SMAX, XLenVT, Legal);
293     setOperationAction(ISD::UMIN, XLenVT, Legal);
294     setOperationAction(ISD::UMAX, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit()) {
297       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
298       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
299       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
300       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
301     }
302   } else {
303     setOperationAction(ISD::CTTZ, XLenVT, Expand);
304     setOperationAction(ISD::CTLZ, XLenVT, Expand);
305     setOperationAction(ISD::CTPOP, XLenVT, Expand);
306 
307     if (Subtarget.is64Bit())
308       setOperationAction(ISD::ABS, MVT::i32, Custom);
309   }
310 
311   if (Subtarget.hasStdExtZbt()) {
312     setOperationAction(ISD::FSHL, XLenVT, Custom);
313     setOperationAction(ISD::FSHR, XLenVT, Custom);
314     setOperationAction(ISD::SELECT, XLenVT, Legal);
315 
316     if (Subtarget.is64Bit()) {
317       setOperationAction(ISD::FSHL, MVT::i32, Custom);
318       setOperationAction(ISD::FSHR, MVT::i32, Custom);
319     }
320   } else {
321     setOperationAction(ISD::SELECT, XLenVT, Custom);
322   }
323 
324   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
325       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
326       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
327       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
328       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
329       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
330       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
331 
332   static const ISD::CondCode FPCCToExpand[] = {
333       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
334       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
335       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
336 
337   static const ISD::NodeType FPOpToExpand[] = {
338       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
339       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
340 
341   if (Subtarget.hasStdExtZfh())
342     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
343 
344   if (Subtarget.hasStdExtZfh()) {
345     for (auto NT : FPLegalNodeTypes)
346       setOperationAction(NT, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
348     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
349     for (auto CC : FPCCToExpand)
350       setCondCodeAction(CC, MVT::f16, Expand);
351     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
352     setOperationAction(ISD::SELECT, MVT::f16, Custom);
353     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
354 
355     setOperationAction(ISD::FREM,       MVT::f16, Promote);
356     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
357     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
358     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
359     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
360     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
361     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
362     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
363     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
364     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
365     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
366     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
367     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
368     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
369     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
370     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
371     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
372     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
373 
374     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
375     // complete support for all operations in LegalizeDAG.
376 
377     // We need to custom promote this.
378     if (Subtarget.is64Bit())
379       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
380   }
381 
382   if (Subtarget.hasStdExtF()) {
383     for (auto NT : FPLegalNodeTypes)
384       setOperationAction(NT, MVT::f32, Legal);
385     for (auto CC : FPCCToExpand)
386       setCondCodeAction(CC, MVT::f32, Expand);
387     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
388     setOperationAction(ISD::SELECT, MVT::f32, Custom);
389     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
390     for (auto Op : FPOpToExpand)
391       setOperationAction(Op, MVT::f32, Expand);
392     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
393     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394   }
395 
396   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
397     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
398 
399   if (Subtarget.hasStdExtD()) {
400     for (auto NT : FPLegalNodeTypes)
401       setOperationAction(NT, MVT::f64, Legal);
402     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
403     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
404     for (auto CC : FPCCToExpand)
405       setCondCodeAction(CC, MVT::f64, Expand);
406     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
407     setOperationAction(ISD::SELECT, MVT::f64, Custom);
408     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
409     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
410     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
411     for (auto Op : FPOpToExpand)
412       setOperationAction(Op, MVT::f64, Expand);
413     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
414     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
415   }
416 
417   if (Subtarget.is64Bit()) {
418     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
419     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
420     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
421     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
422   }
423 
424   if (Subtarget.hasStdExtF()) {
425     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
426     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
427 
428     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
429     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
430     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
431     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
432 
433     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
434     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
435   }
436 
437   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
438   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
439   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
440   setOperationAction(ISD::JumpTable, XLenVT, Custom);
441 
442   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
443 
444   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
445   // Unfortunately this can't be determined just from the ISA naming string.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
447                      Subtarget.is64Bit() ? Legal : Custom);
448 
449   setOperationAction(ISD::TRAP, MVT::Other, Legal);
450   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
451   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
452   if (Subtarget.is64Bit())
453     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
454 
455   if (Subtarget.hasStdExtA()) {
456     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
457     setMinCmpXchgSizeInBits(32);
458   } else {
459     setMaxAtomicSizeInBitsSupported(0);
460   }
461 
462   setBooleanContents(ZeroOrOneBooleanContent);
463 
464   if (Subtarget.hasVInstructions()) {
465     setBooleanVectorContents(ZeroOrOneBooleanContent);
466 
467     setOperationAction(ISD::VSCALE, XLenVT, Custom);
468 
469     // RVV intrinsics may have illegal operands.
470     // We also need to custom legalize vmv.x.s.
471     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
472     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
473     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
474     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
475     if (Subtarget.is64Bit()) {
476       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
477     } else {
478       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
479       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
480     }
481 
482     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
483     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
484 
485     static const unsigned IntegerVPOps[] = {
486         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
487         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
488         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
489         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
490         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
491         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
492         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
493         ISD::VP_MERGE,       ISD::VP_SELECT};
494 
495     static const unsigned FloatingPointVPOps[] = {
496         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
497         ISD::VP_FDIV,        ISD::VP_FNEG,        ISD::VP_FMA,
498         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN,
499         ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,       ISD::VP_SELECT};
500 
501     if (!Subtarget.is64Bit()) {
502       // We must custom-lower certain vXi64 operations on RV32 due to the vector
503       // element type being illegal.
504       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
505       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
506 
507       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
508       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
509       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
510       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
511       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
512       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
513       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
514       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
515 
516       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
517       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
518       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
519       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
520       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
521       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
522       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
523       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
524     }
525 
526     for (MVT VT : BoolVecVTs) {
527       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
528 
529       // Mask VTs are custom-expanded into a series of standard nodes
530       setOperationAction(ISD::TRUNCATE, VT, Custom);
531       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
532       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
533       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
534 
535       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
536       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
537 
538       setOperationAction(ISD::SELECT, VT, Custom);
539       setOperationAction(ISD::SELECT_CC, VT, Expand);
540       setOperationAction(ISD::VSELECT, VT, Expand);
541       setOperationAction(ISD::VP_MERGE, VT, Expand);
542       setOperationAction(ISD::VP_SELECT, VT, Expand);
543 
544       setOperationAction(ISD::VP_AND, VT, Custom);
545       setOperationAction(ISD::VP_OR, VT, Custom);
546       setOperationAction(ISD::VP_XOR, VT, Custom);
547 
548       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
549       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
550       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
551 
552       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
553       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
554       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
555 
556       // RVV has native int->float & float->int conversions where the
557       // element type sizes are within one power-of-two of each other. Any
558       // wider distances between type sizes have to be lowered as sequences
559       // which progressively narrow the gap in stages.
560       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
561       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
562       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
563       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
564 
565       // Expand all extending loads to types larger than this, and truncating
566       // stores from types larger than this.
567       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
568         setTruncStoreAction(OtherVT, VT, Expand);
569         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
570         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
571         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
572       }
573     }
574 
575     for (MVT VT : IntVecVTs) {
576       if (VT.getVectorElementType() == MVT::i64 &&
577           !Subtarget.hasVInstructionsI64())
578         continue;
579 
580       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
581       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
582 
583       // Vectors implement MULHS/MULHU.
584       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
585       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
586 
587       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
588       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
589         setOperationAction(ISD::MULHU, VT, Expand);
590         setOperationAction(ISD::MULHS, VT, Expand);
591       }
592 
593       setOperationAction(ISD::SMIN, VT, Legal);
594       setOperationAction(ISD::SMAX, VT, Legal);
595       setOperationAction(ISD::UMIN, VT, Legal);
596       setOperationAction(ISD::UMAX, VT, Legal);
597 
598       setOperationAction(ISD::ROTL, VT, Expand);
599       setOperationAction(ISD::ROTR, VT, Expand);
600 
601       setOperationAction(ISD::CTTZ, VT, Expand);
602       setOperationAction(ISD::CTLZ, VT, Expand);
603       setOperationAction(ISD::CTPOP, VT, Expand);
604 
605       setOperationAction(ISD::BSWAP, VT, Expand);
606 
607       // Custom-lower extensions and truncations from/to mask types.
608       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
609       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
610       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
611 
612       // RVV has native int->float & float->int conversions where the
613       // element type sizes are within one power-of-two of each other. Any
614       // wider distances between type sizes have to be lowered as sequences
615       // which progressively narrow the gap in stages.
616       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
617       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
618       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
619       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
620 
621       setOperationAction(ISD::SADDSAT, VT, Legal);
622       setOperationAction(ISD::UADDSAT, VT, Legal);
623       setOperationAction(ISD::SSUBSAT, VT, Legal);
624       setOperationAction(ISD::USUBSAT, VT, Legal);
625 
626       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
627       // nodes which truncate by one power of two at a time.
628       setOperationAction(ISD::TRUNCATE, VT, Custom);
629 
630       // Custom-lower insert/extract operations to simplify patterns.
631       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
632       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
633 
634       // Custom-lower reduction operations to set up the corresponding custom
635       // nodes' operands.
636       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
637       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
638       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
639       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
640       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
641       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
642       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
643       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
644 
645       for (unsigned VPOpc : IntegerVPOps)
646         setOperationAction(VPOpc, VT, Custom);
647 
648       setOperationAction(ISD::LOAD, VT, Custom);
649       setOperationAction(ISD::STORE, VT, Custom);
650 
651       setOperationAction(ISD::MLOAD, VT, Custom);
652       setOperationAction(ISD::MSTORE, VT, Custom);
653       setOperationAction(ISD::MGATHER, VT, Custom);
654       setOperationAction(ISD::MSCATTER, VT, Custom);
655 
656       setOperationAction(ISD::VP_LOAD, VT, Custom);
657       setOperationAction(ISD::VP_STORE, VT, Custom);
658       setOperationAction(ISD::VP_GATHER, VT, Custom);
659       setOperationAction(ISD::VP_SCATTER, VT, Custom);
660 
661       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
662       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
663       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
664 
665       setOperationAction(ISD::SELECT, VT, Custom);
666       setOperationAction(ISD::SELECT_CC, VT, Expand);
667 
668       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
669       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
670 
671       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
672         setTruncStoreAction(VT, OtherVT, Expand);
673         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
674         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
675         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
676       }
677 
678       // Splice
679       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
680 
681       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
682       // type that can represent the value exactly.
683       if (VT.getVectorElementType() != MVT::i64) {
684         MVT FloatEltVT =
685             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
686         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
687         if (isTypeLegal(FloatVT)) {
688           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
689           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
690         }
691       }
692     }
693 
694     // Expand various CCs to best match the RVV ISA, which natively supports UNE
695     // but no other unordered comparisons, and supports all ordered comparisons
696     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
697     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
698     // and we pattern-match those back to the "original", swapping operands once
699     // more. This way we catch both operations and both "vf" and "fv" forms with
700     // fewer patterns.
701     static const ISD::CondCode VFPCCToExpand[] = {
702         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
703         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
704         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
705     };
706 
707     // Sets common operation actions on RVV floating-point vector types.
708     const auto SetCommonVFPActions = [&](MVT VT) {
709       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
710       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
711       // sizes are within one power-of-two of each other. Therefore conversions
712       // between vXf16 and vXf64 must be lowered as sequences which convert via
713       // vXf32.
714       setOperationAction(ISD::FP_ROUND, VT, Custom);
715       setOperationAction(ISD::FP_EXTEND, VT, Custom);
716       // Custom-lower insert/extract operations to simplify patterns.
717       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
718       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
719       // Expand various condition codes (explained above).
720       for (auto CC : VFPCCToExpand)
721         setCondCodeAction(CC, VT, Expand);
722 
723       setOperationAction(ISD::FMINNUM, VT, Legal);
724       setOperationAction(ISD::FMAXNUM, VT, Legal);
725 
726       setOperationAction(ISD::FTRUNC, VT, Custom);
727       setOperationAction(ISD::FCEIL, VT, Custom);
728       setOperationAction(ISD::FFLOOR, VT, Custom);
729       setOperationAction(ISD::FROUND, VT, Custom);
730 
731       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
732       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
733       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
734       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
735 
736       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
737 
738       setOperationAction(ISD::LOAD, VT, Custom);
739       setOperationAction(ISD::STORE, VT, Custom);
740 
741       setOperationAction(ISD::MLOAD, VT, Custom);
742       setOperationAction(ISD::MSTORE, VT, Custom);
743       setOperationAction(ISD::MGATHER, VT, Custom);
744       setOperationAction(ISD::MSCATTER, VT, Custom);
745 
746       setOperationAction(ISD::VP_LOAD, VT, Custom);
747       setOperationAction(ISD::VP_STORE, VT, Custom);
748       setOperationAction(ISD::VP_GATHER, VT, Custom);
749       setOperationAction(ISD::VP_SCATTER, VT, Custom);
750 
751       setOperationAction(ISD::SELECT, VT, Custom);
752       setOperationAction(ISD::SELECT_CC, VT, Expand);
753 
754       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
755       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
756       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
757 
758       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
759       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
760 
761       for (unsigned VPOpc : FloatingPointVPOps)
762         setOperationAction(VPOpc, VT, Custom);
763     };
764 
765     // Sets common extload/truncstore actions on RVV floating-point vector
766     // types.
767     const auto SetCommonVFPExtLoadTruncStoreActions =
768         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
769           for (auto SmallVT : SmallerVTs) {
770             setTruncStoreAction(VT, SmallVT, Expand);
771             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
772           }
773         };
774 
775     if (Subtarget.hasVInstructionsF16())
776       for (MVT VT : F16VecVTs)
777         SetCommonVFPActions(VT);
778 
779     for (MVT VT : F32VecVTs) {
780       if (Subtarget.hasVInstructionsF32())
781         SetCommonVFPActions(VT);
782       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
783     }
784 
785     for (MVT VT : F64VecVTs) {
786       if (Subtarget.hasVInstructionsF64())
787         SetCommonVFPActions(VT);
788       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
789       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
790     }
791 
792     if (Subtarget.useRVVForFixedLengthVectors()) {
793       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
794         if (!useRVVForFixedLengthVectorVT(VT))
795           continue;
796 
797         // By default everything must be expanded.
798         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
799           setOperationAction(Op, VT, Expand);
800         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
801           setTruncStoreAction(VT, OtherVT, Expand);
802           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
803           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
804           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
805         }
806 
807         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
808         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
809         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
810 
811         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
812         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
813 
814         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
815         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
816 
817         setOperationAction(ISD::LOAD, VT, Custom);
818         setOperationAction(ISD::STORE, VT, Custom);
819 
820         setOperationAction(ISD::SETCC, VT, Custom);
821 
822         setOperationAction(ISD::SELECT, VT, Custom);
823 
824         setOperationAction(ISD::TRUNCATE, VT, Custom);
825 
826         setOperationAction(ISD::BITCAST, VT, Custom);
827 
828         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
829         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
830         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
831 
832         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
833         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
834         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
835 
836         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
837         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
838         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
839         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
840 
841         // Operations below are different for between masks and other vectors.
842         if (VT.getVectorElementType() == MVT::i1) {
843           setOperationAction(ISD::VP_AND, VT, Custom);
844           setOperationAction(ISD::VP_OR, VT, Custom);
845           setOperationAction(ISD::VP_XOR, VT, Custom);
846           setOperationAction(ISD::AND, VT, Custom);
847           setOperationAction(ISD::OR, VT, Custom);
848           setOperationAction(ISD::XOR, VT, Custom);
849           continue;
850         }
851 
852         // Use SPLAT_VECTOR to prevent type legalization from destroying the
853         // splats when type legalizing i64 scalar on RV32.
854         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
855         // improvements first.
856         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
857           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
858           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
859         }
860 
861         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
862         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
863 
864         setOperationAction(ISD::MLOAD, VT, Custom);
865         setOperationAction(ISD::MSTORE, VT, Custom);
866         setOperationAction(ISD::MGATHER, VT, Custom);
867         setOperationAction(ISD::MSCATTER, VT, Custom);
868 
869         setOperationAction(ISD::VP_LOAD, VT, Custom);
870         setOperationAction(ISD::VP_STORE, VT, Custom);
871         setOperationAction(ISD::VP_GATHER, VT, Custom);
872         setOperationAction(ISD::VP_SCATTER, VT, Custom);
873 
874         setOperationAction(ISD::ADD, VT, Custom);
875         setOperationAction(ISD::MUL, VT, Custom);
876         setOperationAction(ISD::SUB, VT, Custom);
877         setOperationAction(ISD::AND, VT, Custom);
878         setOperationAction(ISD::OR, VT, Custom);
879         setOperationAction(ISD::XOR, VT, Custom);
880         setOperationAction(ISD::SDIV, VT, Custom);
881         setOperationAction(ISD::SREM, VT, Custom);
882         setOperationAction(ISD::UDIV, VT, Custom);
883         setOperationAction(ISD::UREM, VT, Custom);
884         setOperationAction(ISD::SHL, VT, Custom);
885         setOperationAction(ISD::SRA, VT, Custom);
886         setOperationAction(ISD::SRL, VT, Custom);
887 
888         setOperationAction(ISD::SMIN, VT, Custom);
889         setOperationAction(ISD::SMAX, VT, Custom);
890         setOperationAction(ISD::UMIN, VT, Custom);
891         setOperationAction(ISD::UMAX, VT, Custom);
892         setOperationAction(ISD::ABS,  VT, Custom);
893 
894         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
895         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
896           setOperationAction(ISD::MULHS, VT, Custom);
897           setOperationAction(ISD::MULHU, VT, Custom);
898         }
899 
900         setOperationAction(ISD::SADDSAT, VT, Custom);
901         setOperationAction(ISD::UADDSAT, VT, Custom);
902         setOperationAction(ISD::SSUBSAT, VT, Custom);
903         setOperationAction(ISD::USUBSAT, VT, Custom);
904 
905         setOperationAction(ISD::VSELECT, VT, Custom);
906         setOperationAction(ISD::SELECT_CC, VT, Expand);
907 
908         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
909         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
910         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
911 
912         // Custom-lower reduction operations to set up the corresponding custom
913         // nodes' operands.
914         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
915         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
916         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
917         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
918         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
919 
920         for (unsigned VPOpc : IntegerVPOps)
921           setOperationAction(VPOpc, VT, Custom);
922 
923         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
924         // type that can represent the value exactly.
925         if (VT.getVectorElementType() != MVT::i64) {
926           MVT FloatEltVT =
927               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
928           EVT FloatVT =
929               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
930           if (isTypeLegal(FloatVT)) {
931             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
932             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
933           }
934         }
935       }
936 
937       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
938         if (!useRVVForFixedLengthVectorVT(VT))
939           continue;
940 
941         // By default everything must be expanded.
942         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
943           setOperationAction(Op, VT, Expand);
944         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
945           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
946           setTruncStoreAction(VT, OtherVT, Expand);
947         }
948 
949         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
950         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
951         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
952 
953         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
954         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
955         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
956         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
957         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
958 
959         setOperationAction(ISD::LOAD, VT, Custom);
960         setOperationAction(ISD::STORE, VT, Custom);
961         setOperationAction(ISD::MLOAD, VT, Custom);
962         setOperationAction(ISD::MSTORE, VT, Custom);
963         setOperationAction(ISD::MGATHER, VT, Custom);
964         setOperationAction(ISD::MSCATTER, VT, Custom);
965 
966         setOperationAction(ISD::VP_LOAD, VT, Custom);
967         setOperationAction(ISD::VP_STORE, VT, Custom);
968         setOperationAction(ISD::VP_GATHER, VT, Custom);
969         setOperationAction(ISD::VP_SCATTER, VT, Custom);
970 
971         setOperationAction(ISD::FADD, VT, Custom);
972         setOperationAction(ISD::FSUB, VT, Custom);
973         setOperationAction(ISD::FMUL, VT, Custom);
974         setOperationAction(ISD::FDIV, VT, Custom);
975         setOperationAction(ISD::FNEG, VT, Custom);
976         setOperationAction(ISD::FABS, VT, Custom);
977         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
978         setOperationAction(ISD::FSQRT, VT, Custom);
979         setOperationAction(ISD::FMA, VT, Custom);
980         setOperationAction(ISD::FMINNUM, VT, Custom);
981         setOperationAction(ISD::FMAXNUM, VT, Custom);
982 
983         setOperationAction(ISD::FP_ROUND, VT, Custom);
984         setOperationAction(ISD::FP_EXTEND, VT, Custom);
985 
986         setOperationAction(ISD::FTRUNC, VT, Custom);
987         setOperationAction(ISD::FCEIL, VT, Custom);
988         setOperationAction(ISD::FFLOOR, VT, Custom);
989         setOperationAction(ISD::FROUND, VT, Custom);
990 
991         for (auto CC : VFPCCToExpand)
992           setCondCodeAction(CC, VT, Expand);
993 
994         setOperationAction(ISD::VSELECT, VT, Custom);
995         setOperationAction(ISD::SELECT, VT, Custom);
996         setOperationAction(ISD::SELECT_CC, VT, Expand);
997 
998         setOperationAction(ISD::BITCAST, VT, Custom);
999 
1000         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1001         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1002         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1003         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1004 
1005         for (unsigned VPOpc : FloatingPointVPOps)
1006           setOperationAction(VPOpc, VT, Custom);
1007       }
1008 
1009       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1010       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1011       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1012       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1013       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1014       if (Subtarget.hasStdExtZfh())
1015         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1016       if (Subtarget.hasStdExtF())
1017         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1018       if (Subtarget.hasStdExtD())
1019         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1020     }
1021   }
1022 
1023   // Function alignments.
1024   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1025   setMinFunctionAlignment(FunctionAlignment);
1026   setPrefFunctionAlignment(FunctionAlignment);
1027 
1028   setMinimumJumpTableEntries(5);
1029 
1030   // Jumps are expensive, compared to logic
1031   setJumpIsExpensive();
1032 
1033   setTargetDAGCombine(ISD::ADD);
1034   setTargetDAGCombine(ISD::SUB);
1035   setTargetDAGCombine(ISD::AND);
1036   setTargetDAGCombine(ISD::OR);
1037   setTargetDAGCombine(ISD::XOR);
1038   if (Subtarget.hasStdExtZbp()) {
1039     setTargetDAGCombine(ISD::ROTL);
1040     setTargetDAGCombine(ISD::ROTR);
1041   }
1042   setTargetDAGCombine(ISD::ANY_EXTEND);
1043   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1044   if (Subtarget.hasStdExtZfh())
1045     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1046   if (Subtarget.hasStdExtF()) {
1047     setTargetDAGCombine(ISD::ZERO_EXTEND);
1048     setTargetDAGCombine(ISD::FP_TO_SINT);
1049     setTargetDAGCombine(ISD::FP_TO_UINT);
1050     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1051     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1052   }
1053   if (Subtarget.hasVInstructions()) {
1054     setTargetDAGCombine(ISD::FCOPYSIGN);
1055     setTargetDAGCombine(ISD::MGATHER);
1056     setTargetDAGCombine(ISD::MSCATTER);
1057     setTargetDAGCombine(ISD::VP_GATHER);
1058     setTargetDAGCombine(ISD::VP_SCATTER);
1059     setTargetDAGCombine(ISD::SRA);
1060     setTargetDAGCombine(ISD::SRL);
1061     setTargetDAGCombine(ISD::SHL);
1062     setTargetDAGCombine(ISD::STORE);
1063     setTargetDAGCombine(ISD::SPLAT_VECTOR);
1064   }
1065 
1066   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1067   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1068 }
1069 
1070 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1071                                             LLVMContext &Context,
1072                                             EVT VT) const {
1073   if (!VT.isVector())
1074     return getPointerTy(DL);
1075   if (Subtarget.hasVInstructions() &&
1076       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1077     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1078   return VT.changeVectorElementTypeToInteger();
1079 }
1080 
1081 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1082   return Subtarget.getXLenVT();
1083 }
1084 
1085 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1086                                              const CallInst &I,
1087                                              MachineFunction &MF,
1088                                              unsigned Intrinsic) const {
1089   auto &DL = I.getModule()->getDataLayout();
1090   switch (Intrinsic) {
1091   default:
1092     return false;
1093   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1094   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1100   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1101   case Intrinsic::riscv_masked_cmpxchg_i32:
1102     Info.opc = ISD::INTRINSIC_W_CHAIN;
1103     Info.memVT = MVT::i32;
1104     Info.ptrVal = I.getArgOperand(0);
1105     Info.offset = 0;
1106     Info.align = Align(4);
1107     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1108                  MachineMemOperand::MOVolatile;
1109     return true;
1110   case Intrinsic::riscv_masked_strided_load:
1111     Info.opc = ISD::INTRINSIC_W_CHAIN;
1112     Info.ptrVal = I.getArgOperand(1);
1113     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1114     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1115     Info.size = MemoryLocation::UnknownSize;
1116     Info.flags |= MachineMemOperand::MOLoad;
1117     return true;
1118   case Intrinsic::riscv_masked_strided_store:
1119     Info.opc = ISD::INTRINSIC_VOID;
1120     Info.ptrVal = I.getArgOperand(1);
1121     Info.memVT =
1122         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1123     Info.align = Align(
1124         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1125         8);
1126     Info.size = MemoryLocation::UnknownSize;
1127     Info.flags |= MachineMemOperand::MOStore;
1128     return true;
1129   }
1130 }
1131 
1132 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1133                                                 const AddrMode &AM, Type *Ty,
1134                                                 unsigned AS,
1135                                                 Instruction *I) const {
1136   // No global is ever allowed as a base.
1137   if (AM.BaseGV)
1138     return false;
1139 
1140   // Require a 12-bit signed offset.
1141   if (!isInt<12>(AM.BaseOffs))
1142     return false;
1143 
1144   switch (AM.Scale) {
1145   case 0: // "r+i" or just "i", depending on HasBaseReg.
1146     break;
1147   case 1:
1148     if (!AM.HasBaseReg) // allow "r+i".
1149       break;
1150     return false; // disallow "r+r" or "r+r+i".
1151   default:
1152     return false;
1153   }
1154 
1155   return true;
1156 }
1157 
1158 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1159   return isInt<12>(Imm);
1160 }
1161 
1162 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1163   return isInt<12>(Imm);
1164 }
1165 
1166 // On RV32, 64-bit integers are split into their high and low parts and held
1167 // in two different registers, so the trunc is free since the low register can
1168 // just be used.
1169 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1170   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1171     return false;
1172   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1173   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1174   return (SrcBits == 64 && DestBits == 32);
1175 }
1176 
1177 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1178   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1179       !SrcVT.isInteger() || !DstVT.isInteger())
1180     return false;
1181   unsigned SrcBits = SrcVT.getSizeInBits();
1182   unsigned DestBits = DstVT.getSizeInBits();
1183   return (SrcBits == 64 && DestBits == 32);
1184 }
1185 
1186 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1187   // Zexts are free if they can be combined with a load.
1188   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1189   // poorly with type legalization of compares preferring sext.
1190   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1191     EVT MemVT = LD->getMemoryVT();
1192     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1193         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1194          LD->getExtensionType() == ISD::ZEXTLOAD))
1195       return true;
1196   }
1197 
1198   return TargetLowering::isZExtFree(Val, VT2);
1199 }
1200 
1201 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1202   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1203 }
1204 
1205 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1206   return Subtarget.hasStdExtZbb();
1207 }
1208 
1209 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1210   return Subtarget.hasStdExtZbb();
1211 }
1212 
1213 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1214   EVT VT = Y.getValueType();
1215 
1216   // FIXME: Support vectors once we have tests.
1217   if (VT.isVector())
1218     return false;
1219 
1220   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1221           Subtarget.hasStdExtZbkb()) &&
1222          !isa<ConstantSDNode>(Y);
1223 }
1224 
1225 /// Check if sinking \p I's operands to I's basic block is profitable, because
1226 /// the operands can be folded into a target instruction, e.g.
1227 /// splats of scalars can fold into vector instructions.
1228 bool RISCVTargetLowering::shouldSinkOperands(
1229     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1230   using namespace llvm::PatternMatch;
1231 
1232   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1233     return false;
1234 
1235   auto IsSinker = [&](Instruction *I, int Operand) {
1236     switch (I->getOpcode()) {
1237     case Instruction::Add:
1238     case Instruction::Sub:
1239     case Instruction::Mul:
1240     case Instruction::And:
1241     case Instruction::Or:
1242     case Instruction::Xor:
1243     case Instruction::FAdd:
1244     case Instruction::FSub:
1245     case Instruction::FMul:
1246     case Instruction::FDiv:
1247     case Instruction::ICmp:
1248     case Instruction::FCmp:
1249       return true;
1250     case Instruction::Shl:
1251     case Instruction::LShr:
1252     case Instruction::AShr:
1253     case Instruction::UDiv:
1254     case Instruction::SDiv:
1255     case Instruction::URem:
1256     case Instruction::SRem:
1257       return Operand == 1;
1258     case Instruction::Call:
1259       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1260         switch (II->getIntrinsicID()) {
1261         case Intrinsic::fma:
1262         case Intrinsic::vp_fma:
1263           return Operand == 0 || Operand == 1;
1264         // FIXME: Our patterns can only match vx/vf instructions when the splat
1265         // it on the RHS, because TableGen doesn't recognize our VP operations
1266         // as commutative.
1267         case Intrinsic::vp_add:
1268         case Intrinsic::vp_mul:
1269         case Intrinsic::vp_and:
1270         case Intrinsic::vp_or:
1271         case Intrinsic::vp_xor:
1272         case Intrinsic::vp_fadd:
1273         case Intrinsic::vp_fmul:
1274         case Intrinsic::vp_shl:
1275         case Intrinsic::vp_lshr:
1276         case Intrinsic::vp_ashr:
1277         case Intrinsic::vp_udiv:
1278         case Intrinsic::vp_sdiv:
1279         case Intrinsic::vp_urem:
1280         case Intrinsic::vp_srem:
1281           return Operand == 1;
1282         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1283         // explicit patterns for both LHS and RHS (as 'vr' versions).
1284         case Intrinsic::vp_sub:
1285         case Intrinsic::vp_fsub:
1286         case Intrinsic::vp_fdiv:
1287           return Operand == 0 || Operand == 1;
1288         default:
1289           return false;
1290         }
1291       }
1292       return false;
1293     default:
1294       return false;
1295     }
1296   };
1297 
1298   for (auto OpIdx : enumerate(I->operands())) {
1299     if (!IsSinker(I, OpIdx.index()))
1300       continue;
1301 
1302     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1303     // Make sure we are not already sinking this operand
1304     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1305       continue;
1306 
1307     // We are looking for a splat that can be sunk.
1308     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1309                              m_Undef(), m_ZeroMask())))
1310       continue;
1311 
1312     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1313     // and vector registers
1314     for (Use &U : Op->uses()) {
1315       Instruction *Insn = cast<Instruction>(U.getUser());
1316       if (!IsSinker(Insn, U.getOperandNo()))
1317         return false;
1318     }
1319 
1320     Ops.push_back(&Op->getOperandUse(0));
1321     Ops.push_back(&OpIdx.value());
1322   }
1323   return true;
1324 }
1325 
1326 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1327                                        bool ForCodeSize) const {
1328   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1329   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1330     return false;
1331   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1332     return false;
1333   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1334     return false;
1335   return Imm.isZero();
1336 }
1337 
1338 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1339   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1340          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1341          (VT == MVT::f64 && Subtarget.hasStdExtD());
1342 }
1343 
1344 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1345                                                       CallingConv::ID CC,
1346                                                       EVT VT) const {
1347   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1348   // We might still end up using a GPR but that will be decided based on ABI.
1349   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1350   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1351     return MVT::f32;
1352 
1353   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1354 }
1355 
1356 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1357                                                            CallingConv::ID CC,
1358                                                            EVT VT) const {
1359   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1360   // We might still end up using a GPR but that will be decided based on ABI.
1361   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1362   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1363     return 1;
1364 
1365   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1366 }
1367 
1368 // Changes the condition code and swaps operands if necessary, so the SetCC
1369 // operation matches one of the comparisons supported directly by branches
1370 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1371 // with 1/-1.
1372 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1373                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1374   // Convert X > -1 to X >= 0.
1375   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1376     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1377     CC = ISD::SETGE;
1378     return;
1379   }
1380   // Convert X < 1 to 0 >= X.
1381   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1382     RHS = LHS;
1383     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1384     CC = ISD::SETGE;
1385     return;
1386   }
1387 
1388   switch (CC) {
1389   default:
1390     break;
1391   case ISD::SETGT:
1392   case ISD::SETLE:
1393   case ISD::SETUGT:
1394   case ISD::SETULE:
1395     CC = ISD::getSetCCSwappedOperands(CC);
1396     std::swap(LHS, RHS);
1397     break;
1398   }
1399 }
1400 
1401 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1402   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1403   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1404   if (VT.getVectorElementType() == MVT::i1)
1405     KnownSize *= 8;
1406 
1407   switch (KnownSize) {
1408   default:
1409     llvm_unreachable("Invalid LMUL.");
1410   case 8:
1411     return RISCVII::VLMUL::LMUL_F8;
1412   case 16:
1413     return RISCVII::VLMUL::LMUL_F4;
1414   case 32:
1415     return RISCVII::VLMUL::LMUL_F2;
1416   case 64:
1417     return RISCVII::VLMUL::LMUL_1;
1418   case 128:
1419     return RISCVII::VLMUL::LMUL_2;
1420   case 256:
1421     return RISCVII::VLMUL::LMUL_4;
1422   case 512:
1423     return RISCVII::VLMUL::LMUL_8;
1424   }
1425 }
1426 
1427 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1428   switch (LMul) {
1429   default:
1430     llvm_unreachable("Invalid LMUL.");
1431   case RISCVII::VLMUL::LMUL_F8:
1432   case RISCVII::VLMUL::LMUL_F4:
1433   case RISCVII::VLMUL::LMUL_F2:
1434   case RISCVII::VLMUL::LMUL_1:
1435     return RISCV::VRRegClassID;
1436   case RISCVII::VLMUL::LMUL_2:
1437     return RISCV::VRM2RegClassID;
1438   case RISCVII::VLMUL::LMUL_4:
1439     return RISCV::VRM4RegClassID;
1440   case RISCVII::VLMUL::LMUL_8:
1441     return RISCV::VRM8RegClassID;
1442   }
1443 }
1444 
1445 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1446   RISCVII::VLMUL LMUL = getLMUL(VT);
1447   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1448       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1449       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1450       LMUL == RISCVII::VLMUL::LMUL_1) {
1451     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1452                   "Unexpected subreg numbering");
1453     return RISCV::sub_vrm1_0 + Index;
1454   }
1455   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1456     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1457                   "Unexpected subreg numbering");
1458     return RISCV::sub_vrm2_0 + Index;
1459   }
1460   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1461     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1462                   "Unexpected subreg numbering");
1463     return RISCV::sub_vrm4_0 + Index;
1464   }
1465   llvm_unreachable("Invalid vector type.");
1466 }
1467 
1468 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1469   if (VT.getVectorElementType() == MVT::i1)
1470     return RISCV::VRRegClassID;
1471   return getRegClassIDForLMUL(getLMUL(VT));
1472 }
1473 
1474 // Attempt to decompose a subvector insert/extract between VecVT and
1475 // SubVecVT via subregister indices. Returns the subregister index that
1476 // can perform the subvector insert/extract with the given element index, as
1477 // well as the index corresponding to any leftover subvectors that must be
1478 // further inserted/extracted within the register class for SubVecVT.
1479 std::pair<unsigned, unsigned>
1480 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1481     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1482     const RISCVRegisterInfo *TRI) {
1483   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1484                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1485                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1486                 "Register classes not ordered");
1487   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1488   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1489   // Try to compose a subregister index that takes us from the incoming
1490   // LMUL>1 register class down to the outgoing one. At each step we half
1491   // the LMUL:
1492   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1493   // Note that this is not guaranteed to find a subregister index, such as
1494   // when we are extracting from one VR type to another.
1495   unsigned SubRegIdx = RISCV::NoSubRegister;
1496   for (const unsigned RCID :
1497        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1498     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1499       VecVT = VecVT.getHalfNumVectorElementsVT();
1500       bool IsHi =
1501           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1502       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1503                                             getSubregIndexByMVT(VecVT, IsHi));
1504       if (IsHi)
1505         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1506     }
1507   return {SubRegIdx, InsertExtractIdx};
1508 }
1509 
1510 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1511 // stores for those types.
1512 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1513   return !Subtarget.useRVVForFixedLengthVectors() ||
1514          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1515 }
1516 
1517 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1518   if (ScalarTy->isPointerTy())
1519     return true;
1520 
1521   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1522       ScalarTy->isIntegerTy(32))
1523     return true;
1524 
1525   if (ScalarTy->isIntegerTy(64))
1526     return Subtarget.hasVInstructionsI64();
1527 
1528   if (ScalarTy->isHalfTy())
1529     return Subtarget.hasVInstructionsF16();
1530   if (ScalarTy->isFloatTy())
1531     return Subtarget.hasVInstructionsF32();
1532   if (ScalarTy->isDoubleTy())
1533     return Subtarget.hasVInstructionsF64();
1534 
1535   return false;
1536 }
1537 
1538 static SDValue getVLOperand(SDValue Op) {
1539   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1540           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1541          "Unexpected opcode");
1542   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1543   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1544   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1545       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1546   if (!II)
1547     return SDValue();
1548   return Op.getOperand(II->VLOperand + 1 + HasChain);
1549 }
1550 
1551 static bool useRVVForFixedLengthVectorVT(MVT VT,
1552                                          const RISCVSubtarget &Subtarget) {
1553   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1554   if (!Subtarget.useRVVForFixedLengthVectors())
1555     return false;
1556 
1557   // We only support a set of vector types with a consistent maximum fixed size
1558   // across all supported vector element types to avoid legalization issues.
1559   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1560   // fixed-length vector type we support is 1024 bytes.
1561   if (VT.getFixedSizeInBits() > 1024 * 8)
1562     return false;
1563 
1564   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1565 
1566   MVT EltVT = VT.getVectorElementType();
1567 
1568   // Don't use RVV for vectors we cannot scalarize if required.
1569   switch (EltVT.SimpleTy) {
1570   // i1 is supported but has different rules.
1571   default:
1572     return false;
1573   case MVT::i1:
1574     // Masks can only use a single register.
1575     if (VT.getVectorNumElements() > MinVLen)
1576       return false;
1577     MinVLen /= 8;
1578     break;
1579   case MVT::i8:
1580   case MVT::i16:
1581   case MVT::i32:
1582     break;
1583   case MVT::i64:
1584     if (!Subtarget.hasVInstructionsI64())
1585       return false;
1586     break;
1587   case MVT::f16:
1588     if (!Subtarget.hasVInstructionsF16())
1589       return false;
1590     break;
1591   case MVT::f32:
1592     if (!Subtarget.hasVInstructionsF32())
1593       return false;
1594     break;
1595   case MVT::f64:
1596     if (!Subtarget.hasVInstructionsF64())
1597       return false;
1598     break;
1599   }
1600 
1601   // Reject elements larger than ELEN.
1602   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1603     return false;
1604 
1605   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1606   // Don't use RVV for types that don't fit.
1607   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1608     return false;
1609 
1610   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1611   // the base fixed length RVV support in place.
1612   if (!VT.isPow2VectorType())
1613     return false;
1614 
1615   return true;
1616 }
1617 
1618 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1619   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1620 }
1621 
1622 // Return the largest legal scalable vector type that matches VT's element type.
1623 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1624                                             const RISCVSubtarget &Subtarget) {
1625   // This may be called before legal types are setup.
1626   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1627           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1628          "Expected legal fixed length vector!");
1629 
1630   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1631   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1632 
1633   MVT EltVT = VT.getVectorElementType();
1634   switch (EltVT.SimpleTy) {
1635   default:
1636     llvm_unreachable("unexpected element type for RVV container");
1637   case MVT::i1:
1638   case MVT::i8:
1639   case MVT::i16:
1640   case MVT::i32:
1641   case MVT::i64:
1642   case MVT::f16:
1643   case MVT::f32:
1644   case MVT::f64: {
1645     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1646     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1647     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1648     unsigned NumElts =
1649         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1650     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1651     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1652     return MVT::getScalableVectorVT(EltVT, NumElts);
1653   }
1654   }
1655 }
1656 
1657 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1658                                             const RISCVSubtarget &Subtarget) {
1659   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1660                                           Subtarget);
1661 }
1662 
1663 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1664   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1665 }
1666 
1667 // Grow V to consume an entire RVV register.
1668 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1669                                        const RISCVSubtarget &Subtarget) {
1670   assert(VT.isScalableVector() &&
1671          "Expected to convert into a scalable vector!");
1672   assert(V.getValueType().isFixedLengthVector() &&
1673          "Expected a fixed length vector operand!");
1674   SDLoc DL(V);
1675   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1676   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1677 }
1678 
1679 // Shrink V so it's just big enough to maintain a VT's worth of data.
1680 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1681                                          const RISCVSubtarget &Subtarget) {
1682   assert(VT.isFixedLengthVector() &&
1683          "Expected to convert into a fixed length vector!");
1684   assert(V.getValueType().isScalableVector() &&
1685          "Expected a scalable vector operand!");
1686   SDLoc DL(V);
1687   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1688   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1689 }
1690 
1691 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1692 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1693 // the vector type that it is contained in.
1694 static std::pair<SDValue, SDValue>
1695 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1696                 const RISCVSubtarget &Subtarget) {
1697   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1698   MVT XLenVT = Subtarget.getXLenVT();
1699   SDValue VL = VecVT.isFixedLengthVector()
1700                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1701                    : DAG.getRegister(RISCV::X0, XLenVT);
1702   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1703   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1704   return {Mask, VL};
1705 }
1706 
1707 // As above but assuming the given type is a scalable vector type.
1708 static std::pair<SDValue, SDValue>
1709 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1710                         const RISCVSubtarget &Subtarget) {
1711   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1712   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1713 }
1714 
1715 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1716 // of either is (currently) supported. This can get us into an infinite loop
1717 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1718 // as a ..., etc.
1719 // Until either (or both) of these can reliably lower any node, reporting that
1720 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1721 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1722 // which is not desirable.
1723 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1724     EVT VT, unsigned DefinedValues) const {
1725   return false;
1726 }
1727 
1728 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1729                                   const RISCVSubtarget &Subtarget) {
1730   // RISCV FP-to-int conversions saturate to the destination register size, but
1731   // don't produce 0 for nan. We can use a conversion instruction and fix the
1732   // nan case with a compare and a select.
1733   SDValue Src = Op.getOperand(0);
1734 
1735   EVT DstVT = Op.getValueType();
1736   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1737 
1738   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1739   unsigned Opc;
1740   if (SatVT == DstVT)
1741     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1742   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1743     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1744   else
1745     return SDValue();
1746   // FIXME: Support other SatVTs by clamping before or after the conversion.
1747 
1748   SDLoc DL(Op);
1749   SDValue FpToInt = DAG.getNode(
1750       Opc, DL, DstVT, Src,
1751       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1752 
1753   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1754   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1755 }
1756 
1757 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1758 // and back. Taking care to avoid converting values that are nan or already
1759 // correct.
1760 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1761 // have FRM dependencies modeled yet.
1762 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1763   MVT VT = Op.getSimpleValueType();
1764   assert(VT.isVector() && "Unexpected type");
1765 
1766   SDLoc DL(Op);
1767 
1768   // Freeze the source since we are increasing the number of uses.
1769   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1770 
1771   // Truncate to integer and convert back to FP.
1772   MVT IntVT = VT.changeVectorElementTypeToInteger();
1773   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1774   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1775 
1776   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1777 
1778   if (Op.getOpcode() == ISD::FCEIL) {
1779     // If the truncated value is the greater than or equal to the original
1780     // value, we've computed the ceil. Otherwise, we went the wrong way and
1781     // need to increase by 1.
1782     // FIXME: This should use a masked operation. Handle here or in isel?
1783     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1784                                  DAG.getConstantFP(1.0, DL, VT));
1785     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1786     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1787   } else if (Op.getOpcode() == ISD::FFLOOR) {
1788     // If the truncated value is the less than or equal to the original value,
1789     // we've computed the floor. Otherwise, we went the wrong way and need to
1790     // decrease by 1.
1791     // FIXME: This should use a masked operation. Handle here or in isel?
1792     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1793                                  DAG.getConstantFP(1.0, DL, VT));
1794     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1795     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1796   }
1797 
1798   // Restore the original sign so that -0.0 is preserved.
1799   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1800 
1801   // Determine the largest integer that can be represented exactly. This and
1802   // values larger than it don't have any fractional bits so don't need to
1803   // be converted.
1804   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1805   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1806   APFloat MaxVal = APFloat(FltSem);
1807   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1808                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1809   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1810 
1811   // If abs(Src) was larger than MaxVal or nan, keep it.
1812   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1813   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1814   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1815 }
1816 
1817 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1818 // This mode isn't supported in vector hardware on RISCV. But as long as we
1819 // aren't compiling with trapping math, we can emulate this with
1820 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1821 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1822 // dependencies modeled yet.
1823 // FIXME: Use masked operations to avoid final merge.
1824 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1825   MVT VT = Op.getSimpleValueType();
1826   assert(VT.isVector() && "Unexpected type");
1827 
1828   SDLoc DL(Op);
1829 
1830   // Freeze the source since we are increasing the number of uses.
1831   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1832 
1833   // We do the conversion on the absolute value and fix the sign at the end.
1834   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1835 
1836   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1837   bool Ignored;
1838   APFloat Point5Pred = APFloat(0.5f);
1839   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1840   Point5Pred.next(/*nextDown*/ true);
1841 
1842   // Add the adjustment.
1843   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1844                                DAG.getConstantFP(Point5Pred, DL, VT));
1845 
1846   // Truncate to integer and convert back to fp.
1847   MVT IntVT = VT.changeVectorElementTypeToInteger();
1848   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1849   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1850 
1851   // Restore the original sign.
1852   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1853 
1854   // Determine the largest integer that can be represented exactly. This and
1855   // values larger than it don't have any fractional bits so don't need to
1856   // be converted.
1857   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1858   APFloat MaxVal = APFloat(FltSem);
1859   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1860                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1861   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1862 
1863   // If abs(Src) was larger than MaxVal or nan, keep it.
1864   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1865   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1866   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1867 }
1868 
1869 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1870                                  const RISCVSubtarget &Subtarget) {
1871   MVT VT = Op.getSimpleValueType();
1872   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1873 
1874   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1875 
1876   SDLoc DL(Op);
1877   SDValue Mask, VL;
1878   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1879 
1880   unsigned Opc =
1881       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1882   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
1883                               Op.getOperand(0), VL);
1884   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1885 }
1886 
1887 struct VIDSequence {
1888   int64_t StepNumerator;
1889   unsigned StepDenominator;
1890   int64_t Addend;
1891 };
1892 
1893 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1894 // to the (non-zero) step S and start value X. This can be then lowered as the
1895 // RVV sequence (VID * S) + X, for example.
1896 // The step S is represented as an integer numerator divided by a positive
1897 // denominator. Note that the implementation currently only identifies
1898 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1899 // cannot detect 2/3, for example.
1900 // Note that this method will also match potentially unappealing index
1901 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1902 // determine whether this is worth generating code for.
1903 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1904   unsigned NumElts = Op.getNumOperands();
1905   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1906   if (!Op.getValueType().isInteger())
1907     return None;
1908 
1909   Optional<unsigned> SeqStepDenom;
1910   Optional<int64_t> SeqStepNum, SeqAddend;
1911   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1912   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1913   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1914     // Assume undef elements match the sequence; we just have to be careful
1915     // when interpolating across them.
1916     if (Op.getOperand(Idx).isUndef())
1917       continue;
1918     // The BUILD_VECTOR must be all constants.
1919     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1920       return None;
1921 
1922     uint64_t Val = Op.getConstantOperandVal(Idx) &
1923                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1924 
1925     if (PrevElt) {
1926       // Calculate the step since the last non-undef element, and ensure
1927       // it's consistent across the entire sequence.
1928       unsigned IdxDiff = Idx - PrevElt->second;
1929       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1930 
1931       // A zero-value value difference means that we're somewhere in the middle
1932       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1933       // step change before evaluating the sequence.
1934       if (ValDiff != 0) {
1935         int64_t Remainder = ValDiff % IdxDiff;
1936         // Normalize the step if it's greater than 1.
1937         if (Remainder != ValDiff) {
1938           // The difference must cleanly divide the element span.
1939           if (Remainder != 0)
1940             return None;
1941           ValDiff /= IdxDiff;
1942           IdxDiff = 1;
1943         }
1944 
1945         if (!SeqStepNum)
1946           SeqStepNum = ValDiff;
1947         else if (ValDiff != SeqStepNum)
1948           return None;
1949 
1950         if (!SeqStepDenom)
1951           SeqStepDenom = IdxDiff;
1952         else if (IdxDiff != *SeqStepDenom)
1953           return None;
1954       }
1955     }
1956 
1957     // Record and/or check any addend.
1958     if (SeqStepNum && SeqStepDenom) {
1959       uint64_t ExpectedVal =
1960           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1961       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1962       if (!SeqAddend)
1963         SeqAddend = Addend;
1964       else if (SeqAddend != Addend)
1965         return None;
1966     }
1967 
1968     // Record this non-undef element for later.
1969     if (!PrevElt || PrevElt->first != Val)
1970       PrevElt = std::make_pair(Val, Idx);
1971   }
1972   // We need to have logged both a step and an addend for this to count as
1973   // a legal index sequence.
1974   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1975     return None;
1976 
1977   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1978 }
1979 
1980 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1981 // and lower it as a VRGATHER_VX_VL from the source vector.
1982 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1983                                   SelectionDAG &DAG,
1984                                   const RISCVSubtarget &Subtarget) {
1985   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1986     return SDValue();
1987   SDValue Vec = SplatVal.getOperand(0);
1988   // Only perform this optimization on vectors of the same size for simplicity.
1989   if (Vec.getValueType() != VT)
1990     return SDValue();
1991   SDValue Idx = SplatVal.getOperand(1);
1992   // The index must be a legal type.
1993   if (Idx.getValueType() != Subtarget.getXLenVT())
1994     return SDValue();
1995 
1996   MVT ContainerVT = VT;
1997   if (VT.isFixedLengthVector()) {
1998     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1999     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2000   }
2001 
2002   SDValue Mask, VL;
2003   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2004 
2005   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2006                                Idx, Mask, VL);
2007 
2008   if (!VT.isFixedLengthVector())
2009     return Gather;
2010 
2011   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2012 }
2013 
2014 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2015                                  const RISCVSubtarget &Subtarget) {
2016   MVT VT = Op.getSimpleValueType();
2017   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2018 
2019   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2020 
2021   SDLoc DL(Op);
2022   SDValue Mask, VL;
2023   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2024 
2025   MVT XLenVT = Subtarget.getXLenVT();
2026   unsigned NumElts = Op.getNumOperands();
2027 
2028   if (VT.getVectorElementType() == MVT::i1) {
2029     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2030       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2031       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2032     }
2033 
2034     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2035       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2036       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2037     }
2038 
2039     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2040     // scalar integer chunks whose bit-width depends on the number of mask
2041     // bits and XLEN.
2042     // First, determine the most appropriate scalar integer type to use. This
2043     // is at most XLenVT, but may be shrunk to a smaller vector element type
2044     // according to the size of the final vector - use i8 chunks rather than
2045     // XLenVT if we're producing a v8i1. This results in more consistent
2046     // codegen across RV32 and RV64.
2047     unsigned NumViaIntegerBits =
2048         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2049     NumViaIntegerBits = std::min(NumViaIntegerBits,
2050                                  Subtarget.getMaxELENForFixedLengthVectors());
2051     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2052       // If we have to use more than one INSERT_VECTOR_ELT then this
2053       // optimization is likely to increase code size; avoid peforming it in
2054       // such a case. We can use a load from a constant pool in this case.
2055       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2056         return SDValue();
2057       // Now we can create our integer vector type. Note that it may be larger
2058       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2059       MVT IntegerViaVecVT =
2060           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2061                            divideCeil(NumElts, NumViaIntegerBits));
2062 
2063       uint64_t Bits = 0;
2064       unsigned BitPos = 0, IntegerEltIdx = 0;
2065       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2066 
2067       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2068         // Once we accumulate enough bits to fill our scalar type, insert into
2069         // our vector and clear our accumulated data.
2070         if (I != 0 && I % NumViaIntegerBits == 0) {
2071           if (NumViaIntegerBits <= 32)
2072             Bits = SignExtend64(Bits, 32);
2073           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2074           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2075                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2076           Bits = 0;
2077           BitPos = 0;
2078           IntegerEltIdx++;
2079         }
2080         SDValue V = Op.getOperand(I);
2081         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2082         Bits |= ((uint64_t)BitValue << BitPos);
2083       }
2084 
2085       // Insert the (remaining) scalar value into position in our integer
2086       // vector type.
2087       if (NumViaIntegerBits <= 32)
2088         Bits = SignExtend64(Bits, 32);
2089       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2090       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2091                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2092 
2093       if (NumElts < NumViaIntegerBits) {
2094         // If we're producing a smaller vector than our minimum legal integer
2095         // type, bitcast to the equivalent (known-legal) mask type, and extract
2096         // our final mask.
2097         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2098         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2099         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2100                           DAG.getConstant(0, DL, XLenVT));
2101       } else {
2102         // Else we must have produced an integer type with the same size as the
2103         // mask type; bitcast for the final result.
2104         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2105         Vec = DAG.getBitcast(VT, Vec);
2106       }
2107 
2108       return Vec;
2109     }
2110 
2111     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2112     // vector type, we have a legal equivalently-sized i8 type, so we can use
2113     // that.
2114     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2115     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2116 
2117     SDValue WideVec;
2118     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2119       // For a splat, perform a scalar truncate before creating the wider
2120       // vector.
2121       assert(Splat.getValueType() == XLenVT &&
2122              "Unexpected type for i1 splat value");
2123       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2124                           DAG.getConstant(1, DL, XLenVT));
2125       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2126     } else {
2127       SmallVector<SDValue, 8> Ops(Op->op_values());
2128       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2129       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2130       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2131     }
2132 
2133     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2134   }
2135 
2136   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2137     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2138       return Gather;
2139     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2140                                         : RISCVISD::VMV_V_X_VL;
2141     Splat =
2142         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2143     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2144   }
2145 
2146   // Try and match index sequences, which we can lower to the vid instruction
2147   // with optional modifications. An all-undef vector is matched by
2148   // getSplatValue, above.
2149   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2150     int64_t StepNumerator = SimpleVID->StepNumerator;
2151     unsigned StepDenominator = SimpleVID->StepDenominator;
2152     int64_t Addend = SimpleVID->Addend;
2153 
2154     assert(StepNumerator != 0 && "Invalid step");
2155     bool Negate = false;
2156     int64_t SplatStepVal = StepNumerator;
2157     unsigned StepOpcode = ISD::MUL;
2158     if (StepNumerator != 1) {
2159       if (isPowerOf2_64(std::abs(StepNumerator))) {
2160         Negate = StepNumerator < 0;
2161         StepOpcode = ISD::SHL;
2162         SplatStepVal = Log2_64(std::abs(StepNumerator));
2163       }
2164     }
2165 
2166     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2167     // threshold since it's the immediate value many RVV instructions accept.
2168     // There is no vmul.vi instruction so ensure multiply constant can fit in
2169     // a single addi instruction.
2170     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2171          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2172         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2173       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2174       // Convert right out of the scalable type so we can use standard ISD
2175       // nodes for the rest of the computation. If we used scalable types with
2176       // these, we'd lose the fixed-length vector info and generate worse
2177       // vsetvli code.
2178       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2179       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2180           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2181         SDValue SplatStep = DAG.getSplatVector(
2182             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2183         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2184       }
2185       if (StepDenominator != 1) {
2186         SDValue SplatStep = DAG.getSplatVector(
2187             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2188         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2189       }
2190       if (Addend != 0 || Negate) {
2191         SDValue SplatAddend =
2192             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2193         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2194       }
2195       return VID;
2196     }
2197   }
2198 
2199   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2200   // when re-interpreted as a vector with a larger element type. For example,
2201   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2202   // could be instead splat as
2203   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2204   // TODO: This optimization could also work on non-constant splats, but it
2205   // would require bit-manipulation instructions to construct the splat value.
2206   SmallVector<SDValue> Sequence;
2207   unsigned EltBitSize = VT.getScalarSizeInBits();
2208   const auto *BV = cast<BuildVectorSDNode>(Op);
2209   if (VT.isInteger() && EltBitSize < 64 &&
2210       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2211       BV->getRepeatedSequence(Sequence) &&
2212       (Sequence.size() * EltBitSize) <= 64) {
2213     unsigned SeqLen = Sequence.size();
2214     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2215     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2216     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2217             ViaIntVT == MVT::i64) &&
2218            "Unexpected sequence type");
2219 
2220     unsigned EltIdx = 0;
2221     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2222     uint64_t SplatValue = 0;
2223     // Construct the amalgamated value which can be splatted as this larger
2224     // vector type.
2225     for (const auto &SeqV : Sequence) {
2226       if (!SeqV.isUndef())
2227         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2228                        << (EltIdx * EltBitSize));
2229       EltIdx++;
2230     }
2231 
2232     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2233     // achieve better constant materializion.
2234     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2235       SplatValue = SignExtend64(SplatValue, 32);
2236 
2237     // Since we can't introduce illegal i64 types at this stage, we can only
2238     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2239     // way we can use RVV instructions to splat.
2240     assert((ViaIntVT.bitsLE(XLenVT) ||
2241             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2242            "Unexpected bitcast sequence");
2243     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2244       SDValue ViaVL =
2245           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2246       MVT ViaContainerVT =
2247           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2248       SDValue Splat =
2249           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2250                       DAG.getUNDEF(ViaContainerVT),
2251                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2252       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2253       return DAG.getBitcast(VT, Splat);
2254     }
2255   }
2256 
2257   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2258   // which constitute a large proportion of the elements. In such cases we can
2259   // splat a vector with the dominant element and make up the shortfall with
2260   // INSERT_VECTOR_ELTs.
2261   // Note that this includes vectors of 2 elements by association. The
2262   // upper-most element is the "dominant" one, allowing us to use a splat to
2263   // "insert" the upper element, and an insert of the lower element at position
2264   // 0, which improves codegen.
2265   SDValue DominantValue;
2266   unsigned MostCommonCount = 0;
2267   DenseMap<SDValue, unsigned> ValueCounts;
2268   unsigned NumUndefElts =
2269       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2270 
2271   // Track the number of scalar loads we know we'd be inserting, estimated as
2272   // any non-zero floating-point constant. Other kinds of element are either
2273   // already in registers or are materialized on demand. The threshold at which
2274   // a vector load is more desirable than several scalar materializion and
2275   // vector-insertion instructions is not known.
2276   unsigned NumScalarLoads = 0;
2277 
2278   for (SDValue V : Op->op_values()) {
2279     if (V.isUndef())
2280       continue;
2281 
2282     ValueCounts.insert(std::make_pair(V, 0));
2283     unsigned &Count = ValueCounts[V];
2284 
2285     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2286       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2287 
2288     // Is this value dominant? In case of a tie, prefer the highest element as
2289     // it's cheaper to insert near the beginning of a vector than it is at the
2290     // end.
2291     if (++Count >= MostCommonCount) {
2292       DominantValue = V;
2293       MostCommonCount = Count;
2294     }
2295   }
2296 
2297   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2298   unsigned NumDefElts = NumElts - NumUndefElts;
2299   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2300 
2301   // Don't perform this optimization when optimizing for size, since
2302   // materializing elements and inserting them tends to cause code bloat.
2303   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2304       ((MostCommonCount > DominantValueCountThreshold) ||
2305        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2306     // Start by splatting the most common element.
2307     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2308 
2309     DenseSet<SDValue> Processed{DominantValue};
2310     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2311     for (const auto &OpIdx : enumerate(Op->ops())) {
2312       const SDValue &V = OpIdx.value();
2313       if (V.isUndef() || !Processed.insert(V).second)
2314         continue;
2315       if (ValueCounts[V] == 1) {
2316         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2317                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2318       } else {
2319         // Blend in all instances of this value using a VSELECT, using a
2320         // mask where each bit signals whether that element is the one
2321         // we're after.
2322         SmallVector<SDValue> Ops;
2323         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2324           return DAG.getConstant(V == V1, DL, XLenVT);
2325         });
2326         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2327                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2328                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2329       }
2330     }
2331 
2332     return Vec;
2333   }
2334 
2335   return SDValue();
2336 }
2337 
2338 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2339                                    SDValue Lo, SDValue Hi, SDValue VL,
2340                                    SelectionDAG &DAG) {
2341   bool HasPassthru = Passthru && !Passthru.isUndef();
2342   if (!HasPassthru && !Passthru)
2343     Passthru = DAG.getUNDEF(VT);
2344   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2345     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2346     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2347     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2348     // node in order to try and match RVV vector/scalar instructions.
2349     if ((LoC >> 31) == HiC)
2350       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2351 
2352     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2353     // vmv.v.x whose EEW = 32 to lower it.
2354     auto *Const = dyn_cast<ConstantSDNode>(VL);
2355     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2356       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2357       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2358       // access the subtarget here now.
2359       auto InterVec = DAG.getNode(
2360           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2361                                   DAG.getRegister(RISCV::X0, MVT::i32));
2362       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2363     }
2364   }
2365 
2366   // Fall back to a stack store and stride x0 vector load.
2367   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2368                      Hi, VL);
2369 }
2370 
2371 // Called by type legalization to handle splat of i64 on RV32.
2372 // FIXME: We can optimize this when the type has sign or zero bits in one
2373 // of the halves.
2374 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2375                                    SDValue Scalar, SDValue VL,
2376                                    SelectionDAG &DAG) {
2377   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2378   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2379                            DAG.getConstant(0, DL, MVT::i32));
2380   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2381                            DAG.getConstant(1, DL, MVT::i32));
2382   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2383 }
2384 
2385 // This function lowers a splat of a scalar operand Splat with the vector
2386 // length VL. It ensures the final sequence is type legal, which is useful when
2387 // lowering a splat after type legalization.
2388 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2389                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2390                                 const RISCVSubtarget &Subtarget) {
2391   bool HasPassthru = Passthru && !Passthru.isUndef();
2392   if (!HasPassthru && !Passthru)
2393     Passthru = DAG.getUNDEF(VT);
2394   if (VT.isFloatingPoint()) {
2395     // If VL is 1, we could use vfmv.s.f.
2396     if (isOneConstant(VL))
2397       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2398     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2399   }
2400 
2401   MVT XLenVT = Subtarget.getXLenVT();
2402 
2403   // Simplest case is that the operand needs to be promoted to XLenVT.
2404   if (Scalar.getValueType().bitsLE(XLenVT)) {
2405     // If the operand is a constant, sign extend to increase our chances
2406     // of being able to use a .vi instruction. ANY_EXTEND would become a
2407     // a zero extend and the simm5 check in isel would fail.
2408     // FIXME: Should we ignore the upper bits in isel instead?
2409     unsigned ExtOpc =
2410         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2411     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2412     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2413     // If VL is 1 and the scalar value won't benefit from immediate, we could
2414     // use vmv.s.x.
2415     if (isOneConstant(VL) &&
2416         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2417       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2418     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2419   }
2420 
2421   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2422          "Unexpected scalar for splat lowering!");
2423 
2424   if (isOneConstant(VL) && isNullConstant(Scalar))
2425     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2426                        DAG.getConstant(0, DL, XLenVT), VL);
2427 
2428   // Otherwise use the more complicated splatting algorithm.
2429   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2430 }
2431 
2432 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2433                                 const RISCVSubtarget &Subtarget) {
2434   // We need to be able to widen elements to the next larger integer type.
2435   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2436     return false;
2437 
2438   int Size = Mask.size();
2439   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2440 
2441   int Srcs[] = {-1, -1};
2442   for (int i = 0; i != Size; ++i) {
2443     // Ignore undef elements.
2444     if (Mask[i] < 0)
2445       continue;
2446 
2447     // Is this an even or odd element.
2448     int Pol = i % 2;
2449 
2450     // Ensure we consistently use the same source for this element polarity.
2451     int Src = Mask[i] / Size;
2452     if (Srcs[Pol] < 0)
2453       Srcs[Pol] = Src;
2454     if (Srcs[Pol] != Src)
2455       return false;
2456 
2457     // Make sure the element within the source is appropriate for this element
2458     // in the destination.
2459     int Elt = Mask[i] % Size;
2460     if (Elt != i / 2)
2461       return false;
2462   }
2463 
2464   // We need to find a source for each polarity and they can't be the same.
2465   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2466     return false;
2467 
2468   // Swap the sources if the second source was in the even polarity.
2469   SwapSources = Srcs[0] > Srcs[1];
2470 
2471   return true;
2472 }
2473 
2474 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2475 /// and then extract the original number of elements from the rotated result.
2476 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2477 /// returned rotation amount is for a rotate right, where elements move from
2478 /// higher elements to lower elements. \p LoSrc indicates the first source
2479 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2480 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2481 /// 0 or 1 if a rotation is found.
2482 ///
2483 /// NOTE: We talk about rotate to the right which matches how bit shift and
2484 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2485 /// and the table below write vectors with the lowest elements on the left.
2486 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2487   int Size = Mask.size();
2488 
2489   // We need to detect various ways of spelling a rotation:
2490   //   [11, 12, 13, 14, 15,  0,  1,  2]
2491   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2492   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2493   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2494   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2495   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2496   int Rotation = 0;
2497   LoSrc = -1;
2498   HiSrc = -1;
2499   for (int i = 0; i != Size; ++i) {
2500     int M = Mask[i];
2501     if (M < 0)
2502       continue;
2503 
2504     // Determine where a rotate vector would have started.
2505     int StartIdx = i - (M % Size);
2506     // The identity rotation isn't interesting, stop.
2507     if (StartIdx == 0)
2508       return -1;
2509 
2510     // If we found the tail of a vector the rotation must be the missing
2511     // front. If we found the head of a vector, it must be how much of the
2512     // head.
2513     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2514 
2515     if (Rotation == 0)
2516       Rotation = CandidateRotation;
2517     else if (Rotation != CandidateRotation)
2518       // The rotations don't match, so we can't match this mask.
2519       return -1;
2520 
2521     // Compute which value this mask is pointing at.
2522     int MaskSrc = M < Size ? 0 : 1;
2523 
2524     // Compute which of the two target values this index should be assigned to.
2525     // This reflects whether the high elements are remaining or the low elemnts
2526     // are remaining.
2527     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2528 
2529     // Either set up this value if we've not encountered it before, or check
2530     // that it remains consistent.
2531     if (TargetSrc < 0)
2532       TargetSrc = MaskSrc;
2533     else if (TargetSrc != MaskSrc)
2534       // This may be a rotation, but it pulls from the inputs in some
2535       // unsupported interleaving.
2536       return -1;
2537   }
2538 
2539   // Check that we successfully analyzed the mask, and normalize the results.
2540   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2541   assert((LoSrc >= 0 || HiSrc >= 0) &&
2542          "Failed to find a rotated input vector!");
2543 
2544   return Rotation;
2545 }
2546 
2547 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2548                                    const RISCVSubtarget &Subtarget) {
2549   SDValue V1 = Op.getOperand(0);
2550   SDValue V2 = Op.getOperand(1);
2551   SDLoc DL(Op);
2552   MVT XLenVT = Subtarget.getXLenVT();
2553   MVT VT = Op.getSimpleValueType();
2554   unsigned NumElts = VT.getVectorNumElements();
2555   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2556 
2557   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2558 
2559   SDValue TrueMask, VL;
2560   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2561 
2562   if (SVN->isSplat()) {
2563     const int Lane = SVN->getSplatIndex();
2564     if (Lane >= 0) {
2565       MVT SVT = VT.getVectorElementType();
2566 
2567       // Turn splatted vector load into a strided load with an X0 stride.
2568       SDValue V = V1;
2569       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2570       // with undef.
2571       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2572       int Offset = Lane;
2573       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2574         int OpElements =
2575             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2576         V = V.getOperand(Offset / OpElements);
2577         Offset %= OpElements;
2578       }
2579 
2580       // We need to ensure the load isn't atomic or volatile.
2581       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2582         auto *Ld = cast<LoadSDNode>(V);
2583         Offset *= SVT.getStoreSize();
2584         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2585                                                    TypeSize::Fixed(Offset), DL);
2586 
2587         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2588         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2589           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2590           SDValue IntID =
2591               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2592           SDValue Ops[] = {Ld->getChain(),
2593                            IntID,
2594                            DAG.getUNDEF(ContainerVT),
2595                            NewAddr,
2596                            DAG.getRegister(RISCV::X0, XLenVT),
2597                            VL};
2598           SDValue NewLoad = DAG.getMemIntrinsicNode(
2599               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2600               DAG.getMachineFunction().getMachineMemOperand(
2601                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2602           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2603           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2604         }
2605 
2606         // Otherwise use a scalar load and splat. This will give the best
2607         // opportunity to fold a splat into the operation. ISel can turn it into
2608         // the x0 strided load if we aren't able to fold away the select.
2609         if (SVT.isFloatingPoint())
2610           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2611                           Ld->getPointerInfo().getWithOffset(Offset),
2612                           Ld->getOriginalAlign(),
2613                           Ld->getMemOperand()->getFlags());
2614         else
2615           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2616                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2617                              Ld->getOriginalAlign(),
2618                              Ld->getMemOperand()->getFlags());
2619         DAG.makeEquivalentMemoryOrdering(Ld, V);
2620 
2621         unsigned Opc =
2622             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2623         SDValue Splat =
2624             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2625         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2626       }
2627 
2628       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2629       assert(Lane < (int)NumElts && "Unexpected lane!");
2630       SDValue Gather =
2631           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2632                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2633       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2634     }
2635   }
2636 
2637   ArrayRef<int> Mask = SVN->getMask();
2638 
2639   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2640   // be undef which can be handled with a single SLIDEDOWN/UP.
2641   int LoSrc, HiSrc;
2642   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2643   if (Rotation > 0) {
2644     SDValue LoV, HiV;
2645     if (LoSrc >= 0) {
2646       LoV = LoSrc == 0 ? V1 : V2;
2647       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2648     }
2649     if (HiSrc >= 0) {
2650       HiV = HiSrc == 0 ? V1 : V2;
2651       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2652     }
2653 
2654     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2655     // to slide LoV up by (NumElts - Rotation).
2656     unsigned InvRotate = NumElts - Rotation;
2657 
2658     SDValue Res = DAG.getUNDEF(ContainerVT);
2659     if (HiV) {
2660       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2661       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2662       // causes multiple vsetvlis in some test cases such as lowering
2663       // reduce.mul
2664       SDValue DownVL = VL;
2665       if (LoV)
2666         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2667       Res =
2668           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2669                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2670     }
2671     if (LoV)
2672       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2673                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2674 
2675     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2676   }
2677 
2678   // Detect an interleave shuffle and lower to
2679   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2680   bool SwapSources;
2681   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2682     // Swap sources if needed.
2683     if (SwapSources)
2684       std::swap(V1, V2);
2685 
2686     // Extract the lower half of the vectors.
2687     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2688     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2689                      DAG.getConstant(0, DL, XLenVT));
2690     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2691                      DAG.getConstant(0, DL, XLenVT));
2692 
2693     // Double the element width and halve the number of elements in an int type.
2694     unsigned EltBits = VT.getScalarSizeInBits();
2695     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2696     MVT WideIntVT =
2697         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2698     // Convert this to a scalable vector. We need to base this on the
2699     // destination size to ensure there's always a type with a smaller LMUL.
2700     MVT WideIntContainerVT =
2701         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2702 
2703     // Convert sources to scalable vectors with the same element count as the
2704     // larger type.
2705     MVT HalfContainerVT = MVT::getVectorVT(
2706         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2707     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2708     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2709 
2710     // Cast sources to integer.
2711     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2712     MVT IntHalfVT =
2713         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2714     V1 = DAG.getBitcast(IntHalfVT, V1);
2715     V2 = DAG.getBitcast(IntHalfVT, V2);
2716 
2717     // Freeze V2 since we use it twice and we need to be sure that the add and
2718     // multiply see the same value.
2719     V2 = DAG.getFreeze(V2);
2720 
2721     // Recreate TrueMask using the widened type's element count.
2722     MVT MaskVT =
2723         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2724     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2725 
2726     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2727     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2728                               V2, TrueMask, VL);
2729     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2730     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2731                                      DAG.getUNDEF(IntHalfVT),
2732                                      DAG.getAllOnesConstant(DL, XLenVT));
2733     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2734                                    V2, Multiplier, TrueMask, VL);
2735     // Add the new copies to our previous addition giving us 2^eltbits copies of
2736     // V2. This is equivalent to shifting V2 left by eltbits. This should
2737     // combine with the vwmulu.vv above to form vwmaccu.vv.
2738     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2739                       TrueMask, VL);
2740     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2741     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2742     // vector VT.
2743     ContainerVT =
2744         MVT::getVectorVT(VT.getVectorElementType(),
2745                          WideIntContainerVT.getVectorElementCount() * 2);
2746     Add = DAG.getBitcast(ContainerVT, Add);
2747     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2748   }
2749 
2750   // Detect shuffles which can be re-expressed as vector selects; these are
2751   // shuffles in which each element in the destination is taken from an element
2752   // at the corresponding index in either source vectors.
2753   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2754     int MaskIndex = MaskIdx.value();
2755     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2756   });
2757 
2758   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2759 
2760   SmallVector<SDValue> MaskVals;
2761   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2762   // merged with a second vrgather.
2763   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2764 
2765   // By default we preserve the original operand order, and use a mask to
2766   // select LHS as true and RHS as false. However, since RVV vector selects may
2767   // feature splats but only on the LHS, we may choose to invert our mask and
2768   // instead select between RHS and LHS.
2769   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2770   bool InvertMask = IsSelect == SwapOps;
2771 
2772   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2773   // half.
2774   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2775 
2776   // Now construct the mask that will be used by the vselect or blended
2777   // vrgather operation. For vrgathers, construct the appropriate indices into
2778   // each vector.
2779   for (int MaskIndex : Mask) {
2780     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2781     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2782     if (!IsSelect) {
2783       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2784       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2785                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2786                                      : DAG.getUNDEF(XLenVT));
2787       GatherIndicesRHS.push_back(
2788           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2789                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2790       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2791         ++LHSIndexCounts[MaskIndex];
2792       if (!IsLHSOrUndefIndex)
2793         ++RHSIndexCounts[MaskIndex - NumElts];
2794     }
2795   }
2796 
2797   if (SwapOps) {
2798     std::swap(V1, V2);
2799     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2800   }
2801 
2802   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2803   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2804   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2805 
2806   if (IsSelect)
2807     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2808 
2809   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2810     // On such a large vector we're unable to use i8 as the index type.
2811     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2812     // may involve vector splitting if we're already at LMUL=8, or our
2813     // user-supplied maximum fixed-length LMUL.
2814     return SDValue();
2815   }
2816 
2817   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2818   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2819   MVT IndexVT = VT.changeTypeToInteger();
2820   // Since we can't introduce illegal index types at this stage, use i16 and
2821   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2822   // than XLenVT.
2823   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2824     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2825     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2826   }
2827 
2828   MVT IndexContainerVT =
2829       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2830 
2831   SDValue Gather;
2832   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2833   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2834   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2835     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2836                               Subtarget);
2837   } else {
2838     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2839     // If only one index is used, we can use a "splat" vrgather.
2840     // TODO: We can splat the most-common index and fix-up any stragglers, if
2841     // that's beneficial.
2842     if (LHSIndexCounts.size() == 1) {
2843       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2844       Gather =
2845           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2846                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2847     } else {
2848       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2849       LHSIndices =
2850           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2851 
2852       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2853                            TrueMask, VL);
2854     }
2855   }
2856 
2857   // If a second vector operand is used by this shuffle, blend it in with an
2858   // additional vrgather.
2859   if (!V2.isUndef()) {
2860     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2861     // If only one index is used, we can use a "splat" vrgather.
2862     // TODO: We can splat the most-common index and fix-up any stragglers, if
2863     // that's beneficial.
2864     if (RHSIndexCounts.size() == 1) {
2865       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2866       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2867                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2868     } else {
2869       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2870       RHSIndices =
2871           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2872       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2873                        VL);
2874     }
2875 
2876     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2877     SelectMask =
2878         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2879 
2880     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2881                          Gather, VL);
2882   }
2883 
2884   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2885 }
2886 
2887 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2888   // Support splats for any type. These should type legalize well.
2889   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2890     return true;
2891 
2892   // Only support legal VTs for other shuffles for now.
2893   if (!isTypeLegal(VT))
2894     return false;
2895 
2896   MVT SVT = VT.getSimpleVT();
2897 
2898   bool SwapSources;
2899   int LoSrc, HiSrc;
2900   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2901          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2902 }
2903 
2904 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2905                                      SDLoc DL, SelectionDAG &DAG,
2906                                      const RISCVSubtarget &Subtarget) {
2907   if (VT.isScalableVector())
2908     return DAG.getFPExtendOrRound(Op, DL, VT);
2909   assert(VT.isFixedLengthVector() &&
2910          "Unexpected value type for RVV FP extend/round lowering");
2911   SDValue Mask, VL;
2912   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2913   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2914                         ? RISCVISD::FP_EXTEND_VL
2915                         : RISCVISD::FP_ROUND_VL;
2916   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2917 }
2918 
2919 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2920 // the exponent.
2921 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2922   MVT VT = Op.getSimpleValueType();
2923   unsigned EltSize = VT.getScalarSizeInBits();
2924   SDValue Src = Op.getOperand(0);
2925   SDLoc DL(Op);
2926 
2927   // We need a FP type that can represent the value.
2928   // TODO: Use f16 for i8 when possible?
2929   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2930   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2931 
2932   // Legal types should have been checked in the RISCVTargetLowering
2933   // constructor.
2934   // TODO: Splitting may make sense in some cases.
2935   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2936          "Expected legal float type!");
2937 
2938   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2939   // The trailing zero count is equal to log2 of this single bit value.
2940   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2941     SDValue Neg =
2942         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2943     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2944   }
2945 
2946   // We have a legal FP type, convert to it.
2947   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2948   // Bitcast to integer and shift the exponent to the LSB.
2949   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2950   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2951   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2952   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2953                               DAG.getConstant(ShiftAmt, DL, IntVT));
2954   // Truncate back to original type to allow vnsrl.
2955   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2956   // The exponent contains log2 of the value in biased form.
2957   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2958 
2959   // For trailing zeros, we just need to subtract the bias.
2960   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2961     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2962                        DAG.getConstant(ExponentBias, DL, VT));
2963 
2964   // For leading zeros, we need to remove the bias and convert from log2 to
2965   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2966   unsigned Adjust = ExponentBias + (EltSize - 1);
2967   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2968 }
2969 
2970 // While RVV has alignment restrictions, we should always be able to load as a
2971 // legal equivalently-sized byte-typed vector instead. This method is
2972 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2973 // the load is already correctly-aligned, it returns SDValue().
2974 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2975                                                     SelectionDAG &DAG) const {
2976   auto *Load = cast<LoadSDNode>(Op);
2977   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2978 
2979   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2980                                      Load->getMemoryVT(),
2981                                      *Load->getMemOperand()))
2982     return SDValue();
2983 
2984   SDLoc DL(Op);
2985   MVT VT = Op.getSimpleValueType();
2986   unsigned EltSizeBits = VT.getScalarSizeInBits();
2987   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2988          "Unexpected unaligned RVV load type");
2989   MVT NewVT =
2990       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2991   assert(NewVT.isValid() &&
2992          "Expecting equally-sized RVV vector types to be legal");
2993   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2994                           Load->getPointerInfo(), Load->getOriginalAlign(),
2995                           Load->getMemOperand()->getFlags());
2996   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2997 }
2998 
2999 // While RVV has alignment restrictions, we should always be able to store as a
3000 // legal equivalently-sized byte-typed vector instead. This method is
3001 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3002 // returns SDValue() if the store is already correctly aligned.
3003 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3004                                                      SelectionDAG &DAG) const {
3005   auto *Store = cast<StoreSDNode>(Op);
3006   assert(Store && Store->getValue().getValueType().isVector() &&
3007          "Expected vector store");
3008 
3009   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3010                                      Store->getMemoryVT(),
3011                                      *Store->getMemOperand()))
3012     return SDValue();
3013 
3014   SDLoc DL(Op);
3015   SDValue StoredVal = Store->getValue();
3016   MVT VT = StoredVal.getSimpleValueType();
3017   unsigned EltSizeBits = VT.getScalarSizeInBits();
3018   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3019          "Unexpected unaligned RVV store type");
3020   MVT NewVT =
3021       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3022   assert(NewVT.isValid() &&
3023          "Expecting equally-sized RVV vector types to be legal");
3024   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3025   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3026                       Store->getPointerInfo(), Store->getOriginalAlign(),
3027                       Store->getMemOperand()->getFlags());
3028 }
3029 
3030 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3031                                             SelectionDAG &DAG) const {
3032   switch (Op.getOpcode()) {
3033   default:
3034     report_fatal_error("unimplemented operand");
3035   case ISD::GlobalAddress:
3036     return lowerGlobalAddress(Op, DAG);
3037   case ISD::BlockAddress:
3038     return lowerBlockAddress(Op, DAG);
3039   case ISD::ConstantPool:
3040     return lowerConstantPool(Op, DAG);
3041   case ISD::JumpTable:
3042     return lowerJumpTable(Op, DAG);
3043   case ISD::GlobalTLSAddress:
3044     return lowerGlobalTLSAddress(Op, DAG);
3045   case ISD::SELECT:
3046     return lowerSELECT(Op, DAG);
3047   case ISD::BRCOND:
3048     return lowerBRCOND(Op, DAG);
3049   case ISD::VASTART:
3050     return lowerVASTART(Op, DAG);
3051   case ISD::FRAMEADDR:
3052     return lowerFRAMEADDR(Op, DAG);
3053   case ISD::RETURNADDR:
3054     return lowerRETURNADDR(Op, DAG);
3055   case ISD::SHL_PARTS:
3056     return lowerShiftLeftParts(Op, DAG);
3057   case ISD::SRA_PARTS:
3058     return lowerShiftRightParts(Op, DAG, true);
3059   case ISD::SRL_PARTS:
3060     return lowerShiftRightParts(Op, DAG, false);
3061   case ISD::BITCAST: {
3062     SDLoc DL(Op);
3063     EVT VT = Op.getValueType();
3064     SDValue Op0 = Op.getOperand(0);
3065     EVT Op0VT = Op0.getValueType();
3066     MVT XLenVT = Subtarget.getXLenVT();
3067     if (VT.isFixedLengthVector()) {
3068       // We can handle fixed length vector bitcasts with a simple replacement
3069       // in isel.
3070       if (Op0VT.isFixedLengthVector())
3071         return Op;
3072       // When bitcasting from scalar to fixed-length vector, insert the scalar
3073       // into a one-element vector of the result type, and perform a vector
3074       // bitcast.
3075       if (!Op0VT.isVector()) {
3076         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3077         if (!isTypeLegal(BVT))
3078           return SDValue();
3079         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3080                                               DAG.getUNDEF(BVT), Op0,
3081                                               DAG.getConstant(0, DL, XLenVT)));
3082       }
3083       return SDValue();
3084     }
3085     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3086     // thus: bitcast the vector to a one-element vector type whose element type
3087     // is the same as the result type, and extract the first element.
3088     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3089       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3090       if (!isTypeLegal(BVT))
3091         return SDValue();
3092       SDValue BVec = DAG.getBitcast(BVT, Op0);
3093       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3094                          DAG.getConstant(0, DL, XLenVT));
3095     }
3096     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3097       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3098       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3099       return FPConv;
3100     }
3101     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3102         Subtarget.hasStdExtF()) {
3103       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3104       SDValue FPConv =
3105           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3106       return FPConv;
3107     }
3108     return SDValue();
3109   }
3110   case ISD::INTRINSIC_WO_CHAIN:
3111     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3112   case ISD::INTRINSIC_W_CHAIN:
3113     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3114   case ISD::INTRINSIC_VOID:
3115     return LowerINTRINSIC_VOID(Op, DAG);
3116   case ISD::BSWAP:
3117   case ISD::BITREVERSE: {
3118     MVT VT = Op.getSimpleValueType();
3119     SDLoc DL(Op);
3120     if (Subtarget.hasStdExtZbp()) {
3121       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3122       // Start with the maximum immediate value which is the bitwidth - 1.
3123       unsigned Imm = VT.getSizeInBits() - 1;
3124       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3125       if (Op.getOpcode() == ISD::BSWAP)
3126         Imm &= ~0x7U;
3127       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3128                          DAG.getConstant(Imm, DL, VT));
3129     }
3130     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3131     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3132     // Expand bitreverse to a bswap(rev8) followed by brev8.
3133     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3134     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3135     // as brev8 by an isel pattern.
3136     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3137                        DAG.getConstant(7, DL, VT));
3138   }
3139   case ISD::FSHL:
3140   case ISD::FSHR: {
3141     MVT VT = Op.getSimpleValueType();
3142     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3143     SDLoc DL(Op);
3144     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3145     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3146     // accidentally setting the extra bit.
3147     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3148     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3149                                 DAG.getConstant(ShAmtWidth, DL, VT));
3150     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3151     // instruction use different orders. fshl will return its first operand for
3152     // shift of zero, fshr will return its second operand. fsl and fsr both
3153     // return rs1 so the ISD nodes need to have different operand orders.
3154     // Shift amount is in rs2.
3155     SDValue Op0 = Op.getOperand(0);
3156     SDValue Op1 = Op.getOperand(1);
3157     unsigned Opc = RISCVISD::FSL;
3158     if (Op.getOpcode() == ISD::FSHR) {
3159       std::swap(Op0, Op1);
3160       Opc = RISCVISD::FSR;
3161     }
3162     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3163   }
3164   case ISD::TRUNCATE: {
3165     SDLoc DL(Op);
3166     MVT VT = Op.getSimpleValueType();
3167     // Only custom-lower vector truncates
3168     if (!VT.isVector())
3169       return Op;
3170 
3171     // Truncates to mask types are handled differently
3172     if (VT.getVectorElementType() == MVT::i1)
3173       return lowerVectorMaskTrunc(Op, DAG);
3174 
3175     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3176     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3177     // truncate by one power of two at a time.
3178     MVT DstEltVT = VT.getVectorElementType();
3179 
3180     SDValue Src = Op.getOperand(0);
3181     MVT SrcVT = Src.getSimpleValueType();
3182     MVT SrcEltVT = SrcVT.getVectorElementType();
3183 
3184     assert(DstEltVT.bitsLT(SrcEltVT) &&
3185            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3186            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3187            "Unexpected vector truncate lowering");
3188 
3189     MVT ContainerVT = SrcVT;
3190     if (SrcVT.isFixedLengthVector()) {
3191       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3192       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3193     }
3194 
3195     SDValue Result = Src;
3196     SDValue Mask, VL;
3197     std::tie(Mask, VL) =
3198         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3199     LLVMContext &Context = *DAG.getContext();
3200     const ElementCount Count = ContainerVT.getVectorElementCount();
3201     do {
3202       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3203       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3204       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3205                            Mask, VL);
3206     } while (SrcEltVT != DstEltVT);
3207 
3208     if (SrcVT.isFixedLengthVector())
3209       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3210 
3211     return Result;
3212   }
3213   case ISD::ANY_EXTEND:
3214   case ISD::ZERO_EXTEND:
3215     if (Op.getOperand(0).getValueType().isVector() &&
3216         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3217       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3218     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3219   case ISD::SIGN_EXTEND:
3220     if (Op.getOperand(0).getValueType().isVector() &&
3221         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3222       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3223     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3224   case ISD::SPLAT_VECTOR_PARTS:
3225     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3226   case ISD::INSERT_VECTOR_ELT:
3227     return lowerINSERT_VECTOR_ELT(Op, DAG);
3228   case ISD::EXTRACT_VECTOR_ELT:
3229     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3230   case ISD::VSCALE: {
3231     MVT VT = Op.getSimpleValueType();
3232     SDLoc DL(Op);
3233     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3234     // We define our scalable vector types for lmul=1 to use a 64 bit known
3235     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3236     // vscale as VLENB / 8.
3237     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3238     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3239       report_fatal_error("Support for VLEN==32 is incomplete.");
3240     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3241       // We assume VLENB is a multiple of 8. We manually choose the best shift
3242       // here because SimplifyDemandedBits isn't always able to simplify it.
3243       uint64_t Val = Op.getConstantOperandVal(0);
3244       if (isPowerOf2_64(Val)) {
3245         uint64_t Log2 = Log2_64(Val);
3246         if (Log2 < 3)
3247           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3248                              DAG.getConstant(3 - Log2, DL, VT));
3249         if (Log2 > 3)
3250           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3251                              DAG.getConstant(Log2 - 3, DL, VT));
3252         return VLENB;
3253       }
3254       // If the multiplier is a multiple of 8, scale it down to avoid needing
3255       // to shift the VLENB value.
3256       if ((Val % 8) == 0)
3257         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3258                            DAG.getConstant(Val / 8, DL, VT));
3259     }
3260 
3261     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3262                                  DAG.getConstant(3, DL, VT));
3263     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3264   }
3265   case ISD::FPOWI: {
3266     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3267     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3268     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3269         Op.getOperand(1).getValueType() == MVT::i32) {
3270       SDLoc DL(Op);
3271       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3272       SDValue Powi =
3273           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3274       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3275                          DAG.getIntPtrConstant(0, DL));
3276     }
3277     return SDValue();
3278   }
3279   case ISD::FP_EXTEND: {
3280     // RVV can only do fp_extend to types double the size as the source. We
3281     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3282     // via f32.
3283     SDLoc DL(Op);
3284     MVT VT = Op.getSimpleValueType();
3285     SDValue Src = Op.getOperand(0);
3286     MVT SrcVT = Src.getSimpleValueType();
3287 
3288     // Prepare any fixed-length vector operands.
3289     MVT ContainerVT = VT;
3290     if (SrcVT.isFixedLengthVector()) {
3291       ContainerVT = getContainerForFixedLengthVector(VT);
3292       MVT SrcContainerVT =
3293           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3294       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3295     }
3296 
3297     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3298         SrcVT.getVectorElementType() != MVT::f16) {
3299       // For scalable vectors, we only need to close the gap between
3300       // vXf16->vXf64.
3301       if (!VT.isFixedLengthVector())
3302         return Op;
3303       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3304       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3305       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3306     }
3307 
3308     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3309     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3310     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3311         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3312 
3313     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3314                                            DL, DAG, Subtarget);
3315     if (VT.isFixedLengthVector())
3316       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3317     return Extend;
3318   }
3319   case ISD::FP_ROUND: {
3320     // RVV can only do fp_round to types half the size as the source. We
3321     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3322     // conversion instruction.
3323     SDLoc DL(Op);
3324     MVT VT = Op.getSimpleValueType();
3325     SDValue Src = Op.getOperand(0);
3326     MVT SrcVT = Src.getSimpleValueType();
3327 
3328     // Prepare any fixed-length vector operands.
3329     MVT ContainerVT = VT;
3330     if (VT.isFixedLengthVector()) {
3331       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3332       ContainerVT =
3333           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3334       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3335     }
3336 
3337     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3338         SrcVT.getVectorElementType() != MVT::f64) {
3339       // For scalable vectors, we only need to close the gap between
3340       // vXf64<->vXf16.
3341       if (!VT.isFixedLengthVector())
3342         return Op;
3343       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3344       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3345       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3346     }
3347 
3348     SDValue Mask, VL;
3349     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3350 
3351     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3352     SDValue IntermediateRound =
3353         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3354     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3355                                           DL, DAG, Subtarget);
3356 
3357     if (VT.isFixedLengthVector())
3358       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3359     return Round;
3360   }
3361   case ISD::FP_TO_SINT:
3362   case ISD::FP_TO_UINT:
3363   case ISD::SINT_TO_FP:
3364   case ISD::UINT_TO_FP: {
3365     // RVV can only do fp<->int conversions to types half/double the size as
3366     // the source. We custom-lower any conversions that do two hops into
3367     // sequences.
3368     MVT VT = Op.getSimpleValueType();
3369     if (!VT.isVector())
3370       return Op;
3371     SDLoc DL(Op);
3372     SDValue Src = Op.getOperand(0);
3373     MVT EltVT = VT.getVectorElementType();
3374     MVT SrcVT = Src.getSimpleValueType();
3375     MVT SrcEltVT = SrcVT.getVectorElementType();
3376     unsigned EltSize = EltVT.getSizeInBits();
3377     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3378     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3379            "Unexpected vector element types");
3380 
3381     bool IsInt2FP = SrcEltVT.isInteger();
3382     // Widening conversions
3383     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3384       if (IsInt2FP) {
3385         // Do a regular integer sign/zero extension then convert to float.
3386         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3387                                       VT.getVectorElementCount());
3388         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3389                                  ? ISD::ZERO_EXTEND
3390                                  : ISD::SIGN_EXTEND;
3391         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3392         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3393       }
3394       // FP2Int
3395       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3396       // Do one doubling fp_extend then complete the operation by converting
3397       // to int.
3398       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3399       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3400       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3401     }
3402 
3403     // Narrowing conversions
3404     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3405       if (IsInt2FP) {
3406         // One narrowing int_to_fp, then an fp_round.
3407         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3408         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3409         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3410         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3411       }
3412       // FP2Int
3413       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3414       // representable by the integer, the result is poison.
3415       MVT IVecVT =
3416           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3417                            VT.getVectorElementCount());
3418       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3419       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3420     }
3421 
3422     // Scalable vectors can exit here. Patterns will handle equally-sized
3423     // conversions halving/doubling ones.
3424     if (!VT.isFixedLengthVector())
3425       return Op;
3426 
3427     // For fixed-length vectors we lower to a custom "VL" node.
3428     unsigned RVVOpc = 0;
3429     switch (Op.getOpcode()) {
3430     default:
3431       llvm_unreachable("Impossible opcode");
3432     case ISD::FP_TO_SINT:
3433       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3434       break;
3435     case ISD::FP_TO_UINT:
3436       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3437       break;
3438     case ISD::SINT_TO_FP:
3439       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3440       break;
3441     case ISD::UINT_TO_FP:
3442       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3443       break;
3444     }
3445 
3446     MVT ContainerVT, SrcContainerVT;
3447     // Derive the reference container type from the larger vector type.
3448     if (SrcEltSize > EltSize) {
3449       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3450       ContainerVT =
3451           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3452     } else {
3453       ContainerVT = getContainerForFixedLengthVector(VT);
3454       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3455     }
3456 
3457     SDValue Mask, VL;
3458     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3459 
3460     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3461     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3462     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3463   }
3464   case ISD::FP_TO_SINT_SAT:
3465   case ISD::FP_TO_UINT_SAT:
3466     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3467   case ISD::FTRUNC:
3468   case ISD::FCEIL:
3469   case ISD::FFLOOR:
3470     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3471   case ISD::FROUND:
3472     return lowerFROUND(Op, DAG);
3473   case ISD::VECREDUCE_ADD:
3474   case ISD::VECREDUCE_UMAX:
3475   case ISD::VECREDUCE_SMAX:
3476   case ISD::VECREDUCE_UMIN:
3477   case ISD::VECREDUCE_SMIN:
3478     return lowerVECREDUCE(Op, DAG);
3479   case ISD::VECREDUCE_AND:
3480   case ISD::VECREDUCE_OR:
3481   case ISD::VECREDUCE_XOR:
3482     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3483       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3484     return lowerVECREDUCE(Op, DAG);
3485   case ISD::VECREDUCE_FADD:
3486   case ISD::VECREDUCE_SEQ_FADD:
3487   case ISD::VECREDUCE_FMIN:
3488   case ISD::VECREDUCE_FMAX:
3489     return lowerFPVECREDUCE(Op, DAG);
3490   case ISD::VP_REDUCE_ADD:
3491   case ISD::VP_REDUCE_UMAX:
3492   case ISD::VP_REDUCE_SMAX:
3493   case ISD::VP_REDUCE_UMIN:
3494   case ISD::VP_REDUCE_SMIN:
3495   case ISD::VP_REDUCE_FADD:
3496   case ISD::VP_REDUCE_SEQ_FADD:
3497   case ISD::VP_REDUCE_FMIN:
3498   case ISD::VP_REDUCE_FMAX:
3499     return lowerVPREDUCE(Op, DAG);
3500   case ISD::VP_REDUCE_AND:
3501   case ISD::VP_REDUCE_OR:
3502   case ISD::VP_REDUCE_XOR:
3503     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3504       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3505     return lowerVPREDUCE(Op, DAG);
3506   case ISD::INSERT_SUBVECTOR:
3507     return lowerINSERT_SUBVECTOR(Op, DAG);
3508   case ISD::EXTRACT_SUBVECTOR:
3509     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3510   case ISD::STEP_VECTOR:
3511     return lowerSTEP_VECTOR(Op, DAG);
3512   case ISD::VECTOR_REVERSE:
3513     return lowerVECTOR_REVERSE(Op, DAG);
3514   case ISD::VECTOR_SPLICE:
3515     return lowerVECTOR_SPLICE(Op, DAG);
3516   case ISD::BUILD_VECTOR:
3517     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3518   case ISD::SPLAT_VECTOR:
3519     if (Op.getValueType().getVectorElementType() == MVT::i1)
3520       return lowerVectorMaskSplat(Op, DAG);
3521     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3522   case ISD::VECTOR_SHUFFLE:
3523     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3524   case ISD::CONCAT_VECTORS: {
3525     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3526     // better than going through the stack, as the default expansion does.
3527     SDLoc DL(Op);
3528     MVT VT = Op.getSimpleValueType();
3529     unsigned NumOpElts =
3530         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3531     SDValue Vec = DAG.getUNDEF(VT);
3532     for (const auto &OpIdx : enumerate(Op->ops())) {
3533       SDValue SubVec = OpIdx.value();
3534       // Don't insert undef subvectors.
3535       if (SubVec.isUndef())
3536         continue;
3537       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3538                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3539     }
3540     return Vec;
3541   }
3542   case ISD::LOAD:
3543     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3544       return V;
3545     if (Op.getValueType().isFixedLengthVector())
3546       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3547     return Op;
3548   case ISD::STORE:
3549     if (auto V = expandUnalignedRVVStore(Op, DAG))
3550       return V;
3551     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3552       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3553     return Op;
3554   case ISD::MLOAD:
3555   case ISD::VP_LOAD:
3556     return lowerMaskedLoad(Op, DAG);
3557   case ISD::MSTORE:
3558   case ISD::VP_STORE:
3559     return lowerMaskedStore(Op, DAG);
3560   case ISD::SETCC:
3561     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3562   case ISD::ADD:
3563     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3564   case ISD::SUB:
3565     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3566   case ISD::MUL:
3567     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3568   case ISD::MULHS:
3569     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3570   case ISD::MULHU:
3571     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3572   case ISD::AND:
3573     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3574                                               RISCVISD::AND_VL);
3575   case ISD::OR:
3576     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3577                                               RISCVISD::OR_VL);
3578   case ISD::XOR:
3579     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3580                                               RISCVISD::XOR_VL);
3581   case ISD::SDIV:
3582     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3583   case ISD::SREM:
3584     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3585   case ISD::UDIV:
3586     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3587   case ISD::UREM:
3588     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3589   case ISD::SHL:
3590   case ISD::SRA:
3591   case ISD::SRL:
3592     if (Op.getSimpleValueType().isFixedLengthVector())
3593       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3594     // This can be called for an i32 shift amount that needs to be promoted.
3595     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3596            "Unexpected custom legalisation");
3597     return SDValue();
3598   case ISD::SADDSAT:
3599     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3600   case ISD::UADDSAT:
3601     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3602   case ISD::SSUBSAT:
3603     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3604   case ISD::USUBSAT:
3605     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3606   case ISD::FADD:
3607     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3608   case ISD::FSUB:
3609     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3610   case ISD::FMUL:
3611     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3612   case ISD::FDIV:
3613     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3614   case ISD::FNEG:
3615     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3616   case ISD::FABS:
3617     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3618   case ISD::FSQRT:
3619     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3620   case ISD::FMA:
3621     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3622   case ISD::SMIN:
3623     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3624   case ISD::SMAX:
3625     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3626   case ISD::UMIN:
3627     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3628   case ISD::UMAX:
3629     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3630   case ISD::FMINNUM:
3631     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3632   case ISD::FMAXNUM:
3633     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3634   case ISD::ABS:
3635     return lowerABS(Op, DAG);
3636   case ISD::CTLZ_ZERO_UNDEF:
3637   case ISD::CTTZ_ZERO_UNDEF:
3638     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3639   case ISD::VSELECT:
3640     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3641   case ISD::FCOPYSIGN:
3642     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3643   case ISD::MGATHER:
3644   case ISD::VP_GATHER:
3645     return lowerMaskedGather(Op, DAG);
3646   case ISD::MSCATTER:
3647   case ISD::VP_SCATTER:
3648     return lowerMaskedScatter(Op, DAG);
3649   case ISD::FLT_ROUNDS_:
3650     return lowerGET_ROUNDING(Op, DAG);
3651   case ISD::SET_ROUNDING:
3652     return lowerSET_ROUNDING(Op, DAG);
3653   case ISD::VP_SELECT:
3654     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3655   case ISD::VP_MERGE:
3656     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3657   case ISD::VP_ADD:
3658     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3659   case ISD::VP_SUB:
3660     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3661   case ISD::VP_MUL:
3662     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3663   case ISD::VP_SDIV:
3664     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3665   case ISD::VP_UDIV:
3666     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3667   case ISD::VP_SREM:
3668     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3669   case ISD::VP_UREM:
3670     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3671   case ISD::VP_AND:
3672     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3673   case ISD::VP_OR:
3674     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3675   case ISD::VP_XOR:
3676     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3677   case ISD::VP_ASHR:
3678     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3679   case ISD::VP_LSHR:
3680     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3681   case ISD::VP_SHL:
3682     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3683   case ISD::VP_FADD:
3684     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3685   case ISD::VP_FSUB:
3686     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3687   case ISD::VP_FMUL:
3688     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3689   case ISD::VP_FDIV:
3690     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3691   case ISD::VP_FNEG:
3692     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3693   case ISD::VP_FMA:
3694     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3695   }
3696 }
3697 
3698 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3699                              SelectionDAG &DAG, unsigned Flags) {
3700   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3701 }
3702 
3703 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3704                              SelectionDAG &DAG, unsigned Flags) {
3705   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3706                                    Flags);
3707 }
3708 
3709 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3710                              SelectionDAG &DAG, unsigned Flags) {
3711   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3712                                    N->getOffset(), Flags);
3713 }
3714 
3715 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3716                              SelectionDAG &DAG, unsigned Flags) {
3717   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3718 }
3719 
3720 template <class NodeTy>
3721 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3722                                      bool IsLocal) const {
3723   SDLoc DL(N);
3724   EVT Ty = getPointerTy(DAG.getDataLayout());
3725 
3726   if (isPositionIndependent()) {
3727     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3728     if (IsLocal)
3729       // Use PC-relative addressing to access the symbol. This generates the
3730       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3731       // %pcrel_lo(auipc)).
3732       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3733 
3734     // Use PC-relative addressing to access the GOT for this symbol, then load
3735     // the address from the GOT. This generates the pattern (PseudoLA sym),
3736     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3737     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3738   }
3739 
3740   switch (getTargetMachine().getCodeModel()) {
3741   default:
3742     report_fatal_error("Unsupported code model for lowering");
3743   case CodeModel::Small: {
3744     // Generate a sequence for accessing addresses within the first 2 GiB of
3745     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3746     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3747     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3748     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3749     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3750   }
3751   case CodeModel::Medium: {
3752     // Generate a sequence for accessing addresses within any 2GiB range within
3753     // the address space. This generates the pattern (PseudoLLA sym), which
3754     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3755     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3756     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3757   }
3758   }
3759 }
3760 
3761 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3762                                                 SelectionDAG &DAG) const {
3763   SDLoc DL(Op);
3764   EVT Ty = Op.getValueType();
3765   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3766   int64_t Offset = N->getOffset();
3767   MVT XLenVT = Subtarget.getXLenVT();
3768 
3769   const GlobalValue *GV = N->getGlobal();
3770   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3771   SDValue Addr = getAddr(N, DAG, IsLocal);
3772 
3773   // In order to maximise the opportunity for common subexpression elimination,
3774   // emit a separate ADD node for the global address offset instead of folding
3775   // it in the global address node. Later peephole optimisations may choose to
3776   // fold it back in when profitable.
3777   if (Offset != 0)
3778     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3779                        DAG.getConstant(Offset, DL, XLenVT));
3780   return Addr;
3781 }
3782 
3783 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3784                                                SelectionDAG &DAG) const {
3785   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3786 
3787   return getAddr(N, DAG);
3788 }
3789 
3790 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3791                                                SelectionDAG &DAG) const {
3792   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3793 
3794   return getAddr(N, DAG);
3795 }
3796 
3797 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3798                                             SelectionDAG &DAG) const {
3799   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3800 
3801   return getAddr(N, DAG);
3802 }
3803 
3804 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3805                                               SelectionDAG &DAG,
3806                                               bool UseGOT) const {
3807   SDLoc DL(N);
3808   EVT Ty = getPointerTy(DAG.getDataLayout());
3809   const GlobalValue *GV = N->getGlobal();
3810   MVT XLenVT = Subtarget.getXLenVT();
3811 
3812   if (UseGOT) {
3813     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3814     // load the address from the GOT and add the thread pointer. This generates
3815     // the pattern (PseudoLA_TLS_IE sym), which expands to
3816     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3817     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3818     SDValue Load =
3819         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3820 
3821     // Add the thread pointer.
3822     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3823     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3824   }
3825 
3826   // Generate a sequence for accessing the address relative to the thread
3827   // pointer, with the appropriate adjustment for the thread pointer offset.
3828   // This generates the pattern
3829   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3830   SDValue AddrHi =
3831       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3832   SDValue AddrAdd =
3833       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3834   SDValue AddrLo =
3835       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3836 
3837   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3838   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3839   SDValue MNAdd = SDValue(
3840       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3841       0);
3842   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3843 }
3844 
3845 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3846                                                SelectionDAG &DAG) const {
3847   SDLoc DL(N);
3848   EVT Ty = getPointerTy(DAG.getDataLayout());
3849   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3850   const GlobalValue *GV = N->getGlobal();
3851 
3852   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3853   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3854   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3855   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3856   SDValue Load =
3857       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3858 
3859   // Prepare argument list to generate call.
3860   ArgListTy Args;
3861   ArgListEntry Entry;
3862   Entry.Node = Load;
3863   Entry.Ty = CallTy;
3864   Args.push_back(Entry);
3865 
3866   // Setup call to __tls_get_addr.
3867   TargetLowering::CallLoweringInfo CLI(DAG);
3868   CLI.setDebugLoc(DL)
3869       .setChain(DAG.getEntryNode())
3870       .setLibCallee(CallingConv::C, CallTy,
3871                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3872                     std::move(Args));
3873 
3874   return LowerCallTo(CLI).first;
3875 }
3876 
3877 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3878                                                    SelectionDAG &DAG) const {
3879   SDLoc DL(Op);
3880   EVT Ty = Op.getValueType();
3881   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3882   int64_t Offset = N->getOffset();
3883   MVT XLenVT = Subtarget.getXLenVT();
3884 
3885   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3886 
3887   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3888       CallingConv::GHC)
3889     report_fatal_error("In GHC calling convention TLS is not supported");
3890 
3891   SDValue Addr;
3892   switch (Model) {
3893   case TLSModel::LocalExec:
3894     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3895     break;
3896   case TLSModel::InitialExec:
3897     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3898     break;
3899   case TLSModel::LocalDynamic:
3900   case TLSModel::GeneralDynamic:
3901     Addr = getDynamicTLSAddr(N, DAG);
3902     break;
3903   }
3904 
3905   // In order to maximise the opportunity for common subexpression elimination,
3906   // emit a separate ADD node for the global address offset instead of folding
3907   // it in the global address node. Later peephole optimisations may choose to
3908   // fold it back in when profitable.
3909   if (Offset != 0)
3910     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3911                        DAG.getConstant(Offset, DL, XLenVT));
3912   return Addr;
3913 }
3914 
3915 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3916   SDValue CondV = Op.getOperand(0);
3917   SDValue TrueV = Op.getOperand(1);
3918   SDValue FalseV = Op.getOperand(2);
3919   SDLoc DL(Op);
3920   MVT VT = Op.getSimpleValueType();
3921   MVT XLenVT = Subtarget.getXLenVT();
3922 
3923   // Lower vector SELECTs to VSELECTs by splatting the condition.
3924   if (VT.isVector()) {
3925     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3926     SDValue CondSplat = VT.isScalableVector()
3927                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3928                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3929     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3930   }
3931 
3932   // If the result type is XLenVT and CondV is the output of a SETCC node
3933   // which also operated on XLenVT inputs, then merge the SETCC node into the
3934   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3935   // compare+branch instructions. i.e.:
3936   // (select (setcc lhs, rhs, cc), truev, falsev)
3937   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3938   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3939       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3940     SDValue LHS = CondV.getOperand(0);
3941     SDValue RHS = CondV.getOperand(1);
3942     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3943     ISD::CondCode CCVal = CC->get();
3944 
3945     // Special case for a select of 2 constants that have a diffence of 1.
3946     // Normally this is done by DAGCombine, but if the select is introduced by
3947     // type legalization or op legalization, we miss it. Restricting to SETLT
3948     // case for now because that is what signed saturating add/sub need.
3949     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3950     // but we would probably want to swap the true/false values if the condition
3951     // is SETGE/SETLE to avoid an XORI.
3952     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3953         CCVal == ISD::SETLT) {
3954       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3955       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3956       if (TrueVal - 1 == FalseVal)
3957         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3958       if (TrueVal + 1 == FalseVal)
3959         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3960     }
3961 
3962     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3963 
3964     SDValue TargetCC = DAG.getCondCode(CCVal);
3965     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3966     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3967   }
3968 
3969   // Otherwise:
3970   // (select condv, truev, falsev)
3971   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3972   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3973   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3974 
3975   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3976 
3977   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3978 }
3979 
3980 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3981   SDValue CondV = Op.getOperand(1);
3982   SDLoc DL(Op);
3983   MVT XLenVT = Subtarget.getXLenVT();
3984 
3985   if (CondV.getOpcode() == ISD::SETCC &&
3986       CondV.getOperand(0).getValueType() == XLenVT) {
3987     SDValue LHS = CondV.getOperand(0);
3988     SDValue RHS = CondV.getOperand(1);
3989     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3990 
3991     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3992 
3993     SDValue TargetCC = DAG.getCondCode(CCVal);
3994     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3995                        LHS, RHS, TargetCC, Op.getOperand(2));
3996   }
3997 
3998   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3999                      CondV, DAG.getConstant(0, DL, XLenVT),
4000                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4001 }
4002 
4003 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4004   MachineFunction &MF = DAG.getMachineFunction();
4005   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4006 
4007   SDLoc DL(Op);
4008   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4009                                  getPointerTy(MF.getDataLayout()));
4010 
4011   // vastart just stores the address of the VarArgsFrameIndex slot into the
4012   // memory location argument.
4013   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4014   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4015                       MachinePointerInfo(SV));
4016 }
4017 
4018 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4019                                             SelectionDAG &DAG) const {
4020   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4021   MachineFunction &MF = DAG.getMachineFunction();
4022   MachineFrameInfo &MFI = MF.getFrameInfo();
4023   MFI.setFrameAddressIsTaken(true);
4024   Register FrameReg = RI.getFrameRegister(MF);
4025   int XLenInBytes = Subtarget.getXLen() / 8;
4026 
4027   EVT VT = Op.getValueType();
4028   SDLoc DL(Op);
4029   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4030   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4031   while (Depth--) {
4032     int Offset = -(XLenInBytes * 2);
4033     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4034                               DAG.getIntPtrConstant(Offset, DL));
4035     FrameAddr =
4036         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4037   }
4038   return FrameAddr;
4039 }
4040 
4041 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4042                                              SelectionDAG &DAG) const {
4043   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4044   MachineFunction &MF = DAG.getMachineFunction();
4045   MachineFrameInfo &MFI = MF.getFrameInfo();
4046   MFI.setReturnAddressIsTaken(true);
4047   MVT XLenVT = Subtarget.getXLenVT();
4048   int XLenInBytes = Subtarget.getXLen() / 8;
4049 
4050   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4051     return SDValue();
4052 
4053   EVT VT = Op.getValueType();
4054   SDLoc DL(Op);
4055   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4056   if (Depth) {
4057     int Off = -XLenInBytes;
4058     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4059     SDValue Offset = DAG.getConstant(Off, DL, VT);
4060     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4061                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4062                        MachinePointerInfo());
4063   }
4064 
4065   // Return the value of the return address register, marking it an implicit
4066   // live-in.
4067   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4068   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4069 }
4070 
4071 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4072                                                  SelectionDAG &DAG) const {
4073   SDLoc DL(Op);
4074   SDValue Lo = Op.getOperand(0);
4075   SDValue Hi = Op.getOperand(1);
4076   SDValue Shamt = Op.getOperand(2);
4077   EVT VT = Lo.getValueType();
4078 
4079   // if Shamt-XLEN < 0: // Shamt < XLEN
4080   //   Lo = Lo << Shamt
4081   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4082   // else:
4083   //   Lo = 0
4084   //   Hi = Lo << (Shamt-XLEN)
4085 
4086   SDValue Zero = DAG.getConstant(0, DL, VT);
4087   SDValue One = DAG.getConstant(1, DL, VT);
4088   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4089   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4090   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4091   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4092 
4093   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4094   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4095   SDValue ShiftRightLo =
4096       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4097   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4098   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4099   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4100 
4101   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4102 
4103   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4104   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4105 
4106   SDValue Parts[2] = {Lo, Hi};
4107   return DAG.getMergeValues(Parts, DL);
4108 }
4109 
4110 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4111                                                   bool IsSRA) const {
4112   SDLoc DL(Op);
4113   SDValue Lo = Op.getOperand(0);
4114   SDValue Hi = Op.getOperand(1);
4115   SDValue Shamt = Op.getOperand(2);
4116   EVT VT = Lo.getValueType();
4117 
4118   // SRA expansion:
4119   //   if Shamt-XLEN < 0: // Shamt < XLEN
4120   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4121   //     Hi = Hi >>s Shamt
4122   //   else:
4123   //     Lo = Hi >>s (Shamt-XLEN);
4124   //     Hi = Hi >>s (XLEN-1)
4125   //
4126   // SRL expansion:
4127   //   if Shamt-XLEN < 0: // Shamt < XLEN
4128   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4129   //     Hi = Hi >>u Shamt
4130   //   else:
4131   //     Lo = Hi >>u (Shamt-XLEN);
4132   //     Hi = 0;
4133 
4134   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4135 
4136   SDValue Zero = DAG.getConstant(0, DL, VT);
4137   SDValue One = DAG.getConstant(1, DL, VT);
4138   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4139   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4140   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4141   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4142 
4143   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4144   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4145   SDValue ShiftLeftHi =
4146       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4147   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4148   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4149   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4150   SDValue HiFalse =
4151       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4152 
4153   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4154 
4155   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4156   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4157 
4158   SDValue Parts[2] = {Lo, Hi};
4159   return DAG.getMergeValues(Parts, DL);
4160 }
4161 
4162 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4163 // legal equivalently-sized i8 type, so we can use that as a go-between.
4164 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4165                                                   SelectionDAG &DAG) const {
4166   SDLoc DL(Op);
4167   MVT VT = Op.getSimpleValueType();
4168   SDValue SplatVal = Op.getOperand(0);
4169   // All-zeros or all-ones splats are handled specially.
4170   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4171     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4172     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4173   }
4174   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4175     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4176     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4177   }
4178   MVT XLenVT = Subtarget.getXLenVT();
4179   assert(SplatVal.getValueType() == XLenVT &&
4180          "Unexpected type for i1 splat value");
4181   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4182   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4183                          DAG.getConstant(1, DL, XLenVT));
4184   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4185   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4186   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4187 }
4188 
4189 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4190 // illegal (currently only vXi64 RV32).
4191 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4192 // them to VMV_V_X_VL.
4193 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4194                                                      SelectionDAG &DAG) const {
4195   SDLoc DL(Op);
4196   MVT VecVT = Op.getSimpleValueType();
4197   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4198          "Unexpected SPLAT_VECTOR_PARTS lowering");
4199 
4200   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4201   SDValue Lo = Op.getOperand(0);
4202   SDValue Hi = Op.getOperand(1);
4203 
4204   if (VecVT.isFixedLengthVector()) {
4205     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4206     SDLoc DL(Op);
4207     SDValue Mask, VL;
4208     std::tie(Mask, VL) =
4209         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4210 
4211     SDValue Res =
4212         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4213     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4214   }
4215 
4216   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4217     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4218     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4219     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4220     // node in order to try and match RVV vector/scalar instructions.
4221     if ((LoC >> 31) == HiC)
4222       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4223                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4224   }
4225 
4226   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4227   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4228       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4229       Hi.getConstantOperandVal(1) == 31)
4230     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4231                        DAG.getRegister(RISCV::X0, MVT::i32));
4232 
4233   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4234   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4235                      DAG.getUNDEF(VecVT), Lo, Hi,
4236                      DAG.getRegister(RISCV::X0, MVT::i32));
4237 }
4238 
4239 // Custom-lower extensions from mask vectors by using a vselect either with 1
4240 // for zero/any-extension or -1 for sign-extension:
4241 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4242 // Note that any-extension is lowered identically to zero-extension.
4243 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4244                                                 int64_t ExtTrueVal) const {
4245   SDLoc DL(Op);
4246   MVT VecVT = Op.getSimpleValueType();
4247   SDValue Src = Op.getOperand(0);
4248   // Only custom-lower extensions from mask types
4249   assert(Src.getValueType().isVector() &&
4250          Src.getValueType().getVectorElementType() == MVT::i1);
4251 
4252   MVT XLenVT = Subtarget.getXLenVT();
4253   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4254   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4255 
4256   if (VecVT.isScalableVector()) {
4257     // Be careful not to introduce illegal scalar types at this stage, and be
4258     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4259     // illegal and must be expanded. Since we know that the constants are
4260     // sign-extended 32-bit values, we use VMV_V_X_VL directly.
4261     bool IsRV32E64 =
4262         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4263 
4264     if (!IsRV32E64) {
4265       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4266       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4267     } else {
4268       SplatZero =
4269           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4270                       SplatZero, DAG.getRegister(RISCV::X0, XLenVT));
4271       SplatTrueVal =
4272           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4273                       SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT));
4274     }
4275 
4276     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4277   }
4278 
4279   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4280   MVT I1ContainerVT =
4281       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4282 
4283   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4284 
4285   SDValue Mask, VL;
4286   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4287 
4288   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4289                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4290   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4291                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4292   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4293                                SplatTrueVal, SplatZero, VL);
4294 
4295   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4296 }
4297 
4298 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4299     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4300   MVT ExtVT = Op.getSimpleValueType();
4301   // Only custom-lower extensions from fixed-length vector types.
4302   if (!ExtVT.isFixedLengthVector())
4303     return Op;
4304   MVT VT = Op.getOperand(0).getSimpleValueType();
4305   // Grab the canonical container type for the extended type. Infer the smaller
4306   // type from that to ensure the same number of vector elements, as we know
4307   // the LMUL will be sufficient to hold the smaller type.
4308   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4309   // Get the extended container type manually to ensure the same number of
4310   // vector elements between source and dest.
4311   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4312                                      ContainerExtVT.getVectorElementCount());
4313 
4314   SDValue Op1 =
4315       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4316 
4317   SDLoc DL(Op);
4318   SDValue Mask, VL;
4319   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4320 
4321   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4322 
4323   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4324 }
4325 
4326 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4327 // setcc operation:
4328 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4329 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4330                                                   SelectionDAG &DAG) const {
4331   SDLoc DL(Op);
4332   EVT MaskVT = Op.getValueType();
4333   // Only expect to custom-lower truncations to mask types
4334   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4335          "Unexpected type for vector mask lowering");
4336   SDValue Src = Op.getOperand(0);
4337   MVT VecVT = Src.getSimpleValueType();
4338 
4339   // If this is a fixed vector, we need to convert it to a scalable vector.
4340   MVT ContainerVT = VecVT;
4341   if (VecVT.isFixedLengthVector()) {
4342     ContainerVT = getContainerForFixedLengthVector(VecVT);
4343     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4344   }
4345 
4346   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4347   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4348 
4349   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4350                          DAG.getUNDEF(ContainerVT), SplatOne);
4351   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4352                           DAG.getUNDEF(ContainerVT), SplatZero);
4353 
4354   if (VecVT.isScalableVector()) {
4355     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4356     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4357   }
4358 
4359   SDValue Mask, VL;
4360   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4361 
4362   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4363   SDValue Trunc =
4364       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4365   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4366                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4367   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4368 }
4369 
4370 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4371 // first position of a vector, and that vector is slid up to the insert index.
4372 // By limiting the active vector length to index+1 and merging with the
4373 // original vector (with an undisturbed tail policy for elements >= VL), we
4374 // achieve the desired result of leaving all elements untouched except the one
4375 // at VL-1, which is replaced with the desired value.
4376 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4377                                                     SelectionDAG &DAG) const {
4378   SDLoc DL(Op);
4379   MVT VecVT = Op.getSimpleValueType();
4380   SDValue Vec = Op.getOperand(0);
4381   SDValue Val = Op.getOperand(1);
4382   SDValue Idx = Op.getOperand(2);
4383 
4384   if (VecVT.getVectorElementType() == MVT::i1) {
4385     // FIXME: For now we just promote to an i8 vector and insert into that,
4386     // but this is probably not optimal.
4387     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4388     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4389     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4390     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4391   }
4392 
4393   MVT ContainerVT = VecVT;
4394   // If the operand is a fixed-length vector, convert to a scalable one.
4395   if (VecVT.isFixedLengthVector()) {
4396     ContainerVT = getContainerForFixedLengthVector(VecVT);
4397     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4398   }
4399 
4400   MVT XLenVT = Subtarget.getXLenVT();
4401 
4402   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4403   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4404   // Even i64-element vectors on RV32 can be lowered without scalar
4405   // legalization if the most-significant 32 bits of the value are not affected
4406   // by the sign-extension of the lower 32 bits.
4407   // TODO: We could also catch sign extensions of a 32-bit value.
4408   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4409     const auto *CVal = cast<ConstantSDNode>(Val);
4410     if (isInt<32>(CVal->getSExtValue())) {
4411       IsLegalInsert = true;
4412       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4413     }
4414   }
4415 
4416   SDValue Mask, VL;
4417   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4418 
4419   SDValue ValInVec;
4420 
4421   if (IsLegalInsert) {
4422     unsigned Opc =
4423         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4424     if (isNullConstant(Idx)) {
4425       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4426       if (!VecVT.isFixedLengthVector())
4427         return Vec;
4428       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4429     }
4430     ValInVec =
4431         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4432   } else {
4433     // On RV32, i64-element vectors must be specially handled to place the
4434     // value at element 0, by using two vslide1up instructions in sequence on
4435     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4436     // this.
4437     SDValue One = DAG.getConstant(1, DL, XLenVT);
4438     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4439     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4440     MVT I32ContainerVT =
4441         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4442     SDValue I32Mask =
4443         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4444     // Limit the active VL to two.
4445     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4446     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4447     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4448     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4449                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4450     // First slide in the hi value, then the lo in underneath it.
4451     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4452                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4453                            I32Mask, InsertI64VL);
4454     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4455                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4456                            I32Mask, InsertI64VL);
4457     // Bitcast back to the right container type.
4458     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4459   }
4460 
4461   // Now that the value is in a vector, slide it into position.
4462   SDValue InsertVL =
4463       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4464   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4465                                 ValInVec, Idx, Mask, InsertVL);
4466   if (!VecVT.isFixedLengthVector())
4467     return Slideup;
4468   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4469 }
4470 
4471 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4472 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4473 // types this is done using VMV_X_S to allow us to glean information about the
4474 // sign bits of the result.
4475 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4476                                                      SelectionDAG &DAG) const {
4477   SDLoc DL(Op);
4478   SDValue Idx = Op.getOperand(1);
4479   SDValue Vec = Op.getOperand(0);
4480   EVT EltVT = Op.getValueType();
4481   MVT VecVT = Vec.getSimpleValueType();
4482   MVT XLenVT = Subtarget.getXLenVT();
4483 
4484   if (VecVT.getVectorElementType() == MVT::i1) {
4485     if (VecVT.isFixedLengthVector()) {
4486       unsigned NumElts = VecVT.getVectorNumElements();
4487       if (NumElts >= 8) {
4488         MVT WideEltVT;
4489         unsigned WidenVecLen;
4490         SDValue ExtractElementIdx;
4491         SDValue ExtractBitIdx;
4492         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4493         MVT LargestEltVT = MVT::getIntegerVT(
4494             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4495         if (NumElts <= LargestEltVT.getSizeInBits()) {
4496           assert(isPowerOf2_32(NumElts) &&
4497                  "the number of elements should be power of 2");
4498           WideEltVT = MVT::getIntegerVT(NumElts);
4499           WidenVecLen = 1;
4500           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4501           ExtractBitIdx = Idx;
4502         } else {
4503           WideEltVT = LargestEltVT;
4504           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4505           // extract element index = index / element width
4506           ExtractElementIdx = DAG.getNode(
4507               ISD::SRL, DL, XLenVT, Idx,
4508               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4509           // mask bit index = index % element width
4510           ExtractBitIdx = DAG.getNode(
4511               ISD::AND, DL, XLenVT, Idx,
4512               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4513         }
4514         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4515         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4516         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4517                                          Vec, ExtractElementIdx);
4518         // Extract the bit from GPR.
4519         SDValue ShiftRight =
4520             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4521         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4522                            DAG.getConstant(1, DL, XLenVT));
4523       }
4524     }
4525     // Otherwise, promote to an i8 vector and extract from that.
4526     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4527     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4528     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4529   }
4530 
4531   // If this is a fixed vector, we need to convert it to a scalable vector.
4532   MVT ContainerVT = VecVT;
4533   if (VecVT.isFixedLengthVector()) {
4534     ContainerVT = getContainerForFixedLengthVector(VecVT);
4535     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4536   }
4537 
4538   // If the index is 0, the vector is already in the right position.
4539   if (!isNullConstant(Idx)) {
4540     // Use a VL of 1 to avoid processing more elements than we need.
4541     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4542     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4543     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4544     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4545                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4546   }
4547 
4548   if (!EltVT.isInteger()) {
4549     // Floating-point extracts are handled in TableGen.
4550     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4551                        DAG.getConstant(0, DL, XLenVT));
4552   }
4553 
4554   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4555   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4556 }
4557 
4558 // Some RVV intrinsics may claim that they want an integer operand to be
4559 // promoted or expanded.
4560 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4561                                           const RISCVSubtarget &Subtarget) {
4562   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4563           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4564          "Unexpected opcode");
4565 
4566   if (!Subtarget.hasVInstructions())
4567     return SDValue();
4568 
4569   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4570   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4571   SDLoc DL(Op);
4572 
4573   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4574       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4575   if (!II || !II->hasSplatOperand())
4576     return SDValue();
4577 
4578   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4579   assert(SplatOp < Op.getNumOperands());
4580 
4581   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4582   SDValue &ScalarOp = Operands[SplatOp];
4583   MVT OpVT = ScalarOp.getSimpleValueType();
4584   MVT XLenVT = Subtarget.getXLenVT();
4585 
4586   // If this isn't a scalar, or its type is XLenVT we're done.
4587   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4588     return SDValue();
4589 
4590   // Simplest case is that the operand needs to be promoted to XLenVT.
4591   if (OpVT.bitsLT(XLenVT)) {
4592     // If the operand is a constant, sign extend to increase our chances
4593     // of being able to use a .vi instruction. ANY_EXTEND would become a
4594     // a zero extend and the simm5 check in isel would fail.
4595     // FIXME: Should we ignore the upper bits in isel instead?
4596     unsigned ExtOpc =
4597         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4598     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4599     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4600   }
4601 
4602   // Use the previous operand to get the vXi64 VT. The result might be a mask
4603   // VT for compares. Using the previous operand assumes that the previous
4604   // operand will never have a smaller element size than a scalar operand and
4605   // that a widening operation never uses SEW=64.
4606   // NOTE: If this fails the below assert, we can probably just find the
4607   // element count from any operand or result and use it to construct the VT.
4608   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4609   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4610 
4611   // The more complex case is when the scalar is larger than XLenVT.
4612   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4613          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4614 
4615   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4616   // on the instruction to sign-extend since SEW>XLEN.
4617   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4618     if (isInt<32>(CVal->getSExtValue())) {
4619       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4620       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4621     }
4622   }
4623 
4624   // We need to convert the scalar to a splat vector.
4625   // FIXME: Can we implicitly truncate the scalar if it is known to
4626   // be sign extended?
4627   SDValue VL = getVLOperand(Op);
4628   assert(VL.getValueType() == XLenVT);
4629   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4630   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4631 }
4632 
4633 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4634                                                      SelectionDAG &DAG) const {
4635   unsigned IntNo = Op.getConstantOperandVal(0);
4636   SDLoc DL(Op);
4637   MVT XLenVT = Subtarget.getXLenVT();
4638 
4639   switch (IntNo) {
4640   default:
4641     break; // Don't custom lower most intrinsics.
4642   case Intrinsic::thread_pointer: {
4643     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4644     return DAG.getRegister(RISCV::X4, PtrVT);
4645   }
4646   case Intrinsic::riscv_orc_b:
4647   case Intrinsic::riscv_brev8: {
4648     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4649     unsigned Opc =
4650         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4651     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4652                        DAG.getConstant(7, DL, XLenVT));
4653   }
4654   case Intrinsic::riscv_grev:
4655   case Intrinsic::riscv_gorc: {
4656     unsigned Opc =
4657         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4658     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4659   }
4660   case Intrinsic::riscv_zip:
4661   case Intrinsic::riscv_unzip: {
4662     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4663     // For i32 the immdiate is 15. For i64 the immediate is 31.
4664     unsigned Opc =
4665         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4666     unsigned BitWidth = Op.getValueSizeInBits();
4667     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4668     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4669                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4670   }
4671   case Intrinsic::riscv_shfl:
4672   case Intrinsic::riscv_unshfl: {
4673     unsigned Opc =
4674         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4675     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4676   }
4677   case Intrinsic::riscv_bcompress:
4678   case Intrinsic::riscv_bdecompress: {
4679     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4680                                                        : RISCVISD::BDECOMPRESS;
4681     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4682   }
4683   case Intrinsic::riscv_bfp:
4684     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4685                        Op.getOperand(2));
4686   case Intrinsic::riscv_fsl:
4687     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4688                        Op.getOperand(2), Op.getOperand(3));
4689   case Intrinsic::riscv_fsr:
4690     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4691                        Op.getOperand(2), Op.getOperand(3));
4692   case Intrinsic::riscv_vmv_x_s:
4693     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4694     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4695                        Op.getOperand(1));
4696   case Intrinsic::riscv_vmv_v_x:
4697     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4698                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4699                             Subtarget);
4700   case Intrinsic::riscv_vfmv_v_f:
4701     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4702                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4703   case Intrinsic::riscv_vmv_s_x: {
4704     SDValue Scalar = Op.getOperand(2);
4705 
4706     if (Scalar.getValueType().bitsLE(XLenVT)) {
4707       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4708       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4709                          Op.getOperand(1), Scalar, Op.getOperand(3));
4710     }
4711 
4712     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4713 
4714     // This is an i64 value that lives in two scalar registers. We have to
4715     // insert this in a convoluted way. First we build vXi64 splat containing
4716     // the/ two values that we assemble using some bit math. Next we'll use
4717     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4718     // to merge element 0 from our splat into the source vector.
4719     // FIXME: This is probably not the best way to do this, but it is
4720     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4721     // point.
4722     //   sw lo, (a0)
4723     //   sw hi, 4(a0)
4724     //   vlse vX, (a0)
4725     //
4726     //   vid.v      vVid
4727     //   vmseq.vx   mMask, vVid, 0
4728     //   vmerge.vvm vDest, vSrc, vVal, mMask
4729     MVT VT = Op.getSimpleValueType();
4730     SDValue Vec = Op.getOperand(1);
4731     SDValue VL = getVLOperand(Op);
4732 
4733     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4734     if (Op.getOperand(1).isUndef())
4735       return SplattedVal;
4736     SDValue SplattedIdx =
4737         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4738                     DAG.getConstant(0, DL, MVT::i32), VL);
4739 
4740     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4741     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4742     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4743     SDValue SelectCond =
4744         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4745                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4746     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4747                        Vec, VL);
4748   }
4749   case Intrinsic::riscv_vslide1up:
4750   case Intrinsic::riscv_vslide1down:
4751   case Intrinsic::riscv_vslide1up_mask:
4752   case Intrinsic::riscv_vslide1down_mask: {
4753     // We need to special case these when the scalar is larger than XLen.
4754     unsigned NumOps = Op.getNumOperands();
4755     bool IsMasked = NumOps == 7;
4756     SDValue Scalar = Op.getOperand(3);
4757     if (Scalar.getValueType().bitsLE(XLenVT))
4758       break;
4759 
4760     // Splatting a sign extended constant is fine.
4761     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4762       if (isInt<32>(CVal->getSExtValue()))
4763         break;
4764 
4765     MVT VT = Op.getSimpleValueType();
4766     assert(VT.getVectorElementType() == MVT::i64 &&
4767            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4768 
4769     // Convert the vector source to the equivalent nxvXi32 vector.
4770     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4771     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(2));
4772 
4773     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4774                                    DAG.getConstant(0, DL, XLenVT));
4775     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4776                                    DAG.getConstant(1, DL, XLenVT));
4777 
4778     // Double the VL since we halved SEW.
4779     SDValue VL = getVLOperand(Op);
4780     SDValue I32VL =
4781         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4782 
4783     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4784     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4785 
4786     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4787     // instructions.
4788     SDValue Passthru = DAG.getBitcast(I32VT, Op.getOperand(1));
4789     if (!IsMasked) {
4790       if (IntNo == Intrinsic::riscv_vslide1up) {
4791         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4792                           ScalarHi, I32Mask, I32VL);
4793         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4794                           ScalarLo, I32Mask, I32VL);
4795       } else {
4796         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4797                           ScalarLo, I32Mask, I32VL);
4798         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4799                           ScalarHi, I32Mask, I32VL);
4800       }
4801     } else {
4802       // TODO Those VSLIDE1 could be TAMA because we use vmerge to select
4803       // maskedoff
4804       SDValue Undef = DAG.getUNDEF(I32VT);
4805       if (IntNo == Intrinsic::riscv_vslide1up_mask) {
4806         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec,
4807                           ScalarHi, I32Mask, I32VL);
4808         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec,
4809                           ScalarLo, I32Mask, I32VL);
4810       } else {
4811         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec,
4812                           ScalarLo, I32Mask, I32VL);
4813         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec,
4814                           ScalarHi, I32Mask, I32VL);
4815       }
4816     }
4817 
4818     // Convert back to nxvXi64.
4819     Vec = DAG.getBitcast(VT, Vec);
4820 
4821     if (!IsMasked)
4822       return Vec;
4823     // Apply mask after the operation.
4824     SDValue Mask = Op.getOperand(NumOps - 3);
4825     SDValue MaskedOff = Op.getOperand(1);
4826     // Assume Policy operand is the last operand.
4827     uint64_t Policy = Op.getConstantOperandVal(NumOps - 1);
4828     // We don't need to select maskedoff if it's undef.
4829     if (MaskedOff.isUndef())
4830       return Vec;
4831     // TAMU
4832     if (Policy == RISCVII::TAIL_AGNOSTIC)
4833       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4834                          VL);
4835     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4836     // It's fine because vmerge does not care mask policy.
4837     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4838   }
4839   }
4840 
4841   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4842 }
4843 
4844 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4845                                                     SelectionDAG &DAG) const {
4846   unsigned IntNo = Op.getConstantOperandVal(1);
4847   switch (IntNo) {
4848   default:
4849     break;
4850   case Intrinsic::riscv_masked_strided_load: {
4851     SDLoc DL(Op);
4852     MVT XLenVT = Subtarget.getXLenVT();
4853 
4854     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4855     // the selection of the masked intrinsics doesn't do this for us.
4856     SDValue Mask = Op.getOperand(5);
4857     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4858 
4859     MVT VT = Op->getSimpleValueType(0);
4860     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4861 
4862     SDValue PassThru = Op.getOperand(2);
4863     if (!IsUnmasked) {
4864       MVT MaskVT =
4865           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4866       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4867       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4868     }
4869 
4870     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4871 
4872     SDValue IntID = DAG.getTargetConstant(
4873         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4874         XLenVT);
4875 
4876     auto *Load = cast<MemIntrinsicSDNode>(Op);
4877     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4878     if (IsUnmasked)
4879       Ops.push_back(DAG.getUNDEF(ContainerVT));
4880     else
4881       Ops.push_back(PassThru);
4882     Ops.push_back(Op.getOperand(3)); // Ptr
4883     Ops.push_back(Op.getOperand(4)); // Stride
4884     if (!IsUnmasked)
4885       Ops.push_back(Mask);
4886     Ops.push_back(VL);
4887     if (!IsUnmasked) {
4888       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4889       Ops.push_back(Policy);
4890     }
4891 
4892     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4893     SDValue Result =
4894         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4895                                 Load->getMemoryVT(), Load->getMemOperand());
4896     SDValue Chain = Result.getValue(1);
4897     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4898     return DAG.getMergeValues({Result, Chain}, DL);
4899   }
4900   }
4901 
4902   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4903 }
4904 
4905 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4906                                                  SelectionDAG &DAG) const {
4907   unsigned IntNo = Op.getConstantOperandVal(1);
4908   switch (IntNo) {
4909   default:
4910     break;
4911   case Intrinsic::riscv_masked_strided_store: {
4912     SDLoc DL(Op);
4913     MVT XLenVT = Subtarget.getXLenVT();
4914 
4915     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4916     // the selection of the masked intrinsics doesn't do this for us.
4917     SDValue Mask = Op.getOperand(5);
4918     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4919 
4920     SDValue Val = Op.getOperand(2);
4921     MVT VT = Val.getSimpleValueType();
4922     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4923 
4924     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4925     if (!IsUnmasked) {
4926       MVT MaskVT =
4927           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4928       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4929     }
4930 
4931     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4932 
4933     SDValue IntID = DAG.getTargetConstant(
4934         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4935         XLenVT);
4936 
4937     auto *Store = cast<MemIntrinsicSDNode>(Op);
4938     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4939     Ops.push_back(Val);
4940     Ops.push_back(Op.getOperand(3)); // Ptr
4941     Ops.push_back(Op.getOperand(4)); // Stride
4942     if (!IsUnmasked)
4943       Ops.push_back(Mask);
4944     Ops.push_back(VL);
4945 
4946     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4947                                    Ops, Store->getMemoryVT(),
4948                                    Store->getMemOperand());
4949   }
4950   }
4951 
4952   return SDValue();
4953 }
4954 
4955 static MVT getLMUL1VT(MVT VT) {
4956   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4957          "Unexpected vector MVT");
4958   return MVT::getScalableVectorVT(
4959       VT.getVectorElementType(),
4960       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4961 }
4962 
4963 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4964   switch (ISDOpcode) {
4965   default:
4966     llvm_unreachable("Unhandled reduction");
4967   case ISD::VECREDUCE_ADD:
4968     return RISCVISD::VECREDUCE_ADD_VL;
4969   case ISD::VECREDUCE_UMAX:
4970     return RISCVISD::VECREDUCE_UMAX_VL;
4971   case ISD::VECREDUCE_SMAX:
4972     return RISCVISD::VECREDUCE_SMAX_VL;
4973   case ISD::VECREDUCE_UMIN:
4974     return RISCVISD::VECREDUCE_UMIN_VL;
4975   case ISD::VECREDUCE_SMIN:
4976     return RISCVISD::VECREDUCE_SMIN_VL;
4977   case ISD::VECREDUCE_AND:
4978     return RISCVISD::VECREDUCE_AND_VL;
4979   case ISD::VECREDUCE_OR:
4980     return RISCVISD::VECREDUCE_OR_VL;
4981   case ISD::VECREDUCE_XOR:
4982     return RISCVISD::VECREDUCE_XOR_VL;
4983   }
4984 }
4985 
4986 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4987                                                          SelectionDAG &DAG,
4988                                                          bool IsVP) const {
4989   SDLoc DL(Op);
4990   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4991   MVT VecVT = Vec.getSimpleValueType();
4992   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4993           Op.getOpcode() == ISD::VECREDUCE_OR ||
4994           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4995           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4996           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4997           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4998          "Unexpected reduction lowering");
4999 
5000   MVT XLenVT = Subtarget.getXLenVT();
5001   assert(Op.getValueType() == XLenVT &&
5002          "Expected reduction output to be legalized to XLenVT");
5003 
5004   MVT ContainerVT = VecVT;
5005   if (VecVT.isFixedLengthVector()) {
5006     ContainerVT = getContainerForFixedLengthVector(VecVT);
5007     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5008   }
5009 
5010   SDValue Mask, VL;
5011   if (IsVP) {
5012     Mask = Op.getOperand(2);
5013     VL = Op.getOperand(3);
5014   } else {
5015     std::tie(Mask, VL) =
5016         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5017   }
5018 
5019   unsigned BaseOpc;
5020   ISD::CondCode CC;
5021   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5022 
5023   switch (Op.getOpcode()) {
5024   default:
5025     llvm_unreachable("Unhandled reduction");
5026   case ISD::VECREDUCE_AND:
5027   case ISD::VP_REDUCE_AND: {
5028     // vcpop ~x == 0
5029     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5030     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5031     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5032     CC = ISD::SETEQ;
5033     BaseOpc = ISD::AND;
5034     break;
5035   }
5036   case ISD::VECREDUCE_OR:
5037   case ISD::VP_REDUCE_OR:
5038     // vcpop x != 0
5039     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5040     CC = ISD::SETNE;
5041     BaseOpc = ISD::OR;
5042     break;
5043   case ISD::VECREDUCE_XOR:
5044   case ISD::VP_REDUCE_XOR: {
5045     // ((vcpop x) & 1) != 0
5046     SDValue One = DAG.getConstant(1, DL, XLenVT);
5047     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5048     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5049     CC = ISD::SETNE;
5050     BaseOpc = ISD::XOR;
5051     break;
5052   }
5053   }
5054 
5055   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5056 
5057   if (!IsVP)
5058     return SetCC;
5059 
5060   // Now include the start value in the operation.
5061   // Note that we must return the start value when no elements are operated
5062   // upon. The vcpop instructions we've emitted in each case above will return
5063   // 0 for an inactive vector, and so we've already received the neutral value:
5064   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5065   // can simply include the start value.
5066   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5067 }
5068 
5069 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5070                                             SelectionDAG &DAG) const {
5071   SDLoc DL(Op);
5072   SDValue Vec = Op.getOperand(0);
5073   EVT VecEVT = Vec.getValueType();
5074 
5075   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5076 
5077   // Due to ordering in legalize types we may have a vector type that needs to
5078   // be split. Do that manually so we can get down to a legal type.
5079   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5080          TargetLowering::TypeSplitVector) {
5081     SDValue Lo, Hi;
5082     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5083     VecEVT = Lo.getValueType();
5084     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5085   }
5086 
5087   // TODO: The type may need to be widened rather than split. Or widened before
5088   // it can be split.
5089   if (!isTypeLegal(VecEVT))
5090     return SDValue();
5091 
5092   MVT VecVT = VecEVT.getSimpleVT();
5093   MVT VecEltVT = VecVT.getVectorElementType();
5094   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5095 
5096   MVT ContainerVT = VecVT;
5097   if (VecVT.isFixedLengthVector()) {
5098     ContainerVT = getContainerForFixedLengthVector(VecVT);
5099     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5100   }
5101 
5102   MVT M1VT = getLMUL1VT(ContainerVT);
5103   MVT XLenVT = Subtarget.getXLenVT();
5104 
5105   SDValue Mask, VL;
5106   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5107 
5108   SDValue NeutralElem =
5109       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5110   SDValue IdentitySplat =
5111       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5112                        M1VT, DL, DAG, Subtarget);
5113   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5114                                   IdentitySplat, Mask, VL);
5115   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5116                              DAG.getConstant(0, DL, XLenVT));
5117   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5118 }
5119 
5120 // Given a reduction op, this function returns the matching reduction opcode,
5121 // the vector SDValue and the scalar SDValue required to lower this to a
5122 // RISCVISD node.
5123 static std::tuple<unsigned, SDValue, SDValue>
5124 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5125   SDLoc DL(Op);
5126   auto Flags = Op->getFlags();
5127   unsigned Opcode = Op.getOpcode();
5128   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5129   switch (Opcode) {
5130   default:
5131     llvm_unreachable("Unhandled reduction");
5132   case ISD::VECREDUCE_FADD: {
5133     // Use positive zero if we can. It is cheaper to materialize.
5134     SDValue Zero =
5135         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5136     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5137   }
5138   case ISD::VECREDUCE_SEQ_FADD:
5139     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5140                            Op.getOperand(0));
5141   case ISD::VECREDUCE_FMIN:
5142     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5143                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5144   case ISD::VECREDUCE_FMAX:
5145     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5146                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5147   }
5148 }
5149 
5150 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5151                                               SelectionDAG &DAG) const {
5152   SDLoc DL(Op);
5153   MVT VecEltVT = Op.getSimpleValueType();
5154 
5155   unsigned RVVOpcode;
5156   SDValue VectorVal, ScalarVal;
5157   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5158       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5159   MVT VecVT = VectorVal.getSimpleValueType();
5160 
5161   MVT ContainerVT = VecVT;
5162   if (VecVT.isFixedLengthVector()) {
5163     ContainerVT = getContainerForFixedLengthVector(VecVT);
5164     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5165   }
5166 
5167   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5168   MVT XLenVT = Subtarget.getXLenVT();
5169 
5170   SDValue Mask, VL;
5171   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5172 
5173   SDValue ScalarSplat =
5174       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5175                        M1VT, DL, DAG, Subtarget);
5176   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5177                                   VectorVal, ScalarSplat, Mask, VL);
5178   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5179                      DAG.getConstant(0, DL, XLenVT));
5180 }
5181 
5182 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5183   switch (ISDOpcode) {
5184   default:
5185     llvm_unreachable("Unhandled reduction");
5186   case ISD::VP_REDUCE_ADD:
5187     return RISCVISD::VECREDUCE_ADD_VL;
5188   case ISD::VP_REDUCE_UMAX:
5189     return RISCVISD::VECREDUCE_UMAX_VL;
5190   case ISD::VP_REDUCE_SMAX:
5191     return RISCVISD::VECREDUCE_SMAX_VL;
5192   case ISD::VP_REDUCE_UMIN:
5193     return RISCVISD::VECREDUCE_UMIN_VL;
5194   case ISD::VP_REDUCE_SMIN:
5195     return RISCVISD::VECREDUCE_SMIN_VL;
5196   case ISD::VP_REDUCE_AND:
5197     return RISCVISD::VECREDUCE_AND_VL;
5198   case ISD::VP_REDUCE_OR:
5199     return RISCVISD::VECREDUCE_OR_VL;
5200   case ISD::VP_REDUCE_XOR:
5201     return RISCVISD::VECREDUCE_XOR_VL;
5202   case ISD::VP_REDUCE_FADD:
5203     return RISCVISD::VECREDUCE_FADD_VL;
5204   case ISD::VP_REDUCE_SEQ_FADD:
5205     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5206   case ISD::VP_REDUCE_FMAX:
5207     return RISCVISD::VECREDUCE_FMAX_VL;
5208   case ISD::VP_REDUCE_FMIN:
5209     return RISCVISD::VECREDUCE_FMIN_VL;
5210   }
5211 }
5212 
5213 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5214                                            SelectionDAG &DAG) const {
5215   SDLoc DL(Op);
5216   SDValue Vec = Op.getOperand(1);
5217   EVT VecEVT = Vec.getValueType();
5218 
5219   // TODO: The type may need to be widened rather than split. Or widened before
5220   // it can be split.
5221   if (!isTypeLegal(VecEVT))
5222     return SDValue();
5223 
5224   MVT VecVT = VecEVT.getSimpleVT();
5225   MVT VecEltVT = VecVT.getVectorElementType();
5226   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5227 
5228   MVT ContainerVT = VecVT;
5229   if (VecVT.isFixedLengthVector()) {
5230     ContainerVT = getContainerForFixedLengthVector(VecVT);
5231     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5232   }
5233 
5234   SDValue VL = Op.getOperand(3);
5235   SDValue Mask = Op.getOperand(2);
5236 
5237   MVT M1VT = getLMUL1VT(ContainerVT);
5238   MVT XLenVT = Subtarget.getXLenVT();
5239   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5240 
5241   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5242                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5243                                         DL, DAG, Subtarget);
5244   SDValue Reduction =
5245       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5246   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5247                              DAG.getConstant(0, DL, XLenVT));
5248   if (!VecVT.isInteger())
5249     return Elt0;
5250   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5251 }
5252 
5253 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5254                                                    SelectionDAG &DAG) const {
5255   SDValue Vec = Op.getOperand(0);
5256   SDValue SubVec = Op.getOperand(1);
5257   MVT VecVT = Vec.getSimpleValueType();
5258   MVT SubVecVT = SubVec.getSimpleValueType();
5259 
5260   SDLoc DL(Op);
5261   MVT XLenVT = Subtarget.getXLenVT();
5262   unsigned OrigIdx = Op.getConstantOperandVal(2);
5263   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5264 
5265   // We don't have the ability to slide mask vectors up indexed by their i1
5266   // elements; the smallest we can do is i8. Often we are able to bitcast to
5267   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5268   // into a scalable one, we might not necessarily have enough scalable
5269   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5270   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5271       (OrigIdx != 0 || !Vec.isUndef())) {
5272     if (VecVT.getVectorMinNumElements() >= 8 &&
5273         SubVecVT.getVectorMinNumElements() >= 8) {
5274       assert(OrigIdx % 8 == 0 && "Invalid index");
5275       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5276              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5277              "Unexpected mask vector lowering");
5278       OrigIdx /= 8;
5279       SubVecVT =
5280           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5281                            SubVecVT.isScalableVector());
5282       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5283                                VecVT.isScalableVector());
5284       Vec = DAG.getBitcast(VecVT, Vec);
5285       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5286     } else {
5287       // We can't slide this mask vector up indexed by its i1 elements.
5288       // This poses a problem when we wish to insert a scalable vector which
5289       // can't be re-expressed as a larger type. Just choose the slow path and
5290       // extend to a larger type, then truncate back down.
5291       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5292       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5293       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5294       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5295       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5296                         Op.getOperand(2));
5297       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5298       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5299     }
5300   }
5301 
5302   // If the subvector vector is a fixed-length type, we cannot use subregister
5303   // manipulation to simplify the codegen; we don't know which register of a
5304   // LMUL group contains the specific subvector as we only know the minimum
5305   // register size. Therefore we must slide the vector group up the full
5306   // amount.
5307   if (SubVecVT.isFixedLengthVector()) {
5308     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5309       return Op;
5310     MVT ContainerVT = VecVT;
5311     if (VecVT.isFixedLengthVector()) {
5312       ContainerVT = getContainerForFixedLengthVector(VecVT);
5313       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5314     }
5315     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5316                          DAG.getUNDEF(ContainerVT), SubVec,
5317                          DAG.getConstant(0, DL, XLenVT));
5318     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5319       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5320       return DAG.getBitcast(Op.getValueType(), SubVec);
5321     }
5322     SDValue Mask =
5323         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5324     // Set the vector length to only the number of elements we care about. Note
5325     // that for slideup this includes the offset.
5326     SDValue VL =
5327         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5328     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5329     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5330                                   SubVec, SlideupAmt, Mask, VL);
5331     if (VecVT.isFixedLengthVector())
5332       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5333     return DAG.getBitcast(Op.getValueType(), Slideup);
5334   }
5335 
5336   unsigned SubRegIdx, RemIdx;
5337   std::tie(SubRegIdx, RemIdx) =
5338       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5339           VecVT, SubVecVT, OrigIdx, TRI);
5340 
5341   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5342   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5343                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5344                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5345 
5346   // 1. If the Idx has been completely eliminated and this subvector's size is
5347   // a vector register or a multiple thereof, or the surrounding elements are
5348   // undef, then this is a subvector insert which naturally aligns to a vector
5349   // register. These can easily be handled using subregister manipulation.
5350   // 2. If the subvector is smaller than a vector register, then the insertion
5351   // must preserve the undisturbed elements of the register. We do this by
5352   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5353   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5354   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5355   // LMUL=1 type back into the larger vector (resolving to another subregister
5356   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5357   // to avoid allocating a large register group to hold our subvector.
5358   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5359     return Op;
5360 
5361   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5362   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5363   // (in our case undisturbed). This means we can set up a subvector insertion
5364   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5365   // size of the subvector.
5366   MVT InterSubVT = VecVT;
5367   SDValue AlignedExtract = Vec;
5368   unsigned AlignedIdx = OrigIdx - RemIdx;
5369   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5370     InterSubVT = getLMUL1VT(VecVT);
5371     // Extract a subvector equal to the nearest full vector register type. This
5372     // should resolve to a EXTRACT_SUBREG instruction.
5373     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5374                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5375   }
5376 
5377   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5378   // For scalable vectors this must be further multiplied by vscale.
5379   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5380 
5381   SDValue Mask, VL;
5382   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5383 
5384   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5385   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5386   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5387   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5388 
5389   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5390                        DAG.getUNDEF(InterSubVT), SubVec,
5391                        DAG.getConstant(0, DL, XLenVT));
5392 
5393   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5394                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5395 
5396   // If required, insert this subvector back into the correct vector register.
5397   // This should resolve to an INSERT_SUBREG instruction.
5398   if (VecVT.bitsGT(InterSubVT))
5399     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5400                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5401 
5402   // We might have bitcast from a mask type: cast back to the original type if
5403   // required.
5404   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5405 }
5406 
5407 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5408                                                     SelectionDAG &DAG) const {
5409   SDValue Vec = Op.getOperand(0);
5410   MVT SubVecVT = Op.getSimpleValueType();
5411   MVT VecVT = Vec.getSimpleValueType();
5412 
5413   SDLoc DL(Op);
5414   MVT XLenVT = Subtarget.getXLenVT();
5415   unsigned OrigIdx = Op.getConstantOperandVal(1);
5416   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5417 
5418   // We don't have the ability to slide mask vectors down indexed by their i1
5419   // elements; the smallest we can do is i8. Often we are able to bitcast to
5420   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5421   // from a scalable one, we might not necessarily have enough scalable
5422   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5423   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5424     if (VecVT.getVectorMinNumElements() >= 8 &&
5425         SubVecVT.getVectorMinNumElements() >= 8) {
5426       assert(OrigIdx % 8 == 0 && "Invalid index");
5427       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5428              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5429              "Unexpected mask vector lowering");
5430       OrigIdx /= 8;
5431       SubVecVT =
5432           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5433                            SubVecVT.isScalableVector());
5434       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5435                                VecVT.isScalableVector());
5436       Vec = DAG.getBitcast(VecVT, Vec);
5437     } else {
5438       // We can't slide this mask vector down, indexed by its i1 elements.
5439       // This poses a problem when we wish to extract a scalable vector which
5440       // can't be re-expressed as a larger type. Just choose the slow path and
5441       // extend to a larger type, then truncate back down.
5442       // TODO: We could probably improve this when extracting certain fixed
5443       // from fixed, where we can extract as i8 and shift the correct element
5444       // right to reach the desired subvector?
5445       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5446       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5447       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5448       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5449                         Op.getOperand(1));
5450       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5451       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5452     }
5453   }
5454 
5455   // If the subvector vector is a fixed-length type, we cannot use subregister
5456   // manipulation to simplify the codegen; we don't know which register of a
5457   // LMUL group contains the specific subvector as we only know the minimum
5458   // register size. Therefore we must slide the vector group down the full
5459   // amount.
5460   if (SubVecVT.isFixedLengthVector()) {
5461     // With an index of 0 this is a cast-like subvector, which can be performed
5462     // with subregister operations.
5463     if (OrigIdx == 0)
5464       return Op;
5465     MVT ContainerVT = VecVT;
5466     if (VecVT.isFixedLengthVector()) {
5467       ContainerVT = getContainerForFixedLengthVector(VecVT);
5468       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5469     }
5470     SDValue Mask =
5471         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5472     // Set the vector length to only the number of elements we care about. This
5473     // avoids sliding down elements we're going to discard straight away.
5474     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5475     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5476     SDValue Slidedown =
5477         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5478                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5479     // Now we can use a cast-like subvector extract to get the result.
5480     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5481                             DAG.getConstant(0, DL, XLenVT));
5482     return DAG.getBitcast(Op.getValueType(), Slidedown);
5483   }
5484 
5485   unsigned SubRegIdx, RemIdx;
5486   std::tie(SubRegIdx, RemIdx) =
5487       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5488           VecVT, SubVecVT, OrigIdx, TRI);
5489 
5490   // If the Idx has been completely eliminated then this is a subvector extract
5491   // which naturally aligns to a vector register. These can easily be handled
5492   // using subregister manipulation.
5493   if (RemIdx == 0)
5494     return Op;
5495 
5496   // Else we must shift our vector register directly to extract the subvector.
5497   // Do this using VSLIDEDOWN.
5498 
5499   // If the vector type is an LMUL-group type, extract a subvector equal to the
5500   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5501   // instruction.
5502   MVT InterSubVT = VecVT;
5503   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5504     InterSubVT = getLMUL1VT(VecVT);
5505     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5506                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5507   }
5508 
5509   // Slide this vector register down by the desired number of elements in order
5510   // to place the desired subvector starting at element 0.
5511   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5512   // For scalable vectors this must be further multiplied by vscale.
5513   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5514 
5515   SDValue Mask, VL;
5516   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5517   SDValue Slidedown =
5518       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5519                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5520 
5521   // Now the vector is in the right position, extract our final subvector. This
5522   // should resolve to a COPY.
5523   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5524                           DAG.getConstant(0, DL, XLenVT));
5525 
5526   // We might have bitcast from a mask type: cast back to the original type if
5527   // required.
5528   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5529 }
5530 
5531 // Lower step_vector to the vid instruction. Any non-identity step value must
5532 // be accounted for my manual expansion.
5533 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5534                                               SelectionDAG &DAG) const {
5535   SDLoc DL(Op);
5536   MVT VT = Op.getSimpleValueType();
5537   MVT XLenVT = Subtarget.getXLenVT();
5538   SDValue Mask, VL;
5539   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5540   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5541   uint64_t StepValImm = Op.getConstantOperandVal(0);
5542   if (StepValImm != 1) {
5543     if (isPowerOf2_64(StepValImm)) {
5544       SDValue StepVal =
5545           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5546                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5547       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5548     } else {
5549       SDValue StepVal = lowerScalarSplat(
5550           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5551           VL, VT, DL, DAG, Subtarget);
5552       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5553     }
5554   }
5555   return StepVec;
5556 }
5557 
5558 // Implement vector_reverse using vrgather.vv with indices determined by
5559 // subtracting the id of each element from (VLMAX-1). This will convert
5560 // the indices like so:
5561 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5562 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5563 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5564                                                  SelectionDAG &DAG) const {
5565   SDLoc DL(Op);
5566   MVT VecVT = Op.getSimpleValueType();
5567   unsigned EltSize = VecVT.getScalarSizeInBits();
5568   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5569 
5570   unsigned MaxVLMAX = 0;
5571   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5572   if (VectorBitsMax != 0)
5573     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5574 
5575   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5576   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5577 
5578   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5579   // to use vrgatherei16.vv.
5580   // TODO: It's also possible to use vrgatherei16.vv for other types to
5581   // decrease register width for the index calculation.
5582   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5583     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5584     // Reverse each half, then reassemble them in reverse order.
5585     // NOTE: It's also possible that after splitting that VLMAX no longer
5586     // requires vrgatherei16.vv.
5587     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5588       SDValue Lo, Hi;
5589       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5590       EVT LoVT, HiVT;
5591       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5592       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5593       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5594       // Reassemble the low and high pieces reversed.
5595       // FIXME: This is a CONCAT_VECTORS.
5596       SDValue Res =
5597           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5598                       DAG.getIntPtrConstant(0, DL));
5599       return DAG.getNode(
5600           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5601           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5602     }
5603 
5604     // Just promote the int type to i16 which will double the LMUL.
5605     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5606     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5607   }
5608 
5609   MVT XLenVT = Subtarget.getXLenVT();
5610   SDValue Mask, VL;
5611   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5612 
5613   // Calculate VLMAX-1 for the desired SEW.
5614   unsigned MinElts = VecVT.getVectorMinNumElements();
5615   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5616                               DAG.getConstant(MinElts, DL, XLenVT));
5617   SDValue VLMinus1 =
5618       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5619 
5620   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5621   bool IsRV32E64 =
5622       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5623   SDValue SplatVL;
5624   if (!IsRV32E64)
5625     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5626   else
5627     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5628                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5629 
5630   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5631   SDValue Indices =
5632       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5633 
5634   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5635 }
5636 
5637 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5638                                                 SelectionDAG &DAG) const {
5639   SDLoc DL(Op);
5640   SDValue V1 = Op.getOperand(0);
5641   SDValue V2 = Op.getOperand(1);
5642   MVT XLenVT = Subtarget.getXLenVT();
5643   MVT VecVT = Op.getSimpleValueType();
5644 
5645   unsigned MinElts = VecVT.getVectorMinNumElements();
5646   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5647                               DAG.getConstant(MinElts, DL, XLenVT));
5648 
5649   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5650   SDValue DownOffset, UpOffset;
5651   if (ImmValue >= 0) {
5652     // The operand is a TargetConstant, we need to rebuild it as a regular
5653     // constant.
5654     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5655     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5656   } else {
5657     // The operand is a TargetConstant, we need to rebuild it as a regular
5658     // constant rather than negating the original operand.
5659     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5660     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5661   }
5662 
5663   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5664   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5665 
5666   SDValue SlideDown =
5667       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5668                   DownOffset, TrueMask, UpOffset);
5669   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5670                      TrueMask,
5671                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5672 }
5673 
5674 SDValue
5675 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5676                                                      SelectionDAG &DAG) const {
5677   SDLoc DL(Op);
5678   auto *Load = cast<LoadSDNode>(Op);
5679 
5680   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5681                                         Load->getMemoryVT(),
5682                                         *Load->getMemOperand()) &&
5683          "Expecting a correctly-aligned load");
5684 
5685   MVT VT = Op.getSimpleValueType();
5686   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5687 
5688   SDValue VL =
5689       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5690 
5691   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5692   SDValue NewLoad = DAG.getMemIntrinsicNode(
5693       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5694       Load->getMemoryVT(), Load->getMemOperand());
5695 
5696   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5697   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5698 }
5699 
5700 SDValue
5701 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5702                                                       SelectionDAG &DAG) const {
5703   SDLoc DL(Op);
5704   auto *Store = cast<StoreSDNode>(Op);
5705 
5706   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5707                                         Store->getMemoryVT(),
5708                                         *Store->getMemOperand()) &&
5709          "Expecting a correctly-aligned store");
5710 
5711   SDValue StoreVal = Store->getValue();
5712   MVT VT = StoreVal.getSimpleValueType();
5713 
5714   // If the size less than a byte, we need to pad with zeros to make a byte.
5715   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5716     VT = MVT::v8i1;
5717     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5718                            DAG.getConstant(0, DL, VT), StoreVal,
5719                            DAG.getIntPtrConstant(0, DL));
5720   }
5721 
5722   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5723 
5724   SDValue VL =
5725       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5726 
5727   SDValue NewValue =
5728       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5729   return DAG.getMemIntrinsicNode(
5730       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5731       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5732       Store->getMemoryVT(), Store->getMemOperand());
5733 }
5734 
5735 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5736                                              SelectionDAG &DAG) const {
5737   SDLoc DL(Op);
5738   MVT VT = Op.getSimpleValueType();
5739 
5740   const auto *MemSD = cast<MemSDNode>(Op);
5741   EVT MemVT = MemSD->getMemoryVT();
5742   MachineMemOperand *MMO = MemSD->getMemOperand();
5743   SDValue Chain = MemSD->getChain();
5744   SDValue BasePtr = MemSD->getBasePtr();
5745 
5746   SDValue Mask, PassThru, VL;
5747   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5748     Mask = VPLoad->getMask();
5749     PassThru = DAG.getUNDEF(VT);
5750     VL = VPLoad->getVectorLength();
5751   } else {
5752     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5753     Mask = MLoad->getMask();
5754     PassThru = MLoad->getPassThru();
5755   }
5756 
5757   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5758 
5759   MVT XLenVT = Subtarget.getXLenVT();
5760 
5761   MVT ContainerVT = VT;
5762   if (VT.isFixedLengthVector()) {
5763     ContainerVT = getContainerForFixedLengthVector(VT);
5764     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5765     if (!IsUnmasked) {
5766       MVT MaskVT =
5767           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5768       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5769     }
5770   }
5771 
5772   if (!VL)
5773     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5774 
5775   unsigned IntID =
5776       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5777   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5778   if (IsUnmasked)
5779     Ops.push_back(DAG.getUNDEF(ContainerVT));
5780   else
5781     Ops.push_back(PassThru);
5782   Ops.push_back(BasePtr);
5783   if (!IsUnmasked)
5784     Ops.push_back(Mask);
5785   Ops.push_back(VL);
5786   if (!IsUnmasked)
5787     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5788 
5789   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5790 
5791   SDValue Result =
5792       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5793   Chain = Result.getValue(1);
5794 
5795   if (VT.isFixedLengthVector())
5796     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5797 
5798   return DAG.getMergeValues({Result, Chain}, DL);
5799 }
5800 
5801 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5802                                               SelectionDAG &DAG) const {
5803   SDLoc DL(Op);
5804 
5805   const auto *MemSD = cast<MemSDNode>(Op);
5806   EVT MemVT = MemSD->getMemoryVT();
5807   MachineMemOperand *MMO = MemSD->getMemOperand();
5808   SDValue Chain = MemSD->getChain();
5809   SDValue BasePtr = MemSD->getBasePtr();
5810   SDValue Val, Mask, VL;
5811 
5812   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5813     Val = VPStore->getValue();
5814     Mask = VPStore->getMask();
5815     VL = VPStore->getVectorLength();
5816   } else {
5817     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5818     Val = MStore->getValue();
5819     Mask = MStore->getMask();
5820   }
5821 
5822   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5823 
5824   MVT VT = Val.getSimpleValueType();
5825   MVT XLenVT = Subtarget.getXLenVT();
5826 
5827   MVT ContainerVT = VT;
5828   if (VT.isFixedLengthVector()) {
5829     ContainerVT = getContainerForFixedLengthVector(VT);
5830 
5831     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5832     if (!IsUnmasked) {
5833       MVT MaskVT =
5834           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5835       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5836     }
5837   }
5838 
5839   if (!VL)
5840     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5841 
5842   unsigned IntID =
5843       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5844   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5845   Ops.push_back(Val);
5846   Ops.push_back(BasePtr);
5847   if (!IsUnmasked)
5848     Ops.push_back(Mask);
5849   Ops.push_back(VL);
5850 
5851   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5852                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5853 }
5854 
5855 SDValue
5856 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5857                                                       SelectionDAG &DAG) const {
5858   MVT InVT = Op.getOperand(0).getSimpleValueType();
5859   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5860 
5861   MVT VT = Op.getSimpleValueType();
5862 
5863   SDValue Op1 =
5864       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5865   SDValue Op2 =
5866       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5867 
5868   SDLoc DL(Op);
5869   SDValue VL =
5870       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5871 
5872   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5873   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5874 
5875   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5876                             Op.getOperand(2), Mask, VL);
5877 
5878   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5879 }
5880 
5881 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5882     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5883   MVT VT = Op.getSimpleValueType();
5884 
5885   if (VT.getVectorElementType() == MVT::i1)
5886     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5887 
5888   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5889 }
5890 
5891 SDValue
5892 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5893                                                       SelectionDAG &DAG) const {
5894   unsigned Opc;
5895   switch (Op.getOpcode()) {
5896   default: llvm_unreachable("Unexpected opcode!");
5897   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5898   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5899   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5900   }
5901 
5902   return lowerToScalableOp(Op, DAG, Opc);
5903 }
5904 
5905 // Lower vector ABS to smax(X, sub(0, X)).
5906 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5907   SDLoc DL(Op);
5908   MVT VT = Op.getSimpleValueType();
5909   SDValue X = Op.getOperand(0);
5910 
5911   assert(VT.isFixedLengthVector() && "Unexpected type");
5912 
5913   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5914   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5915 
5916   SDValue Mask, VL;
5917   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5918 
5919   SDValue SplatZero = DAG.getNode(
5920       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5921       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5922   SDValue NegX =
5923       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5924   SDValue Max =
5925       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5926 
5927   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5928 }
5929 
5930 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5931     SDValue Op, SelectionDAG &DAG) const {
5932   SDLoc DL(Op);
5933   MVT VT = Op.getSimpleValueType();
5934   SDValue Mag = Op.getOperand(0);
5935   SDValue Sign = Op.getOperand(1);
5936   assert(Mag.getValueType() == Sign.getValueType() &&
5937          "Can only handle COPYSIGN with matching types.");
5938 
5939   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5940   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5941   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5942 
5943   SDValue Mask, VL;
5944   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5945 
5946   SDValue CopySign =
5947       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5948 
5949   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5950 }
5951 
5952 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5953     SDValue Op, SelectionDAG &DAG) const {
5954   MVT VT = Op.getSimpleValueType();
5955   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5956 
5957   MVT I1ContainerVT =
5958       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5959 
5960   SDValue CC =
5961       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5962   SDValue Op1 =
5963       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5964   SDValue Op2 =
5965       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5966 
5967   SDLoc DL(Op);
5968   SDValue Mask, VL;
5969   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5970 
5971   SDValue Select =
5972       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5973 
5974   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5975 }
5976 
5977 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5978                                                unsigned NewOpc,
5979                                                bool HasMask) const {
5980   MVT VT = Op.getSimpleValueType();
5981   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5982 
5983   // Create list of operands by converting existing ones to scalable types.
5984   SmallVector<SDValue, 6> Ops;
5985   for (const SDValue &V : Op->op_values()) {
5986     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5987 
5988     // Pass through non-vector operands.
5989     if (!V.getValueType().isVector()) {
5990       Ops.push_back(V);
5991       continue;
5992     }
5993 
5994     // "cast" fixed length vector to a scalable vector.
5995     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5996            "Only fixed length vectors are supported!");
5997     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5998   }
5999 
6000   SDLoc DL(Op);
6001   SDValue Mask, VL;
6002   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6003   if (HasMask)
6004     Ops.push_back(Mask);
6005   Ops.push_back(VL);
6006 
6007   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6008   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6009 }
6010 
6011 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6012 // * Operands of each node are assumed to be in the same order.
6013 // * The EVL operand is promoted from i32 to i64 on RV64.
6014 // * Fixed-length vectors are converted to their scalable-vector container
6015 //   types.
6016 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6017                                        unsigned RISCVISDOpc) const {
6018   SDLoc DL(Op);
6019   MVT VT = Op.getSimpleValueType();
6020   SmallVector<SDValue, 4> Ops;
6021 
6022   for (const auto &OpIdx : enumerate(Op->ops())) {
6023     SDValue V = OpIdx.value();
6024     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6025     // Pass through operands which aren't fixed-length vectors.
6026     if (!V.getValueType().isFixedLengthVector()) {
6027       Ops.push_back(V);
6028       continue;
6029     }
6030     // "cast" fixed length vector to a scalable vector.
6031     MVT OpVT = V.getSimpleValueType();
6032     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6033     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6034            "Only fixed length vectors are supported!");
6035     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6036   }
6037 
6038   if (!VT.isFixedLengthVector())
6039     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6040 
6041   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6042 
6043   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6044 
6045   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6046 }
6047 
6048 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6049                                             unsigned MaskOpc,
6050                                             unsigned VecOpc) const {
6051   MVT VT = Op.getSimpleValueType();
6052   if (VT.getVectorElementType() != MVT::i1)
6053     return lowerVPOp(Op, DAG, VecOpc);
6054 
6055   // It is safe to drop mask parameter as masked-off elements are undef.
6056   SDValue Op1 = Op->getOperand(0);
6057   SDValue Op2 = Op->getOperand(1);
6058   SDValue VL = Op->getOperand(3);
6059 
6060   MVT ContainerVT = VT;
6061   const bool IsFixed = VT.isFixedLengthVector();
6062   if (IsFixed) {
6063     ContainerVT = getContainerForFixedLengthVector(VT);
6064     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6065     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6066   }
6067 
6068   SDLoc DL(Op);
6069   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6070   if (!IsFixed)
6071     return Val;
6072   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6073 }
6074 
6075 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6076 // matched to a RVV indexed load. The RVV indexed load instructions only
6077 // support the "unsigned unscaled" addressing mode; indices are implicitly
6078 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6079 // signed or scaled indexing is extended to the XLEN value type and scaled
6080 // accordingly.
6081 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6082                                                SelectionDAG &DAG) const {
6083   SDLoc DL(Op);
6084   MVT VT = Op.getSimpleValueType();
6085 
6086   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6087   EVT MemVT = MemSD->getMemoryVT();
6088   MachineMemOperand *MMO = MemSD->getMemOperand();
6089   SDValue Chain = MemSD->getChain();
6090   SDValue BasePtr = MemSD->getBasePtr();
6091 
6092   ISD::LoadExtType LoadExtType;
6093   SDValue Index, Mask, PassThru, VL;
6094 
6095   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6096     Index = VPGN->getIndex();
6097     Mask = VPGN->getMask();
6098     PassThru = DAG.getUNDEF(VT);
6099     VL = VPGN->getVectorLength();
6100     // VP doesn't support extending loads.
6101     LoadExtType = ISD::NON_EXTLOAD;
6102   } else {
6103     // Else it must be a MGATHER.
6104     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6105     Index = MGN->getIndex();
6106     Mask = MGN->getMask();
6107     PassThru = MGN->getPassThru();
6108     LoadExtType = MGN->getExtensionType();
6109   }
6110 
6111   MVT IndexVT = Index.getSimpleValueType();
6112   MVT XLenVT = Subtarget.getXLenVT();
6113 
6114   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6115          "Unexpected VTs!");
6116   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6117   // Targets have to explicitly opt-in for extending vector loads.
6118   assert(LoadExtType == ISD::NON_EXTLOAD &&
6119          "Unexpected extending MGATHER/VP_GATHER");
6120   (void)LoadExtType;
6121 
6122   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6123   // the selection of the masked intrinsics doesn't do this for us.
6124   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6125 
6126   MVT ContainerVT = VT;
6127   if (VT.isFixedLengthVector()) {
6128     // We need to use the larger of the result and index type to determine the
6129     // scalable type to use so we don't increase LMUL for any operand/result.
6130     if (VT.bitsGE(IndexVT)) {
6131       ContainerVT = getContainerForFixedLengthVector(VT);
6132       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6133                                  ContainerVT.getVectorElementCount());
6134     } else {
6135       IndexVT = getContainerForFixedLengthVector(IndexVT);
6136       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6137                                      IndexVT.getVectorElementCount());
6138     }
6139 
6140     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6141 
6142     if (!IsUnmasked) {
6143       MVT MaskVT =
6144           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6145       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6146       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6147     }
6148   }
6149 
6150   if (!VL)
6151     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6152 
6153   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6154     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6155     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6156                                    VL);
6157     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6158                         TrueMask, VL);
6159   }
6160 
6161   unsigned IntID =
6162       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6163   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6164   if (IsUnmasked)
6165     Ops.push_back(DAG.getUNDEF(ContainerVT));
6166   else
6167     Ops.push_back(PassThru);
6168   Ops.push_back(BasePtr);
6169   Ops.push_back(Index);
6170   if (!IsUnmasked)
6171     Ops.push_back(Mask);
6172   Ops.push_back(VL);
6173   if (!IsUnmasked)
6174     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6175 
6176   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6177   SDValue Result =
6178       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6179   Chain = Result.getValue(1);
6180 
6181   if (VT.isFixedLengthVector())
6182     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6183 
6184   return DAG.getMergeValues({Result, Chain}, DL);
6185 }
6186 
6187 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6188 // matched to a RVV indexed store. The RVV indexed store instructions only
6189 // support the "unsigned unscaled" addressing mode; indices are implicitly
6190 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6191 // signed or scaled indexing is extended to the XLEN value type and scaled
6192 // accordingly.
6193 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6194                                                 SelectionDAG &DAG) const {
6195   SDLoc DL(Op);
6196   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6197   EVT MemVT = MemSD->getMemoryVT();
6198   MachineMemOperand *MMO = MemSD->getMemOperand();
6199   SDValue Chain = MemSD->getChain();
6200   SDValue BasePtr = MemSD->getBasePtr();
6201 
6202   bool IsTruncatingStore = false;
6203   SDValue Index, Mask, Val, VL;
6204 
6205   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6206     Index = VPSN->getIndex();
6207     Mask = VPSN->getMask();
6208     Val = VPSN->getValue();
6209     VL = VPSN->getVectorLength();
6210     // VP doesn't support truncating stores.
6211     IsTruncatingStore = false;
6212   } else {
6213     // Else it must be a MSCATTER.
6214     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6215     Index = MSN->getIndex();
6216     Mask = MSN->getMask();
6217     Val = MSN->getValue();
6218     IsTruncatingStore = MSN->isTruncatingStore();
6219   }
6220 
6221   MVT VT = Val.getSimpleValueType();
6222   MVT IndexVT = Index.getSimpleValueType();
6223   MVT XLenVT = Subtarget.getXLenVT();
6224 
6225   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6226          "Unexpected VTs!");
6227   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6228   // Targets have to explicitly opt-in for extending vector loads and
6229   // truncating vector stores.
6230   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6231   (void)IsTruncatingStore;
6232 
6233   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6234   // the selection of the masked intrinsics doesn't do this for us.
6235   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6236 
6237   MVT ContainerVT = VT;
6238   if (VT.isFixedLengthVector()) {
6239     // We need to use the larger of the value and index type to determine the
6240     // scalable type to use so we don't increase LMUL for any operand/result.
6241     if (VT.bitsGE(IndexVT)) {
6242       ContainerVT = getContainerForFixedLengthVector(VT);
6243       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6244                                  ContainerVT.getVectorElementCount());
6245     } else {
6246       IndexVT = getContainerForFixedLengthVector(IndexVT);
6247       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6248                                      IndexVT.getVectorElementCount());
6249     }
6250 
6251     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6252     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6253 
6254     if (!IsUnmasked) {
6255       MVT MaskVT =
6256           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6257       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6258     }
6259   }
6260 
6261   if (!VL)
6262     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6263 
6264   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6265     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6266     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6267                                    VL);
6268     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6269                         TrueMask, VL);
6270   }
6271 
6272   unsigned IntID =
6273       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6274   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6275   Ops.push_back(Val);
6276   Ops.push_back(BasePtr);
6277   Ops.push_back(Index);
6278   if (!IsUnmasked)
6279     Ops.push_back(Mask);
6280   Ops.push_back(VL);
6281 
6282   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6283                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6284 }
6285 
6286 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6287                                                SelectionDAG &DAG) const {
6288   const MVT XLenVT = Subtarget.getXLenVT();
6289   SDLoc DL(Op);
6290   SDValue Chain = Op->getOperand(0);
6291   SDValue SysRegNo = DAG.getTargetConstant(
6292       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6293   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6294   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6295 
6296   // Encoding used for rounding mode in RISCV differs from that used in
6297   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6298   // table, which consists of a sequence of 4-bit fields, each representing
6299   // corresponding FLT_ROUNDS mode.
6300   static const int Table =
6301       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6302       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6303       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6304       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6305       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6306 
6307   SDValue Shift =
6308       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6309   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6310                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6311   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6312                                DAG.getConstant(7, DL, XLenVT));
6313 
6314   return DAG.getMergeValues({Masked, Chain}, DL);
6315 }
6316 
6317 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6318                                                SelectionDAG &DAG) const {
6319   const MVT XLenVT = Subtarget.getXLenVT();
6320   SDLoc DL(Op);
6321   SDValue Chain = Op->getOperand(0);
6322   SDValue RMValue = Op->getOperand(1);
6323   SDValue SysRegNo = DAG.getTargetConstant(
6324       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6325 
6326   // Encoding used for rounding mode in RISCV differs from that used in
6327   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6328   // a table, which consists of a sequence of 4-bit fields, each representing
6329   // corresponding RISCV mode.
6330   static const unsigned Table =
6331       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6332       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6333       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6334       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6335       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6336 
6337   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6338                               DAG.getConstant(2, DL, XLenVT));
6339   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6340                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6341   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6342                         DAG.getConstant(0x7, DL, XLenVT));
6343   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6344                      RMValue);
6345 }
6346 
6347 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6348   switch (IntNo) {
6349   default:
6350     llvm_unreachable("Unexpected Intrinsic");
6351   case Intrinsic::riscv_grev:
6352     return RISCVISD::GREVW;
6353   case Intrinsic::riscv_gorc:
6354     return RISCVISD::GORCW;
6355   case Intrinsic::riscv_bcompress:
6356     return RISCVISD::BCOMPRESSW;
6357   case Intrinsic::riscv_bdecompress:
6358     return RISCVISD::BDECOMPRESSW;
6359   case Intrinsic::riscv_bfp:
6360     return RISCVISD::BFPW;
6361   case Intrinsic::riscv_fsl:
6362     return RISCVISD::FSLW;
6363   case Intrinsic::riscv_fsr:
6364     return RISCVISD::FSRW;
6365   }
6366 }
6367 
6368 // Converts the given intrinsic to a i64 operation with any extension.
6369 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6370                                          unsigned IntNo) {
6371   SDLoc DL(N);
6372   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6373   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6374   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6375   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6376   // ReplaceNodeResults requires we maintain the same type for the return value.
6377   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6378 }
6379 
6380 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6381 // form of the given Opcode.
6382 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6383   switch (Opcode) {
6384   default:
6385     llvm_unreachable("Unexpected opcode");
6386   case ISD::SHL:
6387     return RISCVISD::SLLW;
6388   case ISD::SRA:
6389     return RISCVISD::SRAW;
6390   case ISD::SRL:
6391     return RISCVISD::SRLW;
6392   case ISD::SDIV:
6393     return RISCVISD::DIVW;
6394   case ISD::UDIV:
6395     return RISCVISD::DIVUW;
6396   case ISD::UREM:
6397     return RISCVISD::REMUW;
6398   case ISD::ROTL:
6399     return RISCVISD::ROLW;
6400   case ISD::ROTR:
6401     return RISCVISD::RORW;
6402   case RISCVISD::GREV:
6403     return RISCVISD::GREVW;
6404   case RISCVISD::GORC:
6405     return RISCVISD::GORCW;
6406   }
6407 }
6408 
6409 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6410 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6411 // otherwise be promoted to i64, making it difficult to select the
6412 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6413 // type i8/i16/i32 is lost.
6414 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6415                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6416   SDLoc DL(N);
6417   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6418   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6419   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6420   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6421   // ReplaceNodeResults requires we maintain the same type for the return value.
6422   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6423 }
6424 
6425 // Converts the given 32-bit operation to a i64 operation with signed extension
6426 // semantic to reduce the signed extension instructions.
6427 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6428   SDLoc DL(N);
6429   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6430   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6431   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6432   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6433                                DAG.getValueType(MVT::i32));
6434   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6435 }
6436 
6437 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6438                                              SmallVectorImpl<SDValue> &Results,
6439                                              SelectionDAG &DAG) const {
6440   SDLoc DL(N);
6441   switch (N->getOpcode()) {
6442   default:
6443     llvm_unreachable("Don't know how to custom type legalize this operation!");
6444   case ISD::STRICT_FP_TO_SINT:
6445   case ISD::STRICT_FP_TO_UINT:
6446   case ISD::FP_TO_SINT:
6447   case ISD::FP_TO_UINT: {
6448     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6449            "Unexpected custom legalisation");
6450     bool IsStrict = N->isStrictFPOpcode();
6451     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6452                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6453     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6454     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6455         TargetLowering::TypeSoftenFloat) {
6456       if (!isTypeLegal(Op0.getValueType()))
6457         return;
6458       if (IsStrict) {
6459         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6460                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6461         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6462         SDValue Res = DAG.getNode(
6463             Opc, DL, VTs, N->getOperand(0), Op0,
6464             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6465         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6466         Results.push_back(Res.getValue(1));
6467         return;
6468       }
6469       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6470       SDValue Res =
6471           DAG.getNode(Opc, DL, MVT::i64, Op0,
6472                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6473       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6474       return;
6475     }
6476     // If the FP type needs to be softened, emit a library call using the 'si'
6477     // version. If we left it to default legalization we'd end up with 'di'. If
6478     // the FP type doesn't need to be softened just let generic type
6479     // legalization promote the result type.
6480     RTLIB::Libcall LC;
6481     if (IsSigned)
6482       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6483     else
6484       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6485     MakeLibCallOptions CallOptions;
6486     EVT OpVT = Op0.getValueType();
6487     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6488     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6489     SDValue Result;
6490     std::tie(Result, Chain) =
6491         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6492     Results.push_back(Result);
6493     if (IsStrict)
6494       Results.push_back(Chain);
6495     break;
6496   }
6497   case ISD::READCYCLECOUNTER: {
6498     assert(!Subtarget.is64Bit() &&
6499            "READCYCLECOUNTER only has custom type legalization on riscv32");
6500 
6501     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6502     SDValue RCW =
6503         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6504 
6505     Results.push_back(
6506         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6507     Results.push_back(RCW.getValue(2));
6508     break;
6509   }
6510   case ISD::MUL: {
6511     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6512     unsigned XLen = Subtarget.getXLen();
6513     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6514     if (Size > XLen) {
6515       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6516       SDValue LHS = N->getOperand(0);
6517       SDValue RHS = N->getOperand(1);
6518       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6519 
6520       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6521       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6522       // We need exactly one side to be unsigned.
6523       if (LHSIsU == RHSIsU)
6524         return;
6525 
6526       auto MakeMULPair = [&](SDValue S, SDValue U) {
6527         MVT XLenVT = Subtarget.getXLenVT();
6528         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6529         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6530         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6531         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6532         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6533       };
6534 
6535       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6536       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6537 
6538       // The other operand should be signed, but still prefer MULH when
6539       // possible.
6540       if (RHSIsU && LHSIsS && !RHSIsS)
6541         Results.push_back(MakeMULPair(LHS, RHS));
6542       else if (LHSIsU && RHSIsS && !LHSIsS)
6543         Results.push_back(MakeMULPair(RHS, LHS));
6544 
6545       return;
6546     }
6547     LLVM_FALLTHROUGH;
6548   }
6549   case ISD::ADD:
6550   case ISD::SUB:
6551     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6552            "Unexpected custom legalisation");
6553     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6554     break;
6555   case ISD::SHL:
6556   case ISD::SRA:
6557   case ISD::SRL:
6558     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6559            "Unexpected custom legalisation");
6560     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6561       Results.push_back(customLegalizeToWOp(N, DAG));
6562       break;
6563     }
6564 
6565     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6566     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6567     // shift amount.
6568     if (N->getOpcode() == ISD::SHL) {
6569       SDLoc DL(N);
6570       SDValue NewOp0 =
6571           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6572       SDValue NewOp1 =
6573           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6574       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6575       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6576                                    DAG.getValueType(MVT::i32));
6577       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6578     }
6579 
6580     break;
6581   case ISD::ROTL:
6582   case ISD::ROTR:
6583     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6584            "Unexpected custom legalisation");
6585     Results.push_back(customLegalizeToWOp(N, DAG));
6586     break;
6587   case ISD::CTTZ:
6588   case ISD::CTTZ_ZERO_UNDEF:
6589   case ISD::CTLZ:
6590   case ISD::CTLZ_ZERO_UNDEF: {
6591     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6592            "Unexpected custom legalisation");
6593 
6594     SDValue NewOp0 =
6595         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6596     bool IsCTZ =
6597         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6598     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6599     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6600     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6601     return;
6602   }
6603   case ISD::SDIV:
6604   case ISD::UDIV:
6605   case ISD::UREM: {
6606     MVT VT = N->getSimpleValueType(0);
6607     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6608            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6609            "Unexpected custom legalisation");
6610     // Don't promote division/remainder by constant since we should expand those
6611     // to multiply by magic constant.
6612     // FIXME: What if the expansion is disabled for minsize.
6613     if (N->getOperand(1).getOpcode() == ISD::Constant)
6614       return;
6615 
6616     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6617     // the upper 32 bits. For other types we need to sign or zero extend
6618     // based on the opcode.
6619     unsigned ExtOpc = ISD::ANY_EXTEND;
6620     if (VT != MVT::i32)
6621       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6622                                            : ISD::ZERO_EXTEND;
6623 
6624     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6625     break;
6626   }
6627   case ISD::UADDO:
6628   case ISD::USUBO: {
6629     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6630            "Unexpected custom legalisation");
6631     bool IsAdd = N->getOpcode() == ISD::UADDO;
6632     // Create an ADDW or SUBW.
6633     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6634     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6635     SDValue Res =
6636         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6637     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6638                       DAG.getValueType(MVT::i32));
6639 
6640     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6641     // Since the inputs are sign extended from i32, this is equivalent to
6642     // comparing the lower 32 bits.
6643     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6644     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6645                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6646 
6647     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6648     Results.push_back(Overflow);
6649     return;
6650   }
6651   case ISD::UADDSAT:
6652   case ISD::USUBSAT: {
6653     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6654            "Unexpected custom legalisation");
6655     if (Subtarget.hasStdExtZbb()) {
6656       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6657       // sign extend allows overflow of the lower 32 bits to be detected on
6658       // the promoted size.
6659       SDValue LHS =
6660           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6661       SDValue RHS =
6662           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6663       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6664       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6665       return;
6666     }
6667 
6668     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6669     // promotion for UADDO/USUBO.
6670     Results.push_back(expandAddSubSat(N, DAG));
6671     return;
6672   }
6673   case ISD::ABS: {
6674     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6675            "Unexpected custom legalisation");
6676           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6677 
6678     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6679 
6680     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6681 
6682     // Freeze the source so we can increase it's use count.
6683     Src = DAG.getFreeze(Src);
6684 
6685     // Copy sign bit to all bits using the sraiw pattern.
6686     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6687                                    DAG.getValueType(MVT::i32));
6688     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6689                            DAG.getConstant(31, DL, MVT::i64));
6690 
6691     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6692     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6693 
6694     // NOTE: The result is only required to be anyextended, but sext is
6695     // consistent with type legalization of sub.
6696     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6697                          DAG.getValueType(MVT::i32));
6698     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6699     return;
6700   }
6701   case ISD::BITCAST: {
6702     EVT VT = N->getValueType(0);
6703     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6704     SDValue Op0 = N->getOperand(0);
6705     EVT Op0VT = Op0.getValueType();
6706     MVT XLenVT = Subtarget.getXLenVT();
6707     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6708       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6709       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6710     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6711                Subtarget.hasStdExtF()) {
6712       SDValue FPConv =
6713           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6714       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6715     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6716                isTypeLegal(Op0VT)) {
6717       // Custom-legalize bitcasts from fixed-length vector types to illegal
6718       // scalar types in order to improve codegen. Bitcast the vector to a
6719       // one-element vector type whose element type is the same as the result
6720       // type, and extract the first element.
6721       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6722       if (isTypeLegal(BVT)) {
6723         SDValue BVec = DAG.getBitcast(BVT, Op0);
6724         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6725                                       DAG.getConstant(0, DL, XLenVT)));
6726       }
6727     }
6728     break;
6729   }
6730   case RISCVISD::GREV:
6731   case RISCVISD::GORC: {
6732     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6733            "Unexpected custom legalisation");
6734     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6735     // This is similar to customLegalizeToWOp, except that we pass the second
6736     // operand (a TargetConstant) straight through: it is already of type
6737     // XLenVT.
6738     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6739     SDValue NewOp0 =
6740         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6741     SDValue NewOp1 =
6742         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6743     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6744     // ReplaceNodeResults requires we maintain the same type for the return
6745     // value.
6746     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6747     break;
6748   }
6749   case RISCVISD::SHFL: {
6750     // There is no SHFLIW instruction, but we can just promote the operation.
6751     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6752            "Unexpected custom legalisation");
6753     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6754     SDValue NewOp0 =
6755         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6756     SDValue NewOp1 =
6757         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6758     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6759     // ReplaceNodeResults requires we maintain the same type for the return
6760     // value.
6761     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6762     break;
6763   }
6764   case ISD::BSWAP:
6765   case ISD::BITREVERSE: {
6766     MVT VT = N->getSimpleValueType(0);
6767     MVT XLenVT = Subtarget.getXLenVT();
6768     assert((VT == MVT::i8 || VT == MVT::i16 ||
6769             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6770            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6771     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6772     unsigned Imm = VT.getSizeInBits() - 1;
6773     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6774     if (N->getOpcode() == ISD::BSWAP)
6775       Imm &= ~0x7U;
6776     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6777     SDValue GREVI =
6778         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6779     // ReplaceNodeResults requires we maintain the same type for the return
6780     // value.
6781     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6782     break;
6783   }
6784   case ISD::FSHL:
6785   case ISD::FSHR: {
6786     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6787            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6788     SDValue NewOp0 =
6789         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6790     SDValue NewOp1 =
6791         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6792     SDValue NewShAmt =
6793         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6794     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6795     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6796     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6797                            DAG.getConstant(0x1f, DL, MVT::i64));
6798     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6799     // instruction use different orders. fshl will return its first operand for
6800     // shift of zero, fshr will return its second operand. fsl and fsr both
6801     // return rs1 so the ISD nodes need to have different operand orders.
6802     // Shift amount is in rs2.
6803     unsigned Opc = RISCVISD::FSLW;
6804     if (N->getOpcode() == ISD::FSHR) {
6805       std::swap(NewOp0, NewOp1);
6806       Opc = RISCVISD::FSRW;
6807     }
6808     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6809     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6810     break;
6811   }
6812   case ISD::EXTRACT_VECTOR_ELT: {
6813     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6814     // type is illegal (currently only vXi64 RV32).
6815     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6816     // transferred to the destination register. We issue two of these from the
6817     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6818     // first element.
6819     SDValue Vec = N->getOperand(0);
6820     SDValue Idx = N->getOperand(1);
6821 
6822     // The vector type hasn't been legalized yet so we can't issue target
6823     // specific nodes if it needs legalization.
6824     // FIXME: We would manually legalize if it's important.
6825     if (!isTypeLegal(Vec.getValueType()))
6826       return;
6827 
6828     MVT VecVT = Vec.getSimpleValueType();
6829 
6830     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6831            VecVT.getVectorElementType() == MVT::i64 &&
6832            "Unexpected EXTRACT_VECTOR_ELT legalization");
6833 
6834     // If this is a fixed vector, we need to convert it to a scalable vector.
6835     MVT ContainerVT = VecVT;
6836     if (VecVT.isFixedLengthVector()) {
6837       ContainerVT = getContainerForFixedLengthVector(VecVT);
6838       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6839     }
6840 
6841     MVT XLenVT = Subtarget.getXLenVT();
6842 
6843     // Use a VL of 1 to avoid processing more elements than we need.
6844     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6845     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6846     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6847 
6848     // Unless the index is known to be 0, we must slide the vector down to get
6849     // the desired element into index 0.
6850     if (!isNullConstant(Idx)) {
6851       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6852                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6853     }
6854 
6855     // Extract the lower XLEN bits of the correct vector element.
6856     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6857 
6858     // To extract the upper XLEN bits of the vector element, shift the first
6859     // element right by 32 bits and re-extract the lower XLEN bits.
6860     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6861                                      DAG.getUNDEF(ContainerVT),
6862                                      DAG.getConstant(32, DL, XLenVT), VL);
6863     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6864                                  ThirtyTwoV, Mask, VL);
6865 
6866     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6867 
6868     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6869     break;
6870   }
6871   case ISD::INTRINSIC_WO_CHAIN: {
6872     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6873     switch (IntNo) {
6874     default:
6875       llvm_unreachable(
6876           "Don't know how to custom type legalize this intrinsic!");
6877     case Intrinsic::riscv_grev:
6878     case Intrinsic::riscv_gorc:
6879     case Intrinsic::riscv_bcompress:
6880     case Intrinsic::riscv_bdecompress:
6881     case Intrinsic::riscv_bfp: {
6882       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6883              "Unexpected custom legalisation");
6884       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6885       break;
6886     }
6887     case Intrinsic::riscv_fsl:
6888     case Intrinsic::riscv_fsr: {
6889       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6890              "Unexpected custom legalisation");
6891       SDValue NewOp1 =
6892           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6893       SDValue NewOp2 =
6894           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6895       SDValue NewOp3 =
6896           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6897       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6898       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6899       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6900       break;
6901     }
6902     case Intrinsic::riscv_orc_b: {
6903       // Lower to the GORCI encoding for orc.b with the operand extended.
6904       SDValue NewOp =
6905           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6906       // If Zbp is enabled, use GORCIW which will sign extend the result.
6907       unsigned Opc =
6908           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6909       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6910                                 DAG.getConstant(7, DL, MVT::i64));
6911       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6912       return;
6913     }
6914     case Intrinsic::riscv_shfl:
6915     case Intrinsic::riscv_unshfl: {
6916       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6917              "Unexpected custom legalisation");
6918       SDValue NewOp1 =
6919           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6920       SDValue NewOp2 =
6921           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6922       unsigned Opc =
6923           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6924       // There is no (UN)SHFLIW. If the control word is a constant, we can use
6925       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
6926       // will be shuffled the same way as the lower 32 bit half, but the two
6927       // halves won't cross.
6928       if (isa<ConstantSDNode>(NewOp2)) {
6929         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6930                              DAG.getConstant(0xf, DL, MVT::i64));
6931         Opc =
6932             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6933       }
6934       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6935       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6936       break;
6937     }
6938     case Intrinsic::riscv_vmv_x_s: {
6939       EVT VT = N->getValueType(0);
6940       MVT XLenVT = Subtarget.getXLenVT();
6941       if (VT.bitsLT(XLenVT)) {
6942         // Simple case just extract using vmv.x.s and truncate.
6943         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6944                                       Subtarget.getXLenVT(), N->getOperand(1));
6945         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6946         return;
6947       }
6948 
6949       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6950              "Unexpected custom legalization");
6951 
6952       // We need to do the move in two steps.
6953       SDValue Vec = N->getOperand(1);
6954       MVT VecVT = Vec.getSimpleValueType();
6955 
6956       // First extract the lower XLEN bits of the element.
6957       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6958 
6959       // To extract the upper XLEN bits of the vector element, shift the first
6960       // element right by 32 bits and re-extract the lower XLEN bits.
6961       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6962       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6963       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6964       SDValue ThirtyTwoV =
6965           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
6966                       DAG.getConstant(32, DL, XLenVT), VL);
6967       SDValue LShr32 =
6968           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6969       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6970 
6971       Results.push_back(
6972           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6973       break;
6974     }
6975     }
6976     break;
6977   }
6978   case ISD::VECREDUCE_ADD:
6979   case ISD::VECREDUCE_AND:
6980   case ISD::VECREDUCE_OR:
6981   case ISD::VECREDUCE_XOR:
6982   case ISD::VECREDUCE_SMAX:
6983   case ISD::VECREDUCE_UMAX:
6984   case ISD::VECREDUCE_SMIN:
6985   case ISD::VECREDUCE_UMIN:
6986     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6987       Results.push_back(V);
6988     break;
6989   case ISD::VP_REDUCE_ADD:
6990   case ISD::VP_REDUCE_AND:
6991   case ISD::VP_REDUCE_OR:
6992   case ISD::VP_REDUCE_XOR:
6993   case ISD::VP_REDUCE_SMAX:
6994   case ISD::VP_REDUCE_UMAX:
6995   case ISD::VP_REDUCE_SMIN:
6996   case ISD::VP_REDUCE_UMIN:
6997     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6998       Results.push_back(V);
6999     break;
7000   case ISD::FLT_ROUNDS_: {
7001     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7002     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7003     Results.push_back(Res.getValue(0));
7004     Results.push_back(Res.getValue(1));
7005     break;
7006   }
7007   }
7008 }
7009 
7010 // A structure to hold one of the bit-manipulation patterns below. Together, a
7011 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7012 //   (or (and (shl x, 1), 0xAAAAAAAA),
7013 //       (and (srl x, 1), 0x55555555))
7014 struct RISCVBitmanipPat {
7015   SDValue Op;
7016   unsigned ShAmt;
7017   bool IsSHL;
7018 
7019   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7020     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7021   }
7022 };
7023 
7024 // Matches patterns of the form
7025 //   (and (shl x, C2), (C1 << C2))
7026 //   (and (srl x, C2), C1)
7027 //   (shl (and x, C1), C2)
7028 //   (srl (and x, (C1 << C2)), C2)
7029 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7030 // The expected masks for each shift amount are specified in BitmanipMasks where
7031 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7032 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7033 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7034 // XLen is 64.
7035 static Optional<RISCVBitmanipPat>
7036 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7037   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7038          "Unexpected number of masks");
7039   Optional<uint64_t> Mask;
7040   // Optionally consume a mask around the shift operation.
7041   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7042     Mask = Op.getConstantOperandVal(1);
7043     Op = Op.getOperand(0);
7044   }
7045   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7046     return None;
7047   bool IsSHL = Op.getOpcode() == ISD::SHL;
7048 
7049   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7050     return None;
7051   uint64_t ShAmt = Op.getConstantOperandVal(1);
7052 
7053   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7054   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7055     return None;
7056   // If we don't have enough masks for 64 bit, then we must be trying to
7057   // match SHFL so we're only allowed to shift 1/4 of the width.
7058   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7059     return None;
7060 
7061   SDValue Src = Op.getOperand(0);
7062 
7063   // The expected mask is shifted left when the AND is found around SHL
7064   // patterns.
7065   //   ((x >> 1) & 0x55555555)
7066   //   ((x << 1) & 0xAAAAAAAA)
7067   bool SHLExpMask = IsSHL;
7068 
7069   if (!Mask) {
7070     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7071     // the mask is all ones: consume that now.
7072     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7073       Mask = Src.getConstantOperandVal(1);
7074       Src = Src.getOperand(0);
7075       // The expected mask is now in fact shifted left for SRL, so reverse the
7076       // decision.
7077       //   ((x & 0xAAAAAAAA) >> 1)
7078       //   ((x & 0x55555555) << 1)
7079       SHLExpMask = !SHLExpMask;
7080     } else {
7081       // Use a default shifted mask of all-ones if there's no AND, truncated
7082       // down to the expected width. This simplifies the logic later on.
7083       Mask = maskTrailingOnes<uint64_t>(Width);
7084       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7085     }
7086   }
7087 
7088   unsigned MaskIdx = Log2_32(ShAmt);
7089   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7090 
7091   if (SHLExpMask)
7092     ExpMask <<= ShAmt;
7093 
7094   if (Mask != ExpMask)
7095     return None;
7096 
7097   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7098 }
7099 
7100 // Matches any of the following bit-manipulation patterns:
7101 //   (and (shl x, 1), (0x55555555 << 1))
7102 //   (and (srl x, 1), 0x55555555)
7103 //   (shl (and x, 0x55555555), 1)
7104 //   (srl (and x, (0x55555555 << 1)), 1)
7105 // where the shift amount and mask may vary thus:
7106 //   [1]  = 0x55555555 / 0xAAAAAAAA
7107 //   [2]  = 0x33333333 / 0xCCCCCCCC
7108 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7109 //   [8]  = 0x00FF00FF / 0xFF00FF00
7110 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7111 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7112 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7113   // These are the unshifted masks which we use to match bit-manipulation
7114   // patterns. They may be shifted left in certain circumstances.
7115   static const uint64_t BitmanipMasks[] = {
7116       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7117       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7118 
7119   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7120 }
7121 
7122 // Match the following pattern as a GREVI(W) operation
7123 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7124 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7125                                const RISCVSubtarget &Subtarget) {
7126   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7127   EVT VT = Op.getValueType();
7128 
7129   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7130     auto LHS = matchGREVIPat(Op.getOperand(0));
7131     auto RHS = matchGREVIPat(Op.getOperand(1));
7132     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7133       SDLoc DL(Op);
7134       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7135                          DAG.getConstant(LHS->ShAmt, DL, VT));
7136     }
7137   }
7138   return SDValue();
7139 }
7140 
7141 // Matches any the following pattern as a GORCI(W) operation
7142 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7143 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7144 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7145 // Note that with the variant of 3.,
7146 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7147 // the inner pattern will first be matched as GREVI and then the outer
7148 // pattern will be matched to GORC via the first rule above.
7149 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7150 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7151                                const RISCVSubtarget &Subtarget) {
7152   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7153   EVT VT = Op.getValueType();
7154 
7155   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7156     SDLoc DL(Op);
7157     SDValue Op0 = Op.getOperand(0);
7158     SDValue Op1 = Op.getOperand(1);
7159 
7160     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7161       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7162           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7163           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7164         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7165       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7166       if ((Reverse.getOpcode() == ISD::ROTL ||
7167            Reverse.getOpcode() == ISD::ROTR) &&
7168           Reverse.getOperand(0) == X &&
7169           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7170         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7171         if (RotAmt == (VT.getSizeInBits() / 2))
7172           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7173                              DAG.getConstant(RotAmt, DL, VT));
7174       }
7175       return SDValue();
7176     };
7177 
7178     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7179     if (SDValue V = MatchOROfReverse(Op0, Op1))
7180       return V;
7181     if (SDValue V = MatchOROfReverse(Op1, Op0))
7182       return V;
7183 
7184     // OR is commutable so canonicalize its OR operand to the left
7185     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7186       std::swap(Op0, Op1);
7187     if (Op0.getOpcode() != ISD::OR)
7188       return SDValue();
7189     SDValue OrOp0 = Op0.getOperand(0);
7190     SDValue OrOp1 = Op0.getOperand(1);
7191     auto LHS = matchGREVIPat(OrOp0);
7192     // OR is commutable so swap the operands and try again: x might have been
7193     // on the left
7194     if (!LHS) {
7195       std::swap(OrOp0, OrOp1);
7196       LHS = matchGREVIPat(OrOp0);
7197     }
7198     auto RHS = matchGREVIPat(Op1);
7199     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7200       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7201                          DAG.getConstant(LHS->ShAmt, DL, VT));
7202     }
7203   }
7204   return SDValue();
7205 }
7206 
7207 // Matches any of the following bit-manipulation patterns:
7208 //   (and (shl x, 1), (0x22222222 << 1))
7209 //   (and (srl x, 1), 0x22222222)
7210 //   (shl (and x, 0x22222222), 1)
7211 //   (srl (and x, (0x22222222 << 1)), 1)
7212 // where the shift amount and mask may vary thus:
7213 //   [1]  = 0x22222222 / 0x44444444
7214 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7215 //   [4]  = 0x00F000F0 / 0x0F000F00
7216 //   [8]  = 0x0000FF00 / 0x00FF0000
7217 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7218 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7219   // These are the unshifted masks which we use to match bit-manipulation
7220   // patterns. They may be shifted left in certain circumstances.
7221   static const uint64_t BitmanipMasks[] = {
7222       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7223       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7224 
7225   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7226 }
7227 
7228 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7229 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7230                                const RISCVSubtarget &Subtarget) {
7231   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7232   EVT VT = Op.getValueType();
7233 
7234   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7235     return SDValue();
7236 
7237   SDValue Op0 = Op.getOperand(0);
7238   SDValue Op1 = Op.getOperand(1);
7239 
7240   // Or is commutable so canonicalize the second OR to the LHS.
7241   if (Op0.getOpcode() != ISD::OR)
7242     std::swap(Op0, Op1);
7243   if (Op0.getOpcode() != ISD::OR)
7244     return SDValue();
7245 
7246   // We found an inner OR, so our operands are the operands of the inner OR
7247   // and the other operand of the outer OR.
7248   SDValue A = Op0.getOperand(0);
7249   SDValue B = Op0.getOperand(1);
7250   SDValue C = Op1;
7251 
7252   auto Match1 = matchSHFLPat(A);
7253   auto Match2 = matchSHFLPat(B);
7254 
7255   // If neither matched, we failed.
7256   if (!Match1 && !Match2)
7257     return SDValue();
7258 
7259   // We had at least one match. if one failed, try the remaining C operand.
7260   if (!Match1) {
7261     std::swap(A, C);
7262     Match1 = matchSHFLPat(A);
7263     if (!Match1)
7264       return SDValue();
7265   } else if (!Match2) {
7266     std::swap(B, C);
7267     Match2 = matchSHFLPat(B);
7268     if (!Match2)
7269       return SDValue();
7270   }
7271   assert(Match1 && Match2);
7272 
7273   // Make sure our matches pair up.
7274   if (!Match1->formsPairWith(*Match2))
7275     return SDValue();
7276 
7277   // All the remains is to make sure C is an AND with the same input, that masks
7278   // out the bits that are being shuffled.
7279   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7280       C.getOperand(0) != Match1->Op)
7281     return SDValue();
7282 
7283   uint64_t Mask = C.getConstantOperandVal(1);
7284 
7285   static const uint64_t BitmanipMasks[] = {
7286       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7287       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7288   };
7289 
7290   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7291   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7292   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7293 
7294   if (Mask != ExpMask)
7295     return SDValue();
7296 
7297   SDLoc DL(Op);
7298   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7299                      DAG.getConstant(Match1->ShAmt, DL, VT));
7300 }
7301 
7302 // Optimize (add (shl x, c0), (shl y, c1)) ->
7303 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7304 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7305                                   const RISCVSubtarget &Subtarget) {
7306   // Perform this optimization only in the zba extension.
7307   if (!Subtarget.hasStdExtZba())
7308     return SDValue();
7309 
7310   // Skip for vector types and larger types.
7311   EVT VT = N->getValueType(0);
7312   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7313     return SDValue();
7314 
7315   // The two operand nodes must be SHL and have no other use.
7316   SDValue N0 = N->getOperand(0);
7317   SDValue N1 = N->getOperand(1);
7318   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7319       !N0->hasOneUse() || !N1->hasOneUse())
7320     return SDValue();
7321 
7322   // Check c0 and c1.
7323   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7324   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7325   if (!N0C || !N1C)
7326     return SDValue();
7327   int64_t C0 = N0C->getSExtValue();
7328   int64_t C1 = N1C->getSExtValue();
7329   if (C0 <= 0 || C1 <= 0)
7330     return SDValue();
7331 
7332   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7333   int64_t Bits = std::min(C0, C1);
7334   int64_t Diff = std::abs(C0 - C1);
7335   if (Diff != 1 && Diff != 2 && Diff != 3)
7336     return SDValue();
7337 
7338   // Build nodes.
7339   SDLoc DL(N);
7340   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7341   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7342   SDValue NA0 =
7343       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7344   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7345   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7346 }
7347 
7348 // Combine
7349 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8)
7350 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8)
7351 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8)
7352 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8)
7353 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7354                                           const RISCVSubtarget &Subtarget) {
7355   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7356           N->getOpcode() == RISCVISD::RORW ||
7357           N->getOpcode() == RISCVISD::ROLW) &&
7358          "Unexpected opcode!");
7359   SDValue Src = N->getOperand(0);
7360   SDLoc DL(N);
7361   unsigned Opc;
7362 
7363   if (!Subtarget.hasStdExtZbp())
7364     return SDValue();
7365 
7366   if ((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL) &&
7367       Src.getOpcode() == RISCVISD::GREV)
7368     Opc = RISCVISD::GREV;
7369   else if ((N->getOpcode() == RISCVISD::RORW ||
7370             N->getOpcode() == RISCVISD::ROLW) &&
7371            Src.getOpcode() == RISCVISD::GREVW)
7372     Opc = RISCVISD::GREVW;
7373   else
7374     return SDValue();
7375 
7376   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7377       !isa<ConstantSDNode>(Src.getOperand(1)))
7378     return SDValue();
7379 
7380   unsigned ShAmt1 = N->getConstantOperandVal(1);
7381   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7382   if (ShAmt1 != 16 && ShAmt2 != 24)
7383     return SDValue();
7384 
7385   Src = Src.getOperand(0);
7386   return DAG.getNode(Opc, DL, N->getValueType(0), Src,
7387                      DAG.getConstant(8, DL, N->getOperand(1).getValueType()));
7388 }
7389 
7390 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7391 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7392 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7393 // not undo itself, but they are redundant.
7394 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7395   SDValue Src = N->getOperand(0);
7396 
7397   if (Src.getOpcode() != N->getOpcode())
7398     return SDValue();
7399 
7400   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7401       !isa<ConstantSDNode>(Src.getOperand(1)))
7402     return SDValue();
7403 
7404   unsigned ShAmt1 = N->getConstantOperandVal(1);
7405   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7406   Src = Src.getOperand(0);
7407 
7408   unsigned CombinedShAmt;
7409   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7410     CombinedShAmt = ShAmt1 | ShAmt2;
7411   else
7412     CombinedShAmt = ShAmt1 ^ ShAmt2;
7413 
7414   if (CombinedShAmt == 0)
7415     return Src;
7416 
7417   SDLoc DL(N);
7418   return DAG.getNode(
7419       N->getOpcode(), DL, N->getValueType(0), Src,
7420       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7421 }
7422 
7423 // Combine a constant select operand into its use:
7424 //
7425 // (and (select cond, -1, c), x)
7426 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7427 // (or  (select cond, 0, c), x)
7428 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7429 // (xor (select cond, 0, c), x)
7430 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7431 // (add (select cond, 0, c), x)
7432 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7433 // (sub x, (select cond, 0, c))
7434 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7435 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7436                                    SelectionDAG &DAG, bool AllOnes) {
7437   EVT VT = N->getValueType(0);
7438 
7439   // Skip vectors.
7440   if (VT.isVector())
7441     return SDValue();
7442 
7443   if ((Slct.getOpcode() != ISD::SELECT &&
7444        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7445       !Slct.hasOneUse())
7446     return SDValue();
7447 
7448   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7449     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7450   };
7451 
7452   bool SwapSelectOps;
7453   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7454   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7455   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7456   SDValue NonConstantVal;
7457   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7458     SwapSelectOps = false;
7459     NonConstantVal = FalseVal;
7460   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7461     SwapSelectOps = true;
7462     NonConstantVal = TrueVal;
7463   } else
7464     return SDValue();
7465 
7466   // Slct is now know to be the desired identity constant when CC is true.
7467   TrueVal = OtherOp;
7468   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7469   // Unless SwapSelectOps says the condition should be false.
7470   if (SwapSelectOps)
7471     std::swap(TrueVal, FalseVal);
7472 
7473   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7474     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7475                        {Slct.getOperand(0), Slct.getOperand(1),
7476                         Slct.getOperand(2), TrueVal, FalseVal});
7477 
7478   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7479                      {Slct.getOperand(0), TrueVal, FalseVal});
7480 }
7481 
7482 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7483 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7484                                               bool AllOnes) {
7485   SDValue N0 = N->getOperand(0);
7486   SDValue N1 = N->getOperand(1);
7487   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7488     return Result;
7489   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7490     return Result;
7491   return SDValue();
7492 }
7493 
7494 // Transform (add (mul x, c0), c1) ->
7495 //           (add (mul (add x, c1/c0), c0), c1%c0).
7496 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7497 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7498 // to an infinite loop in DAGCombine if transformed.
7499 // Or transform (add (mul x, c0), c1) ->
7500 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7501 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7502 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7503 // lead to an infinite loop in DAGCombine if transformed.
7504 // Or transform (add (mul x, c0), c1) ->
7505 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7506 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7507 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7508 // lead to an infinite loop in DAGCombine if transformed.
7509 // Or transform (add (mul x, c0), c1) ->
7510 //              (mul (add x, c1/c0), c0).
7511 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7512 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7513                                      const RISCVSubtarget &Subtarget) {
7514   // Skip for vector types and larger types.
7515   EVT VT = N->getValueType(0);
7516   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7517     return SDValue();
7518   // The first operand node must be a MUL and has no other use.
7519   SDValue N0 = N->getOperand(0);
7520   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7521     return SDValue();
7522   // Check if c0 and c1 match above conditions.
7523   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7524   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7525   if (!N0C || !N1C)
7526     return SDValue();
7527   // If N0C has multiple uses it's possible one of the cases in
7528   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7529   // in an infinite loop.
7530   if (!N0C->hasOneUse())
7531     return SDValue();
7532   int64_t C0 = N0C->getSExtValue();
7533   int64_t C1 = N1C->getSExtValue();
7534   int64_t CA, CB;
7535   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7536     return SDValue();
7537   // Search for proper CA (non-zero) and CB that both are simm12.
7538   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7539       !isInt<12>(C0 * (C1 / C0))) {
7540     CA = C1 / C0;
7541     CB = C1 % C0;
7542   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7543              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7544     CA = C1 / C0 + 1;
7545     CB = C1 % C0 - C0;
7546   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7547              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7548     CA = C1 / C0 - 1;
7549     CB = C1 % C0 + C0;
7550   } else
7551     return SDValue();
7552   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7553   SDLoc DL(N);
7554   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7555                              DAG.getConstant(CA, DL, VT));
7556   SDValue New1 =
7557       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7558   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7559 }
7560 
7561 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7562                                  const RISCVSubtarget &Subtarget) {
7563   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7564     return V;
7565   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7566     return V;
7567   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7568   //      (select lhs, rhs, cc, x, (add x, y))
7569   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7570 }
7571 
7572 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7573   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7574   //      (select lhs, rhs, cc, x, (sub x, y))
7575   SDValue N0 = N->getOperand(0);
7576   SDValue N1 = N->getOperand(1);
7577   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7578 }
7579 
7580 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7581   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7582   //      (select lhs, rhs, cc, x, (and x, y))
7583   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7584 }
7585 
7586 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7587                                 const RISCVSubtarget &Subtarget) {
7588   if (Subtarget.hasStdExtZbp()) {
7589     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7590       return GREV;
7591     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7592       return GORC;
7593     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7594       return SHFL;
7595   }
7596 
7597   // fold (or (select cond, 0, y), x) ->
7598   //      (select cond, x, (or x, y))
7599   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7600 }
7601 
7602 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7603   // fold (xor (select cond, 0, y), x) ->
7604   //      (select cond, x, (xor x, y))
7605   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7606 }
7607 
7608 static SDValue performSIGN_EXTEND_INREG(SDNode *N, SelectionDAG &DAG) {
7609   SDValue Src = N->getOperand(0);
7610 
7611   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7612   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7613       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7614     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), N->getValueType(0),
7615                        Src.getOperand(0));
7616 
7617   return SDValue();
7618 }
7619 
7620 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7621 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7622 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7623 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7624 // ADDW/SUBW/MULW.
7625 static SDValue performANY_EXTENDCombine(SDNode *N,
7626                                         TargetLowering::DAGCombinerInfo &DCI,
7627                                         const RISCVSubtarget &Subtarget) {
7628   if (!Subtarget.is64Bit())
7629     return SDValue();
7630 
7631   SelectionDAG &DAG = DCI.DAG;
7632 
7633   SDValue Src = N->getOperand(0);
7634   EVT VT = N->getValueType(0);
7635   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7636     return SDValue();
7637 
7638   // The opcode must be one that can implicitly sign_extend.
7639   // FIXME: Additional opcodes.
7640   switch (Src.getOpcode()) {
7641   default:
7642     return SDValue();
7643   case ISD::MUL:
7644     if (!Subtarget.hasStdExtM())
7645       return SDValue();
7646     LLVM_FALLTHROUGH;
7647   case ISD::ADD:
7648   case ISD::SUB:
7649     break;
7650   }
7651 
7652   // Only handle cases where the result is used by a CopyToReg. That likely
7653   // means the value is a liveout of the basic block. This helps prevent
7654   // infinite combine loops like PR51206.
7655   if (none_of(N->uses(),
7656               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7657     return SDValue();
7658 
7659   SmallVector<SDNode *, 4> SetCCs;
7660   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7661                             UE = Src.getNode()->use_end();
7662        UI != UE; ++UI) {
7663     SDNode *User = *UI;
7664     if (User == N)
7665       continue;
7666     if (UI.getUse().getResNo() != Src.getResNo())
7667       continue;
7668     // All i32 setccs are legalized by sign extending operands.
7669     if (User->getOpcode() == ISD::SETCC) {
7670       SetCCs.push_back(User);
7671       continue;
7672     }
7673     // We don't know if we can extend this user.
7674     break;
7675   }
7676 
7677   // If we don't have any SetCCs, this isn't worthwhile.
7678   if (SetCCs.empty())
7679     return SDValue();
7680 
7681   SDLoc DL(N);
7682   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7683   DCI.CombineTo(N, SExt);
7684 
7685   // Promote all the setccs.
7686   for (SDNode *SetCC : SetCCs) {
7687     SmallVector<SDValue, 4> Ops;
7688 
7689     for (unsigned j = 0; j != 2; ++j) {
7690       SDValue SOp = SetCC->getOperand(j);
7691       if (SOp == Src)
7692         Ops.push_back(SExt);
7693       else
7694         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7695     }
7696 
7697     Ops.push_back(SetCC->getOperand(2));
7698     DCI.CombineTo(SetCC,
7699                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7700   }
7701   return SDValue(N, 0);
7702 }
7703 
7704 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7705 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7706 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7707                                              bool Commute = false) {
7708   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7709           N->getOpcode() == RISCVISD::SUB_VL) &&
7710          "Unexpected opcode");
7711   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7712   SDValue Op0 = N->getOperand(0);
7713   SDValue Op1 = N->getOperand(1);
7714   if (Commute)
7715     std::swap(Op0, Op1);
7716 
7717   MVT VT = N->getSimpleValueType(0);
7718 
7719   // Determine the narrow size for a widening add/sub.
7720   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7721   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7722                                   VT.getVectorElementCount());
7723 
7724   SDValue Mask = N->getOperand(2);
7725   SDValue VL = N->getOperand(3);
7726 
7727   SDLoc DL(N);
7728 
7729   // If the RHS is a sext or zext, we can form a widening op.
7730   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7731        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7732       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7733     unsigned ExtOpc = Op1.getOpcode();
7734     Op1 = Op1.getOperand(0);
7735     // Re-introduce narrower extends if needed.
7736     if (Op1.getValueType() != NarrowVT)
7737       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7738 
7739     unsigned WOpc;
7740     if (ExtOpc == RISCVISD::VSEXT_VL)
7741       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7742     else
7743       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7744 
7745     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7746   }
7747 
7748   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7749   // sext/zext?
7750 
7751   return SDValue();
7752 }
7753 
7754 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7755 // vwsub(u).vv/vx.
7756 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7757   SDValue Op0 = N->getOperand(0);
7758   SDValue Op1 = N->getOperand(1);
7759   SDValue Mask = N->getOperand(2);
7760   SDValue VL = N->getOperand(3);
7761 
7762   MVT VT = N->getSimpleValueType(0);
7763   MVT NarrowVT = Op1.getSimpleValueType();
7764   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7765 
7766   unsigned VOpc;
7767   switch (N->getOpcode()) {
7768   default: llvm_unreachable("Unexpected opcode");
7769   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7770   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7771   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7772   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7773   }
7774 
7775   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7776                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7777 
7778   SDLoc DL(N);
7779 
7780   // If the LHS is a sext or zext, we can narrow this op to the same size as
7781   // the RHS.
7782   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7783        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7784       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7785     unsigned ExtOpc = Op0.getOpcode();
7786     Op0 = Op0.getOperand(0);
7787     // Re-introduce narrower extends if needed.
7788     if (Op0.getValueType() != NarrowVT)
7789       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7790     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7791   }
7792 
7793   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7794                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7795 
7796   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7797   // to commute and use a vwadd(u).vx instead.
7798   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7799       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
7800     Op0 = Op0.getOperand(1);
7801 
7802     // See if have enough sign bits or zero bits in the scalar to use a
7803     // widening add/sub by splatting to smaller element size.
7804     unsigned EltBits = VT.getScalarSizeInBits();
7805     unsigned ScalarBits = Op0.getValueSizeInBits();
7806     // Make sure we're getting all element bits from the scalar register.
7807     // FIXME: Support implicit sign extension of vmv.v.x?
7808     if (ScalarBits < EltBits)
7809       return SDValue();
7810 
7811     if (IsSigned) {
7812       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7813         return SDValue();
7814     } else {
7815       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7816       if (!DAG.MaskedValueIsZero(Op0, Mask))
7817         return SDValue();
7818     }
7819 
7820     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7821                       DAG.getUNDEF(NarrowVT), Op0, VL);
7822     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7823   }
7824 
7825   return SDValue();
7826 }
7827 
7828 // Try to form VWMUL, VWMULU or VWMULSU.
7829 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7830 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7831                                        bool Commute) {
7832   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7833   SDValue Op0 = N->getOperand(0);
7834   SDValue Op1 = N->getOperand(1);
7835   if (Commute)
7836     std::swap(Op0, Op1);
7837 
7838   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7839   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7840   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7841   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7842     return SDValue();
7843 
7844   SDValue Mask = N->getOperand(2);
7845   SDValue VL = N->getOperand(3);
7846 
7847   // Make sure the mask and VL match.
7848   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7849     return SDValue();
7850 
7851   MVT VT = N->getSimpleValueType(0);
7852 
7853   // Determine the narrow size for a widening multiply.
7854   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7855   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7856                                   VT.getVectorElementCount());
7857 
7858   SDLoc DL(N);
7859 
7860   // See if the other operand is the same opcode.
7861   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7862     if (!Op1.hasOneUse())
7863       return SDValue();
7864 
7865     // Make sure the mask and VL match.
7866     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7867       return SDValue();
7868 
7869     Op1 = Op1.getOperand(0);
7870   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7871     // The operand is a splat of a scalar.
7872 
7873     // The pasthru must be undef for tail agnostic
7874     if (!Op1.getOperand(0).isUndef())
7875       return SDValue();
7876     // The VL must be the same.
7877     if (Op1.getOperand(2) != VL)
7878       return SDValue();
7879 
7880     // Get the scalar value.
7881     Op1 = Op1.getOperand(1);
7882 
7883     // See if have enough sign bits or zero bits in the scalar to use a
7884     // widening multiply by splatting to smaller element size.
7885     unsigned EltBits = VT.getScalarSizeInBits();
7886     unsigned ScalarBits = Op1.getValueSizeInBits();
7887     // Make sure we're getting all element bits from the scalar register.
7888     // FIXME: Support implicit sign extension of vmv.v.x?
7889     if (ScalarBits < EltBits)
7890       return SDValue();
7891 
7892     // If the LHS is a sign extend, try to use vwmul.
7893     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
7894       // Can use vwmul.
7895     } else {
7896       // Otherwise try to use vwmulu or vwmulsu.
7897       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7898       if (DAG.MaskedValueIsZero(Op1, Mask))
7899         IsVWMULSU = IsSignExt;
7900       else
7901         return SDValue();
7902     }
7903 
7904     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7905                       DAG.getUNDEF(NarrowVT), Op1, VL);
7906   } else
7907     return SDValue();
7908 
7909   Op0 = Op0.getOperand(0);
7910 
7911   // Re-introduce narrower extends if needed.
7912   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7913   if (Op0.getValueType() != NarrowVT)
7914     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7915   // vwmulsu requires second operand to be zero extended.
7916   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
7917   if (Op1.getValueType() != NarrowVT)
7918     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7919 
7920   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7921   if (!IsVWMULSU)
7922     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7923   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7924 }
7925 
7926 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7927   switch (Op.getOpcode()) {
7928   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7929   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7930   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7931   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7932   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7933   }
7934 
7935   return RISCVFPRndMode::Invalid;
7936 }
7937 
7938 // Fold
7939 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7940 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7941 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7942 //   (fp_to_int (fceil X))      -> fcvt X, rup
7943 //   (fp_to_int (fround X))     -> fcvt X, rmm
7944 static SDValue performFP_TO_INTCombine(SDNode *N,
7945                                        TargetLowering::DAGCombinerInfo &DCI,
7946                                        const RISCVSubtarget &Subtarget) {
7947   SelectionDAG &DAG = DCI.DAG;
7948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7949   MVT XLenVT = Subtarget.getXLenVT();
7950 
7951   // Only handle XLen or i32 types. Other types narrower than XLen will
7952   // eventually be legalized to XLenVT.
7953   EVT VT = N->getValueType(0);
7954   if (VT != MVT::i32 && VT != XLenVT)
7955     return SDValue();
7956 
7957   SDValue Src = N->getOperand(0);
7958 
7959   // Ensure the FP type is also legal.
7960   if (!TLI.isTypeLegal(Src.getValueType()))
7961     return SDValue();
7962 
7963   // Don't do this for f16 with Zfhmin and not Zfh.
7964   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7965     return SDValue();
7966 
7967   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7968   if (FRM == RISCVFPRndMode::Invalid)
7969     return SDValue();
7970 
7971   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7972 
7973   unsigned Opc;
7974   if (VT == XLenVT)
7975     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7976   else
7977     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7978 
7979   SDLoc DL(N);
7980   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7981                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7982   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7983 }
7984 
7985 // Fold
7986 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7987 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7988 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7989 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7990 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7991 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7992                                        TargetLowering::DAGCombinerInfo &DCI,
7993                                        const RISCVSubtarget &Subtarget) {
7994   SelectionDAG &DAG = DCI.DAG;
7995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7996   MVT XLenVT = Subtarget.getXLenVT();
7997 
7998   // Only handle XLen types. Other types narrower than XLen will eventually be
7999   // legalized to XLenVT.
8000   EVT DstVT = N->getValueType(0);
8001   if (DstVT != XLenVT)
8002     return SDValue();
8003 
8004   SDValue Src = N->getOperand(0);
8005 
8006   // Ensure the FP type is also legal.
8007   if (!TLI.isTypeLegal(Src.getValueType()))
8008     return SDValue();
8009 
8010   // Don't do this for f16 with Zfhmin and not Zfh.
8011   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8012     return SDValue();
8013 
8014   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8015 
8016   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8017   if (FRM == RISCVFPRndMode::Invalid)
8018     return SDValue();
8019 
8020   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8021 
8022   unsigned Opc;
8023   if (SatVT == DstVT)
8024     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8025   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8026     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8027   else
8028     return SDValue();
8029   // FIXME: Support other SatVTs by clamping before or after the conversion.
8030 
8031   Src = Src.getOperand(0);
8032 
8033   SDLoc DL(N);
8034   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8035                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8036 
8037   // RISCV FP-to-int conversions saturate to the destination register size, but
8038   // don't produce 0 for nan.
8039   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8040   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8041 }
8042 
8043 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8044                                                DAGCombinerInfo &DCI) const {
8045   SelectionDAG &DAG = DCI.DAG;
8046 
8047   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8048   // bits are demanded. N will be added to the Worklist if it was not deleted.
8049   // Caller should return SDValue(N, 0) if this returns true.
8050   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8051     SDValue Op = N->getOperand(OpNo);
8052     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8053     if (!SimplifyDemandedBits(Op, Mask, DCI))
8054       return false;
8055 
8056     if (N->getOpcode() != ISD::DELETED_NODE)
8057       DCI.AddToWorklist(N);
8058     return true;
8059   };
8060 
8061   switch (N->getOpcode()) {
8062   default:
8063     break;
8064   case RISCVISD::SplitF64: {
8065     SDValue Op0 = N->getOperand(0);
8066     // If the input to SplitF64 is just BuildPairF64 then the operation is
8067     // redundant. Instead, use BuildPairF64's operands directly.
8068     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8069       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8070 
8071     if (Op0->isUndef()) {
8072       SDValue Lo = DAG.getUNDEF(MVT::i32);
8073       SDValue Hi = DAG.getUNDEF(MVT::i32);
8074       return DCI.CombineTo(N, Lo, Hi);
8075     }
8076 
8077     SDLoc DL(N);
8078 
8079     // It's cheaper to materialise two 32-bit integers than to load a double
8080     // from the constant pool and transfer it to integer registers through the
8081     // stack.
8082     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8083       APInt V = C->getValueAPF().bitcastToAPInt();
8084       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8085       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8086       return DCI.CombineTo(N, Lo, Hi);
8087     }
8088 
8089     // This is a target-specific version of a DAGCombine performed in
8090     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8091     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8092     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8093     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8094         !Op0.getNode()->hasOneUse())
8095       break;
8096     SDValue NewSplitF64 =
8097         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8098                     Op0.getOperand(0));
8099     SDValue Lo = NewSplitF64.getValue(0);
8100     SDValue Hi = NewSplitF64.getValue(1);
8101     APInt SignBit = APInt::getSignMask(32);
8102     if (Op0.getOpcode() == ISD::FNEG) {
8103       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8104                                   DAG.getConstant(SignBit, DL, MVT::i32));
8105       return DCI.CombineTo(N, Lo, NewHi);
8106     }
8107     assert(Op0.getOpcode() == ISD::FABS);
8108     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8109                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8110     return DCI.CombineTo(N, Lo, NewHi);
8111   }
8112   case RISCVISD::SLLW:
8113   case RISCVISD::SRAW:
8114   case RISCVISD::SRLW: {
8115     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8116     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8117         SimplifyDemandedLowBitsHelper(1, 5))
8118       return SDValue(N, 0);
8119 
8120     break;
8121   }
8122   case ISD::ROTR:
8123   case ISD::ROTL:
8124   case RISCVISD::RORW:
8125   case RISCVISD::ROLW: {
8126     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8127       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8128       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8129           SimplifyDemandedLowBitsHelper(1, 5))
8130         return SDValue(N, 0);
8131     }
8132 
8133     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8134   }
8135   case RISCVISD::CLZW:
8136   case RISCVISD::CTZW: {
8137     // Only the lower 32 bits of the first operand are read
8138     if (SimplifyDemandedLowBitsHelper(0, 32))
8139       return SDValue(N, 0);
8140     break;
8141   }
8142   case RISCVISD::GREV:
8143   case RISCVISD::GORC: {
8144     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8145     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8146     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8147     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8148       return SDValue(N, 0);
8149 
8150     return combineGREVI_GORCI(N, DAG);
8151   }
8152   case RISCVISD::GREVW:
8153   case RISCVISD::GORCW: {
8154     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8155     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8156         SimplifyDemandedLowBitsHelper(1, 5))
8157       return SDValue(N, 0);
8158 
8159     return combineGREVI_GORCI(N, DAG);
8160   }
8161   case RISCVISD::SHFL:
8162   case RISCVISD::UNSHFL: {
8163     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8164     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8165     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8166     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8167       return SDValue(N, 0);
8168 
8169     break;
8170   }
8171   case RISCVISD::SHFLW:
8172   case RISCVISD::UNSHFLW: {
8173     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8174     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8175         SimplifyDemandedLowBitsHelper(1, 4))
8176       return SDValue(N, 0);
8177 
8178     break;
8179   }
8180   case RISCVISD::BCOMPRESSW:
8181   case RISCVISD::BDECOMPRESSW: {
8182     // Only the lower 32 bits of LHS and RHS are read.
8183     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8184         SimplifyDemandedLowBitsHelper(1, 32))
8185       return SDValue(N, 0);
8186 
8187     break;
8188   }
8189   case RISCVISD::FMV_X_ANYEXTH:
8190   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8191     SDLoc DL(N);
8192     SDValue Op0 = N->getOperand(0);
8193     MVT VT = N->getSimpleValueType(0);
8194     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8195     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8196     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8197     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8198          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8199         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8200          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8201       assert(Op0.getOperand(0).getValueType() == VT &&
8202              "Unexpected value type!");
8203       return Op0.getOperand(0);
8204     }
8205 
8206     // This is a target-specific version of a DAGCombine performed in
8207     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8208     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8209     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8210     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8211         !Op0.getNode()->hasOneUse())
8212       break;
8213     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8214     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8215     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8216     if (Op0.getOpcode() == ISD::FNEG)
8217       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8218                          DAG.getConstant(SignBit, DL, VT));
8219 
8220     assert(Op0.getOpcode() == ISD::FABS);
8221     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8222                        DAG.getConstant(~SignBit, DL, VT));
8223   }
8224   case ISD::ADD:
8225     return performADDCombine(N, DAG, Subtarget);
8226   case ISD::SUB:
8227     return performSUBCombine(N, DAG);
8228   case ISD::AND:
8229     return performANDCombine(N, DAG);
8230   case ISD::OR:
8231     return performORCombine(N, DAG, Subtarget);
8232   case ISD::XOR:
8233     return performXORCombine(N, DAG);
8234   case ISD::SIGN_EXTEND_INREG:
8235     return performSIGN_EXTEND_INREG(N, DAG);
8236   case ISD::ANY_EXTEND:
8237     return performANY_EXTENDCombine(N, DCI, Subtarget);
8238   case ISD::ZERO_EXTEND:
8239     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8240     // type legalization. This is safe because fp_to_uint produces poison if
8241     // it overflows.
8242     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8243       SDValue Src = N->getOperand(0);
8244       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8245           isTypeLegal(Src.getOperand(0).getValueType()))
8246         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8247                            Src.getOperand(0));
8248       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8249           isTypeLegal(Src.getOperand(1).getValueType())) {
8250         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8251         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8252                                   Src.getOperand(0), Src.getOperand(1));
8253         DCI.CombineTo(N, Res);
8254         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8255         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8256         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8257       }
8258     }
8259     return SDValue();
8260   case RISCVISD::SELECT_CC: {
8261     // Transform
8262     SDValue LHS = N->getOperand(0);
8263     SDValue RHS = N->getOperand(1);
8264     SDValue TrueV = N->getOperand(3);
8265     SDValue FalseV = N->getOperand(4);
8266 
8267     // If the True and False values are the same, we don't need a select_cc.
8268     if (TrueV == FalseV)
8269       return TrueV;
8270 
8271     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8272     if (!ISD::isIntEqualitySetCC(CCVal))
8273       break;
8274 
8275     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8276     //      (select_cc X, Y, lt, trueV, falseV)
8277     // Sometimes the setcc is introduced after select_cc has been formed.
8278     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8279         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8280       // If we're looking for eq 0 instead of ne 0, we need to invert the
8281       // condition.
8282       bool Invert = CCVal == ISD::SETEQ;
8283       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8284       if (Invert)
8285         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8286 
8287       SDLoc DL(N);
8288       RHS = LHS.getOperand(1);
8289       LHS = LHS.getOperand(0);
8290       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8291 
8292       SDValue TargetCC = DAG.getCondCode(CCVal);
8293       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8294                          {LHS, RHS, TargetCC, TrueV, FalseV});
8295     }
8296 
8297     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8298     //      (select_cc X, Y, eq/ne, trueV, falseV)
8299     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8300       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8301                          {LHS.getOperand(0), LHS.getOperand(1),
8302                           N->getOperand(2), TrueV, FalseV});
8303     // (select_cc X, 1, setne, trueV, falseV) ->
8304     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8305     // This can occur when legalizing some floating point comparisons.
8306     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8307     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8308       SDLoc DL(N);
8309       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8310       SDValue TargetCC = DAG.getCondCode(CCVal);
8311       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8312       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8313                          {LHS, RHS, TargetCC, TrueV, FalseV});
8314     }
8315 
8316     break;
8317   }
8318   case RISCVISD::BR_CC: {
8319     SDValue LHS = N->getOperand(1);
8320     SDValue RHS = N->getOperand(2);
8321     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8322     if (!ISD::isIntEqualitySetCC(CCVal))
8323       break;
8324 
8325     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8326     //      (br_cc X, Y, lt, dest)
8327     // Sometimes the setcc is introduced after br_cc has been formed.
8328     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8329         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8330       // If we're looking for eq 0 instead of ne 0, we need to invert the
8331       // condition.
8332       bool Invert = CCVal == ISD::SETEQ;
8333       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8334       if (Invert)
8335         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8336 
8337       SDLoc DL(N);
8338       RHS = LHS.getOperand(1);
8339       LHS = LHS.getOperand(0);
8340       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8341 
8342       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8343                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8344                          N->getOperand(4));
8345     }
8346 
8347     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8348     //      (br_cc X, Y, eq/ne, trueV, falseV)
8349     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8350       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8351                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8352                          N->getOperand(3), N->getOperand(4));
8353 
8354     // (br_cc X, 1, setne, br_cc) ->
8355     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8356     // This can occur when legalizing some floating point comparisons.
8357     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8358     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8359       SDLoc DL(N);
8360       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8361       SDValue TargetCC = DAG.getCondCode(CCVal);
8362       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8363       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8364                          N->getOperand(0), LHS, RHS, TargetCC,
8365                          N->getOperand(4));
8366     }
8367     break;
8368   }
8369   case ISD::FP_TO_SINT:
8370   case ISD::FP_TO_UINT:
8371     return performFP_TO_INTCombine(N, DCI, Subtarget);
8372   case ISD::FP_TO_SINT_SAT:
8373   case ISD::FP_TO_UINT_SAT:
8374     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8375   case ISD::FCOPYSIGN: {
8376     EVT VT = N->getValueType(0);
8377     if (!VT.isVector())
8378       break;
8379     // There is a form of VFSGNJ which injects the negated sign of its second
8380     // operand. Try and bubble any FNEG up after the extend/round to produce
8381     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8382     // TRUNC=1.
8383     SDValue In2 = N->getOperand(1);
8384     // Avoid cases where the extend/round has multiple uses, as duplicating
8385     // those is typically more expensive than removing a fneg.
8386     if (!In2.hasOneUse())
8387       break;
8388     if (In2.getOpcode() != ISD::FP_EXTEND &&
8389         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8390       break;
8391     In2 = In2.getOperand(0);
8392     if (In2.getOpcode() != ISD::FNEG)
8393       break;
8394     SDLoc DL(N);
8395     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8396     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8397                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8398   }
8399   case ISD::MGATHER:
8400   case ISD::MSCATTER:
8401   case ISD::VP_GATHER:
8402   case ISD::VP_SCATTER: {
8403     if (!DCI.isBeforeLegalize())
8404       break;
8405     SDValue Index, ScaleOp;
8406     bool IsIndexScaled = false;
8407     bool IsIndexSigned = false;
8408     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8409       Index = VPGSN->getIndex();
8410       ScaleOp = VPGSN->getScale();
8411       IsIndexScaled = VPGSN->isIndexScaled();
8412       IsIndexSigned = VPGSN->isIndexSigned();
8413     } else {
8414       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8415       Index = MGSN->getIndex();
8416       ScaleOp = MGSN->getScale();
8417       IsIndexScaled = MGSN->isIndexScaled();
8418       IsIndexSigned = MGSN->isIndexSigned();
8419     }
8420     EVT IndexVT = Index.getValueType();
8421     MVT XLenVT = Subtarget.getXLenVT();
8422     // RISCV indexed loads only support the "unsigned unscaled" addressing
8423     // mode, so anything else must be manually legalized.
8424     bool NeedsIdxLegalization =
8425         IsIndexScaled ||
8426         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8427     if (!NeedsIdxLegalization)
8428       break;
8429 
8430     SDLoc DL(N);
8431 
8432     // Any index legalization should first promote to XLenVT, so we don't lose
8433     // bits when scaling. This may create an illegal index type so we let
8434     // LLVM's legalization take care of the splitting.
8435     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8436     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8437       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8438       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8439                           DL, IndexVT, Index);
8440     }
8441 
8442     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8443     if (IsIndexScaled && Scale != 1) {
8444       // Manually scale the indices by the element size.
8445       // TODO: Sanitize the scale operand here?
8446       // TODO: For VP nodes, should we use VP_SHL here?
8447       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8448       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8449       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8450     }
8451 
8452     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8453     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8454       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8455                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8456                               VPGN->getScale(), VPGN->getMask(),
8457                               VPGN->getVectorLength()},
8458                              VPGN->getMemOperand(), NewIndexTy);
8459     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8460       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8461                               {VPSN->getChain(), VPSN->getValue(),
8462                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8463                                VPSN->getMask(), VPSN->getVectorLength()},
8464                               VPSN->getMemOperand(), NewIndexTy);
8465     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8466       return DAG.getMaskedGather(
8467           N->getVTList(), MGN->getMemoryVT(), DL,
8468           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8469            MGN->getBasePtr(), Index, MGN->getScale()},
8470           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8471     const auto *MSN = cast<MaskedScatterSDNode>(N);
8472     return DAG.getMaskedScatter(
8473         N->getVTList(), MSN->getMemoryVT(), DL,
8474         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8475          Index, MSN->getScale()},
8476         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8477   }
8478   case RISCVISD::SRA_VL:
8479   case RISCVISD::SRL_VL:
8480   case RISCVISD::SHL_VL: {
8481     SDValue ShAmt = N->getOperand(1);
8482     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8483       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8484       SDLoc DL(N);
8485       SDValue VL = N->getOperand(3);
8486       EVT VT = N->getValueType(0);
8487       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8488                           ShAmt.getOperand(1), VL);
8489       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8490                          N->getOperand(2), N->getOperand(3));
8491     }
8492     break;
8493   }
8494   case ISD::SRA:
8495   case ISD::SRL:
8496   case ISD::SHL: {
8497     SDValue ShAmt = N->getOperand(1);
8498     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8499       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8500       SDLoc DL(N);
8501       EVT VT = N->getValueType(0);
8502       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8503                           ShAmt.getOperand(1),
8504                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8505       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8506     }
8507     break;
8508   }
8509   case RISCVISD::ADD_VL:
8510     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8511       return V;
8512     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8513   case RISCVISD::SUB_VL:
8514     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8515   case RISCVISD::VWADD_W_VL:
8516   case RISCVISD::VWADDU_W_VL:
8517   case RISCVISD::VWSUB_W_VL:
8518   case RISCVISD::VWSUBU_W_VL:
8519     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8520   case RISCVISD::MUL_VL:
8521     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8522       return V;
8523     // Mul is commutative.
8524     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8525   case ISD::STORE: {
8526     auto *Store = cast<StoreSDNode>(N);
8527     SDValue Val = Store->getValue();
8528     // Combine store of vmv.x.s to vse with VL of 1.
8529     // FIXME: Support FP.
8530     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8531       SDValue Src = Val.getOperand(0);
8532       EVT VecVT = Src.getValueType();
8533       EVT MemVT = Store->getMemoryVT();
8534       // The memory VT and the element type must match.
8535       if (VecVT.getVectorElementType() == MemVT) {
8536         SDLoc DL(N);
8537         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8538         return DAG.getStoreVP(
8539             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8540             DAG.getConstant(1, DL, MaskVT),
8541             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8542             Store->getMemOperand(), Store->getAddressingMode(),
8543             Store->isTruncatingStore(), /*IsCompress*/ false);
8544       }
8545     }
8546 
8547     break;
8548   }
8549   case ISD::SPLAT_VECTOR: {
8550     EVT VT = N->getValueType(0);
8551     // Only perform this combine on legal MVT types.
8552     if (!isTypeLegal(VT))
8553       break;
8554     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8555                                          DAG, Subtarget))
8556       return Gather;
8557     break;
8558   }
8559   case RISCVISD::VMV_V_X_VL: {
8560     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8561     // scalar input.
8562     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8563     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8564     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8565       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8566         return SDValue(N, 0);
8567 
8568     break;
8569   }
8570   case ISD::INTRINSIC_WO_CHAIN: {
8571     unsigned IntNo = N->getConstantOperandVal(0);
8572     switch (IntNo) {
8573       // By default we do not combine any intrinsic.
8574     default:
8575       return SDValue();
8576     case Intrinsic::riscv_vcpop:
8577     case Intrinsic::riscv_vcpop_mask:
8578     case Intrinsic::riscv_vfirst:
8579     case Intrinsic::riscv_vfirst_mask: {
8580       SDValue VL = N->getOperand(2);
8581       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8582           IntNo == Intrinsic::riscv_vfirst_mask)
8583         VL = N->getOperand(3);
8584       if (!isNullConstant(VL))
8585         return SDValue();
8586       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8587       SDLoc DL(N);
8588       EVT VT = N->getValueType(0);
8589       if (IntNo == Intrinsic::riscv_vfirst ||
8590           IntNo == Intrinsic::riscv_vfirst_mask)
8591         return DAG.getConstant(-1, DL, VT);
8592       return DAG.getConstant(0, DL, VT);
8593     }
8594     }
8595   }
8596   }
8597 
8598   return SDValue();
8599 }
8600 
8601 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8602     const SDNode *N, CombineLevel Level) const {
8603   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8604   // materialised in fewer instructions than `(OP _, c1)`:
8605   //
8606   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8607   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8608   SDValue N0 = N->getOperand(0);
8609   EVT Ty = N0.getValueType();
8610   if (Ty.isScalarInteger() &&
8611       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8612     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8613     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8614     if (C1 && C2) {
8615       const APInt &C1Int = C1->getAPIntValue();
8616       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8617 
8618       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8619       // and the combine should happen, to potentially allow further combines
8620       // later.
8621       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8622           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8623         return true;
8624 
8625       // We can materialise `c1` in an add immediate, so it's "free", and the
8626       // combine should be prevented.
8627       if (C1Int.getMinSignedBits() <= 64 &&
8628           isLegalAddImmediate(C1Int.getSExtValue()))
8629         return false;
8630 
8631       // Neither constant will fit into an immediate, so find materialisation
8632       // costs.
8633       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8634                                               Subtarget.getFeatureBits(),
8635                                               /*CompressionCost*/true);
8636       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8637           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8638           /*CompressionCost*/true);
8639 
8640       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8641       // combine should be prevented.
8642       if (C1Cost < ShiftedC1Cost)
8643         return false;
8644     }
8645   }
8646   return true;
8647 }
8648 
8649 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8650     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8651     TargetLoweringOpt &TLO) const {
8652   // Delay this optimization as late as possible.
8653   if (!TLO.LegalOps)
8654     return false;
8655 
8656   EVT VT = Op.getValueType();
8657   if (VT.isVector())
8658     return false;
8659 
8660   // Only handle AND for now.
8661   if (Op.getOpcode() != ISD::AND)
8662     return false;
8663 
8664   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8665   if (!C)
8666     return false;
8667 
8668   const APInt &Mask = C->getAPIntValue();
8669 
8670   // Clear all non-demanded bits initially.
8671   APInt ShrunkMask = Mask & DemandedBits;
8672 
8673   // Try to make a smaller immediate by setting undemanded bits.
8674 
8675   APInt ExpandedMask = Mask | ~DemandedBits;
8676 
8677   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8678     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8679   };
8680   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8681     if (NewMask == Mask)
8682       return true;
8683     SDLoc DL(Op);
8684     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8685     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8686     return TLO.CombineTo(Op, NewOp);
8687   };
8688 
8689   // If the shrunk mask fits in sign extended 12 bits, let the target
8690   // independent code apply it.
8691   if (ShrunkMask.isSignedIntN(12))
8692     return false;
8693 
8694   // Preserve (and X, 0xffff) when zext.h is supported.
8695   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8696     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8697     if (IsLegalMask(NewMask))
8698       return UseMask(NewMask);
8699   }
8700 
8701   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8702   if (VT == MVT::i64) {
8703     APInt NewMask = APInt(64, 0xffffffff);
8704     if (IsLegalMask(NewMask))
8705       return UseMask(NewMask);
8706   }
8707 
8708   // For the remaining optimizations, we need to be able to make a negative
8709   // number through a combination of mask and undemanded bits.
8710   if (!ExpandedMask.isNegative())
8711     return false;
8712 
8713   // What is the fewest number of bits we need to represent the negative number.
8714   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8715 
8716   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8717   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8718   APInt NewMask = ShrunkMask;
8719   if (MinSignedBits <= 12)
8720     NewMask.setBitsFrom(11);
8721   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8722     NewMask.setBitsFrom(31);
8723   else
8724     return false;
8725 
8726   // Check that our new mask is a subset of the demanded mask.
8727   assert(IsLegalMask(NewMask));
8728   return UseMask(NewMask);
8729 }
8730 
8731 static void computeGREV(APInt &Src, unsigned ShAmt) {
8732   ShAmt &= Src.getBitWidth() - 1;
8733   uint64_t x = Src.getZExtValue();
8734   if (ShAmt & 1)
8735     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8736   if (ShAmt & 2)
8737     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8738   if (ShAmt & 4)
8739     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8740   if (ShAmt & 8)
8741     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8742   if (ShAmt & 16)
8743     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8744   if (ShAmt & 32)
8745     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8746   Src = x;
8747 }
8748 
8749 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8750                                                         KnownBits &Known,
8751                                                         const APInt &DemandedElts,
8752                                                         const SelectionDAG &DAG,
8753                                                         unsigned Depth) const {
8754   unsigned BitWidth = Known.getBitWidth();
8755   unsigned Opc = Op.getOpcode();
8756   assert((Opc >= ISD::BUILTIN_OP_END ||
8757           Opc == ISD::INTRINSIC_WO_CHAIN ||
8758           Opc == ISD::INTRINSIC_W_CHAIN ||
8759           Opc == ISD::INTRINSIC_VOID) &&
8760          "Should use MaskedValueIsZero if you don't know whether Op"
8761          " is a target node!");
8762 
8763   Known.resetAll();
8764   switch (Opc) {
8765   default: break;
8766   case RISCVISD::SELECT_CC: {
8767     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8768     // If we don't know any bits, early out.
8769     if (Known.isUnknown())
8770       break;
8771     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8772 
8773     // Only known if known in both the LHS and RHS.
8774     Known = KnownBits::commonBits(Known, Known2);
8775     break;
8776   }
8777   case RISCVISD::REMUW: {
8778     KnownBits Known2;
8779     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8780     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8781     // We only care about the lower 32 bits.
8782     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8783     // Restore the original width by sign extending.
8784     Known = Known.sext(BitWidth);
8785     break;
8786   }
8787   case RISCVISD::DIVUW: {
8788     KnownBits Known2;
8789     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8790     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8791     // We only care about the lower 32 bits.
8792     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8793     // Restore the original width by sign extending.
8794     Known = Known.sext(BitWidth);
8795     break;
8796   }
8797   case RISCVISD::CTZW: {
8798     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8799     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8800     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8801     Known.Zero.setBitsFrom(LowBits);
8802     break;
8803   }
8804   case RISCVISD::CLZW: {
8805     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8806     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8807     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8808     Known.Zero.setBitsFrom(LowBits);
8809     break;
8810   }
8811   case RISCVISD::GREV:
8812   case RISCVISD::GREVW: {
8813     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8814       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8815       if (Opc == RISCVISD::GREVW)
8816         Known = Known.trunc(32);
8817       unsigned ShAmt = C->getZExtValue();
8818       computeGREV(Known.Zero, ShAmt);
8819       computeGREV(Known.One, ShAmt);
8820       if (Opc == RISCVISD::GREVW)
8821         Known = Known.sext(BitWidth);
8822     }
8823     break;
8824   }
8825   case RISCVISD::READ_VLENB: {
8826     // If we know the minimum VLen from Zvl extensions, we can use that to
8827     // determine the trailing zeros of VLENB.
8828     // FIXME: Limit to 128 bit vectors until we have more testing.
8829     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8830     if (MinVLenB > 0)
8831       Known.Zero.setLowBits(Log2_32(MinVLenB));
8832     // We assume VLENB is no more than 65536 / 8 bytes.
8833     Known.Zero.setBitsFrom(14);
8834     break;
8835   }
8836   case ISD::INTRINSIC_W_CHAIN:
8837   case ISD::INTRINSIC_WO_CHAIN: {
8838     unsigned IntNo =
8839         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8840     switch (IntNo) {
8841     default:
8842       // We can't do anything for most intrinsics.
8843       break;
8844     case Intrinsic::riscv_vsetvli:
8845     case Intrinsic::riscv_vsetvlimax:
8846     case Intrinsic::riscv_vsetvli_opt:
8847     case Intrinsic::riscv_vsetvlimax_opt:
8848       // Assume that VL output is positive and would fit in an int32_t.
8849       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8850       if (BitWidth >= 32)
8851         Known.Zero.setBitsFrom(31);
8852       break;
8853     }
8854     break;
8855   }
8856   }
8857 }
8858 
8859 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8860     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8861     unsigned Depth) const {
8862   switch (Op.getOpcode()) {
8863   default:
8864     break;
8865   case RISCVISD::SELECT_CC: {
8866     unsigned Tmp =
8867         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8868     if (Tmp == 1) return 1;  // Early out.
8869     unsigned Tmp2 =
8870         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8871     return std::min(Tmp, Tmp2);
8872   }
8873   case RISCVISD::SLLW:
8874   case RISCVISD::SRAW:
8875   case RISCVISD::SRLW:
8876   case RISCVISD::DIVW:
8877   case RISCVISD::DIVUW:
8878   case RISCVISD::REMUW:
8879   case RISCVISD::ROLW:
8880   case RISCVISD::RORW:
8881   case RISCVISD::GREVW:
8882   case RISCVISD::GORCW:
8883   case RISCVISD::FSLW:
8884   case RISCVISD::FSRW:
8885   case RISCVISD::SHFLW:
8886   case RISCVISD::UNSHFLW:
8887   case RISCVISD::BCOMPRESSW:
8888   case RISCVISD::BDECOMPRESSW:
8889   case RISCVISD::BFPW:
8890   case RISCVISD::FCVT_W_RV64:
8891   case RISCVISD::FCVT_WU_RV64:
8892   case RISCVISD::STRICT_FCVT_W_RV64:
8893   case RISCVISD::STRICT_FCVT_WU_RV64:
8894     // TODO: As the result is sign-extended, this is conservatively correct. A
8895     // more precise answer could be calculated for SRAW depending on known
8896     // bits in the shift amount.
8897     return 33;
8898   case RISCVISD::SHFL:
8899   case RISCVISD::UNSHFL: {
8900     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8901     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8902     // will stay within the upper 32 bits. If there were more than 32 sign bits
8903     // before there will be at least 33 sign bits after.
8904     if (Op.getValueType() == MVT::i64 &&
8905         isa<ConstantSDNode>(Op.getOperand(1)) &&
8906         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8907       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8908       if (Tmp > 32)
8909         return 33;
8910     }
8911     break;
8912   }
8913   case RISCVISD::VMV_X_S: {
8914     // The number of sign bits of the scalar result is computed by obtaining the
8915     // element type of the input vector operand, subtracting its width from the
8916     // XLEN, and then adding one (sign bit within the element type). If the
8917     // element type is wider than XLen, the least-significant XLEN bits are
8918     // taken.
8919     unsigned XLen = Subtarget.getXLen();
8920     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8921     if (EltBits <= XLen)
8922       return XLen - EltBits + 1;
8923     break;
8924   }
8925   }
8926 
8927   return 1;
8928 }
8929 
8930 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8931                                                   MachineBasicBlock *BB) {
8932   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8933 
8934   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8935   // Should the count have wrapped while it was being read, we need to try
8936   // again.
8937   // ...
8938   // read:
8939   // rdcycleh x3 # load high word of cycle
8940   // rdcycle  x2 # load low word of cycle
8941   // rdcycleh x4 # load high word of cycle
8942   // bne x3, x4, read # check if high word reads match, otherwise try again
8943   // ...
8944 
8945   MachineFunction &MF = *BB->getParent();
8946   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8947   MachineFunction::iterator It = ++BB->getIterator();
8948 
8949   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8950   MF.insert(It, LoopMBB);
8951 
8952   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8953   MF.insert(It, DoneMBB);
8954 
8955   // Transfer the remainder of BB and its successor edges to DoneMBB.
8956   DoneMBB->splice(DoneMBB->begin(), BB,
8957                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8958   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8959 
8960   BB->addSuccessor(LoopMBB);
8961 
8962   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8963   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8964   Register LoReg = MI.getOperand(0).getReg();
8965   Register HiReg = MI.getOperand(1).getReg();
8966   DebugLoc DL = MI.getDebugLoc();
8967 
8968   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8969   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8970       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8971       .addReg(RISCV::X0);
8972   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8973       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8974       .addReg(RISCV::X0);
8975   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8976       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8977       .addReg(RISCV::X0);
8978 
8979   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8980       .addReg(HiReg)
8981       .addReg(ReadAgainReg)
8982       .addMBB(LoopMBB);
8983 
8984   LoopMBB->addSuccessor(LoopMBB);
8985   LoopMBB->addSuccessor(DoneMBB);
8986 
8987   MI.eraseFromParent();
8988 
8989   return DoneMBB;
8990 }
8991 
8992 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8993                                              MachineBasicBlock *BB) {
8994   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8995 
8996   MachineFunction &MF = *BB->getParent();
8997   DebugLoc DL = MI.getDebugLoc();
8998   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8999   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9000   Register LoReg = MI.getOperand(0).getReg();
9001   Register HiReg = MI.getOperand(1).getReg();
9002   Register SrcReg = MI.getOperand(2).getReg();
9003   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9004   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9005 
9006   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9007                           RI);
9008   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9009   MachineMemOperand *MMOLo =
9010       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9011   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9012       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9013   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9014       .addFrameIndex(FI)
9015       .addImm(0)
9016       .addMemOperand(MMOLo);
9017   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9018       .addFrameIndex(FI)
9019       .addImm(4)
9020       .addMemOperand(MMOHi);
9021   MI.eraseFromParent(); // The pseudo instruction is gone now.
9022   return BB;
9023 }
9024 
9025 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9026                                                  MachineBasicBlock *BB) {
9027   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9028          "Unexpected instruction");
9029 
9030   MachineFunction &MF = *BB->getParent();
9031   DebugLoc DL = MI.getDebugLoc();
9032   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9033   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9034   Register DstReg = MI.getOperand(0).getReg();
9035   Register LoReg = MI.getOperand(1).getReg();
9036   Register HiReg = MI.getOperand(2).getReg();
9037   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9038   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9039 
9040   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9041   MachineMemOperand *MMOLo =
9042       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9043   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9044       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9045   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9046       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9047       .addFrameIndex(FI)
9048       .addImm(0)
9049       .addMemOperand(MMOLo);
9050   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9051       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9052       .addFrameIndex(FI)
9053       .addImm(4)
9054       .addMemOperand(MMOHi);
9055   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9056   MI.eraseFromParent(); // The pseudo instruction is gone now.
9057   return BB;
9058 }
9059 
9060 static bool isSelectPseudo(MachineInstr &MI) {
9061   switch (MI.getOpcode()) {
9062   default:
9063     return false;
9064   case RISCV::Select_GPR_Using_CC_GPR:
9065   case RISCV::Select_FPR16_Using_CC_GPR:
9066   case RISCV::Select_FPR32_Using_CC_GPR:
9067   case RISCV::Select_FPR64_Using_CC_GPR:
9068     return true;
9069   }
9070 }
9071 
9072 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9073                                         unsigned RelOpcode, unsigned EqOpcode,
9074                                         const RISCVSubtarget &Subtarget) {
9075   DebugLoc DL = MI.getDebugLoc();
9076   Register DstReg = MI.getOperand(0).getReg();
9077   Register Src1Reg = MI.getOperand(1).getReg();
9078   Register Src2Reg = MI.getOperand(2).getReg();
9079   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9080   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9081   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9082 
9083   // Save the current FFLAGS.
9084   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9085 
9086   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9087                  .addReg(Src1Reg)
9088                  .addReg(Src2Reg);
9089   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9090     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9091 
9092   // Restore the FFLAGS.
9093   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9094       .addReg(SavedFFlags, RegState::Kill);
9095 
9096   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9097   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9098                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9099                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9100   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9101     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9102 
9103   // Erase the pseudoinstruction.
9104   MI.eraseFromParent();
9105   return BB;
9106 }
9107 
9108 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9109                                            MachineBasicBlock *BB,
9110                                            const RISCVSubtarget &Subtarget) {
9111   // To "insert" Select_* instructions, we actually have to insert the triangle
9112   // control-flow pattern.  The incoming instructions know the destination vreg
9113   // to set, the condition code register to branch on, the true/false values to
9114   // select between, and the condcode to use to select the appropriate branch.
9115   //
9116   // We produce the following control flow:
9117   //     HeadMBB
9118   //     |  \
9119   //     |  IfFalseMBB
9120   //     | /
9121   //    TailMBB
9122   //
9123   // When we find a sequence of selects we attempt to optimize their emission
9124   // by sharing the control flow. Currently we only handle cases where we have
9125   // multiple selects with the exact same condition (same LHS, RHS and CC).
9126   // The selects may be interleaved with other instructions if the other
9127   // instructions meet some requirements we deem safe:
9128   // - They are debug instructions. Otherwise,
9129   // - They do not have side-effects, do not access memory and their inputs do
9130   //   not depend on the results of the select pseudo-instructions.
9131   // The TrueV/FalseV operands of the selects cannot depend on the result of
9132   // previous selects in the sequence.
9133   // These conditions could be further relaxed. See the X86 target for a
9134   // related approach and more information.
9135   Register LHS = MI.getOperand(1).getReg();
9136   Register RHS = MI.getOperand(2).getReg();
9137   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9138 
9139   SmallVector<MachineInstr *, 4> SelectDebugValues;
9140   SmallSet<Register, 4> SelectDests;
9141   SelectDests.insert(MI.getOperand(0).getReg());
9142 
9143   MachineInstr *LastSelectPseudo = &MI;
9144 
9145   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9146        SequenceMBBI != E; ++SequenceMBBI) {
9147     if (SequenceMBBI->isDebugInstr())
9148       continue;
9149     else if (isSelectPseudo(*SequenceMBBI)) {
9150       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9151           SequenceMBBI->getOperand(2).getReg() != RHS ||
9152           SequenceMBBI->getOperand(3).getImm() != CC ||
9153           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9154           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9155         break;
9156       LastSelectPseudo = &*SequenceMBBI;
9157       SequenceMBBI->collectDebugValues(SelectDebugValues);
9158       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9159     } else {
9160       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9161           SequenceMBBI->mayLoadOrStore())
9162         break;
9163       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9164             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9165           }))
9166         break;
9167     }
9168   }
9169 
9170   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9171   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9172   DebugLoc DL = MI.getDebugLoc();
9173   MachineFunction::iterator I = ++BB->getIterator();
9174 
9175   MachineBasicBlock *HeadMBB = BB;
9176   MachineFunction *F = BB->getParent();
9177   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9178   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9179 
9180   F->insert(I, IfFalseMBB);
9181   F->insert(I, TailMBB);
9182 
9183   // Transfer debug instructions associated with the selects to TailMBB.
9184   for (MachineInstr *DebugInstr : SelectDebugValues) {
9185     TailMBB->push_back(DebugInstr->removeFromParent());
9186   }
9187 
9188   // Move all instructions after the sequence to TailMBB.
9189   TailMBB->splice(TailMBB->end(), HeadMBB,
9190                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9191   // Update machine-CFG edges by transferring all successors of the current
9192   // block to the new block which will contain the Phi nodes for the selects.
9193   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9194   // Set the successors for HeadMBB.
9195   HeadMBB->addSuccessor(IfFalseMBB);
9196   HeadMBB->addSuccessor(TailMBB);
9197 
9198   // Insert appropriate branch.
9199   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9200     .addReg(LHS)
9201     .addReg(RHS)
9202     .addMBB(TailMBB);
9203 
9204   // IfFalseMBB just falls through to TailMBB.
9205   IfFalseMBB->addSuccessor(TailMBB);
9206 
9207   // Create PHIs for all of the select pseudo-instructions.
9208   auto SelectMBBI = MI.getIterator();
9209   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9210   auto InsertionPoint = TailMBB->begin();
9211   while (SelectMBBI != SelectEnd) {
9212     auto Next = std::next(SelectMBBI);
9213     if (isSelectPseudo(*SelectMBBI)) {
9214       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9215       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9216               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9217           .addReg(SelectMBBI->getOperand(4).getReg())
9218           .addMBB(HeadMBB)
9219           .addReg(SelectMBBI->getOperand(5).getReg())
9220           .addMBB(IfFalseMBB);
9221       SelectMBBI->eraseFromParent();
9222     }
9223     SelectMBBI = Next;
9224   }
9225 
9226   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9227   return TailMBB;
9228 }
9229 
9230 MachineBasicBlock *
9231 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9232                                                  MachineBasicBlock *BB) const {
9233   switch (MI.getOpcode()) {
9234   default:
9235     llvm_unreachable("Unexpected instr type to insert");
9236   case RISCV::ReadCycleWide:
9237     assert(!Subtarget.is64Bit() &&
9238            "ReadCycleWrite is only to be used on riscv32");
9239     return emitReadCycleWidePseudo(MI, BB);
9240   case RISCV::Select_GPR_Using_CC_GPR:
9241   case RISCV::Select_FPR16_Using_CC_GPR:
9242   case RISCV::Select_FPR32_Using_CC_GPR:
9243   case RISCV::Select_FPR64_Using_CC_GPR:
9244     return emitSelectPseudo(MI, BB, Subtarget);
9245   case RISCV::BuildPairF64Pseudo:
9246     return emitBuildPairF64Pseudo(MI, BB);
9247   case RISCV::SplitF64Pseudo:
9248     return emitSplitF64Pseudo(MI, BB);
9249   case RISCV::PseudoQuietFLE_H:
9250     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9251   case RISCV::PseudoQuietFLT_H:
9252     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9253   case RISCV::PseudoQuietFLE_S:
9254     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9255   case RISCV::PseudoQuietFLT_S:
9256     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9257   case RISCV::PseudoQuietFLE_D:
9258     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9259   case RISCV::PseudoQuietFLT_D:
9260     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9261   }
9262 }
9263 
9264 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9265                                                         SDNode *Node) const {
9266   // Add FRM dependency to any instructions with dynamic rounding mode.
9267   unsigned Opc = MI.getOpcode();
9268   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9269   if (Idx < 0)
9270     return;
9271   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9272     return;
9273   // If the instruction already reads FRM, don't add another read.
9274   if (MI.readsRegister(RISCV::FRM))
9275     return;
9276   MI.addOperand(
9277       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9278 }
9279 
9280 // Calling Convention Implementation.
9281 // The expectations for frontend ABI lowering vary from target to target.
9282 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9283 // details, but this is a longer term goal. For now, we simply try to keep the
9284 // role of the frontend as simple and well-defined as possible. The rules can
9285 // be summarised as:
9286 // * Never split up large scalar arguments. We handle them here.
9287 // * If a hardfloat calling convention is being used, and the struct may be
9288 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9289 // available, then pass as two separate arguments. If either the GPRs or FPRs
9290 // are exhausted, then pass according to the rule below.
9291 // * If a struct could never be passed in registers or directly in a stack
9292 // slot (as it is larger than 2*XLEN and the floating point rules don't
9293 // apply), then pass it using a pointer with the byval attribute.
9294 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9295 // word-sized array or a 2*XLEN scalar (depending on alignment).
9296 // * The frontend can determine whether a struct is returned by reference or
9297 // not based on its size and fields. If it will be returned by reference, the
9298 // frontend must modify the prototype so a pointer with the sret annotation is
9299 // passed as the first argument. This is not necessary for large scalar
9300 // returns.
9301 // * Struct return values and varargs should be coerced to structs containing
9302 // register-size fields in the same situations they would be for fixed
9303 // arguments.
9304 
9305 static const MCPhysReg ArgGPRs[] = {
9306   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9307   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9308 };
9309 static const MCPhysReg ArgFPR16s[] = {
9310   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9311   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9312 };
9313 static const MCPhysReg ArgFPR32s[] = {
9314   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9315   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9316 };
9317 static const MCPhysReg ArgFPR64s[] = {
9318   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9319   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9320 };
9321 // This is an interim calling convention and it may be changed in the future.
9322 static const MCPhysReg ArgVRs[] = {
9323     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9324     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9325     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9326 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9327                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9328                                      RISCV::V20M2, RISCV::V22M2};
9329 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9330                                      RISCV::V20M4};
9331 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9332 
9333 // Pass a 2*XLEN argument that has been split into two XLEN values through
9334 // registers or the stack as necessary.
9335 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9336                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9337                                 MVT ValVT2, MVT LocVT2,
9338                                 ISD::ArgFlagsTy ArgFlags2) {
9339   unsigned XLenInBytes = XLen / 8;
9340   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9341     // At least one half can be passed via register.
9342     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9343                                      VA1.getLocVT(), CCValAssign::Full));
9344   } else {
9345     // Both halves must be passed on the stack, with proper alignment.
9346     Align StackAlign =
9347         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9348     State.addLoc(
9349         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9350                             State.AllocateStack(XLenInBytes, StackAlign),
9351                             VA1.getLocVT(), CCValAssign::Full));
9352     State.addLoc(CCValAssign::getMem(
9353         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9354         LocVT2, CCValAssign::Full));
9355     return false;
9356   }
9357 
9358   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9359     // The second half can also be passed via register.
9360     State.addLoc(
9361         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9362   } else {
9363     // The second half is passed via the stack, without additional alignment.
9364     State.addLoc(CCValAssign::getMem(
9365         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9366         LocVT2, CCValAssign::Full));
9367   }
9368 
9369   return false;
9370 }
9371 
9372 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9373                                Optional<unsigned> FirstMaskArgument,
9374                                CCState &State, const RISCVTargetLowering &TLI) {
9375   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9376   if (RC == &RISCV::VRRegClass) {
9377     // Assign the first mask argument to V0.
9378     // This is an interim calling convention and it may be changed in the
9379     // future.
9380     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9381       return State.AllocateReg(RISCV::V0);
9382     return State.AllocateReg(ArgVRs);
9383   }
9384   if (RC == &RISCV::VRM2RegClass)
9385     return State.AllocateReg(ArgVRM2s);
9386   if (RC == &RISCV::VRM4RegClass)
9387     return State.AllocateReg(ArgVRM4s);
9388   if (RC == &RISCV::VRM8RegClass)
9389     return State.AllocateReg(ArgVRM8s);
9390   llvm_unreachable("Unhandled register class for ValueType");
9391 }
9392 
9393 // Implements the RISC-V calling convention. Returns true upon failure.
9394 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9395                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9396                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9397                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9398                      Optional<unsigned> FirstMaskArgument) {
9399   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9400   assert(XLen == 32 || XLen == 64);
9401   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9402 
9403   // Any return value split in to more than two values can't be returned
9404   // directly. Vectors are returned via the available vector registers.
9405   if (!LocVT.isVector() && IsRet && ValNo > 1)
9406     return true;
9407 
9408   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9409   // variadic argument, or if no F16/F32 argument registers are available.
9410   bool UseGPRForF16_F32 = true;
9411   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9412   // variadic argument, or if no F64 argument registers are available.
9413   bool UseGPRForF64 = true;
9414 
9415   switch (ABI) {
9416   default:
9417     llvm_unreachable("Unexpected ABI");
9418   case RISCVABI::ABI_ILP32:
9419   case RISCVABI::ABI_LP64:
9420     break;
9421   case RISCVABI::ABI_ILP32F:
9422   case RISCVABI::ABI_LP64F:
9423     UseGPRForF16_F32 = !IsFixed;
9424     break;
9425   case RISCVABI::ABI_ILP32D:
9426   case RISCVABI::ABI_LP64D:
9427     UseGPRForF16_F32 = !IsFixed;
9428     UseGPRForF64 = !IsFixed;
9429     break;
9430   }
9431 
9432   // FPR16, FPR32, and FPR64 alias each other.
9433   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9434     UseGPRForF16_F32 = true;
9435     UseGPRForF64 = true;
9436   }
9437 
9438   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9439   // similar local variables rather than directly checking against the target
9440   // ABI.
9441 
9442   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9443     LocVT = XLenVT;
9444     LocInfo = CCValAssign::BCvt;
9445   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9446     LocVT = MVT::i64;
9447     LocInfo = CCValAssign::BCvt;
9448   }
9449 
9450   // If this is a variadic argument, the RISC-V calling convention requires
9451   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9452   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9453   // be used regardless of whether the original argument was split during
9454   // legalisation or not. The argument will not be passed by registers if the
9455   // original type is larger than 2*XLEN, so the register alignment rule does
9456   // not apply.
9457   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9458   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9459       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9460     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9461     // Skip 'odd' register if necessary.
9462     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9463       State.AllocateReg(ArgGPRs);
9464   }
9465 
9466   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9467   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9468       State.getPendingArgFlags();
9469 
9470   assert(PendingLocs.size() == PendingArgFlags.size() &&
9471          "PendingLocs and PendingArgFlags out of sync");
9472 
9473   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9474   // registers are exhausted.
9475   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9476     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9477            "Can't lower f64 if it is split");
9478     // Depending on available argument GPRS, f64 may be passed in a pair of
9479     // GPRs, split between a GPR and the stack, or passed completely on the
9480     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9481     // cases.
9482     Register Reg = State.AllocateReg(ArgGPRs);
9483     LocVT = MVT::i32;
9484     if (!Reg) {
9485       unsigned StackOffset = State.AllocateStack(8, Align(8));
9486       State.addLoc(
9487           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9488       return false;
9489     }
9490     if (!State.AllocateReg(ArgGPRs))
9491       State.AllocateStack(4, Align(4));
9492     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9493     return false;
9494   }
9495 
9496   // Fixed-length vectors are located in the corresponding scalable-vector
9497   // container types.
9498   if (ValVT.isFixedLengthVector())
9499     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9500 
9501   // Split arguments might be passed indirectly, so keep track of the pending
9502   // values. Split vectors are passed via a mix of registers and indirectly, so
9503   // treat them as we would any other argument.
9504   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9505     LocVT = XLenVT;
9506     LocInfo = CCValAssign::Indirect;
9507     PendingLocs.push_back(
9508         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9509     PendingArgFlags.push_back(ArgFlags);
9510     if (!ArgFlags.isSplitEnd()) {
9511       return false;
9512     }
9513   }
9514 
9515   // If the split argument only had two elements, it should be passed directly
9516   // in registers or on the stack.
9517   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9518       PendingLocs.size() <= 2) {
9519     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9520     // Apply the normal calling convention rules to the first half of the
9521     // split argument.
9522     CCValAssign VA = PendingLocs[0];
9523     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9524     PendingLocs.clear();
9525     PendingArgFlags.clear();
9526     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9527                                ArgFlags);
9528   }
9529 
9530   // Allocate to a register if possible, or else a stack slot.
9531   Register Reg;
9532   unsigned StoreSizeBytes = XLen / 8;
9533   Align StackAlign = Align(XLen / 8);
9534 
9535   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9536     Reg = State.AllocateReg(ArgFPR16s);
9537   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9538     Reg = State.AllocateReg(ArgFPR32s);
9539   else if (ValVT == MVT::f64 && !UseGPRForF64)
9540     Reg = State.AllocateReg(ArgFPR64s);
9541   else if (ValVT.isVector()) {
9542     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9543     if (!Reg) {
9544       // For return values, the vector must be passed fully via registers or
9545       // via the stack.
9546       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9547       // but we're using all of them.
9548       if (IsRet)
9549         return true;
9550       // Try using a GPR to pass the address
9551       if ((Reg = State.AllocateReg(ArgGPRs))) {
9552         LocVT = XLenVT;
9553         LocInfo = CCValAssign::Indirect;
9554       } else if (ValVT.isScalableVector()) {
9555         LocVT = XLenVT;
9556         LocInfo = CCValAssign::Indirect;
9557       } else {
9558         // Pass fixed-length vectors on the stack.
9559         LocVT = ValVT;
9560         StoreSizeBytes = ValVT.getStoreSize();
9561         // Align vectors to their element sizes, being careful for vXi1
9562         // vectors.
9563         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9564       }
9565     }
9566   } else {
9567     Reg = State.AllocateReg(ArgGPRs);
9568   }
9569 
9570   unsigned StackOffset =
9571       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9572 
9573   // If we reach this point and PendingLocs is non-empty, we must be at the
9574   // end of a split argument that must be passed indirectly.
9575   if (!PendingLocs.empty()) {
9576     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9577     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9578 
9579     for (auto &It : PendingLocs) {
9580       if (Reg)
9581         It.convertToReg(Reg);
9582       else
9583         It.convertToMem(StackOffset);
9584       State.addLoc(It);
9585     }
9586     PendingLocs.clear();
9587     PendingArgFlags.clear();
9588     return false;
9589   }
9590 
9591   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9592           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9593          "Expected an XLenVT or vector types at this stage");
9594 
9595   if (Reg) {
9596     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9597     return false;
9598   }
9599 
9600   // When a floating-point value is passed on the stack, no bit-conversion is
9601   // needed.
9602   if (ValVT.isFloatingPoint()) {
9603     LocVT = ValVT;
9604     LocInfo = CCValAssign::Full;
9605   }
9606   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9607   return false;
9608 }
9609 
9610 template <typename ArgTy>
9611 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9612   for (const auto &ArgIdx : enumerate(Args)) {
9613     MVT ArgVT = ArgIdx.value().VT;
9614     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9615       return ArgIdx.index();
9616   }
9617   return None;
9618 }
9619 
9620 void RISCVTargetLowering::analyzeInputArgs(
9621     MachineFunction &MF, CCState &CCInfo,
9622     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9623     RISCVCCAssignFn Fn) const {
9624   unsigned NumArgs = Ins.size();
9625   FunctionType *FType = MF.getFunction().getFunctionType();
9626 
9627   Optional<unsigned> FirstMaskArgument;
9628   if (Subtarget.hasVInstructions())
9629     FirstMaskArgument = preAssignMask(Ins);
9630 
9631   for (unsigned i = 0; i != NumArgs; ++i) {
9632     MVT ArgVT = Ins[i].VT;
9633     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9634 
9635     Type *ArgTy = nullptr;
9636     if (IsRet)
9637       ArgTy = FType->getReturnType();
9638     else if (Ins[i].isOrigArg())
9639       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9640 
9641     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9642     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9643            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9644            FirstMaskArgument)) {
9645       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9646                         << EVT(ArgVT).getEVTString() << '\n');
9647       llvm_unreachable(nullptr);
9648     }
9649   }
9650 }
9651 
9652 void RISCVTargetLowering::analyzeOutputArgs(
9653     MachineFunction &MF, CCState &CCInfo,
9654     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9655     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9656   unsigned NumArgs = Outs.size();
9657 
9658   Optional<unsigned> FirstMaskArgument;
9659   if (Subtarget.hasVInstructions())
9660     FirstMaskArgument = preAssignMask(Outs);
9661 
9662   for (unsigned i = 0; i != NumArgs; i++) {
9663     MVT ArgVT = Outs[i].VT;
9664     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9665     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9666 
9667     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9668     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9669            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9670            FirstMaskArgument)) {
9671       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9672                         << EVT(ArgVT).getEVTString() << "\n");
9673       llvm_unreachable(nullptr);
9674     }
9675   }
9676 }
9677 
9678 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9679 // values.
9680 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9681                                    const CCValAssign &VA, const SDLoc &DL,
9682                                    const RISCVSubtarget &Subtarget) {
9683   switch (VA.getLocInfo()) {
9684   default:
9685     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9686   case CCValAssign::Full:
9687     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9688       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9689     break;
9690   case CCValAssign::BCvt:
9691     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9692       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9693     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9694       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9695     else
9696       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9697     break;
9698   }
9699   return Val;
9700 }
9701 
9702 // The caller is responsible for loading the full value if the argument is
9703 // passed with CCValAssign::Indirect.
9704 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9705                                 const CCValAssign &VA, const SDLoc &DL,
9706                                 const RISCVTargetLowering &TLI) {
9707   MachineFunction &MF = DAG.getMachineFunction();
9708   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9709   EVT LocVT = VA.getLocVT();
9710   SDValue Val;
9711   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9712   Register VReg = RegInfo.createVirtualRegister(RC);
9713   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9714   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9715 
9716   if (VA.getLocInfo() == CCValAssign::Indirect)
9717     return Val;
9718 
9719   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9720 }
9721 
9722 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9723                                    const CCValAssign &VA, const SDLoc &DL,
9724                                    const RISCVSubtarget &Subtarget) {
9725   EVT LocVT = VA.getLocVT();
9726 
9727   switch (VA.getLocInfo()) {
9728   default:
9729     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9730   case CCValAssign::Full:
9731     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9732       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9733     break;
9734   case CCValAssign::BCvt:
9735     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9736       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9737     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9738       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9739     else
9740       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9741     break;
9742   }
9743   return Val;
9744 }
9745 
9746 // The caller is responsible for loading the full value if the argument is
9747 // passed with CCValAssign::Indirect.
9748 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9749                                 const CCValAssign &VA, const SDLoc &DL) {
9750   MachineFunction &MF = DAG.getMachineFunction();
9751   MachineFrameInfo &MFI = MF.getFrameInfo();
9752   EVT LocVT = VA.getLocVT();
9753   EVT ValVT = VA.getValVT();
9754   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9755   if (ValVT.isScalableVector()) {
9756     // When the value is a scalable vector, we save the pointer which points to
9757     // the scalable vector value in the stack. The ValVT will be the pointer
9758     // type, instead of the scalable vector type.
9759     ValVT = LocVT;
9760   }
9761   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9762                                  /*IsImmutable=*/true);
9763   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9764   SDValue Val;
9765 
9766   ISD::LoadExtType ExtType;
9767   switch (VA.getLocInfo()) {
9768   default:
9769     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9770   case CCValAssign::Full:
9771   case CCValAssign::Indirect:
9772   case CCValAssign::BCvt:
9773     ExtType = ISD::NON_EXTLOAD;
9774     break;
9775   }
9776   Val = DAG.getExtLoad(
9777       ExtType, DL, LocVT, Chain, FIN,
9778       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9779   return Val;
9780 }
9781 
9782 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9783                                        const CCValAssign &VA, const SDLoc &DL) {
9784   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9785          "Unexpected VA");
9786   MachineFunction &MF = DAG.getMachineFunction();
9787   MachineFrameInfo &MFI = MF.getFrameInfo();
9788   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9789 
9790   if (VA.isMemLoc()) {
9791     // f64 is passed on the stack.
9792     int FI =
9793         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9794     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9795     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9796                        MachinePointerInfo::getFixedStack(MF, FI));
9797   }
9798 
9799   assert(VA.isRegLoc() && "Expected register VA assignment");
9800 
9801   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9802   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9803   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9804   SDValue Hi;
9805   if (VA.getLocReg() == RISCV::X17) {
9806     // Second half of f64 is passed on the stack.
9807     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9808     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9809     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9810                      MachinePointerInfo::getFixedStack(MF, FI));
9811   } else {
9812     // Second half of f64 is passed in another GPR.
9813     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9814     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9815     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9816   }
9817   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9818 }
9819 
9820 // FastCC has less than 1% performance improvement for some particular
9821 // benchmark. But theoretically, it may has benenfit for some cases.
9822 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9823                             unsigned ValNo, MVT ValVT, MVT LocVT,
9824                             CCValAssign::LocInfo LocInfo,
9825                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9826                             bool IsFixed, bool IsRet, Type *OrigTy,
9827                             const RISCVTargetLowering &TLI,
9828                             Optional<unsigned> FirstMaskArgument) {
9829 
9830   // X5 and X6 might be used for save-restore libcall.
9831   static const MCPhysReg GPRList[] = {
9832       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9833       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9834       RISCV::X29, RISCV::X30, RISCV::X31};
9835 
9836   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9837     if (unsigned Reg = State.AllocateReg(GPRList)) {
9838       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9839       return false;
9840     }
9841   }
9842 
9843   if (LocVT == MVT::f16) {
9844     static const MCPhysReg FPR16List[] = {
9845         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9846         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9847         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9848         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9849     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9850       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9851       return false;
9852     }
9853   }
9854 
9855   if (LocVT == MVT::f32) {
9856     static const MCPhysReg FPR32List[] = {
9857         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9858         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9859         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9860         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9861     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9862       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9863       return false;
9864     }
9865   }
9866 
9867   if (LocVT == MVT::f64) {
9868     static const MCPhysReg FPR64List[] = {
9869         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9870         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9871         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9872         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9873     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9874       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9875       return false;
9876     }
9877   }
9878 
9879   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9880     unsigned Offset4 = State.AllocateStack(4, Align(4));
9881     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9882     return false;
9883   }
9884 
9885   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9886     unsigned Offset5 = State.AllocateStack(8, Align(8));
9887     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9888     return false;
9889   }
9890 
9891   if (LocVT.isVector()) {
9892     if (unsigned Reg =
9893             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9894       // Fixed-length vectors are located in the corresponding scalable-vector
9895       // container types.
9896       if (ValVT.isFixedLengthVector())
9897         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9898       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9899     } else {
9900       // Try and pass the address via a "fast" GPR.
9901       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9902         LocInfo = CCValAssign::Indirect;
9903         LocVT = TLI.getSubtarget().getXLenVT();
9904         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9905       } else if (ValVT.isFixedLengthVector()) {
9906         auto StackAlign =
9907             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9908         unsigned StackOffset =
9909             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9910         State.addLoc(
9911             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9912       } else {
9913         // Can't pass scalable vectors on the stack.
9914         return true;
9915       }
9916     }
9917 
9918     return false;
9919   }
9920 
9921   return true; // CC didn't match.
9922 }
9923 
9924 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9925                          CCValAssign::LocInfo LocInfo,
9926                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9927 
9928   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9929     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9930     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9931     static const MCPhysReg GPRList[] = {
9932         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9933         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9934     if (unsigned Reg = State.AllocateReg(GPRList)) {
9935       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9936       return false;
9937     }
9938   }
9939 
9940   if (LocVT == MVT::f32) {
9941     // Pass in STG registers: F1, ..., F6
9942     //                        fs0 ... fs5
9943     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9944                                           RISCV::F18_F, RISCV::F19_F,
9945                                           RISCV::F20_F, RISCV::F21_F};
9946     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9947       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9948       return false;
9949     }
9950   }
9951 
9952   if (LocVT == MVT::f64) {
9953     // Pass in STG registers: D1, ..., D6
9954     //                        fs6 ... fs11
9955     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9956                                           RISCV::F24_D, RISCV::F25_D,
9957                                           RISCV::F26_D, RISCV::F27_D};
9958     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9959       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9960       return false;
9961     }
9962   }
9963 
9964   report_fatal_error("No registers left in GHC calling convention");
9965   return true;
9966 }
9967 
9968 // Transform physical registers into virtual registers.
9969 SDValue RISCVTargetLowering::LowerFormalArguments(
9970     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9971     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9972     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9973 
9974   MachineFunction &MF = DAG.getMachineFunction();
9975 
9976   switch (CallConv) {
9977   default:
9978     report_fatal_error("Unsupported calling convention");
9979   case CallingConv::C:
9980   case CallingConv::Fast:
9981     break;
9982   case CallingConv::GHC:
9983     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9984         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9985       report_fatal_error(
9986         "GHC calling convention requires the F and D instruction set extensions");
9987   }
9988 
9989   const Function &Func = MF.getFunction();
9990   if (Func.hasFnAttribute("interrupt")) {
9991     if (!Func.arg_empty())
9992       report_fatal_error(
9993         "Functions with the interrupt attribute cannot have arguments!");
9994 
9995     StringRef Kind =
9996       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9997 
9998     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9999       report_fatal_error(
10000         "Function interrupt attribute argument not supported!");
10001   }
10002 
10003   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10004   MVT XLenVT = Subtarget.getXLenVT();
10005   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10006   // Used with vargs to acumulate store chains.
10007   std::vector<SDValue> OutChains;
10008 
10009   // Assign locations to all of the incoming arguments.
10010   SmallVector<CCValAssign, 16> ArgLocs;
10011   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10012 
10013   if (CallConv == CallingConv::GHC)
10014     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10015   else
10016     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10017                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10018                                                    : CC_RISCV);
10019 
10020   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10021     CCValAssign &VA = ArgLocs[i];
10022     SDValue ArgValue;
10023     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10024     // case.
10025     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10026       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10027     else if (VA.isRegLoc())
10028       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10029     else
10030       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10031 
10032     if (VA.getLocInfo() == CCValAssign::Indirect) {
10033       // If the original argument was split and passed by reference (e.g. i128
10034       // on RV32), we need to load all parts of it here (using the same
10035       // address). Vectors may be partly split to registers and partly to the
10036       // stack, in which case the base address is partly offset and subsequent
10037       // stores are relative to that.
10038       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10039                                    MachinePointerInfo()));
10040       unsigned ArgIndex = Ins[i].OrigArgIndex;
10041       unsigned ArgPartOffset = Ins[i].PartOffset;
10042       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10043       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10044         CCValAssign &PartVA = ArgLocs[i + 1];
10045         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10046         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10047         if (PartVA.getValVT().isScalableVector())
10048           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10049         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10050         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10051                                      MachinePointerInfo()));
10052         ++i;
10053       }
10054       continue;
10055     }
10056     InVals.push_back(ArgValue);
10057   }
10058 
10059   if (IsVarArg) {
10060     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10061     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10062     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10063     MachineFrameInfo &MFI = MF.getFrameInfo();
10064     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10065     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10066 
10067     // Offset of the first variable argument from stack pointer, and size of
10068     // the vararg save area. For now, the varargs save area is either zero or
10069     // large enough to hold a0-a7.
10070     int VaArgOffset, VarArgsSaveSize;
10071 
10072     // If all registers are allocated, then all varargs must be passed on the
10073     // stack and we don't need to save any argregs.
10074     if (ArgRegs.size() == Idx) {
10075       VaArgOffset = CCInfo.getNextStackOffset();
10076       VarArgsSaveSize = 0;
10077     } else {
10078       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10079       VaArgOffset = -VarArgsSaveSize;
10080     }
10081 
10082     // Record the frame index of the first variable argument
10083     // which is a value necessary to VASTART.
10084     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10085     RVFI->setVarArgsFrameIndex(FI);
10086 
10087     // If saving an odd number of registers then create an extra stack slot to
10088     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10089     // offsets to even-numbered registered remain 2*XLEN-aligned.
10090     if (Idx % 2) {
10091       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10092       VarArgsSaveSize += XLenInBytes;
10093     }
10094 
10095     // Copy the integer registers that may have been used for passing varargs
10096     // to the vararg save area.
10097     for (unsigned I = Idx; I < ArgRegs.size();
10098          ++I, VaArgOffset += XLenInBytes) {
10099       const Register Reg = RegInfo.createVirtualRegister(RC);
10100       RegInfo.addLiveIn(ArgRegs[I], Reg);
10101       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10102       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10103       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10104       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10105                                    MachinePointerInfo::getFixedStack(MF, FI));
10106       cast<StoreSDNode>(Store.getNode())
10107           ->getMemOperand()
10108           ->setValue((Value *)nullptr);
10109       OutChains.push_back(Store);
10110     }
10111     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10112   }
10113 
10114   // All stores are grouped in one node to allow the matching between
10115   // the size of Ins and InVals. This only happens for vararg functions.
10116   if (!OutChains.empty()) {
10117     OutChains.push_back(Chain);
10118     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10119   }
10120 
10121   return Chain;
10122 }
10123 
10124 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10125 /// for tail call optimization.
10126 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10127 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10128     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10129     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10130 
10131   auto &Callee = CLI.Callee;
10132   auto CalleeCC = CLI.CallConv;
10133   auto &Outs = CLI.Outs;
10134   auto &Caller = MF.getFunction();
10135   auto CallerCC = Caller.getCallingConv();
10136 
10137   // Exception-handling functions need a special set of instructions to
10138   // indicate a return to the hardware. Tail-calling another function would
10139   // probably break this.
10140   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10141   // should be expanded as new function attributes are introduced.
10142   if (Caller.hasFnAttribute("interrupt"))
10143     return false;
10144 
10145   // Do not tail call opt if the stack is used to pass parameters.
10146   if (CCInfo.getNextStackOffset() != 0)
10147     return false;
10148 
10149   // Do not tail call opt if any parameters need to be passed indirectly.
10150   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10151   // passed indirectly. So the address of the value will be passed in a
10152   // register, or if not available, then the address is put on the stack. In
10153   // order to pass indirectly, space on the stack often needs to be allocated
10154   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10155   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10156   // are passed CCValAssign::Indirect.
10157   for (auto &VA : ArgLocs)
10158     if (VA.getLocInfo() == CCValAssign::Indirect)
10159       return false;
10160 
10161   // Do not tail call opt if either caller or callee uses struct return
10162   // semantics.
10163   auto IsCallerStructRet = Caller.hasStructRetAttr();
10164   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10165   if (IsCallerStructRet || IsCalleeStructRet)
10166     return false;
10167 
10168   // Externally-defined functions with weak linkage should not be
10169   // tail-called. The behaviour of branch instructions in this situation (as
10170   // used for tail calls) is implementation-defined, so we cannot rely on the
10171   // linker replacing the tail call with a return.
10172   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10173     const GlobalValue *GV = G->getGlobal();
10174     if (GV->hasExternalWeakLinkage())
10175       return false;
10176   }
10177 
10178   // The callee has to preserve all registers the caller needs to preserve.
10179   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10180   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10181   if (CalleeCC != CallerCC) {
10182     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10183     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10184       return false;
10185   }
10186 
10187   // Byval parameters hand the function a pointer directly into the stack area
10188   // we want to reuse during a tail call. Working around this *is* possible
10189   // but less efficient and uglier in LowerCall.
10190   for (auto &Arg : Outs)
10191     if (Arg.Flags.isByVal())
10192       return false;
10193 
10194   return true;
10195 }
10196 
10197 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10198   return DAG.getDataLayout().getPrefTypeAlign(
10199       VT.getTypeForEVT(*DAG.getContext()));
10200 }
10201 
10202 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10203 // and output parameter nodes.
10204 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10205                                        SmallVectorImpl<SDValue> &InVals) const {
10206   SelectionDAG &DAG = CLI.DAG;
10207   SDLoc &DL = CLI.DL;
10208   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10209   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10210   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10211   SDValue Chain = CLI.Chain;
10212   SDValue Callee = CLI.Callee;
10213   bool &IsTailCall = CLI.IsTailCall;
10214   CallingConv::ID CallConv = CLI.CallConv;
10215   bool IsVarArg = CLI.IsVarArg;
10216   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10217   MVT XLenVT = Subtarget.getXLenVT();
10218 
10219   MachineFunction &MF = DAG.getMachineFunction();
10220 
10221   // Analyze the operands of the call, assigning locations to each operand.
10222   SmallVector<CCValAssign, 16> ArgLocs;
10223   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10224 
10225   if (CallConv == CallingConv::GHC)
10226     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10227   else
10228     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10229                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10230                                                     : CC_RISCV);
10231 
10232   // Check if it's really possible to do a tail call.
10233   if (IsTailCall)
10234     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10235 
10236   if (IsTailCall)
10237     ++NumTailCalls;
10238   else if (CLI.CB && CLI.CB->isMustTailCall())
10239     report_fatal_error("failed to perform tail call elimination on a call "
10240                        "site marked musttail");
10241 
10242   // Get a count of how many bytes are to be pushed on the stack.
10243   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10244 
10245   // Create local copies for byval args
10246   SmallVector<SDValue, 8> ByValArgs;
10247   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10248     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10249     if (!Flags.isByVal())
10250       continue;
10251 
10252     SDValue Arg = OutVals[i];
10253     unsigned Size = Flags.getByValSize();
10254     Align Alignment = Flags.getNonZeroByValAlign();
10255 
10256     int FI =
10257         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10258     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10259     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10260 
10261     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10262                           /*IsVolatile=*/false,
10263                           /*AlwaysInline=*/false, IsTailCall,
10264                           MachinePointerInfo(), MachinePointerInfo());
10265     ByValArgs.push_back(FIPtr);
10266   }
10267 
10268   if (!IsTailCall)
10269     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10270 
10271   // Copy argument values to their designated locations.
10272   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10273   SmallVector<SDValue, 8> MemOpChains;
10274   SDValue StackPtr;
10275   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10276     CCValAssign &VA = ArgLocs[i];
10277     SDValue ArgValue = OutVals[i];
10278     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10279 
10280     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10281     bool IsF64OnRV32DSoftABI =
10282         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10283     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10284       SDValue SplitF64 = DAG.getNode(
10285           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10286       SDValue Lo = SplitF64.getValue(0);
10287       SDValue Hi = SplitF64.getValue(1);
10288 
10289       Register RegLo = VA.getLocReg();
10290       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10291 
10292       if (RegLo == RISCV::X17) {
10293         // Second half of f64 is passed on the stack.
10294         // Work out the address of the stack slot.
10295         if (!StackPtr.getNode())
10296           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10297         // Emit the store.
10298         MemOpChains.push_back(
10299             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10300       } else {
10301         // Second half of f64 is passed in another GPR.
10302         assert(RegLo < RISCV::X31 && "Invalid register pair");
10303         Register RegHigh = RegLo + 1;
10304         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10305       }
10306       continue;
10307     }
10308 
10309     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10310     // as any other MemLoc.
10311 
10312     // Promote the value if needed.
10313     // For now, only handle fully promoted and indirect arguments.
10314     if (VA.getLocInfo() == CCValAssign::Indirect) {
10315       // Store the argument in a stack slot and pass its address.
10316       Align StackAlign =
10317           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10318                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10319       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10320       // If the original argument was split (e.g. i128), we need
10321       // to store the required parts of it here (and pass just one address).
10322       // Vectors may be partly split to registers and partly to the stack, in
10323       // which case the base address is partly offset and subsequent stores are
10324       // relative to that.
10325       unsigned ArgIndex = Outs[i].OrigArgIndex;
10326       unsigned ArgPartOffset = Outs[i].PartOffset;
10327       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10328       // Calculate the total size to store. We don't have access to what we're
10329       // actually storing other than performing the loop and collecting the
10330       // info.
10331       SmallVector<std::pair<SDValue, SDValue>> Parts;
10332       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10333         SDValue PartValue = OutVals[i + 1];
10334         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10335         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10336         EVT PartVT = PartValue.getValueType();
10337         if (PartVT.isScalableVector())
10338           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10339         StoredSize += PartVT.getStoreSize();
10340         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10341         Parts.push_back(std::make_pair(PartValue, Offset));
10342         ++i;
10343       }
10344       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10345       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10346       MemOpChains.push_back(
10347           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10348                        MachinePointerInfo::getFixedStack(MF, FI)));
10349       for (const auto &Part : Parts) {
10350         SDValue PartValue = Part.first;
10351         SDValue PartOffset = Part.second;
10352         SDValue Address =
10353             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10354         MemOpChains.push_back(
10355             DAG.getStore(Chain, DL, PartValue, Address,
10356                          MachinePointerInfo::getFixedStack(MF, FI)));
10357       }
10358       ArgValue = SpillSlot;
10359     } else {
10360       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10361     }
10362 
10363     // Use local copy if it is a byval arg.
10364     if (Flags.isByVal())
10365       ArgValue = ByValArgs[j++];
10366 
10367     if (VA.isRegLoc()) {
10368       // Queue up the argument copies and emit them at the end.
10369       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10370     } else {
10371       assert(VA.isMemLoc() && "Argument not register or memory");
10372       assert(!IsTailCall && "Tail call not allowed if stack is used "
10373                             "for passing parameters");
10374 
10375       // Work out the address of the stack slot.
10376       if (!StackPtr.getNode())
10377         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10378       SDValue Address =
10379           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10380                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10381 
10382       // Emit the store.
10383       MemOpChains.push_back(
10384           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10385     }
10386   }
10387 
10388   // Join the stores, which are independent of one another.
10389   if (!MemOpChains.empty())
10390     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10391 
10392   SDValue Glue;
10393 
10394   // Build a sequence of copy-to-reg nodes, chained and glued together.
10395   for (auto &Reg : RegsToPass) {
10396     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10397     Glue = Chain.getValue(1);
10398   }
10399 
10400   // Validate that none of the argument registers have been marked as
10401   // reserved, if so report an error. Do the same for the return address if this
10402   // is not a tailcall.
10403   validateCCReservedRegs(RegsToPass, MF);
10404   if (!IsTailCall &&
10405       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10406     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10407         MF.getFunction(),
10408         "Return address register required, but has been reserved."});
10409 
10410   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10411   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10412   // split it and then direct call can be matched by PseudoCALL.
10413   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10414     const GlobalValue *GV = S->getGlobal();
10415 
10416     unsigned OpFlags = RISCVII::MO_CALL;
10417     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10418       OpFlags = RISCVII::MO_PLT;
10419 
10420     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10421   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10422     unsigned OpFlags = RISCVII::MO_CALL;
10423 
10424     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10425                                                  nullptr))
10426       OpFlags = RISCVII::MO_PLT;
10427 
10428     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10429   }
10430 
10431   // The first call operand is the chain and the second is the target address.
10432   SmallVector<SDValue, 8> Ops;
10433   Ops.push_back(Chain);
10434   Ops.push_back(Callee);
10435 
10436   // Add argument registers to the end of the list so that they are
10437   // known live into the call.
10438   for (auto &Reg : RegsToPass)
10439     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10440 
10441   if (!IsTailCall) {
10442     // Add a register mask operand representing the call-preserved registers.
10443     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10444     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10445     assert(Mask && "Missing call preserved mask for calling convention");
10446     Ops.push_back(DAG.getRegisterMask(Mask));
10447   }
10448 
10449   // Glue the call to the argument copies, if any.
10450   if (Glue.getNode())
10451     Ops.push_back(Glue);
10452 
10453   // Emit the call.
10454   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10455 
10456   if (IsTailCall) {
10457     MF.getFrameInfo().setHasTailCall();
10458     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10459   }
10460 
10461   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10462   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10463   Glue = Chain.getValue(1);
10464 
10465   // Mark the end of the call, which is glued to the call itself.
10466   Chain = DAG.getCALLSEQ_END(Chain,
10467                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10468                              DAG.getConstant(0, DL, PtrVT, true),
10469                              Glue, DL);
10470   Glue = Chain.getValue(1);
10471 
10472   // Assign locations to each value returned by this call.
10473   SmallVector<CCValAssign, 16> RVLocs;
10474   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10475   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10476 
10477   // Copy all of the result registers out of their specified physreg.
10478   for (auto &VA : RVLocs) {
10479     // Copy the value out
10480     SDValue RetValue =
10481         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10482     // Glue the RetValue to the end of the call sequence
10483     Chain = RetValue.getValue(1);
10484     Glue = RetValue.getValue(2);
10485 
10486     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10487       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10488       SDValue RetValue2 =
10489           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10490       Chain = RetValue2.getValue(1);
10491       Glue = RetValue2.getValue(2);
10492       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10493                              RetValue2);
10494     }
10495 
10496     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10497 
10498     InVals.push_back(RetValue);
10499   }
10500 
10501   return Chain;
10502 }
10503 
10504 bool RISCVTargetLowering::CanLowerReturn(
10505     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10506     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10507   SmallVector<CCValAssign, 16> RVLocs;
10508   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10509 
10510   Optional<unsigned> FirstMaskArgument;
10511   if (Subtarget.hasVInstructions())
10512     FirstMaskArgument = preAssignMask(Outs);
10513 
10514   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10515     MVT VT = Outs[i].VT;
10516     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10517     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10518     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10519                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10520                  *this, FirstMaskArgument))
10521       return false;
10522   }
10523   return true;
10524 }
10525 
10526 SDValue
10527 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10528                                  bool IsVarArg,
10529                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10530                                  const SmallVectorImpl<SDValue> &OutVals,
10531                                  const SDLoc &DL, SelectionDAG &DAG) const {
10532   const MachineFunction &MF = DAG.getMachineFunction();
10533   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10534 
10535   // Stores the assignment of the return value to a location.
10536   SmallVector<CCValAssign, 16> RVLocs;
10537 
10538   // Info about the registers and stack slot.
10539   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10540                  *DAG.getContext());
10541 
10542   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10543                     nullptr, CC_RISCV);
10544 
10545   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10546     report_fatal_error("GHC functions return void only");
10547 
10548   SDValue Glue;
10549   SmallVector<SDValue, 4> RetOps(1, Chain);
10550 
10551   // Copy the result values into the output registers.
10552   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10553     SDValue Val = OutVals[i];
10554     CCValAssign &VA = RVLocs[i];
10555     assert(VA.isRegLoc() && "Can only return in registers!");
10556 
10557     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10558       // Handle returning f64 on RV32D with a soft float ABI.
10559       assert(VA.isRegLoc() && "Expected return via registers");
10560       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10561                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10562       SDValue Lo = SplitF64.getValue(0);
10563       SDValue Hi = SplitF64.getValue(1);
10564       Register RegLo = VA.getLocReg();
10565       assert(RegLo < RISCV::X31 && "Invalid register pair");
10566       Register RegHi = RegLo + 1;
10567 
10568       if (STI.isRegisterReservedByUser(RegLo) ||
10569           STI.isRegisterReservedByUser(RegHi))
10570         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10571             MF.getFunction(),
10572             "Return value register required, but has been reserved."});
10573 
10574       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10575       Glue = Chain.getValue(1);
10576       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10577       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10578       Glue = Chain.getValue(1);
10579       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10580     } else {
10581       // Handle a 'normal' return.
10582       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10583       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10584 
10585       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10586         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10587             MF.getFunction(),
10588             "Return value register required, but has been reserved."});
10589 
10590       // Guarantee that all emitted copies are stuck together.
10591       Glue = Chain.getValue(1);
10592       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10593     }
10594   }
10595 
10596   RetOps[0] = Chain; // Update chain.
10597 
10598   // Add the glue node if we have it.
10599   if (Glue.getNode()) {
10600     RetOps.push_back(Glue);
10601   }
10602 
10603   unsigned RetOpc = RISCVISD::RET_FLAG;
10604   // Interrupt service routines use different return instructions.
10605   const Function &Func = DAG.getMachineFunction().getFunction();
10606   if (Func.hasFnAttribute("interrupt")) {
10607     if (!Func.getReturnType()->isVoidTy())
10608       report_fatal_error(
10609           "Functions with the interrupt attribute must have void return type!");
10610 
10611     MachineFunction &MF = DAG.getMachineFunction();
10612     StringRef Kind =
10613       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10614 
10615     if (Kind == "user")
10616       RetOpc = RISCVISD::URET_FLAG;
10617     else if (Kind == "supervisor")
10618       RetOpc = RISCVISD::SRET_FLAG;
10619     else
10620       RetOpc = RISCVISD::MRET_FLAG;
10621   }
10622 
10623   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10624 }
10625 
10626 void RISCVTargetLowering::validateCCReservedRegs(
10627     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10628     MachineFunction &MF) const {
10629   const Function &F = MF.getFunction();
10630   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10631 
10632   if (llvm::any_of(Regs, [&STI](auto Reg) {
10633         return STI.isRegisterReservedByUser(Reg.first);
10634       }))
10635     F.getContext().diagnose(DiagnosticInfoUnsupported{
10636         F, "Argument register required, but has been reserved."});
10637 }
10638 
10639 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10640   return CI->isTailCall();
10641 }
10642 
10643 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10644 #define NODE_NAME_CASE(NODE)                                                   \
10645   case RISCVISD::NODE:                                                         \
10646     return "RISCVISD::" #NODE;
10647   // clang-format off
10648   switch ((RISCVISD::NodeType)Opcode) {
10649   case RISCVISD::FIRST_NUMBER:
10650     break;
10651   NODE_NAME_CASE(RET_FLAG)
10652   NODE_NAME_CASE(URET_FLAG)
10653   NODE_NAME_CASE(SRET_FLAG)
10654   NODE_NAME_CASE(MRET_FLAG)
10655   NODE_NAME_CASE(CALL)
10656   NODE_NAME_CASE(SELECT_CC)
10657   NODE_NAME_CASE(BR_CC)
10658   NODE_NAME_CASE(BuildPairF64)
10659   NODE_NAME_CASE(SplitF64)
10660   NODE_NAME_CASE(TAIL)
10661   NODE_NAME_CASE(MULHSU)
10662   NODE_NAME_CASE(SLLW)
10663   NODE_NAME_CASE(SRAW)
10664   NODE_NAME_CASE(SRLW)
10665   NODE_NAME_CASE(DIVW)
10666   NODE_NAME_CASE(DIVUW)
10667   NODE_NAME_CASE(REMUW)
10668   NODE_NAME_CASE(ROLW)
10669   NODE_NAME_CASE(RORW)
10670   NODE_NAME_CASE(CLZW)
10671   NODE_NAME_CASE(CTZW)
10672   NODE_NAME_CASE(FSLW)
10673   NODE_NAME_CASE(FSRW)
10674   NODE_NAME_CASE(FSL)
10675   NODE_NAME_CASE(FSR)
10676   NODE_NAME_CASE(FMV_H_X)
10677   NODE_NAME_CASE(FMV_X_ANYEXTH)
10678   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10679   NODE_NAME_CASE(FMV_W_X_RV64)
10680   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10681   NODE_NAME_CASE(FCVT_X)
10682   NODE_NAME_CASE(FCVT_XU)
10683   NODE_NAME_CASE(FCVT_W_RV64)
10684   NODE_NAME_CASE(FCVT_WU_RV64)
10685   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10686   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10687   NODE_NAME_CASE(READ_CYCLE_WIDE)
10688   NODE_NAME_CASE(GREV)
10689   NODE_NAME_CASE(GREVW)
10690   NODE_NAME_CASE(GORC)
10691   NODE_NAME_CASE(GORCW)
10692   NODE_NAME_CASE(SHFL)
10693   NODE_NAME_CASE(SHFLW)
10694   NODE_NAME_CASE(UNSHFL)
10695   NODE_NAME_CASE(UNSHFLW)
10696   NODE_NAME_CASE(BFP)
10697   NODE_NAME_CASE(BFPW)
10698   NODE_NAME_CASE(BCOMPRESS)
10699   NODE_NAME_CASE(BCOMPRESSW)
10700   NODE_NAME_CASE(BDECOMPRESS)
10701   NODE_NAME_CASE(BDECOMPRESSW)
10702   NODE_NAME_CASE(VMV_V_X_VL)
10703   NODE_NAME_CASE(VFMV_V_F_VL)
10704   NODE_NAME_CASE(VMV_X_S)
10705   NODE_NAME_CASE(VMV_S_X_VL)
10706   NODE_NAME_CASE(VFMV_S_F_VL)
10707   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10708   NODE_NAME_CASE(READ_VLENB)
10709   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10710   NODE_NAME_CASE(VSLIDEUP_VL)
10711   NODE_NAME_CASE(VSLIDE1UP_VL)
10712   NODE_NAME_CASE(VSLIDEDOWN_VL)
10713   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10714   NODE_NAME_CASE(VID_VL)
10715   NODE_NAME_CASE(VFNCVT_ROD_VL)
10716   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10717   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10718   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10719   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10720   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10721   NODE_NAME_CASE(VECREDUCE_AND_VL)
10722   NODE_NAME_CASE(VECREDUCE_OR_VL)
10723   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10724   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10725   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10726   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10727   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10728   NODE_NAME_CASE(ADD_VL)
10729   NODE_NAME_CASE(AND_VL)
10730   NODE_NAME_CASE(MUL_VL)
10731   NODE_NAME_CASE(OR_VL)
10732   NODE_NAME_CASE(SDIV_VL)
10733   NODE_NAME_CASE(SHL_VL)
10734   NODE_NAME_CASE(SREM_VL)
10735   NODE_NAME_CASE(SRA_VL)
10736   NODE_NAME_CASE(SRL_VL)
10737   NODE_NAME_CASE(SUB_VL)
10738   NODE_NAME_CASE(UDIV_VL)
10739   NODE_NAME_CASE(UREM_VL)
10740   NODE_NAME_CASE(XOR_VL)
10741   NODE_NAME_CASE(SADDSAT_VL)
10742   NODE_NAME_CASE(UADDSAT_VL)
10743   NODE_NAME_CASE(SSUBSAT_VL)
10744   NODE_NAME_CASE(USUBSAT_VL)
10745   NODE_NAME_CASE(FADD_VL)
10746   NODE_NAME_CASE(FSUB_VL)
10747   NODE_NAME_CASE(FMUL_VL)
10748   NODE_NAME_CASE(FDIV_VL)
10749   NODE_NAME_CASE(FNEG_VL)
10750   NODE_NAME_CASE(FABS_VL)
10751   NODE_NAME_CASE(FSQRT_VL)
10752   NODE_NAME_CASE(FMA_VL)
10753   NODE_NAME_CASE(FCOPYSIGN_VL)
10754   NODE_NAME_CASE(SMIN_VL)
10755   NODE_NAME_CASE(SMAX_VL)
10756   NODE_NAME_CASE(UMIN_VL)
10757   NODE_NAME_CASE(UMAX_VL)
10758   NODE_NAME_CASE(FMINNUM_VL)
10759   NODE_NAME_CASE(FMAXNUM_VL)
10760   NODE_NAME_CASE(MULHS_VL)
10761   NODE_NAME_CASE(MULHU_VL)
10762   NODE_NAME_CASE(FP_TO_SINT_VL)
10763   NODE_NAME_CASE(FP_TO_UINT_VL)
10764   NODE_NAME_CASE(SINT_TO_FP_VL)
10765   NODE_NAME_CASE(UINT_TO_FP_VL)
10766   NODE_NAME_CASE(FP_EXTEND_VL)
10767   NODE_NAME_CASE(FP_ROUND_VL)
10768   NODE_NAME_CASE(VWMUL_VL)
10769   NODE_NAME_CASE(VWMULU_VL)
10770   NODE_NAME_CASE(VWMULSU_VL)
10771   NODE_NAME_CASE(VWADD_VL)
10772   NODE_NAME_CASE(VWADDU_VL)
10773   NODE_NAME_CASE(VWSUB_VL)
10774   NODE_NAME_CASE(VWSUBU_VL)
10775   NODE_NAME_CASE(VWADD_W_VL)
10776   NODE_NAME_CASE(VWADDU_W_VL)
10777   NODE_NAME_CASE(VWSUB_W_VL)
10778   NODE_NAME_CASE(VWSUBU_W_VL)
10779   NODE_NAME_CASE(SETCC_VL)
10780   NODE_NAME_CASE(VSELECT_VL)
10781   NODE_NAME_CASE(VP_MERGE_VL)
10782   NODE_NAME_CASE(VMAND_VL)
10783   NODE_NAME_CASE(VMOR_VL)
10784   NODE_NAME_CASE(VMXOR_VL)
10785   NODE_NAME_CASE(VMCLR_VL)
10786   NODE_NAME_CASE(VMSET_VL)
10787   NODE_NAME_CASE(VRGATHER_VX_VL)
10788   NODE_NAME_CASE(VRGATHER_VV_VL)
10789   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10790   NODE_NAME_CASE(VSEXT_VL)
10791   NODE_NAME_CASE(VZEXT_VL)
10792   NODE_NAME_CASE(VCPOP_VL)
10793   NODE_NAME_CASE(VLE_VL)
10794   NODE_NAME_CASE(VSE_VL)
10795   NODE_NAME_CASE(READ_CSR)
10796   NODE_NAME_CASE(WRITE_CSR)
10797   NODE_NAME_CASE(SWAP_CSR)
10798   }
10799   // clang-format on
10800   return nullptr;
10801 #undef NODE_NAME_CASE
10802 }
10803 
10804 /// getConstraintType - Given a constraint letter, return the type of
10805 /// constraint it is for this target.
10806 RISCVTargetLowering::ConstraintType
10807 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10808   if (Constraint.size() == 1) {
10809     switch (Constraint[0]) {
10810     default:
10811       break;
10812     case 'f':
10813       return C_RegisterClass;
10814     case 'I':
10815     case 'J':
10816     case 'K':
10817       return C_Immediate;
10818     case 'A':
10819       return C_Memory;
10820     case 'S': // A symbolic address
10821       return C_Other;
10822     }
10823   } else {
10824     if (Constraint == "vr" || Constraint == "vm")
10825       return C_RegisterClass;
10826   }
10827   return TargetLowering::getConstraintType(Constraint);
10828 }
10829 
10830 std::pair<unsigned, const TargetRegisterClass *>
10831 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10832                                                   StringRef Constraint,
10833                                                   MVT VT) const {
10834   // First, see if this is a constraint that directly corresponds to a
10835   // RISCV register class.
10836   if (Constraint.size() == 1) {
10837     switch (Constraint[0]) {
10838     case 'r':
10839       // TODO: Support fixed vectors up to XLen for P extension?
10840       if (VT.isVector())
10841         break;
10842       return std::make_pair(0U, &RISCV::GPRRegClass);
10843     case 'f':
10844       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10845         return std::make_pair(0U, &RISCV::FPR16RegClass);
10846       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10847         return std::make_pair(0U, &RISCV::FPR32RegClass);
10848       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10849         return std::make_pair(0U, &RISCV::FPR64RegClass);
10850       break;
10851     default:
10852       break;
10853     }
10854   } else if (Constraint == "vr") {
10855     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10856                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10857       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10858         return std::make_pair(0U, RC);
10859     }
10860   } else if (Constraint == "vm") {
10861     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10862       return std::make_pair(0U, &RISCV::VMV0RegClass);
10863   }
10864 
10865   // Clang will correctly decode the usage of register name aliases into their
10866   // official names. However, other frontends like `rustc` do not. This allows
10867   // users of these frontends to use the ABI names for registers in LLVM-style
10868   // register constraints.
10869   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10870                                .Case("{zero}", RISCV::X0)
10871                                .Case("{ra}", RISCV::X1)
10872                                .Case("{sp}", RISCV::X2)
10873                                .Case("{gp}", RISCV::X3)
10874                                .Case("{tp}", RISCV::X4)
10875                                .Case("{t0}", RISCV::X5)
10876                                .Case("{t1}", RISCV::X6)
10877                                .Case("{t2}", RISCV::X7)
10878                                .Cases("{s0}", "{fp}", RISCV::X8)
10879                                .Case("{s1}", RISCV::X9)
10880                                .Case("{a0}", RISCV::X10)
10881                                .Case("{a1}", RISCV::X11)
10882                                .Case("{a2}", RISCV::X12)
10883                                .Case("{a3}", RISCV::X13)
10884                                .Case("{a4}", RISCV::X14)
10885                                .Case("{a5}", RISCV::X15)
10886                                .Case("{a6}", RISCV::X16)
10887                                .Case("{a7}", RISCV::X17)
10888                                .Case("{s2}", RISCV::X18)
10889                                .Case("{s3}", RISCV::X19)
10890                                .Case("{s4}", RISCV::X20)
10891                                .Case("{s5}", RISCV::X21)
10892                                .Case("{s6}", RISCV::X22)
10893                                .Case("{s7}", RISCV::X23)
10894                                .Case("{s8}", RISCV::X24)
10895                                .Case("{s9}", RISCV::X25)
10896                                .Case("{s10}", RISCV::X26)
10897                                .Case("{s11}", RISCV::X27)
10898                                .Case("{t3}", RISCV::X28)
10899                                .Case("{t4}", RISCV::X29)
10900                                .Case("{t5}", RISCV::X30)
10901                                .Case("{t6}", RISCV::X31)
10902                                .Default(RISCV::NoRegister);
10903   if (XRegFromAlias != RISCV::NoRegister)
10904     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10905 
10906   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10907   // TableGen record rather than the AsmName to choose registers for InlineAsm
10908   // constraints, plus we want to match those names to the widest floating point
10909   // register type available, manually select floating point registers here.
10910   //
10911   // The second case is the ABI name of the register, so that frontends can also
10912   // use the ABI names in register constraint lists.
10913   if (Subtarget.hasStdExtF()) {
10914     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10915                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10916                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10917                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10918                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10919                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10920                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10921                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10922                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10923                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10924                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10925                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10926                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10927                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10928                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10929                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10930                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10931                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10932                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10933                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10934                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10935                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10936                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10937                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10938                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10939                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10940                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10941                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10942                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10943                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10944                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10945                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10946                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10947                         .Default(RISCV::NoRegister);
10948     if (FReg != RISCV::NoRegister) {
10949       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10950       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10951         unsigned RegNo = FReg - RISCV::F0_F;
10952         unsigned DReg = RISCV::F0_D + RegNo;
10953         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10954       }
10955       if (VT == MVT::f32 || VT == MVT::Other)
10956         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10957       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10958         unsigned RegNo = FReg - RISCV::F0_F;
10959         unsigned HReg = RISCV::F0_H + RegNo;
10960         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10961       }
10962     }
10963   }
10964 
10965   if (Subtarget.hasVInstructions()) {
10966     Register VReg = StringSwitch<Register>(Constraint.lower())
10967                         .Case("{v0}", RISCV::V0)
10968                         .Case("{v1}", RISCV::V1)
10969                         .Case("{v2}", RISCV::V2)
10970                         .Case("{v3}", RISCV::V3)
10971                         .Case("{v4}", RISCV::V4)
10972                         .Case("{v5}", RISCV::V5)
10973                         .Case("{v6}", RISCV::V6)
10974                         .Case("{v7}", RISCV::V7)
10975                         .Case("{v8}", RISCV::V8)
10976                         .Case("{v9}", RISCV::V9)
10977                         .Case("{v10}", RISCV::V10)
10978                         .Case("{v11}", RISCV::V11)
10979                         .Case("{v12}", RISCV::V12)
10980                         .Case("{v13}", RISCV::V13)
10981                         .Case("{v14}", RISCV::V14)
10982                         .Case("{v15}", RISCV::V15)
10983                         .Case("{v16}", RISCV::V16)
10984                         .Case("{v17}", RISCV::V17)
10985                         .Case("{v18}", RISCV::V18)
10986                         .Case("{v19}", RISCV::V19)
10987                         .Case("{v20}", RISCV::V20)
10988                         .Case("{v21}", RISCV::V21)
10989                         .Case("{v22}", RISCV::V22)
10990                         .Case("{v23}", RISCV::V23)
10991                         .Case("{v24}", RISCV::V24)
10992                         .Case("{v25}", RISCV::V25)
10993                         .Case("{v26}", RISCV::V26)
10994                         .Case("{v27}", RISCV::V27)
10995                         .Case("{v28}", RISCV::V28)
10996                         .Case("{v29}", RISCV::V29)
10997                         .Case("{v30}", RISCV::V30)
10998                         .Case("{v31}", RISCV::V31)
10999                         .Default(RISCV::NoRegister);
11000     if (VReg != RISCV::NoRegister) {
11001       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11002         return std::make_pair(VReg, &RISCV::VMRegClass);
11003       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11004         return std::make_pair(VReg, &RISCV::VRRegClass);
11005       for (const auto *RC :
11006            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11007         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11008           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11009           return std::make_pair(VReg, RC);
11010         }
11011       }
11012     }
11013   }
11014 
11015   std::pair<Register, const TargetRegisterClass *> Res =
11016       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11017 
11018   if (Res.second == &RISCV::GPRF32RegClass) {
11019     if (!Subtarget.is64Bit() || VT == MVT::Other)
11020       return std::make_pair(Res.first, &RISCV::GPRRegClass);
11021     return std::make_pair(0, nullptr);
11022   }
11023 
11024   if (Res.second == &RISCV::GPRF64RegClass ||
11025       Res.second == &RISCV::GPRPF64RegClass) {
11026     if (Subtarget.is64Bit() || VT == MVT::Other)
11027       return std::make_pair(Res.first, &RISCV::GPRRegClass);
11028     return std::make_pair(0, nullptr);
11029   }
11030 
11031   if (Res.second == &RISCV::GPRF16RegClass) {
11032     if (VT == MVT::Other)
11033       return std::make_pair(Res.first, &RISCV::GPRRegClass);
11034     return std::make_pair(0, nullptr);
11035   }
11036 
11037   return Res;
11038 }
11039 
11040 unsigned
11041 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11042   // Currently only support length 1 constraints.
11043   if (ConstraintCode.size() == 1) {
11044     switch (ConstraintCode[0]) {
11045     case 'A':
11046       return InlineAsm::Constraint_A;
11047     default:
11048       break;
11049     }
11050   }
11051 
11052   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11053 }
11054 
11055 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11056     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11057     SelectionDAG &DAG) const {
11058   // Currently only support length 1 constraints.
11059   if (Constraint.length() == 1) {
11060     switch (Constraint[0]) {
11061     case 'I':
11062       // Validate & create a 12-bit signed immediate operand.
11063       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11064         uint64_t CVal = C->getSExtValue();
11065         if (isInt<12>(CVal))
11066           Ops.push_back(
11067               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11068       }
11069       return;
11070     case 'J':
11071       // Validate & create an integer zero operand.
11072       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11073         if (C->getZExtValue() == 0)
11074           Ops.push_back(
11075               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11076       return;
11077     case 'K':
11078       // Validate & create a 5-bit unsigned immediate operand.
11079       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11080         uint64_t CVal = C->getZExtValue();
11081         if (isUInt<5>(CVal))
11082           Ops.push_back(
11083               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11084       }
11085       return;
11086     case 'S':
11087       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11088         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11089                                                  GA->getValueType(0)));
11090       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11091         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11092                                                 BA->getValueType(0)));
11093       }
11094       return;
11095     default:
11096       break;
11097     }
11098   }
11099   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11100 }
11101 
11102 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11103                                                    Instruction *Inst,
11104                                                    AtomicOrdering Ord) const {
11105   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11106     return Builder.CreateFence(Ord);
11107   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11108     return Builder.CreateFence(AtomicOrdering::Release);
11109   return nullptr;
11110 }
11111 
11112 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11113                                                     Instruction *Inst,
11114                                                     AtomicOrdering Ord) const {
11115   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11116     return Builder.CreateFence(AtomicOrdering::Acquire);
11117   return nullptr;
11118 }
11119 
11120 TargetLowering::AtomicExpansionKind
11121 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11122   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11123   // point operations can't be used in an lr/sc sequence without breaking the
11124   // forward-progress guarantee.
11125   if (AI->isFloatingPointOperation())
11126     return AtomicExpansionKind::CmpXChg;
11127 
11128   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11129   if (Size == 8 || Size == 16)
11130     return AtomicExpansionKind::MaskedIntrinsic;
11131   return AtomicExpansionKind::None;
11132 }
11133 
11134 static Intrinsic::ID
11135 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11136   if (XLen == 32) {
11137     switch (BinOp) {
11138     default:
11139       llvm_unreachable("Unexpected AtomicRMW BinOp");
11140     case AtomicRMWInst::Xchg:
11141       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11142     case AtomicRMWInst::Add:
11143       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11144     case AtomicRMWInst::Sub:
11145       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11146     case AtomicRMWInst::Nand:
11147       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11148     case AtomicRMWInst::Max:
11149       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11150     case AtomicRMWInst::Min:
11151       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11152     case AtomicRMWInst::UMax:
11153       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11154     case AtomicRMWInst::UMin:
11155       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11156     }
11157   }
11158 
11159   if (XLen == 64) {
11160     switch (BinOp) {
11161     default:
11162       llvm_unreachable("Unexpected AtomicRMW BinOp");
11163     case AtomicRMWInst::Xchg:
11164       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11165     case AtomicRMWInst::Add:
11166       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11167     case AtomicRMWInst::Sub:
11168       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11169     case AtomicRMWInst::Nand:
11170       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11171     case AtomicRMWInst::Max:
11172       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11173     case AtomicRMWInst::Min:
11174       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11175     case AtomicRMWInst::UMax:
11176       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11177     case AtomicRMWInst::UMin:
11178       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11179     }
11180   }
11181 
11182   llvm_unreachable("Unexpected XLen\n");
11183 }
11184 
11185 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11186     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11187     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11188   unsigned XLen = Subtarget.getXLen();
11189   Value *Ordering =
11190       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11191   Type *Tys[] = {AlignedAddr->getType()};
11192   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11193       AI->getModule(),
11194       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11195 
11196   if (XLen == 64) {
11197     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11198     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11199     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11200   }
11201 
11202   Value *Result;
11203 
11204   // Must pass the shift amount needed to sign extend the loaded value prior
11205   // to performing a signed comparison for min/max. ShiftAmt is the number of
11206   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11207   // is the number of bits to left+right shift the value in order to
11208   // sign-extend.
11209   if (AI->getOperation() == AtomicRMWInst::Min ||
11210       AI->getOperation() == AtomicRMWInst::Max) {
11211     const DataLayout &DL = AI->getModule()->getDataLayout();
11212     unsigned ValWidth =
11213         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11214     Value *SextShamt =
11215         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11216     Result = Builder.CreateCall(LrwOpScwLoop,
11217                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11218   } else {
11219     Result =
11220         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11221   }
11222 
11223   if (XLen == 64)
11224     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11225   return Result;
11226 }
11227 
11228 TargetLowering::AtomicExpansionKind
11229 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11230     AtomicCmpXchgInst *CI) const {
11231   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11232   if (Size == 8 || Size == 16)
11233     return AtomicExpansionKind::MaskedIntrinsic;
11234   return AtomicExpansionKind::None;
11235 }
11236 
11237 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11238     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11239     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11240   unsigned XLen = Subtarget.getXLen();
11241   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11242   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11243   if (XLen == 64) {
11244     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11245     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11246     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11247     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11248   }
11249   Type *Tys[] = {AlignedAddr->getType()};
11250   Function *MaskedCmpXchg =
11251       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11252   Value *Result = Builder.CreateCall(
11253       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11254   if (XLen == 64)
11255     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11256   return Result;
11257 }
11258 
11259 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11260   return false;
11261 }
11262 
11263 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11264                                                EVT VT) const {
11265   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11266     return false;
11267 
11268   switch (FPVT.getSimpleVT().SimpleTy) {
11269   case MVT::f16:
11270     return Subtarget.hasStdExtZfh();
11271   case MVT::f32:
11272     return Subtarget.hasStdExtF();
11273   case MVT::f64:
11274     return Subtarget.hasStdExtD();
11275   default:
11276     return false;
11277   }
11278 }
11279 
11280 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11281   // If we are using the small code model, we can reduce size of jump table
11282   // entry to 4 bytes.
11283   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11284       getTargetMachine().getCodeModel() == CodeModel::Small) {
11285     return MachineJumpTableInfo::EK_Custom32;
11286   }
11287   return TargetLowering::getJumpTableEncoding();
11288 }
11289 
11290 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11291     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11292     unsigned uid, MCContext &Ctx) const {
11293   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11294          getTargetMachine().getCodeModel() == CodeModel::Small);
11295   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11296 }
11297 
11298 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11299                                                      EVT VT) const {
11300   VT = VT.getScalarType();
11301 
11302   if (!VT.isSimple())
11303     return false;
11304 
11305   switch (VT.getSimpleVT().SimpleTy) {
11306   case MVT::f16:
11307     return Subtarget.hasStdExtZfh();
11308   case MVT::f32:
11309     return Subtarget.hasStdExtF();
11310   case MVT::f64:
11311     return Subtarget.hasStdExtD();
11312   default:
11313     break;
11314   }
11315 
11316   return false;
11317 }
11318 
11319 Register RISCVTargetLowering::getExceptionPointerRegister(
11320     const Constant *PersonalityFn) const {
11321   return RISCV::X10;
11322 }
11323 
11324 Register RISCVTargetLowering::getExceptionSelectorRegister(
11325     const Constant *PersonalityFn) const {
11326   return RISCV::X11;
11327 }
11328 
11329 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11330   // Return false to suppress the unnecessary extensions if the LibCall
11331   // arguments or return value is f32 type for LP64 ABI.
11332   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11333   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11334     return false;
11335 
11336   return true;
11337 }
11338 
11339 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11340   if (Subtarget.is64Bit() && Type == MVT::i32)
11341     return true;
11342 
11343   return IsSigned;
11344 }
11345 
11346 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11347                                                  SDValue C) const {
11348   // Check integral scalar types.
11349   if (VT.isScalarInteger()) {
11350     // Omit the optimization if the sub target has the M extension and the data
11351     // size exceeds XLen.
11352     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11353       return false;
11354     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11355       // Break the MUL to a SLLI and an ADD/SUB.
11356       const APInt &Imm = ConstNode->getAPIntValue();
11357       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11358           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11359         return true;
11360       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11361       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11362           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11363            (Imm - 8).isPowerOf2()))
11364         return true;
11365       // Omit the following optimization if the sub target has the M extension
11366       // and the data size >= XLen.
11367       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11368         return false;
11369       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11370       // a pair of LUI/ADDI.
11371       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11372         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11373         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11374             (1 - ImmS).isPowerOf2())
11375         return true;
11376       }
11377     }
11378   }
11379 
11380   return false;
11381 }
11382 
11383 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11384                                                       SDValue ConstNode) const {
11385   // Let the DAGCombiner decide for vectors.
11386   EVT VT = AddNode.getValueType();
11387   if (VT.isVector())
11388     return true;
11389 
11390   // Let the DAGCombiner decide for larger types.
11391   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11392     return true;
11393 
11394   // It is worse if c1 is simm12 while c1*c2 is not.
11395   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11396   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11397   const APInt &C1 = C1Node->getAPIntValue();
11398   const APInt &C2 = C2Node->getAPIntValue();
11399   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11400     return false;
11401 
11402   // Default to true and let the DAGCombiner decide.
11403   return true;
11404 }
11405 
11406 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11407     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11408     bool *Fast) const {
11409   if (!VT.isVector())
11410     return false;
11411 
11412   EVT ElemVT = VT.getVectorElementType();
11413   if (Alignment >= ElemVT.getStoreSize()) {
11414     if (Fast)
11415       *Fast = true;
11416     return true;
11417   }
11418 
11419   return false;
11420 }
11421 
11422 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11423     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11424     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11425   bool IsABIRegCopy = CC.hasValue();
11426   EVT ValueVT = Val.getValueType();
11427   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11428     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11429     // and cast to f32.
11430     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11431     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11432     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11433                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11434     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11435     Parts[0] = Val;
11436     return true;
11437   }
11438 
11439   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11440     LLVMContext &Context = *DAG.getContext();
11441     EVT ValueEltVT = ValueVT.getVectorElementType();
11442     EVT PartEltVT = PartVT.getVectorElementType();
11443     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11444     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11445     if (PartVTBitSize % ValueVTBitSize == 0) {
11446       assert(PartVTBitSize >= ValueVTBitSize);
11447       // If the element types are different, bitcast to the same element type of
11448       // PartVT first.
11449       // Give an example here, we want copy a <vscale x 1 x i8> value to
11450       // <vscale x 4 x i16>.
11451       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11452       // subvector, then we can bitcast to <vscale x 4 x i16>.
11453       if (ValueEltVT != PartEltVT) {
11454         if (PartVTBitSize > ValueVTBitSize) {
11455           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11456           assert(Count != 0 && "The number of element should not be zero.");
11457           EVT SameEltTypeVT =
11458               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11459           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11460                             DAG.getUNDEF(SameEltTypeVT), Val,
11461                             DAG.getVectorIdxConstant(0, DL));
11462         }
11463         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11464       } else {
11465         Val =
11466             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11467                         Val, DAG.getVectorIdxConstant(0, DL));
11468       }
11469       Parts[0] = Val;
11470       return true;
11471     }
11472   }
11473   return false;
11474 }
11475 
11476 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11477     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11478     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11479   bool IsABIRegCopy = CC.hasValue();
11480   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11481     SDValue Val = Parts[0];
11482 
11483     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11484     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11485     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11486     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11487     return Val;
11488   }
11489 
11490   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11491     LLVMContext &Context = *DAG.getContext();
11492     SDValue Val = Parts[0];
11493     EVT ValueEltVT = ValueVT.getVectorElementType();
11494     EVT PartEltVT = PartVT.getVectorElementType();
11495     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11496     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11497     if (PartVTBitSize % ValueVTBitSize == 0) {
11498       assert(PartVTBitSize >= ValueVTBitSize);
11499       EVT SameEltTypeVT = ValueVT;
11500       // If the element types are different, convert it to the same element type
11501       // of PartVT.
11502       // Give an example here, we want copy a <vscale x 1 x i8> value from
11503       // <vscale x 4 x i16>.
11504       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11505       // then we can extract <vscale x 1 x i8>.
11506       if (ValueEltVT != PartEltVT) {
11507         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11508         assert(Count != 0 && "The number of element should not be zero.");
11509         SameEltTypeVT =
11510             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11511         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11512       }
11513       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11514                         DAG.getVectorIdxConstant(0, DL));
11515       return Val;
11516     }
11517   }
11518   return SDValue();
11519 }
11520 
11521 SDValue
11522 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11523                                    SelectionDAG &DAG,
11524                                    SmallVectorImpl<SDNode *> &Created) const {
11525   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11526   if (isIntDivCheap(N->getValueType(0), Attr))
11527     return SDValue(N, 0); // Lower SDIV as SDIV
11528 
11529   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11530          "Unexpected divisor!");
11531 
11532   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11533   if (!Subtarget.hasStdExtZbt())
11534     return SDValue();
11535 
11536   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11537   // Besides, more critical path instructions will be generated when dividing
11538   // by 2. So we keep using the original DAGs for these cases.
11539   unsigned Lg2 = Divisor.countTrailingZeros();
11540   if (Lg2 == 1 || Lg2 >= 12)
11541     return SDValue();
11542 
11543   // fold (sdiv X, pow2)
11544   EVT VT = N->getValueType(0);
11545   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11546     return SDValue();
11547 
11548   SDLoc DL(N);
11549   SDValue N0 = N->getOperand(0);
11550   SDValue Zero = DAG.getConstant(0, DL, VT);
11551   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11552 
11553   // Add (N0 < 0) ? Pow2 - 1 : 0;
11554   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11555   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11556   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11557 
11558   Created.push_back(Cmp.getNode());
11559   Created.push_back(Add.getNode());
11560   Created.push_back(Sel.getNode());
11561 
11562   // Divide by pow2.
11563   SDValue SRA =
11564       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11565 
11566   // If we're dividing by a positive value, we're done.  Otherwise, we must
11567   // negate the result.
11568   if (Divisor.isNonNegative())
11569     return SRA;
11570 
11571   Created.push_back(SRA.getNode());
11572   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11573 }
11574 
11575 #define GET_REGISTER_MATCHER
11576 #include "RISCVGenAsmMatcher.inc"
11577 
11578 Register
11579 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11580                                        const MachineFunction &MF) const {
11581   Register Reg = MatchRegisterAltName(RegName);
11582   if (Reg == RISCV::NoRegister)
11583     Reg = MatchRegisterName(RegName);
11584   if (Reg == RISCV::NoRegister)
11585     report_fatal_error(
11586         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11587   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11588   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11589     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11590                              StringRef(RegName) + "\"."));
11591   return Reg;
11592 }
11593 
11594 namespace llvm {
11595 namespace RISCVVIntrinsicsTable {
11596 
11597 #define GET_RISCVVIntrinsicsTable_IMPL
11598 #include "RISCVGenSearchableTables.inc"
11599 
11600 } // namespace RISCVVIntrinsicsTable
11601 
11602 } // namespace llvm
11603