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,      ISD::VP_FPTOSI,
494         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SEXT,
495         ISD::VP_ZEXT};
496 
497     static const unsigned FloatingPointVPOps[] = {
498         ISD::VP_FADD,        ISD::VP_FSUB,
499         ISD::VP_FMUL,        ISD::VP_FDIV,
500         ISD::VP_FNEG,        ISD::VP_FMA,
501         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
502         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
503         ISD::VP_MERGE,       ISD::VP_SELECT,
504         ISD::VP_SITOFP,      ISD::VP_UITOFP,
505         ISD::VP_SETCC};
506 
507     if (!Subtarget.is64Bit()) {
508       // We must custom-lower certain vXi64 operations on RV32 due to the vector
509       // element type being illegal.
510       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
511       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
512 
513       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
514       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
515       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
516       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
517       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
518       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
519       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
520       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
521 
522       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
523       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
524       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
525       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
526       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
527       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
528       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
529       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
530     }
531 
532     for (MVT VT : BoolVecVTs) {
533       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
534 
535       // Mask VTs are custom-expanded into a series of standard nodes
536       setOperationAction(ISD::TRUNCATE, VT, Custom);
537       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
538       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
539       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
540 
541       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
543 
544       setOperationAction(ISD::SELECT, VT, Custom);
545       setOperationAction(ISD::SELECT_CC, VT, Expand);
546       setOperationAction(ISD::VSELECT, VT, Expand);
547       setOperationAction(ISD::VP_MERGE, VT, Expand);
548       setOperationAction(ISD::VP_SELECT, VT, Expand);
549 
550       setOperationAction(ISD::VP_AND, VT, Custom);
551       setOperationAction(ISD::VP_OR, VT, Custom);
552       setOperationAction(ISD::VP_XOR, VT, Custom);
553 
554       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
555       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
556       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
557 
558       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
559       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
560       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
561 
562       // RVV has native int->float & float->int conversions where the
563       // element type sizes are within one power-of-two of each other. Any
564       // wider distances between type sizes have to be lowered as sequences
565       // which progressively narrow the gap in stages.
566       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
567       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
568       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
569       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
570 
571       // Expand all extending loads to types larger than this, and truncating
572       // stores from types larger than this.
573       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
574         setTruncStoreAction(OtherVT, VT, Expand);
575         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
576         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
577         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
578       }
579 
580       setOperationAction(ISD::VP_FPTOSI, VT, Custom);
581       setOperationAction(ISD::VP_FPTOUI, VT, Custom);
582     }
583 
584     for (MVT VT : IntVecVTs) {
585       if (VT.getVectorElementType() == MVT::i64 &&
586           !Subtarget.hasVInstructionsI64())
587         continue;
588 
589       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
590       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
591 
592       // Vectors implement MULHS/MULHU.
593       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
594       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
595 
596       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
597       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
598         setOperationAction(ISD::MULHU, VT, Expand);
599         setOperationAction(ISD::MULHS, VT, Expand);
600       }
601 
602       setOperationAction(ISD::SMIN, VT, Legal);
603       setOperationAction(ISD::SMAX, VT, Legal);
604       setOperationAction(ISD::UMIN, VT, Legal);
605       setOperationAction(ISD::UMAX, VT, Legal);
606 
607       setOperationAction(ISD::ROTL, VT, Expand);
608       setOperationAction(ISD::ROTR, VT, Expand);
609 
610       setOperationAction(ISD::CTTZ, VT, Expand);
611       setOperationAction(ISD::CTLZ, VT, Expand);
612       setOperationAction(ISD::CTPOP, VT, Expand);
613 
614       setOperationAction(ISD::BSWAP, VT, Expand);
615 
616       // Custom-lower extensions and truncations from/to mask types.
617       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
618       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
619       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
620 
621       // RVV has native int->float & float->int conversions where the
622       // element type sizes are within one power-of-two of each other. Any
623       // wider distances between type sizes have to be lowered as sequences
624       // which progressively narrow the gap in stages.
625       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
626       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
627       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
628       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
629 
630       setOperationAction(ISD::SADDSAT, VT, Legal);
631       setOperationAction(ISD::UADDSAT, VT, Legal);
632       setOperationAction(ISD::SSUBSAT, VT, Legal);
633       setOperationAction(ISD::USUBSAT, VT, Legal);
634 
635       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
636       // nodes which truncate by one power of two at a time.
637       setOperationAction(ISD::TRUNCATE, VT, Custom);
638 
639       // Custom-lower insert/extract operations to simplify patterns.
640       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
641       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
642 
643       // Custom-lower reduction operations to set up the corresponding custom
644       // nodes' operands.
645       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
646       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
647       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
648       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
649       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
650       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
651       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
652       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
653 
654       for (unsigned VPOpc : IntegerVPOps)
655         setOperationAction(VPOpc, VT, Custom);
656 
657       setOperationAction(ISD::LOAD, VT, Custom);
658       setOperationAction(ISD::STORE, VT, Custom);
659 
660       setOperationAction(ISD::MLOAD, VT, Custom);
661       setOperationAction(ISD::MSTORE, VT, Custom);
662       setOperationAction(ISD::MGATHER, VT, Custom);
663       setOperationAction(ISD::MSCATTER, VT, Custom);
664 
665       setOperationAction(ISD::VP_LOAD, VT, Custom);
666       setOperationAction(ISD::VP_STORE, VT, Custom);
667       setOperationAction(ISD::VP_GATHER, VT, Custom);
668       setOperationAction(ISD::VP_SCATTER, VT, Custom);
669 
670       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
671       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
672       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
673 
674       setOperationAction(ISD::SELECT, VT, Custom);
675       setOperationAction(ISD::SELECT_CC, VT, Expand);
676 
677       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
678       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
679 
680       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
681         setTruncStoreAction(VT, OtherVT, Expand);
682         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
683         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
684         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
685       }
686 
687       // Splice
688       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
689 
690       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
691       // type that can represent the value exactly.
692       if (VT.getVectorElementType() != MVT::i64) {
693         MVT FloatEltVT =
694             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
695         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
696         if (isTypeLegal(FloatVT)) {
697           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
698           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
699         }
700       }
701     }
702 
703     // Expand various CCs to best match the RVV ISA, which natively supports UNE
704     // but no other unordered comparisons, and supports all ordered comparisons
705     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
706     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
707     // and we pattern-match those back to the "original", swapping operands once
708     // more. This way we catch both operations and both "vf" and "fv" forms with
709     // fewer patterns.
710     static const ISD::CondCode VFPCCToExpand[] = {
711         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
712         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
713         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
714     };
715 
716     // Sets common operation actions on RVV floating-point vector types.
717     const auto SetCommonVFPActions = [&](MVT VT) {
718       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
719       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
720       // sizes are within one power-of-two of each other. Therefore conversions
721       // between vXf16 and vXf64 must be lowered as sequences which convert via
722       // vXf32.
723       setOperationAction(ISD::FP_ROUND, VT, Custom);
724       setOperationAction(ISD::FP_EXTEND, VT, Custom);
725       // Custom-lower insert/extract operations to simplify patterns.
726       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
727       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
728       // Expand various condition codes (explained above).
729       for (auto CC : VFPCCToExpand)
730         setCondCodeAction(CC, VT, Expand);
731 
732       setOperationAction(ISD::FMINNUM, VT, Legal);
733       setOperationAction(ISD::FMAXNUM, VT, Legal);
734 
735       setOperationAction(ISD::FTRUNC, VT, Custom);
736       setOperationAction(ISD::FCEIL, VT, Custom);
737       setOperationAction(ISD::FFLOOR, VT, Custom);
738       setOperationAction(ISD::FROUND, VT, Custom);
739 
740       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
741       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
742       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
743       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
744 
745       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
746 
747       setOperationAction(ISD::LOAD, VT, Custom);
748       setOperationAction(ISD::STORE, VT, Custom);
749 
750       setOperationAction(ISD::MLOAD, VT, Custom);
751       setOperationAction(ISD::MSTORE, VT, Custom);
752       setOperationAction(ISD::MGATHER, VT, Custom);
753       setOperationAction(ISD::MSCATTER, VT, Custom);
754 
755       setOperationAction(ISD::VP_LOAD, VT, Custom);
756       setOperationAction(ISD::VP_STORE, VT, Custom);
757       setOperationAction(ISD::VP_GATHER, VT, Custom);
758       setOperationAction(ISD::VP_SCATTER, VT, Custom);
759 
760       setOperationAction(ISD::SELECT, VT, Custom);
761       setOperationAction(ISD::SELECT_CC, VT, Expand);
762 
763       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
764       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
765       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
766 
767       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
768       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
769 
770       for (unsigned VPOpc : FloatingPointVPOps)
771         setOperationAction(VPOpc, VT, Custom);
772     };
773 
774     // Sets common extload/truncstore actions on RVV floating-point vector
775     // types.
776     const auto SetCommonVFPExtLoadTruncStoreActions =
777         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
778           for (auto SmallVT : SmallerVTs) {
779             setTruncStoreAction(VT, SmallVT, Expand);
780             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
781           }
782         };
783 
784     if (Subtarget.hasVInstructionsF16())
785       for (MVT VT : F16VecVTs)
786         SetCommonVFPActions(VT);
787 
788     for (MVT VT : F32VecVTs) {
789       if (Subtarget.hasVInstructionsF32())
790         SetCommonVFPActions(VT);
791       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
792     }
793 
794     for (MVT VT : F64VecVTs) {
795       if (Subtarget.hasVInstructionsF64())
796         SetCommonVFPActions(VT);
797       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
798       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
799     }
800 
801     if (Subtarget.useRVVForFixedLengthVectors()) {
802       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
803         if (!useRVVForFixedLengthVectorVT(VT))
804           continue;
805 
806         // By default everything must be expanded.
807         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
808           setOperationAction(Op, VT, Expand);
809         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
810           setTruncStoreAction(VT, OtherVT, Expand);
811           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
812           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
813           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
814         }
815 
816         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
817         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
818         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
819 
820         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
821         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
822 
823         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
824         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
825 
826         setOperationAction(ISD::LOAD, VT, Custom);
827         setOperationAction(ISD::STORE, VT, Custom);
828 
829         setOperationAction(ISD::SETCC, VT, Custom);
830 
831         setOperationAction(ISD::SELECT, VT, Custom);
832 
833         setOperationAction(ISD::TRUNCATE, VT, Custom);
834 
835         setOperationAction(ISD::BITCAST, VT, Custom);
836 
837         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
838         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
839         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
840 
841         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
842         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
843         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
844 
845         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
846         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
847         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
848         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
849 
850         // Operations below are different for between masks and other vectors.
851         if (VT.getVectorElementType() == MVT::i1) {
852           setOperationAction(ISD::VP_AND, VT, Custom);
853           setOperationAction(ISD::VP_OR, VT, Custom);
854           setOperationAction(ISD::VP_XOR, VT, Custom);
855           setOperationAction(ISD::AND, VT, Custom);
856           setOperationAction(ISD::OR, VT, Custom);
857           setOperationAction(ISD::XOR, VT, Custom);
858 
859           setOperationAction(ISD::VP_FPTOSI, VT, Custom);
860           setOperationAction(ISD::VP_FPTOUI, VT, Custom);
861           setOperationAction(ISD::VP_SETCC, VT, Custom);
862           continue;
863         }
864 
865         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
866         // it before type legalization for i64 vectors on RV32. It will then be
867         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
868         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
869         // improvements first.
870         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
871           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
872           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
873         }
874 
875         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
876         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
877 
878         setOperationAction(ISD::MLOAD, VT, Custom);
879         setOperationAction(ISD::MSTORE, VT, Custom);
880         setOperationAction(ISD::MGATHER, VT, Custom);
881         setOperationAction(ISD::MSCATTER, VT, Custom);
882 
883         setOperationAction(ISD::VP_LOAD, VT, Custom);
884         setOperationAction(ISD::VP_STORE, VT, Custom);
885         setOperationAction(ISD::VP_GATHER, VT, Custom);
886         setOperationAction(ISD::VP_SCATTER, VT, Custom);
887 
888         setOperationAction(ISD::ADD, VT, Custom);
889         setOperationAction(ISD::MUL, VT, Custom);
890         setOperationAction(ISD::SUB, VT, Custom);
891         setOperationAction(ISD::AND, VT, Custom);
892         setOperationAction(ISD::OR, VT, Custom);
893         setOperationAction(ISD::XOR, VT, Custom);
894         setOperationAction(ISD::SDIV, VT, Custom);
895         setOperationAction(ISD::SREM, VT, Custom);
896         setOperationAction(ISD::UDIV, VT, Custom);
897         setOperationAction(ISD::UREM, VT, Custom);
898         setOperationAction(ISD::SHL, VT, Custom);
899         setOperationAction(ISD::SRA, VT, Custom);
900         setOperationAction(ISD::SRL, VT, Custom);
901 
902         setOperationAction(ISD::SMIN, VT, Custom);
903         setOperationAction(ISD::SMAX, VT, Custom);
904         setOperationAction(ISD::UMIN, VT, Custom);
905         setOperationAction(ISD::UMAX, VT, Custom);
906         setOperationAction(ISD::ABS,  VT, Custom);
907 
908         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
909         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
910           setOperationAction(ISD::MULHS, VT, Custom);
911           setOperationAction(ISD::MULHU, VT, Custom);
912         }
913 
914         setOperationAction(ISD::SADDSAT, VT, Custom);
915         setOperationAction(ISD::UADDSAT, VT, Custom);
916         setOperationAction(ISD::SSUBSAT, VT, Custom);
917         setOperationAction(ISD::USUBSAT, VT, Custom);
918 
919         setOperationAction(ISD::VSELECT, VT, Custom);
920         setOperationAction(ISD::SELECT_CC, VT, Expand);
921 
922         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
923         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
924         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
925 
926         // Custom-lower reduction operations to set up the corresponding custom
927         // nodes' operands.
928         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
929         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
930         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
931         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
932         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
933 
934         for (unsigned VPOpc : IntegerVPOps)
935           setOperationAction(VPOpc, VT, Custom);
936 
937         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
938         // type that can represent the value exactly.
939         if (VT.getVectorElementType() != MVT::i64) {
940           MVT FloatEltVT =
941               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
942           EVT FloatVT =
943               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
944           if (isTypeLegal(FloatVT)) {
945             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
946             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
947           }
948         }
949       }
950 
951       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
952         if (!useRVVForFixedLengthVectorVT(VT))
953           continue;
954 
955         // By default everything must be expanded.
956         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
957           setOperationAction(Op, VT, Expand);
958         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
959           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
960           setTruncStoreAction(VT, OtherVT, Expand);
961         }
962 
963         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
964         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
965         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
966 
967         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
968         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
969         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
970         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
971         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
972 
973         setOperationAction(ISD::LOAD, VT, Custom);
974         setOperationAction(ISD::STORE, VT, Custom);
975         setOperationAction(ISD::MLOAD, VT, Custom);
976         setOperationAction(ISD::MSTORE, VT, Custom);
977         setOperationAction(ISD::MGATHER, VT, Custom);
978         setOperationAction(ISD::MSCATTER, VT, Custom);
979 
980         setOperationAction(ISD::VP_LOAD, VT, Custom);
981         setOperationAction(ISD::VP_STORE, VT, Custom);
982         setOperationAction(ISD::VP_GATHER, VT, Custom);
983         setOperationAction(ISD::VP_SCATTER, VT, Custom);
984 
985         setOperationAction(ISD::FADD, VT, Custom);
986         setOperationAction(ISD::FSUB, VT, Custom);
987         setOperationAction(ISD::FMUL, VT, Custom);
988         setOperationAction(ISD::FDIV, VT, Custom);
989         setOperationAction(ISD::FNEG, VT, Custom);
990         setOperationAction(ISD::FABS, VT, Custom);
991         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
992         setOperationAction(ISD::FSQRT, VT, Custom);
993         setOperationAction(ISD::FMA, VT, Custom);
994         setOperationAction(ISD::FMINNUM, VT, Custom);
995         setOperationAction(ISD::FMAXNUM, VT, Custom);
996 
997         setOperationAction(ISD::FP_ROUND, VT, Custom);
998         setOperationAction(ISD::FP_EXTEND, VT, Custom);
999 
1000         setOperationAction(ISD::FTRUNC, VT, Custom);
1001         setOperationAction(ISD::FCEIL, VT, Custom);
1002         setOperationAction(ISD::FFLOOR, VT, Custom);
1003         setOperationAction(ISD::FROUND, VT, Custom);
1004 
1005         for (auto CC : VFPCCToExpand)
1006           setCondCodeAction(CC, VT, Expand);
1007 
1008         setOperationAction(ISD::VSELECT, VT, Custom);
1009         setOperationAction(ISD::SELECT, VT, Custom);
1010         setOperationAction(ISD::SELECT_CC, VT, Expand);
1011 
1012         setOperationAction(ISD::BITCAST, VT, Custom);
1013 
1014         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1015         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1016         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1017         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1018 
1019         for (unsigned VPOpc : FloatingPointVPOps)
1020           setOperationAction(VPOpc, VT, Custom);
1021       }
1022 
1023       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1024       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1025       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1026       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1027       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1028       if (Subtarget.hasStdExtZfh())
1029         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1030       if (Subtarget.hasStdExtF())
1031         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1032       if (Subtarget.hasStdExtD())
1033         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1034     }
1035   }
1036 
1037   // Function alignments.
1038   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1039   setMinFunctionAlignment(FunctionAlignment);
1040   setPrefFunctionAlignment(FunctionAlignment);
1041 
1042   setMinimumJumpTableEntries(5);
1043 
1044   // Jumps are expensive, compared to logic
1045   setJumpIsExpensive();
1046 
1047   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
1048                        ISD::OR, ISD::XOR});
1049 
1050   if (Subtarget.hasStdExtZbp())
1051     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
1052   if (Subtarget.hasStdExtZbkb())
1053     setTargetDAGCombine(ISD::BITREVERSE);
1054   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1055     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1056   if (Subtarget.hasStdExtF())
1057     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1058                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
1059   if (Subtarget.hasVInstructions())
1060     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
1061                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
1062                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
1063 
1064   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1065   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1066 }
1067 
1068 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1069                                             LLVMContext &Context,
1070                                             EVT VT) const {
1071   if (!VT.isVector())
1072     return getPointerTy(DL);
1073   if (Subtarget.hasVInstructions() &&
1074       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1075     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1076   return VT.changeVectorElementTypeToInteger();
1077 }
1078 
1079 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1080   return Subtarget.getXLenVT();
1081 }
1082 
1083 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1084                                              const CallInst &I,
1085                                              MachineFunction &MF,
1086                                              unsigned Intrinsic) const {
1087   auto &DL = I.getModule()->getDataLayout();
1088   switch (Intrinsic) {
1089   default:
1090     return false;
1091   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1092   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1093   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1094   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1099   case Intrinsic::riscv_masked_cmpxchg_i32:
1100     Info.opc = ISD::INTRINSIC_W_CHAIN;
1101     Info.memVT = MVT::i32;
1102     Info.ptrVal = I.getArgOperand(0);
1103     Info.offset = 0;
1104     Info.align = Align(4);
1105     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1106                  MachineMemOperand::MOVolatile;
1107     return true;
1108   case Intrinsic::riscv_masked_strided_load:
1109     Info.opc = ISD::INTRINSIC_W_CHAIN;
1110     Info.ptrVal = I.getArgOperand(1);
1111     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1112     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1113     Info.size = MemoryLocation::UnknownSize;
1114     Info.flags |= MachineMemOperand::MOLoad;
1115     return true;
1116   case Intrinsic::riscv_masked_strided_store:
1117     Info.opc = ISD::INTRINSIC_VOID;
1118     Info.ptrVal = I.getArgOperand(1);
1119     Info.memVT =
1120         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1121     Info.align = Align(
1122         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1123         8);
1124     Info.size = MemoryLocation::UnknownSize;
1125     Info.flags |= MachineMemOperand::MOStore;
1126     return true;
1127   case Intrinsic::riscv_seg2_load:
1128   case Intrinsic::riscv_seg3_load:
1129   case Intrinsic::riscv_seg4_load:
1130   case Intrinsic::riscv_seg5_load:
1131   case Intrinsic::riscv_seg6_load:
1132   case Intrinsic::riscv_seg7_load:
1133   case Intrinsic::riscv_seg8_load:
1134     Info.opc = ISD::INTRINSIC_W_CHAIN;
1135     Info.ptrVal = I.getArgOperand(0);
1136     Info.memVT =
1137         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1138     Info.align =
1139         Align(DL.getTypeSizeInBits(
1140                   I.getType()->getStructElementType(0)->getScalarType()) /
1141               8);
1142     Info.size = MemoryLocation::UnknownSize;
1143     Info.flags |= MachineMemOperand::MOLoad;
1144     return true;
1145   }
1146 }
1147 
1148 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1149                                                 const AddrMode &AM, Type *Ty,
1150                                                 unsigned AS,
1151                                                 Instruction *I) const {
1152   // No global is ever allowed as a base.
1153   if (AM.BaseGV)
1154     return false;
1155 
1156   // Require a 12-bit signed offset.
1157   if (!isInt<12>(AM.BaseOffs))
1158     return false;
1159 
1160   switch (AM.Scale) {
1161   case 0: // "r+i" or just "i", depending on HasBaseReg.
1162     break;
1163   case 1:
1164     if (!AM.HasBaseReg) // allow "r+i".
1165       break;
1166     return false; // disallow "r+r" or "r+r+i".
1167   default:
1168     return false;
1169   }
1170 
1171   return true;
1172 }
1173 
1174 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1175   return isInt<12>(Imm);
1176 }
1177 
1178 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1179   return isInt<12>(Imm);
1180 }
1181 
1182 // On RV32, 64-bit integers are split into their high and low parts and held
1183 // in two different registers, so the trunc is free since the low register can
1184 // just be used.
1185 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1186   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1187     return false;
1188   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1189   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1190   return (SrcBits == 64 && DestBits == 32);
1191 }
1192 
1193 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1194   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1195       !SrcVT.isInteger() || !DstVT.isInteger())
1196     return false;
1197   unsigned SrcBits = SrcVT.getSizeInBits();
1198   unsigned DestBits = DstVT.getSizeInBits();
1199   return (SrcBits == 64 && DestBits == 32);
1200 }
1201 
1202 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1203   // Zexts are free if they can be combined with a load.
1204   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1205   // poorly with type legalization of compares preferring sext.
1206   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1207     EVT MemVT = LD->getMemoryVT();
1208     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1209         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1210          LD->getExtensionType() == ISD::ZEXTLOAD))
1211       return true;
1212   }
1213 
1214   return TargetLowering::isZExtFree(Val, VT2);
1215 }
1216 
1217 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1218   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1219 }
1220 
1221 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1222   return Subtarget.hasStdExtZbb();
1223 }
1224 
1225 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1226   return Subtarget.hasStdExtZbb();
1227 }
1228 
1229 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1230   EVT VT = Y.getValueType();
1231 
1232   // FIXME: Support vectors once we have tests.
1233   if (VT.isVector())
1234     return false;
1235 
1236   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1237           Subtarget.hasStdExtZbkb()) &&
1238          !isa<ConstantSDNode>(Y);
1239 }
1240 
1241 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1242   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1243   auto *C = dyn_cast<ConstantSDNode>(Y);
1244   return C && C->getAPIntValue().ule(10);
1245 }
1246 
1247 /// Check if sinking \p I's operands to I's basic block is profitable, because
1248 /// the operands can be folded into a target instruction, e.g.
1249 /// splats of scalars can fold into vector instructions.
1250 bool RISCVTargetLowering::shouldSinkOperands(
1251     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1252   using namespace llvm::PatternMatch;
1253 
1254   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1255     return false;
1256 
1257   auto IsSinker = [&](Instruction *I, int Operand) {
1258     switch (I->getOpcode()) {
1259     case Instruction::Add:
1260     case Instruction::Sub:
1261     case Instruction::Mul:
1262     case Instruction::And:
1263     case Instruction::Or:
1264     case Instruction::Xor:
1265     case Instruction::FAdd:
1266     case Instruction::FSub:
1267     case Instruction::FMul:
1268     case Instruction::FDiv:
1269     case Instruction::ICmp:
1270     case Instruction::FCmp:
1271       return true;
1272     case Instruction::Shl:
1273     case Instruction::LShr:
1274     case Instruction::AShr:
1275     case Instruction::UDiv:
1276     case Instruction::SDiv:
1277     case Instruction::URem:
1278     case Instruction::SRem:
1279       return Operand == 1;
1280     case Instruction::Call:
1281       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1282         switch (II->getIntrinsicID()) {
1283         case Intrinsic::fma:
1284         case Intrinsic::vp_fma:
1285           return Operand == 0 || Operand == 1;
1286         // FIXME: Our patterns can only match vx/vf instructions when the splat
1287         // it on the RHS, because TableGen doesn't recognize our VP operations
1288         // as commutative.
1289         case Intrinsic::vp_add:
1290         case Intrinsic::vp_mul:
1291         case Intrinsic::vp_and:
1292         case Intrinsic::vp_or:
1293         case Intrinsic::vp_xor:
1294         case Intrinsic::vp_fadd:
1295         case Intrinsic::vp_fmul:
1296         case Intrinsic::vp_shl:
1297         case Intrinsic::vp_lshr:
1298         case Intrinsic::vp_ashr:
1299         case Intrinsic::vp_udiv:
1300         case Intrinsic::vp_sdiv:
1301         case Intrinsic::vp_urem:
1302         case Intrinsic::vp_srem:
1303           return Operand == 1;
1304         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1305         // explicit patterns for both LHS and RHS (as 'vr' versions).
1306         case Intrinsic::vp_sub:
1307         case Intrinsic::vp_fsub:
1308         case Intrinsic::vp_fdiv:
1309           return Operand == 0 || Operand == 1;
1310         default:
1311           return false;
1312         }
1313       }
1314       return false;
1315     default:
1316       return false;
1317     }
1318   };
1319 
1320   for (auto OpIdx : enumerate(I->operands())) {
1321     if (!IsSinker(I, OpIdx.index()))
1322       continue;
1323 
1324     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1325     // Make sure we are not already sinking this operand
1326     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1327       continue;
1328 
1329     // We are looking for a splat that can be sunk.
1330     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1331                              m_Undef(), m_ZeroMask())))
1332       continue;
1333 
1334     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1335     // and vector registers
1336     for (Use &U : Op->uses()) {
1337       Instruction *Insn = cast<Instruction>(U.getUser());
1338       if (!IsSinker(Insn, U.getOperandNo()))
1339         return false;
1340     }
1341 
1342     Ops.push_back(&Op->getOperandUse(0));
1343     Ops.push_back(&OpIdx.value());
1344   }
1345   return true;
1346 }
1347 
1348 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1349                                        bool ForCodeSize) const {
1350   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1351   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1352     return false;
1353   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1354     return false;
1355   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1356     return false;
1357   return Imm.isZero();
1358 }
1359 
1360 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1361   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1362          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1363          (VT == MVT::f64 && Subtarget.hasStdExtD());
1364 }
1365 
1366 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1367                                                       CallingConv::ID CC,
1368                                                       EVT VT) const {
1369   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1370   // We might still end up using a GPR but that will be decided based on ABI.
1371   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1372   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1373     return MVT::f32;
1374 
1375   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1376 }
1377 
1378 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1379                                                            CallingConv::ID CC,
1380                                                            EVT VT) const {
1381   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1382   // We might still end up using a GPR but that will be decided based on ABI.
1383   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1384   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1385     return 1;
1386 
1387   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1388 }
1389 
1390 // Changes the condition code and swaps operands if necessary, so the SetCC
1391 // operation matches one of the comparisons supported directly by branches
1392 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1393 // with 1/-1.
1394 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1395                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1396   // Convert X > -1 to X >= 0.
1397   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1398     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1399     CC = ISD::SETGE;
1400     return;
1401   }
1402   // Convert X < 1 to 0 >= X.
1403   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1404     RHS = LHS;
1405     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1406     CC = ISD::SETGE;
1407     return;
1408   }
1409 
1410   switch (CC) {
1411   default:
1412     break;
1413   case ISD::SETGT:
1414   case ISD::SETLE:
1415   case ISD::SETUGT:
1416   case ISD::SETULE:
1417     CC = ISD::getSetCCSwappedOperands(CC);
1418     std::swap(LHS, RHS);
1419     break;
1420   }
1421 }
1422 
1423 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1424   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1425   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1426   if (VT.getVectorElementType() == MVT::i1)
1427     KnownSize *= 8;
1428 
1429   switch (KnownSize) {
1430   default:
1431     llvm_unreachable("Invalid LMUL.");
1432   case 8:
1433     return RISCVII::VLMUL::LMUL_F8;
1434   case 16:
1435     return RISCVII::VLMUL::LMUL_F4;
1436   case 32:
1437     return RISCVII::VLMUL::LMUL_F2;
1438   case 64:
1439     return RISCVII::VLMUL::LMUL_1;
1440   case 128:
1441     return RISCVII::VLMUL::LMUL_2;
1442   case 256:
1443     return RISCVII::VLMUL::LMUL_4;
1444   case 512:
1445     return RISCVII::VLMUL::LMUL_8;
1446   }
1447 }
1448 
1449 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1450   switch (LMul) {
1451   default:
1452     llvm_unreachable("Invalid LMUL.");
1453   case RISCVII::VLMUL::LMUL_F8:
1454   case RISCVII::VLMUL::LMUL_F4:
1455   case RISCVII::VLMUL::LMUL_F2:
1456   case RISCVII::VLMUL::LMUL_1:
1457     return RISCV::VRRegClassID;
1458   case RISCVII::VLMUL::LMUL_2:
1459     return RISCV::VRM2RegClassID;
1460   case RISCVII::VLMUL::LMUL_4:
1461     return RISCV::VRM4RegClassID;
1462   case RISCVII::VLMUL::LMUL_8:
1463     return RISCV::VRM8RegClassID;
1464   }
1465 }
1466 
1467 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1468   RISCVII::VLMUL LMUL = getLMUL(VT);
1469   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1470       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1471       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1472       LMUL == RISCVII::VLMUL::LMUL_1) {
1473     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1474                   "Unexpected subreg numbering");
1475     return RISCV::sub_vrm1_0 + Index;
1476   }
1477   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1478     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1479                   "Unexpected subreg numbering");
1480     return RISCV::sub_vrm2_0 + Index;
1481   }
1482   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1483     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1484                   "Unexpected subreg numbering");
1485     return RISCV::sub_vrm4_0 + Index;
1486   }
1487   llvm_unreachable("Invalid vector type.");
1488 }
1489 
1490 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1491   if (VT.getVectorElementType() == MVT::i1)
1492     return RISCV::VRRegClassID;
1493   return getRegClassIDForLMUL(getLMUL(VT));
1494 }
1495 
1496 // Attempt to decompose a subvector insert/extract between VecVT and
1497 // SubVecVT via subregister indices. Returns the subregister index that
1498 // can perform the subvector insert/extract with the given element index, as
1499 // well as the index corresponding to any leftover subvectors that must be
1500 // further inserted/extracted within the register class for SubVecVT.
1501 std::pair<unsigned, unsigned>
1502 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1503     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1504     const RISCVRegisterInfo *TRI) {
1505   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1506                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1507                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1508                 "Register classes not ordered");
1509   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1510   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1511   // Try to compose a subregister index that takes us from the incoming
1512   // LMUL>1 register class down to the outgoing one. At each step we half
1513   // the LMUL:
1514   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1515   // Note that this is not guaranteed to find a subregister index, such as
1516   // when we are extracting from one VR type to another.
1517   unsigned SubRegIdx = RISCV::NoSubRegister;
1518   for (const unsigned RCID :
1519        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1520     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1521       VecVT = VecVT.getHalfNumVectorElementsVT();
1522       bool IsHi =
1523           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1524       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1525                                             getSubregIndexByMVT(VecVT, IsHi));
1526       if (IsHi)
1527         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1528     }
1529   return {SubRegIdx, InsertExtractIdx};
1530 }
1531 
1532 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1533 // stores for those types.
1534 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1535   return !Subtarget.useRVVForFixedLengthVectors() ||
1536          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1537 }
1538 
1539 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1540   if (ScalarTy->isPointerTy())
1541     return true;
1542 
1543   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1544       ScalarTy->isIntegerTy(32))
1545     return true;
1546 
1547   if (ScalarTy->isIntegerTy(64))
1548     return Subtarget.hasVInstructionsI64();
1549 
1550   if (ScalarTy->isHalfTy())
1551     return Subtarget.hasVInstructionsF16();
1552   if (ScalarTy->isFloatTy())
1553     return Subtarget.hasVInstructionsF32();
1554   if (ScalarTy->isDoubleTy())
1555     return Subtarget.hasVInstructionsF64();
1556 
1557   return false;
1558 }
1559 
1560 static SDValue getVLOperand(SDValue Op) {
1561   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1562           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1563          "Unexpected opcode");
1564   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1565   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1566   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1567       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1568   if (!II)
1569     return SDValue();
1570   return Op.getOperand(II->VLOperand + 1 + HasChain);
1571 }
1572 
1573 static bool useRVVForFixedLengthVectorVT(MVT VT,
1574                                          const RISCVSubtarget &Subtarget) {
1575   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1576   if (!Subtarget.useRVVForFixedLengthVectors())
1577     return false;
1578 
1579   // We only support a set of vector types with a consistent maximum fixed size
1580   // across all supported vector element types to avoid legalization issues.
1581   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1582   // fixed-length vector type we support is 1024 bytes.
1583   if (VT.getFixedSizeInBits() > 1024 * 8)
1584     return false;
1585 
1586   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1587 
1588   MVT EltVT = VT.getVectorElementType();
1589 
1590   // Don't use RVV for vectors we cannot scalarize if required.
1591   switch (EltVT.SimpleTy) {
1592   // i1 is supported but has different rules.
1593   default:
1594     return false;
1595   case MVT::i1:
1596     // Masks can only use a single register.
1597     if (VT.getVectorNumElements() > MinVLen)
1598       return false;
1599     MinVLen /= 8;
1600     break;
1601   case MVT::i8:
1602   case MVT::i16:
1603   case MVT::i32:
1604     break;
1605   case MVT::i64:
1606     if (!Subtarget.hasVInstructionsI64())
1607       return false;
1608     break;
1609   case MVT::f16:
1610     if (!Subtarget.hasVInstructionsF16())
1611       return false;
1612     break;
1613   case MVT::f32:
1614     if (!Subtarget.hasVInstructionsF32())
1615       return false;
1616     break;
1617   case MVT::f64:
1618     if (!Subtarget.hasVInstructionsF64())
1619       return false;
1620     break;
1621   }
1622 
1623   // Reject elements larger than ELEN.
1624   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1625     return false;
1626 
1627   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1628   // Don't use RVV for types that don't fit.
1629   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1630     return false;
1631 
1632   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1633   // the base fixed length RVV support in place.
1634   if (!VT.isPow2VectorType())
1635     return false;
1636 
1637   return true;
1638 }
1639 
1640 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1641   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1642 }
1643 
1644 // Return the largest legal scalable vector type that matches VT's element type.
1645 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1646                                             const RISCVSubtarget &Subtarget) {
1647   // This may be called before legal types are setup.
1648   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1649           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1650          "Expected legal fixed length vector!");
1651 
1652   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1653   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1654 
1655   MVT EltVT = VT.getVectorElementType();
1656   switch (EltVT.SimpleTy) {
1657   default:
1658     llvm_unreachable("unexpected element type for RVV container");
1659   case MVT::i1:
1660   case MVT::i8:
1661   case MVT::i16:
1662   case MVT::i32:
1663   case MVT::i64:
1664   case MVT::f16:
1665   case MVT::f32:
1666   case MVT::f64: {
1667     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1668     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1669     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1670     unsigned NumElts =
1671         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1672     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1673     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1674     return MVT::getScalableVectorVT(EltVT, NumElts);
1675   }
1676   }
1677 }
1678 
1679 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1680                                             const RISCVSubtarget &Subtarget) {
1681   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1682                                           Subtarget);
1683 }
1684 
1685 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1686   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1687 }
1688 
1689 // Grow V to consume an entire RVV register.
1690 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1691                                        const RISCVSubtarget &Subtarget) {
1692   assert(VT.isScalableVector() &&
1693          "Expected to convert into a scalable vector!");
1694   assert(V.getValueType().isFixedLengthVector() &&
1695          "Expected a fixed length vector operand!");
1696   SDLoc DL(V);
1697   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1698   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1699 }
1700 
1701 // Shrink V so it's just big enough to maintain a VT's worth of data.
1702 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1703                                          const RISCVSubtarget &Subtarget) {
1704   assert(VT.isFixedLengthVector() &&
1705          "Expected to convert into a fixed length vector!");
1706   assert(V.getValueType().isScalableVector() &&
1707          "Expected a scalable vector operand!");
1708   SDLoc DL(V);
1709   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1710   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1711 }
1712 
1713 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1714 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1715 // the vector type that it is contained in.
1716 static std::pair<SDValue, SDValue>
1717 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1718                 const RISCVSubtarget &Subtarget) {
1719   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1720   MVT XLenVT = Subtarget.getXLenVT();
1721   SDValue VL = VecVT.isFixedLengthVector()
1722                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1723                    : DAG.getRegister(RISCV::X0, XLenVT);
1724   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1725   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1726   return {Mask, VL};
1727 }
1728 
1729 // As above but assuming the given type is a scalable vector type.
1730 static std::pair<SDValue, SDValue>
1731 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1732                         const RISCVSubtarget &Subtarget) {
1733   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1734   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1735 }
1736 
1737 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1738 // of either is (currently) supported. This can get us into an infinite loop
1739 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1740 // as a ..., etc.
1741 // Until either (or both) of these can reliably lower any node, reporting that
1742 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1743 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1744 // which is not desirable.
1745 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1746     EVT VT, unsigned DefinedValues) const {
1747   return false;
1748 }
1749 
1750 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1751                                   const RISCVSubtarget &Subtarget) {
1752   // RISCV FP-to-int conversions saturate to the destination register size, but
1753   // don't produce 0 for nan. We can use a conversion instruction and fix the
1754   // nan case with a compare and a select.
1755   SDValue Src = Op.getOperand(0);
1756 
1757   EVT DstVT = Op.getValueType();
1758   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1759 
1760   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1761   unsigned Opc;
1762   if (SatVT == DstVT)
1763     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1764   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1765     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1766   else
1767     return SDValue();
1768   // FIXME: Support other SatVTs by clamping before or after the conversion.
1769 
1770   SDLoc DL(Op);
1771   SDValue FpToInt = DAG.getNode(
1772       Opc, DL, DstVT, Src,
1773       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1774 
1775   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1776   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1777 }
1778 
1779 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1780 // and back. Taking care to avoid converting values that are nan or already
1781 // correct.
1782 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1783 // have FRM dependencies modeled yet.
1784 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1785   MVT VT = Op.getSimpleValueType();
1786   assert(VT.isVector() && "Unexpected type");
1787 
1788   SDLoc DL(Op);
1789 
1790   // Freeze the source since we are increasing the number of uses.
1791   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1792 
1793   // Truncate to integer and convert back to FP.
1794   MVT IntVT = VT.changeVectorElementTypeToInteger();
1795   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1796   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1797 
1798   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1799 
1800   if (Op.getOpcode() == ISD::FCEIL) {
1801     // If the truncated value is the greater than or equal to the original
1802     // value, we've computed the ceil. Otherwise, we went the wrong way and
1803     // need to increase by 1.
1804     // FIXME: This should use a masked operation. Handle here or in isel?
1805     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1806                                  DAG.getConstantFP(1.0, DL, VT));
1807     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1808     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1809   } else if (Op.getOpcode() == ISD::FFLOOR) {
1810     // If the truncated value is the less than or equal to the original value,
1811     // we've computed the floor. Otherwise, we went the wrong way and need to
1812     // decrease by 1.
1813     // FIXME: This should use a masked operation. Handle here or in isel?
1814     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1815                                  DAG.getConstantFP(1.0, DL, VT));
1816     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1817     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1818   }
1819 
1820   // Restore the original sign so that -0.0 is preserved.
1821   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1822 
1823   // Determine the largest integer that can be represented exactly. This and
1824   // values larger than it don't have any fractional bits so don't need to
1825   // be converted.
1826   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1827   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1828   APFloat MaxVal = APFloat(FltSem);
1829   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1830                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1831   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1832 
1833   // If abs(Src) was larger than MaxVal or nan, keep it.
1834   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1835   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1836   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1837 }
1838 
1839 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1840 // This mode isn't supported in vector hardware on RISCV. But as long as we
1841 // aren't compiling with trapping math, we can emulate this with
1842 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1843 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1844 // dependencies modeled yet.
1845 // FIXME: Use masked operations to avoid final merge.
1846 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1847   MVT VT = Op.getSimpleValueType();
1848   assert(VT.isVector() && "Unexpected type");
1849 
1850   SDLoc DL(Op);
1851 
1852   // Freeze the source since we are increasing the number of uses.
1853   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1854 
1855   // We do the conversion on the absolute value and fix the sign at the end.
1856   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1857 
1858   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1859   bool Ignored;
1860   APFloat Point5Pred = APFloat(0.5f);
1861   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1862   Point5Pred.next(/*nextDown*/ true);
1863 
1864   // Add the adjustment.
1865   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1866                                DAG.getConstantFP(Point5Pred, DL, VT));
1867 
1868   // Truncate to integer and convert back to fp.
1869   MVT IntVT = VT.changeVectorElementTypeToInteger();
1870   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1871   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1872 
1873   // Restore the original sign.
1874   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1875 
1876   // Determine the largest integer that can be represented exactly. This and
1877   // values larger than it don't have any fractional bits so don't need to
1878   // be converted.
1879   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1880   APFloat MaxVal = APFloat(FltSem);
1881   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1882                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1883   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1884 
1885   // If abs(Src) was larger than MaxVal or nan, keep it.
1886   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1887   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1888   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1889 }
1890 
1891 struct VIDSequence {
1892   int64_t StepNumerator;
1893   unsigned StepDenominator;
1894   int64_t Addend;
1895 };
1896 
1897 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1898 // to the (non-zero) step S and start value X. This can be then lowered as the
1899 // RVV sequence (VID * S) + X, for example.
1900 // The step S is represented as an integer numerator divided by a positive
1901 // denominator. Note that the implementation currently only identifies
1902 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1903 // cannot detect 2/3, for example.
1904 // Note that this method will also match potentially unappealing index
1905 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1906 // determine whether this is worth generating code for.
1907 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1908   unsigned NumElts = Op.getNumOperands();
1909   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1910   if (!Op.getValueType().isInteger())
1911     return None;
1912 
1913   Optional<unsigned> SeqStepDenom;
1914   Optional<int64_t> SeqStepNum, SeqAddend;
1915   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1916   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1917   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1918     // Assume undef elements match the sequence; we just have to be careful
1919     // when interpolating across them.
1920     if (Op.getOperand(Idx).isUndef())
1921       continue;
1922     // The BUILD_VECTOR must be all constants.
1923     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1924       return None;
1925 
1926     uint64_t Val = Op.getConstantOperandVal(Idx) &
1927                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1928 
1929     if (PrevElt) {
1930       // Calculate the step since the last non-undef element, and ensure
1931       // it's consistent across the entire sequence.
1932       unsigned IdxDiff = Idx - PrevElt->second;
1933       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1934 
1935       // A zero-value value difference means that we're somewhere in the middle
1936       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1937       // step change before evaluating the sequence.
1938       if (ValDiff != 0) {
1939         int64_t Remainder = ValDiff % IdxDiff;
1940         // Normalize the step if it's greater than 1.
1941         if (Remainder != ValDiff) {
1942           // The difference must cleanly divide the element span.
1943           if (Remainder != 0)
1944             return None;
1945           ValDiff /= IdxDiff;
1946           IdxDiff = 1;
1947         }
1948 
1949         if (!SeqStepNum)
1950           SeqStepNum = ValDiff;
1951         else if (ValDiff != SeqStepNum)
1952           return None;
1953 
1954         if (!SeqStepDenom)
1955           SeqStepDenom = IdxDiff;
1956         else if (IdxDiff != *SeqStepDenom)
1957           return None;
1958       }
1959     }
1960 
1961     // Record and/or check any addend.
1962     if (SeqStepNum && SeqStepDenom) {
1963       uint64_t ExpectedVal =
1964           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1965       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1966       if (!SeqAddend)
1967         SeqAddend = Addend;
1968       else if (SeqAddend != Addend)
1969         return None;
1970     }
1971 
1972     // Record this non-undef element for later.
1973     if (!PrevElt || PrevElt->first != Val)
1974       PrevElt = std::make_pair(Val, Idx);
1975   }
1976   // We need to have logged both a step and an addend for this to count as
1977   // a legal index sequence.
1978   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1979     return None;
1980 
1981   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1982 }
1983 
1984 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1985 // and lower it as a VRGATHER_VX_VL from the source vector.
1986 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1987                                   SelectionDAG &DAG,
1988                                   const RISCVSubtarget &Subtarget) {
1989   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1990     return SDValue();
1991   SDValue Vec = SplatVal.getOperand(0);
1992   // Only perform this optimization on vectors of the same size for simplicity.
1993   if (Vec.getValueType() != VT)
1994     return SDValue();
1995   SDValue Idx = SplatVal.getOperand(1);
1996   // The index must be a legal type.
1997   if (Idx.getValueType() != Subtarget.getXLenVT())
1998     return SDValue();
1999 
2000   MVT ContainerVT = VT;
2001   if (VT.isFixedLengthVector()) {
2002     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2003     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2004   }
2005 
2006   SDValue Mask, VL;
2007   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2008 
2009   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2010                                Idx, Mask, VL);
2011 
2012   if (!VT.isFixedLengthVector())
2013     return Gather;
2014 
2015   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2016 }
2017 
2018 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2019                                  const RISCVSubtarget &Subtarget) {
2020   MVT VT = Op.getSimpleValueType();
2021   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2022 
2023   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2024 
2025   SDLoc DL(Op);
2026   SDValue Mask, VL;
2027   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2028 
2029   MVT XLenVT = Subtarget.getXLenVT();
2030   unsigned NumElts = Op.getNumOperands();
2031 
2032   if (VT.getVectorElementType() == MVT::i1) {
2033     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2034       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2035       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2036     }
2037 
2038     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2039       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2040       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2041     }
2042 
2043     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2044     // scalar integer chunks whose bit-width depends on the number of mask
2045     // bits and XLEN.
2046     // First, determine the most appropriate scalar integer type to use. This
2047     // is at most XLenVT, but may be shrunk to a smaller vector element type
2048     // according to the size of the final vector - use i8 chunks rather than
2049     // XLenVT if we're producing a v8i1. This results in more consistent
2050     // codegen across RV32 and RV64.
2051     unsigned NumViaIntegerBits =
2052         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2053     NumViaIntegerBits = std::min(NumViaIntegerBits,
2054                                  Subtarget.getMaxELENForFixedLengthVectors());
2055     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2056       // If we have to use more than one INSERT_VECTOR_ELT then this
2057       // optimization is likely to increase code size; avoid peforming it in
2058       // such a case. We can use a load from a constant pool in this case.
2059       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2060         return SDValue();
2061       // Now we can create our integer vector type. Note that it may be larger
2062       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2063       MVT IntegerViaVecVT =
2064           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2065                            divideCeil(NumElts, NumViaIntegerBits));
2066 
2067       uint64_t Bits = 0;
2068       unsigned BitPos = 0, IntegerEltIdx = 0;
2069       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2070 
2071       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2072         // Once we accumulate enough bits to fill our scalar type, insert into
2073         // our vector and clear our accumulated data.
2074         if (I != 0 && I % NumViaIntegerBits == 0) {
2075           if (NumViaIntegerBits <= 32)
2076             Bits = SignExtend64(Bits, 32);
2077           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2078           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2079                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2080           Bits = 0;
2081           BitPos = 0;
2082           IntegerEltIdx++;
2083         }
2084         SDValue V = Op.getOperand(I);
2085         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2086         Bits |= ((uint64_t)BitValue << BitPos);
2087       }
2088 
2089       // Insert the (remaining) scalar value into position in our integer
2090       // vector type.
2091       if (NumViaIntegerBits <= 32)
2092         Bits = SignExtend64(Bits, 32);
2093       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2094       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2095                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2096 
2097       if (NumElts < NumViaIntegerBits) {
2098         // If we're producing a smaller vector than our minimum legal integer
2099         // type, bitcast to the equivalent (known-legal) mask type, and extract
2100         // our final mask.
2101         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2102         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2103         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2104                           DAG.getConstant(0, DL, XLenVT));
2105       } else {
2106         // Else we must have produced an integer type with the same size as the
2107         // mask type; bitcast for the final result.
2108         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2109         Vec = DAG.getBitcast(VT, Vec);
2110       }
2111 
2112       return Vec;
2113     }
2114 
2115     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2116     // vector type, we have a legal equivalently-sized i8 type, so we can use
2117     // that.
2118     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2119     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2120 
2121     SDValue WideVec;
2122     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2123       // For a splat, perform a scalar truncate before creating the wider
2124       // vector.
2125       assert(Splat.getValueType() == XLenVT &&
2126              "Unexpected type for i1 splat value");
2127       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2128                           DAG.getConstant(1, DL, XLenVT));
2129       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2130     } else {
2131       SmallVector<SDValue, 8> Ops(Op->op_values());
2132       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2133       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2134       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2135     }
2136 
2137     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2138   }
2139 
2140   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2141     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2142       return Gather;
2143     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2144                                         : RISCVISD::VMV_V_X_VL;
2145     Splat =
2146         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2147     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2148   }
2149 
2150   // Try and match index sequences, which we can lower to the vid instruction
2151   // with optional modifications. An all-undef vector is matched by
2152   // getSplatValue, above.
2153   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2154     int64_t StepNumerator = SimpleVID->StepNumerator;
2155     unsigned StepDenominator = SimpleVID->StepDenominator;
2156     int64_t Addend = SimpleVID->Addend;
2157 
2158     assert(StepNumerator != 0 && "Invalid step");
2159     bool Negate = false;
2160     int64_t SplatStepVal = StepNumerator;
2161     unsigned StepOpcode = ISD::MUL;
2162     if (StepNumerator != 1) {
2163       if (isPowerOf2_64(std::abs(StepNumerator))) {
2164         Negate = StepNumerator < 0;
2165         StepOpcode = ISD::SHL;
2166         SplatStepVal = Log2_64(std::abs(StepNumerator));
2167       }
2168     }
2169 
2170     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2171     // threshold since it's the immediate value many RVV instructions accept.
2172     // There is no vmul.vi instruction so ensure multiply constant can fit in
2173     // a single addi instruction.
2174     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2175          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2176         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2177       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2178       // Convert right out of the scalable type so we can use standard ISD
2179       // nodes for the rest of the computation. If we used scalable types with
2180       // these, we'd lose the fixed-length vector info and generate worse
2181       // vsetvli code.
2182       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2183       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2184           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2185         SDValue SplatStep = DAG.getSplatBuildVector(
2186             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2187         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2188       }
2189       if (StepDenominator != 1) {
2190         SDValue SplatStep = DAG.getSplatBuildVector(
2191             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2192         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2193       }
2194       if (Addend != 0 || Negate) {
2195         SDValue SplatAddend = DAG.getSplatBuildVector(
2196             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2197         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2198       }
2199       return VID;
2200     }
2201   }
2202 
2203   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2204   // when re-interpreted as a vector with a larger element type. For example,
2205   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2206   // could be instead splat as
2207   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2208   // TODO: This optimization could also work on non-constant splats, but it
2209   // would require bit-manipulation instructions to construct the splat value.
2210   SmallVector<SDValue> Sequence;
2211   unsigned EltBitSize = VT.getScalarSizeInBits();
2212   const auto *BV = cast<BuildVectorSDNode>(Op);
2213   if (VT.isInteger() && EltBitSize < 64 &&
2214       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2215       BV->getRepeatedSequence(Sequence) &&
2216       (Sequence.size() * EltBitSize) <= 64) {
2217     unsigned SeqLen = Sequence.size();
2218     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2219     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2220     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2221             ViaIntVT == MVT::i64) &&
2222            "Unexpected sequence type");
2223 
2224     unsigned EltIdx = 0;
2225     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2226     uint64_t SplatValue = 0;
2227     // Construct the amalgamated value which can be splatted as this larger
2228     // vector type.
2229     for (const auto &SeqV : Sequence) {
2230       if (!SeqV.isUndef())
2231         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2232                        << (EltIdx * EltBitSize));
2233       EltIdx++;
2234     }
2235 
2236     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2237     // achieve better constant materializion.
2238     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2239       SplatValue = SignExtend64(SplatValue, 32);
2240 
2241     // Since we can't introduce illegal i64 types at this stage, we can only
2242     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2243     // way we can use RVV instructions to splat.
2244     assert((ViaIntVT.bitsLE(XLenVT) ||
2245             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2246            "Unexpected bitcast sequence");
2247     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2248       SDValue ViaVL =
2249           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2250       MVT ViaContainerVT =
2251           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2252       SDValue Splat =
2253           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2254                       DAG.getUNDEF(ViaContainerVT),
2255                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2256       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2257       return DAG.getBitcast(VT, Splat);
2258     }
2259   }
2260 
2261   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2262   // which constitute a large proportion of the elements. In such cases we can
2263   // splat a vector with the dominant element and make up the shortfall with
2264   // INSERT_VECTOR_ELTs.
2265   // Note that this includes vectors of 2 elements by association. The
2266   // upper-most element is the "dominant" one, allowing us to use a splat to
2267   // "insert" the upper element, and an insert of the lower element at position
2268   // 0, which improves codegen.
2269   SDValue DominantValue;
2270   unsigned MostCommonCount = 0;
2271   DenseMap<SDValue, unsigned> ValueCounts;
2272   unsigned NumUndefElts =
2273       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2274 
2275   // Track the number of scalar loads we know we'd be inserting, estimated as
2276   // any non-zero floating-point constant. Other kinds of element are either
2277   // already in registers or are materialized on demand. The threshold at which
2278   // a vector load is more desirable than several scalar materializion and
2279   // vector-insertion instructions is not known.
2280   unsigned NumScalarLoads = 0;
2281 
2282   for (SDValue V : Op->op_values()) {
2283     if (V.isUndef())
2284       continue;
2285 
2286     ValueCounts.insert(std::make_pair(V, 0));
2287     unsigned &Count = ValueCounts[V];
2288 
2289     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2290       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2291 
2292     // Is this value dominant? In case of a tie, prefer the highest element as
2293     // it's cheaper to insert near the beginning of a vector than it is at the
2294     // end.
2295     if (++Count >= MostCommonCount) {
2296       DominantValue = V;
2297       MostCommonCount = Count;
2298     }
2299   }
2300 
2301   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2302   unsigned NumDefElts = NumElts - NumUndefElts;
2303   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2304 
2305   // Don't perform this optimization when optimizing for size, since
2306   // materializing elements and inserting them tends to cause code bloat.
2307   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2308       ((MostCommonCount > DominantValueCountThreshold) ||
2309        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2310     // Start by splatting the most common element.
2311     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2312 
2313     DenseSet<SDValue> Processed{DominantValue};
2314     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2315     for (const auto &OpIdx : enumerate(Op->ops())) {
2316       const SDValue &V = OpIdx.value();
2317       if (V.isUndef() || !Processed.insert(V).second)
2318         continue;
2319       if (ValueCounts[V] == 1) {
2320         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2321                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2322       } else {
2323         // Blend in all instances of this value using a VSELECT, using a
2324         // mask where each bit signals whether that element is the one
2325         // we're after.
2326         SmallVector<SDValue> Ops;
2327         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2328           return DAG.getConstant(V == V1, DL, XLenVT);
2329         });
2330         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2331                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2332                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2333       }
2334     }
2335 
2336     return Vec;
2337   }
2338 
2339   return SDValue();
2340 }
2341 
2342 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2343                                    SDValue Lo, SDValue Hi, SDValue VL,
2344                                    SelectionDAG &DAG) {
2345   if (!Passthru)
2346     Passthru = DAG.getUNDEF(VT);
2347   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2348     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2349     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2350     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2351     // node in order to try and match RVV vector/scalar instructions.
2352     if ((LoC >> 31) == HiC)
2353       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2354 
2355     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2356     // vmv.v.x whose EEW = 32 to lower it.
2357     auto *Const = dyn_cast<ConstantSDNode>(VL);
2358     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2359       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2360       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2361       // access the subtarget here now.
2362       auto InterVec = DAG.getNode(
2363           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2364                                   DAG.getRegister(RISCV::X0, MVT::i32));
2365       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2366     }
2367   }
2368 
2369   // Fall back to a stack store and stride x0 vector load.
2370   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2371                      Hi, VL);
2372 }
2373 
2374 // Called by type legalization to handle splat of i64 on RV32.
2375 // FIXME: We can optimize this when the type has sign or zero bits in one
2376 // of the halves.
2377 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2378                                    SDValue Scalar, SDValue VL,
2379                                    SelectionDAG &DAG) {
2380   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2381   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2382                            DAG.getConstant(0, DL, MVT::i32));
2383   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2384                            DAG.getConstant(1, DL, MVT::i32));
2385   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2386 }
2387 
2388 // This function lowers a splat of a scalar operand Splat with the vector
2389 // length VL. It ensures the final sequence is type legal, which is useful when
2390 // lowering a splat after type legalization.
2391 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2392                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2393                                 const RISCVSubtarget &Subtarget) {
2394   bool HasPassthru = Passthru && !Passthru.isUndef();
2395   if (!HasPassthru && !Passthru)
2396     Passthru = DAG.getUNDEF(VT);
2397   if (VT.isFloatingPoint()) {
2398     // If VL is 1, we could use vfmv.s.f.
2399     if (isOneConstant(VL))
2400       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2401     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2402   }
2403 
2404   MVT XLenVT = Subtarget.getXLenVT();
2405 
2406   // Simplest case is that the operand needs to be promoted to XLenVT.
2407   if (Scalar.getValueType().bitsLE(XLenVT)) {
2408     // If the operand is a constant, sign extend to increase our chances
2409     // of being able to use a .vi instruction. ANY_EXTEND would become a
2410     // a zero extend and the simm5 check in isel would fail.
2411     // FIXME: Should we ignore the upper bits in isel instead?
2412     unsigned ExtOpc =
2413         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2414     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2415     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2416     // If VL is 1 and the scalar value won't benefit from immediate, we could
2417     // use vmv.s.x.
2418     if (isOneConstant(VL) &&
2419         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2420       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2421     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2422   }
2423 
2424   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2425          "Unexpected scalar for splat lowering!");
2426 
2427   if (isOneConstant(VL) && isNullConstant(Scalar))
2428     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2429                        DAG.getConstant(0, DL, XLenVT), VL);
2430 
2431   // Otherwise use the more complicated splatting algorithm.
2432   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2433 }
2434 
2435 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2436                                 const RISCVSubtarget &Subtarget) {
2437   // We need to be able to widen elements to the next larger integer type.
2438   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2439     return false;
2440 
2441   int Size = Mask.size();
2442   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2443 
2444   int Srcs[] = {-1, -1};
2445   for (int i = 0; i != Size; ++i) {
2446     // Ignore undef elements.
2447     if (Mask[i] < 0)
2448       continue;
2449 
2450     // Is this an even or odd element.
2451     int Pol = i % 2;
2452 
2453     // Ensure we consistently use the same source for this element polarity.
2454     int Src = Mask[i] / Size;
2455     if (Srcs[Pol] < 0)
2456       Srcs[Pol] = Src;
2457     if (Srcs[Pol] != Src)
2458       return false;
2459 
2460     // Make sure the element within the source is appropriate for this element
2461     // in the destination.
2462     int Elt = Mask[i] % Size;
2463     if (Elt != i / 2)
2464       return false;
2465   }
2466 
2467   // We need to find a source for each polarity and they can't be the same.
2468   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2469     return false;
2470 
2471   // Swap the sources if the second source was in the even polarity.
2472   SwapSources = Srcs[0] > Srcs[1];
2473 
2474   return true;
2475 }
2476 
2477 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2478 /// and then extract the original number of elements from the rotated result.
2479 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2480 /// returned rotation amount is for a rotate right, where elements move from
2481 /// higher elements to lower elements. \p LoSrc indicates the first source
2482 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2483 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2484 /// 0 or 1 if a rotation is found.
2485 ///
2486 /// NOTE: We talk about rotate to the right which matches how bit shift and
2487 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2488 /// and the table below write vectors with the lowest elements on the left.
2489 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2490   int Size = Mask.size();
2491 
2492   // We need to detect various ways of spelling a rotation:
2493   //   [11, 12, 13, 14, 15,  0,  1,  2]
2494   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2495   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2496   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2497   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2498   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2499   int Rotation = 0;
2500   LoSrc = -1;
2501   HiSrc = -1;
2502   for (int i = 0; i != Size; ++i) {
2503     int M = Mask[i];
2504     if (M < 0)
2505       continue;
2506 
2507     // Determine where a rotate vector would have started.
2508     int StartIdx = i - (M % Size);
2509     // The identity rotation isn't interesting, stop.
2510     if (StartIdx == 0)
2511       return -1;
2512 
2513     // If we found the tail of a vector the rotation must be the missing
2514     // front. If we found the head of a vector, it must be how much of the
2515     // head.
2516     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2517 
2518     if (Rotation == 0)
2519       Rotation = CandidateRotation;
2520     else if (Rotation != CandidateRotation)
2521       // The rotations don't match, so we can't match this mask.
2522       return -1;
2523 
2524     // Compute which value this mask is pointing at.
2525     int MaskSrc = M < Size ? 0 : 1;
2526 
2527     // Compute which of the two target values this index should be assigned to.
2528     // This reflects whether the high elements are remaining or the low elemnts
2529     // are remaining.
2530     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2531 
2532     // Either set up this value if we've not encountered it before, or check
2533     // that it remains consistent.
2534     if (TargetSrc < 0)
2535       TargetSrc = MaskSrc;
2536     else if (TargetSrc != MaskSrc)
2537       // This may be a rotation, but it pulls from the inputs in some
2538       // unsupported interleaving.
2539       return -1;
2540   }
2541 
2542   // Check that we successfully analyzed the mask, and normalize the results.
2543   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2544   assert((LoSrc >= 0 || HiSrc >= 0) &&
2545          "Failed to find a rotated input vector!");
2546 
2547   return Rotation;
2548 }
2549 
2550 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2551                                    const RISCVSubtarget &Subtarget) {
2552   SDValue V1 = Op.getOperand(0);
2553   SDValue V2 = Op.getOperand(1);
2554   SDLoc DL(Op);
2555   MVT XLenVT = Subtarget.getXLenVT();
2556   MVT VT = Op.getSimpleValueType();
2557   unsigned NumElts = VT.getVectorNumElements();
2558   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2559 
2560   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2561 
2562   SDValue TrueMask, VL;
2563   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2564 
2565   if (SVN->isSplat()) {
2566     const int Lane = SVN->getSplatIndex();
2567     if (Lane >= 0) {
2568       MVT SVT = VT.getVectorElementType();
2569 
2570       // Turn splatted vector load into a strided load with an X0 stride.
2571       SDValue V = V1;
2572       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2573       // with undef.
2574       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2575       int Offset = Lane;
2576       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2577         int OpElements =
2578             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2579         V = V.getOperand(Offset / OpElements);
2580         Offset %= OpElements;
2581       }
2582 
2583       // We need to ensure the load isn't atomic or volatile.
2584       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2585         auto *Ld = cast<LoadSDNode>(V);
2586         Offset *= SVT.getStoreSize();
2587         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2588                                                    TypeSize::Fixed(Offset), DL);
2589 
2590         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2591         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2592           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2593           SDValue IntID =
2594               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2595           SDValue Ops[] = {Ld->getChain(),
2596                            IntID,
2597                            DAG.getUNDEF(ContainerVT),
2598                            NewAddr,
2599                            DAG.getRegister(RISCV::X0, XLenVT),
2600                            VL};
2601           SDValue NewLoad = DAG.getMemIntrinsicNode(
2602               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2603               DAG.getMachineFunction().getMachineMemOperand(
2604                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2605           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2606           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2607         }
2608 
2609         // Otherwise use a scalar load and splat. This will give the best
2610         // opportunity to fold a splat into the operation. ISel can turn it into
2611         // the x0 strided load if we aren't able to fold away the select.
2612         if (SVT.isFloatingPoint())
2613           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2614                           Ld->getPointerInfo().getWithOffset(Offset),
2615                           Ld->getOriginalAlign(),
2616                           Ld->getMemOperand()->getFlags());
2617         else
2618           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2619                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2620                              Ld->getOriginalAlign(),
2621                              Ld->getMemOperand()->getFlags());
2622         DAG.makeEquivalentMemoryOrdering(Ld, V);
2623 
2624         unsigned Opc =
2625             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2626         SDValue Splat =
2627             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2628         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2629       }
2630 
2631       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2632       assert(Lane < (int)NumElts && "Unexpected lane!");
2633       SDValue Gather =
2634           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2635                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2636       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2637     }
2638   }
2639 
2640   ArrayRef<int> Mask = SVN->getMask();
2641 
2642   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2643   // be undef which can be handled with a single SLIDEDOWN/UP.
2644   int LoSrc, HiSrc;
2645   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2646   if (Rotation > 0) {
2647     SDValue LoV, HiV;
2648     if (LoSrc >= 0) {
2649       LoV = LoSrc == 0 ? V1 : V2;
2650       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2651     }
2652     if (HiSrc >= 0) {
2653       HiV = HiSrc == 0 ? V1 : V2;
2654       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2655     }
2656 
2657     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2658     // to slide LoV up by (NumElts - Rotation).
2659     unsigned InvRotate = NumElts - Rotation;
2660 
2661     SDValue Res = DAG.getUNDEF(ContainerVT);
2662     if (HiV) {
2663       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2664       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2665       // causes multiple vsetvlis in some test cases such as lowering
2666       // reduce.mul
2667       SDValue DownVL = VL;
2668       if (LoV)
2669         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2670       Res =
2671           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2672                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2673     }
2674     if (LoV)
2675       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2676                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2677 
2678     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2679   }
2680 
2681   // Detect an interleave shuffle and lower to
2682   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2683   bool SwapSources;
2684   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2685     // Swap sources if needed.
2686     if (SwapSources)
2687       std::swap(V1, V2);
2688 
2689     // Extract the lower half of the vectors.
2690     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2691     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2692                      DAG.getConstant(0, DL, XLenVT));
2693     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2694                      DAG.getConstant(0, DL, XLenVT));
2695 
2696     // Double the element width and halve the number of elements in an int type.
2697     unsigned EltBits = VT.getScalarSizeInBits();
2698     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2699     MVT WideIntVT =
2700         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2701     // Convert this to a scalable vector. We need to base this on the
2702     // destination size to ensure there's always a type with a smaller LMUL.
2703     MVT WideIntContainerVT =
2704         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2705 
2706     // Convert sources to scalable vectors with the same element count as the
2707     // larger type.
2708     MVT HalfContainerVT = MVT::getVectorVT(
2709         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2710     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2711     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2712 
2713     // Cast sources to integer.
2714     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2715     MVT IntHalfVT =
2716         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2717     V1 = DAG.getBitcast(IntHalfVT, V1);
2718     V2 = DAG.getBitcast(IntHalfVT, V2);
2719 
2720     // Freeze V2 since we use it twice and we need to be sure that the add and
2721     // multiply see the same value.
2722     V2 = DAG.getFreeze(V2);
2723 
2724     // Recreate TrueMask using the widened type's element count.
2725     MVT MaskVT =
2726         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2727     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2728 
2729     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2730     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2731                               V2, TrueMask, VL);
2732     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2733     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2734                                      DAG.getUNDEF(IntHalfVT),
2735                                      DAG.getAllOnesConstant(DL, XLenVT));
2736     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2737                                    V2, Multiplier, TrueMask, VL);
2738     // Add the new copies to our previous addition giving us 2^eltbits copies of
2739     // V2. This is equivalent to shifting V2 left by eltbits. This should
2740     // combine with the vwmulu.vv above to form vwmaccu.vv.
2741     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2742                       TrueMask, VL);
2743     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2744     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2745     // vector VT.
2746     ContainerVT =
2747         MVT::getVectorVT(VT.getVectorElementType(),
2748                          WideIntContainerVT.getVectorElementCount() * 2);
2749     Add = DAG.getBitcast(ContainerVT, Add);
2750     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2751   }
2752 
2753   // Detect shuffles which can be re-expressed as vector selects; these are
2754   // shuffles in which each element in the destination is taken from an element
2755   // at the corresponding index in either source vectors.
2756   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2757     int MaskIndex = MaskIdx.value();
2758     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2759   });
2760 
2761   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2762 
2763   SmallVector<SDValue> MaskVals;
2764   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2765   // merged with a second vrgather.
2766   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2767 
2768   // By default we preserve the original operand order, and use a mask to
2769   // select LHS as true and RHS as false. However, since RVV vector selects may
2770   // feature splats but only on the LHS, we may choose to invert our mask and
2771   // instead select between RHS and LHS.
2772   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2773   bool InvertMask = IsSelect == SwapOps;
2774 
2775   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2776   // half.
2777   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2778 
2779   // Now construct the mask that will be used by the vselect or blended
2780   // vrgather operation. For vrgathers, construct the appropriate indices into
2781   // each vector.
2782   for (int MaskIndex : Mask) {
2783     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2784     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2785     if (!IsSelect) {
2786       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2787       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2788                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2789                                      : DAG.getUNDEF(XLenVT));
2790       GatherIndicesRHS.push_back(
2791           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2792                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2793       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2794         ++LHSIndexCounts[MaskIndex];
2795       if (!IsLHSOrUndefIndex)
2796         ++RHSIndexCounts[MaskIndex - NumElts];
2797     }
2798   }
2799 
2800   if (SwapOps) {
2801     std::swap(V1, V2);
2802     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2803   }
2804 
2805   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2806   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2807   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2808 
2809   if (IsSelect)
2810     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2811 
2812   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2813     // On such a large vector we're unable to use i8 as the index type.
2814     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2815     // may involve vector splitting if we're already at LMUL=8, or our
2816     // user-supplied maximum fixed-length LMUL.
2817     return SDValue();
2818   }
2819 
2820   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2821   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2822   MVT IndexVT = VT.changeTypeToInteger();
2823   // Since we can't introduce illegal index types at this stage, use i16 and
2824   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2825   // than XLenVT.
2826   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2827     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2828     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2829   }
2830 
2831   MVT IndexContainerVT =
2832       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2833 
2834   SDValue Gather;
2835   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2836   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2837   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2838     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2839                               Subtarget);
2840   } else {
2841     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2842     // If only one index is used, we can use a "splat" vrgather.
2843     // TODO: We can splat the most-common index and fix-up any stragglers, if
2844     // that's beneficial.
2845     if (LHSIndexCounts.size() == 1) {
2846       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2847       Gather =
2848           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2849                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2850     } else {
2851       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2852       LHSIndices =
2853           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2854 
2855       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2856                            TrueMask, VL);
2857     }
2858   }
2859 
2860   // If a second vector operand is used by this shuffle, blend it in with an
2861   // additional vrgather.
2862   if (!V2.isUndef()) {
2863     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2864     // If only one index is used, we can use a "splat" vrgather.
2865     // TODO: We can splat the most-common index and fix-up any stragglers, if
2866     // that's beneficial.
2867     if (RHSIndexCounts.size() == 1) {
2868       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2869       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2870                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2871     } else {
2872       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2873       RHSIndices =
2874           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2875       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2876                        VL);
2877     }
2878 
2879     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2880     SelectMask =
2881         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2882 
2883     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2884                          Gather, VL);
2885   }
2886 
2887   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2888 }
2889 
2890 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2891   // Support splats for any type. These should type legalize well.
2892   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2893     return true;
2894 
2895   // Only support legal VTs for other shuffles for now.
2896   if (!isTypeLegal(VT))
2897     return false;
2898 
2899   MVT SVT = VT.getSimpleVT();
2900 
2901   bool SwapSources;
2902   int LoSrc, HiSrc;
2903   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2904          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2905 }
2906 
2907 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2908                                      SDLoc DL, SelectionDAG &DAG,
2909                                      const RISCVSubtarget &Subtarget) {
2910   if (VT.isScalableVector())
2911     return DAG.getFPExtendOrRound(Op, DL, VT);
2912   assert(VT.isFixedLengthVector() &&
2913          "Unexpected value type for RVV FP extend/round lowering");
2914   SDValue Mask, VL;
2915   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2916   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2917                         ? RISCVISD::FP_EXTEND_VL
2918                         : RISCVISD::FP_ROUND_VL;
2919   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2920 }
2921 
2922 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2923 // the exponent.
2924 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2925   MVT VT = Op.getSimpleValueType();
2926   unsigned EltSize = VT.getScalarSizeInBits();
2927   SDValue Src = Op.getOperand(0);
2928   SDLoc DL(Op);
2929 
2930   // We need a FP type that can represent the value.
2931   // TODO: Use f16 for i8 when possible?
2932   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2933   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2934 
2935   // Legal types should have been checked in the RISCVTargetLowering
2936   // constructor.
2937   // TODO: Splitting may make sense in some cases.
2938   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2939          "Expected legal float type!");
2940 
2941   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2942   // The trailing zero count is equal to log2 of this single bit value.
2943   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2944     SDValue Neg =
2945         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2946     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2947   }
2948 
2949   // We have a legal FP type, convert to it.
2950   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2951   // Bitcast to integer and shift the exponent to the LSB.
2952   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2953   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2954   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2955   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2956                               DAG.getConstant(ShiftAmt, DL, IntVT));
2957   // Truncate back to original type to allow vnsrl.
2958   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2959   // The exponent contains log2 of the value in biased form.
2960   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2961 
2962   // For trailing zeros, we just need to subtract the bias.
2963   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2964     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2965                        DAG.getConstant(ExponentBias, DL, VT));
2966 
2967   // For leading zeros, we need to remove the bias and convert from log2 to
2968   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2969   unsigned Adjust = ExponentBias + (EltSize - 1);
2970   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2971 }
2972 
2973 // While RVV has alignment restrictions, we should always be able to load as a
2974 // legal equivalently-sized byte-typed vector instead. This method is
2975 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2976 // the load is already correctly-aligned, it returns SDValue().
2977 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2978                                                     SelectionDAG &DAG) const {
2979   auto *Load = cast<LoadSDNode>(Op);
2980   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2981 
2982   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2983                                      Load->getMemoryVT(),
2984                                      *Load->getMemOperand()))
2985     return SDValue();
2986 
2987   SDLoc DL(Op);
2988   MVT VT = Op.getSimpleValueType();
2989   unsigned EltSizeBits = VT.getScalarSizeInBits();
2990   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2991          "Unexpected unaligned RVV load type");
2992   MVT NewVT =
2993       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2994   assert(NewVT.isValid() &&
2995          "Expecting equally-sized RVV vector types to be legal");
2996   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2997                           Load->getPointerInfo(), Load->getOriginalAlign(),
2998                           Load->getMemOperand()->getFlags());
2999   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3000 }
3001 
3002 // While RVV has alignment restrictions, we should always be able to store as a
3003 // legal equivalently-sized byte-typed vector instead. This method is
3004 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3005 // returns SDValue() if the store is already correctly aligned.
3006 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3007                                                      SelectionDAG &DAG) const {
3008   auto *Store = cast<StoreSDNode>(Op);
3009   assert(Store && Store->getValue().getValueType().isVector() &&
3010          "Expected vector store");
3011 
3012   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3013                                      Store->getMemoryVT(),
3014                                      *Store->getMemOperand()))
3015     return SDValue();
3016 
3017   SDLoc DL(Op);
3018   SDValue StoredVal = Store->getValue();
3019   MVT VT = StoredVal.getSimpleValueType();
3020   unsigned EltSizeBits = VT.getScalarSizeInBits();
3021   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3022          "Unexpected unaligned RVV store type");
3023   MVT NewVT =
3024       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3025   assert(NewVT.isValid() &&
3026          "Expecting equally-sized RVV vector types to be legal");
3027   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3028   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3029                       Store->getPointerInfo(), Store->getOriginalAlign(),
3030                       Store->getMemOperand()->getFlags());
3031 }
3032 
3033 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3034                                             SelectionDAG &DAG) const {
3035   switch (Op.getOpcode()) {
3036   default:
3037     report_fatal_error("unimplemented operand");
3038   case ISD::GlobalAddress:
3039     return lowerGlobalAddress(Op, DAG);
3040   case ISD::BlockAddress:
3041     return lowerBlockAddress(Op, DAG);
3042   case ISD::ConstantPool:
3043     return lowerConstantPool(Op, DAG);
3044   case ISD::JumpTable:
3045     return lowerJumpTable(Op, DAG);
3046   case ISD::GlobalTLSAddress:
3047     return lowerGlobalTLSAddress(Op, DAG);
3048   case ISD::SELECT:
3049     return lowerSELECT(Op, DAG);
3050   case ISD::BRCOND:
3051     return lowerBRCOND(Op, DAG);
3052   case ISD::VASTART:
3053     return lowerVASTART(Op, DAG);
3054   case ISD::FRAMEADDR:
3055     return lowerFRAMEADDR(Op, DAG);
3056   case ISD::RETURNADDR:
3057     return lowerRETURNADDR(Op, DAG);
3058   case ISD::SHL_PARTS:
3059     return lowerShiftLeftParts(Op, DAG);
3060   case ISD::SRA_PARTS:
3061     return lowerShiftRightParts(Op, DAG, true);
3062   case ISD::SRL_PARTS:
3063     return lowerShiftRightParts(Op, DAG, false);
3064   case ISD::BITCAST: {
3065     SDLoc DL(Op);
3066     EVT VT = Op.getValueType();
3067     SDValue Op0 = Op.getOperand(0);
3068     EVT Op0VT = Op0.getValueType();
3069     MVT XLenVT = Subtarget.getXLenVT();
3070     if (VT.isFixedLengthVector()) {
3071       // We can handle fixed length vector bitcasts with a simple replacement
3072       // in isel.
3073       if (Op0VT.isFixedLengthVector())
3074         return Op;
3075       // When bitcasting from scalar to fixed-length vector, insert the scalar
3076       // into a one-element vector of the result type, and perform a vector
3077       // bitcast.
3078       if (!Op0VT.isVector()) {
3079         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3080         if (!isTypeLegal(BVT))
3081           return SDValue();
3082         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3083                                               DAG.getUNDEF(BVT), Op0,
3084                                               DAG.getConstant(0, DL, XLenVT)));
3085       }
3086       return SDValue();
3087     }
3088     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3089     // thus: bitcast the vector to a one-element vector type whose element type
3090     // is the same as the result type, and extract the first element.
3091     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3092       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3093       if (!isTypeLegal(BVT))
3094         return SDValue();
3095       SDValue BVec = DAG.getBitcast(BVT, Op0);
3096       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3097                          DAG.getConstant(0, DL, XLenVT));
3098     }
3099     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3100       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3101       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3102       return FPConv;
3103     }
3104     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3105         Subtarget.hasStdExtF()) {
3106       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3107       SDValue FPConv =
3108           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3109       return FPConv;
3110     }
3111     return SDValue();
3112   }
3113   case ISD::INTRINSIC_WO_CHAIN:
3114     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3115   case ISD::INTRINSIC_W_CHAIN:
3116     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3117   case ISD::INTRINSIC_VOID:
3118     return LowerINTRINSIC_VOID(Op, DAG);
3119   case ISD::BSWAP:
3120   case ISD::BITREVERSE: {
3121     MVT VT = Op.getSimpleValueType();
3122     SDLoc DL(Op);
3123     if (Subtarget.hasStdExtZbp()) {
3124       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3125       // Start with the maximum immediate value which is the bitwidth - 1.
3126       unsigned Imm = VT.getSizeInBits() - 1;
3127       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3128       if (Op.getOpcode() == ISD::BSWAP)
3129         Imm &= ~0x7U;
3130       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3131                          DAG.getConstant(Imm, DL, VT));
3132     }
3133     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3134     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3135     // Expand bitreverse to a bswap(rev8) followed by brev8.
3136     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3137     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3138     // as brev8 by an isel pattern.
3139     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3140                        DAG.getConstant(7, DL, VT));
3141   }
3142   case ISD::FSHL:
3143   case ISD::FSHR: {
3144     MVT VT = Op.getSimpleValueType();
3145     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3146     SDLoc DL(Op);
3147     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3148     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3149     // accidentally setting the extra bit.
3150     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3151     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3152                                 DAG.getConstant(ShAmtWidth, DL, VT));
3153     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3154     // instruction use different orders. fshl will return its first operand for
3155     // shift of zero, fshr will return its second operand. fsl and fsr both
3156     // return rs1 so the ISD nodes need to have different operand orders.
3157     // Shift amount is in rs2.
3158     SDValue Op0 = Op.getOperand(0);
3159     SDValue Op1 = Op.getOperand(1);
3160     unsigned Opc = RISCVISD::FSL;
3161     if (Op.getOpcode() == ISD::FSHR) {
3162       std::swap(Op0, Op1);
3163       Opc = RISCVISD::FSR;
3164     }
3165     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3166   }
3167   case ISD::TRUNCATE: {
3168     SDLoc DL(Op);
3169     MVT VT = Op.getSimpleValueType();
3170     // Only custom-lower vector truncates
3171     if (!VT.isVector())
3172       return Op;
3173 
3174     // Truncates to mask types are handled differently
3175     if (VT.getVectorElementType() == MVT::i1)
3176       return lowerVectorMaskTrunc(Op, DAG);
3177 
3178     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3179     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3180     // truncate by one power of two at a time.
3181     MVT DstEltVT = VT.getVectorElementType();
3182 
3183     SDValue Src = Op.getOperand(0);
3184     MVT SrcVT = Src.getSimpleValueType();
3185     MVT SrcEltVT = SrcVT.getVectorElementType();
3186 
3187     assert(DstEltVT.bitsLT(SrcEltVT) &&
3188            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3189            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3190            "Unexpected vector truncate lowering");
3191 
3192     MVT ContainerVT = SrcVT;
3193     if (SrcVT.isFixedLengthVector()) {
3194       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3195       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3196     }
3197 
3198     SDValue Result = Src;
3199     SDValue Mask, VL;
3200     std::tie(Mask, VL) =
3201         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3202     LLVMContext &Context = *DAG.getContext();
3203     const ElementCount Count = ContainerVT.getVectorElementCount();
3204     do {
3205       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3206       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3207       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3208                            Mask, VL);
3209     } while (SrcEltVT != DstEltVT);
3210 
3211     if (SrcVT.isFixedLengthVector())
3212       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3213 
3214     return Result;
3215   }
3216   case ISD::ANY_EXTEND:
3217   case ISD::ZERO_EXTEND:
3218     if (Op.getOperand(0).getValueType().isVector() &&
3219         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3220       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3221     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3222   case ISD::SIGN_EXTEND:
3223     if (Op.getOperand(0).getValueType().isVector() &&
3224         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3225       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3226     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3227   case ISD::SPLAT_VECTOR_PARTS:
3228     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3229   case ISD::INSERT_VECTOR_ELT:
3230     return lowerINSERT_VECTOR_ELT(Op, DAG);
3231   case ISD::EXTRACT_VECTOR_ELT:
3232     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3233   case ISD::VSCALE: {
3234     MVT VT = Op.getSimpleValueType();
3235     SDLoc DL(Op);
3236     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3237     // We define our scalable vector types for lmul=1 to use a 64 bit known
3238     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3239     // vscale as VLENB / 8.
3240     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3241     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3242       report_fatal_error("Support for VLEN==32 is incomplete.");
3243     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3244       // We assume VLENB is a multiple of 8. We manually choose the best shift
3245       // here because SimplifyDemandedBits isn't always able to simplify it.
3246       uint64_t Val = Op.getConstantOperandVal(0);
3247       if (isPowerOf2_64(Val)) {
3248         uint64_t Log2 = Log2_64(Val);
3249         if (Log2 < 3)
3250           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3251                              DAG.getConstant(3 - Log2, DL, VT));
3252         if (Log2 > 3)
3253           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3254                              DAG.getConstant(Log2 - 3, DL, VT));
3255         return VLENB;
3256       }
3257       // If the multiplier is a multiple of 8, scale it down to avoid needing
3258       // to shift the VLENB value.
3259       if ((Val % 8) == 0)
3260         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3261                            DAG.getConstant(Val / 8, DL, VT));
3262     }
3263 
3264     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3265                                  DAG.getConstant(3, DL, VT));
3266     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3267   }
3268   case ISD::FPOWI: {
3269     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3270     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3271     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3272         Op.getOperand(1).getValueType() == MVT::i32) {
3273       SDLoc DL(Op);
3274       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3275       SDValue Powi =
3276           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3277       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3278                          DAG.getIntPtrConstant(0, DL));
3279     }
3280     return SDValue();
3281   }
3282   case ISD::FP_EXTEND: {
3283     // RVV can only do fp_extend to types double the size as the source. We
3284     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3285     // via f32.
3286     SDLoc DL(Op);
3287     MVT VT = Op.getSimpleValueType();
3288     SDValue Src = Op.getOperand(0);
3289     MVT SrcVT = Src.getSimpleValueType();
3290 
3291     // Prepare any fixed-length vector operands.
3292     MVT ContainerVT = VT;
3293     if (SrcVT.isFixedLengthVector()) {
3294       ContainerVT = getContainerForFixedLengthVector(VT);
3295       MVT SrcContainerVT =
3296           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3297       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3298     }
3299 
3300     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3301         SrcVT.getVectorElementType() != MVT::f16) {
3302       // For scalable vectors, we only need to close the gap between
3303       // vXf16->vXf64.
3304       if (!VT.isFixedLengthVector())
3305         return Op;
3306       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3307       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3308       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3309     }
3310 
3311     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3312     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3313     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3314         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3315 
3316     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3317                                            DL, DAG, Subtarget);
3318     if (VT.isFixedLengthVector())
3319       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3320     return Extend;
3321   }
3322   case ISD::FP_ROUND: {
3323     // RVV can only do fp_round to types half the size as the source. We
3324     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3325     // conversion instruction.
3326     SDLoc DL(Op);
3327     MVT VT = Op.getSimpleValueType();
3328     SDValue Src = Op.getOperand(0);
3329     MVT SrcVT = Src.getSimpleValueType();
3330 
3331     // Prepare any fixed-length vector operands.
3332     MVT ContainerVT = VT;
3333     if (VT.isFixedLengthVector()) {
3334       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3335       ContainerVT =
3336           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3337       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3338     }
3339 
3340     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3341         SrcVT.getVectorElementType() != MVT::f64) {
3342       // For scalable vectors, we only need to close the gap between
3343       // vXf64<->vXf16.
3344       if (!VT.isFixedLengthVector())
3345         return Op;
3346       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3347       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3348       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3349     }
3350 
3351     SDValue Mask, VL;
3352     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3353 
3354     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3355     SDValue IntermediateRound =
3356         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3357     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3358                                           DL, DAG, Subtarget);
3359 
3360     if (VT.isFixedLengthVector())
3361       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3362     return Round;
3363   }
3364   case ISD::FP_TO_SINT:
3365   case ISD::FP_TO_UINT:
3366   case ISD::SINT_TO_FP:
3367   case ISD::UINT_TO_FP: {
3368     // RVV can only do fp<->int conversions to types half/double the size as
3369     // the source. We custom-lower any conversions that do two hops into
3370     // sequences.
3371     MVT VT = Op.getSimpleValueType();
3372     if (!VT.isVector())
3373       return Op;
3374     SDLoc DL(Op);
3375     SDValue Src = Op.getOperand(0);
3376     MVT EltVT = VT.getVectorElementType();
3377     MVT SrcVT = Src.getSimpleValueType();
3378     MVT SrcEltVT = SrcVT.getVectorElementType();
3379     unsigned EltSize = EltVT.getSizeInBits();
3380     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3381     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3382            "Unexpected vector element types");
3383 
3384     bool IsInt2FP = SrcEltVT.isInteger();
3385     // Widening conversions
3386     if (EltSize > (2 * SrcEltSize)) {
3387       if (IsInt2FP) {
3388         // Do a regular integer sign/zero extension then convert to float.
3389         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3390                                       VT.getVectorElementCount());
3391         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3392                                  ? ISD::ZERO_EXTEND
3393                                  : ISD::SIGN_EXTEND;
3394         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3395         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3396       }
3397       // FP2Int
3398       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3399       // Do one doubling fp_extend then complete the operation by converting
3400       // to int.
3401       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3402       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3403       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3404     }
3405 
3406     // Narrowing conversions
3407     if (SrcEltSize > (2 * EltSize)) {
3408       if (IsInt2FP) {
3409         // One narrowing int_to_fp, then an fp_round.
3410         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3411         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3412         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3413         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3414       }
3415       // FP2Int
3416       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3417       // representable by the integer, the result is poison.
3418       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3419                                     VT.getVectorElementCount());
3420       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3421       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3422     }
3423 
3424     // Scalable vectors can exit here. Patterns will handle equally-sized
3425     // conversions halving/doubling ones.
3426     if (!VT.isFixedLengthVector())
3427       return Op;
3428 
3429     // For fixed-length vectors we lower to a custom "VL" node.
3430     unsigned RVVOpc = 0;
3431     switch (Op.getOpcode()) {
3432     default:
3433       llvm_unreachable("Impossible opcode");
3434     case ISD::FP_TO_SINT:
3435       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3436       break;
3437     case ISD::FP_TO_UINT:
3438       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3439       break;
3440     case ISD::SINT_TO_FP:
3441       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3442       break;
3443     case ISD::UINT_TO_FP:
3444       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3445       break;
3446     }
3447 
3448     MVT ContainerVT, SrcContainerVT;
3449     // Derive the reference container type from the larger vector type.
3450     if (SrcEltSize > EltSize) {
3451       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3452       ContainerVT =
3453           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3454     } else {
3455       ContainerVT = getContainerForFixedLengthVector(VT);
3456       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3457     }
3458 
3459     SDValue Mask, VL;
3460     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3461 
3462     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3463     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3464     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3465   }
3466   case ISD::FP_TO_SINT_SAT:
3467   case ISD::FP_TO_UINT_SAT:
3468     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3469   case ISD::FTRUNC:
3470   case ISD::FCEIL:
3471   case ISD::FFLOOR:
3472     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3473   case ISD::FROUND:
3474     return lowerFROUND(Op, DAG);
3475   case ISD::VECREDUCE_ADD:
3476   case ISD::VECREDUCE_UMAX:
3477   case ISD::VECREDUCE_SMAX:
3478   case ISD::VECREDUCE_UMIN:
3479   case ISD::VECREDUCE_SMIN:
3480     return lowerVECREDUCE(Op, DAG);
3481   case ISD::VECREDUCE_AND:
3482   case ISD::VECREDUCE_OR:
3483   case ISD::VECREDUCE_XOR:
3484     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3485       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3486     return lowerVECREDUCE(Op, DAG);
3487   case ISD::VECREDUCE_FADD:
3488   case ISD::VECREDUCE_SEQ_FADD:
3489   case ISD::VECREDUCE_FMIN:
3490   case ISD::VECREDUCE_FMAX:
3491     return lowerFPVECREDUCE(Op, DAG);
3492   case ISD::VP_REDUCE_ADD:
3493   case ISD::VP_REDUCE_UMAX:
3494   case ISD::VP_REDUCE_SMAX:
3495   case ISD::VP_REDUCE_UMIN:
3496   case ISD::VP_REDUCE_SMIN:
3497   case ISD::VP_REDUCE_FADD:
3498   case ISD::VP_REDUCE_SEQ_FADD:
3499   case ISD::VP_REDUCE_FMIN:
3500   case ISD::VP_REDUCE_FMAX:
3501     return lowerVPREDUCE(Op, DAG);
3502   case ISD::VP_REDUCE_AND:
3503   case ISD::VP_REDUCE_OR:
3504   case ISD::VP_REDUCE_XOR:
3505     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3506       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3507     return lowerVPREDUCE(Op, DAG);
3508   case ISD::INSERT_SUBVECTOR:
3509     return lowerINSERT_SUBVECTOR(Op, DAG);
3510   case ISD::EXTRACT_SUBVECTOR:
3511     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3512   case ISD::STEP_VECTOR:
3513     return lowerSTEP_VECTOR(Op, DAG);
3514   case ISD::VECTOR_REVERSE:
3515     return lowerVECTOR_REVERSE(Op, DAG);
3516   case ISD::VECTOR_SPLICE:
3517     return lowerVECTOR_SPLICE(Op, DAG);
3518   case ISD::BUILD_VECTOR:
3519     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3520   case ISD::SPLAT_VECTOR:
3521     if (Op.getValueType().getVectorElementType() == MVT::i1)
3522       return lowerVectorMaskSplat(Op, DAG);
3523     return SDValue();
3524   case ISD::VECTOR_SHUFFLE:
3525     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3526   case ISD::CONCAT_VECTORS: {
3527     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3528     // better than going through the stack, as the default expansion does.
3529     SDLoc DL(Op);
3530     MVT VT = Op.getSimpleValueType();
3531     unsigned NumOpElts =
3532         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3533     SDValue Vec = DAG.getUNDEF(VT);
3534     for (const auto &OpIdx : enumerate(Op->ops())) {
3535       SDValue SubVec = OpIdx.value();
3536       // Don't insert undef subvectors.
3537       if (SubVec.isUndef())
3538         continue;
3539       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3540                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3541     }
3542     return Vec;
3543   }
3544   case ISD::LOAD:
3545     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3546       return V;
3547     if (Op.getValueType().isFixedLengthVector())
3548       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3549     return Op;
3550   case ISD::STORE:
3551     if (auto V = expandUnalignedRVVStore(Op, DAG))
3552       return V;
3553     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3554       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3555     return Op;
3556   case ISD::MLOAD:
3557   case ISD::VP_LOAD:
3558     return lowerMaskedLoad(Op, DAG);
3559   case ISD::MSTORE:
3560   case ISD::VP_STORE:
3561     return lowerMaskedStore(Op, DAG);
3562   case ISD::SETCC:
3563     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3564   case ISD::ADD:
3565     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3566   case ISD::SUB:
3567     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3568   case ISD::MUL:
3569     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3570   case ISD::MULHS:
3571     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3572   case ISD::MULHU:
3573     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3574   case ISD::AND:
3575     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3576                                               RISCVISD::AND_VL);
3577   case ISD::OR:
3578     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3579                                               RISCVISD::OR_VL);
3580   case ISD::XOR:
3581     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3582                                               RISCVISD::XOR_VL);
3583   case ISD::SDIV:
3584     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3585   case ISD::SREM:
3586     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3587   case ISD::UDIV:
3588     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3589   case ISD::UREM:
3590     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3591   case ISD::SHL:
3592   case ISD::SRA:
3593   case ISD::SRL:
3594     if (Op.getSimpleValueType().isFixedLengthVector())
3595       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3596     // This can be called for an i32 shift amount that needs to be promoted.
3597     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3598            "Unexpected custom legalisation");
3599     return SDValue();
3600   case ISD::SADDSAT:
3601     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3602   case ISD::UADDSAT:
3603     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3604   case ISD::SSUBSAT:
3605     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3606   case ISD::USUBSAT:
3607     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3608   case ISD::FADD:
3609     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3610   case ISD::FSUB:
3611     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3612   case ISD::FMUL:
3613     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3614   case ISD::FDIV:
3615     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3616   case ISD::FNEG:
3617     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3618   case ISD::FABS:
3619     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3620   case ISD::FSQRT:
3621     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3622   case ISD::FMA:
3623     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3624   case ISD::SMIN:
3625     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3626   case ISD::SMAX:
3627     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3628   case ISD::UMIN:
3629     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3630   case ISD::UMAX:
3631     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3632   case ISD::FMINNUM:
3633     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3634   case ISD::FMAXNUM:
3635     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3636   case ISD::ABS:
3637     return lowerABS(Op, DAG);
3638   case ISD::CTLZ_ZERO_UNDEF:
3639   case ISD::CTTZ_ZERO_UNDEF:
3640     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3641   case ISD::VSELECT:
3642     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3643   case ISD::FCOPYSIGN:
3644     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3645   case ISD::MGATHER:
3646   case ISD::VP_GATHER:
3647     return lowerMaskedGather(Op, DAG);
3648   case ISD::MSCATTER:
3649   case ISD::VP_SCATTER:
3650     return lowerMaskedScatter(Op, DAG);
3651   case ISD::FLT_ROUNDS_:
3652     return lowerGET_ROUNDING(Op, DAG);
3653   case ISD::SET_ROUNDING:
3654     return lowerSET_ROUNDING(Op, DAG);
3655   case ISD::VP_SELECT:
3656     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3657   case ISD::VP_MERGE:
3658     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3659   case ISD::VP_ADD:
3660     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3661   case ISD::VP_SUB:
3662     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3663   case ISD::VP_MUL:
3664     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3665   case ISD::VP_SDIV:
3666     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3667   case ISD::VP_UDIV:
3668     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3669   case ISD::VP_SREM:
3670     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3671   case ISD::VP_UREM:
3672     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3673   case ISD::VP_AND:
3674     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3675   case ISD::VP_OR:
3676     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3677   case ISD::VP_XOR:
3678     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3679   case ISD::VP_ASHR:
3680     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3681   case ISD::VP_LSHR:
3682     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3683   case ISD::VP_SHL:
3684     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3685   case ISD::VP_FADD:
3686     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3687   case ISD::VP_FSUB:
3688     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3689   case ISD::VP_FMUL:
3690     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3691   case ISD::VP_FDIV:
3692     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3693   case ISD::VP_FNEG:
3694     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3695   case ISD::VP_FMA:
3696     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3697   case ISD::VP_SEXT:
3698   case ISD::VP_ZEXT:
3699     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3700       return lowerVPExtMaskOp(Op, DAG);
3701     return lowerVPOp(Op, DAG,
3702                      Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL
3703                                                     : RISCVISD::VZEXT_VL);
3704   case ISD::VP_FPTOSI:
3705     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3706   case ISD::VP_FPTOUI:
3707     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3708   case ISD::VP_SITOFP:
3709     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3710   case ISD::VP_UITOFP:
3711     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3712   case ISD::VP_SETCC:
3713     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3714   }
3715 }
3716 
3717 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3718                              SelectionDAG &DAG, unsigned Flags) {
3719   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3720 }
3721 
3722 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3723                              SelectionDAG &DAG, unsigned Flags) {
3724   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3725                                    Flags);
3726 }
3727 
3728 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3729                              SelectionDAG &DAG, unsigned Flags) {
3730   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3731                                    N->getOffset(), Flags);
3732 }
3733 
3734 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3735                              SelectionDAG &DAG, unsigned Flags) {
3736   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3737 }
3738 
3739 template <class NodeTy>
3740 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3741                                      bool IsLocal) const {
3742   SDLoc DL(N);
3743   EVT Ty = getPointerTy(DAG.getDataLayout());
3744 
3745   if (isPositionIndependent()) {
3746     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3747     if (IsLocal)
3748       // Use PC-relative addressing to access the symbol. This generates the
3749       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3750       // %pcrel_lo(auipc)).
3751       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3752 
3753     // Use PC-relative addressing to access the GOT for this symbol, then load
3754     // the address from the GOT. This generates the pattern (PseudoLA sym),
3755     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3756     SDValue Load =
3757         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3758     MachineFunction &MF = DAG.getMachineFunction();
3759     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3760         MachinePointerInfo::getGOT(MF),
3761         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3762             MachineMemOperand::MOInvariant,
3763         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3764     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3765     return Load;
3766   }
3767 
3768   switch (getTargetMachine().getCodeModel()) {
3769   default:
3770     report_fatal_error("Unsupported code model for lowering");
3771   case CodeModel::Small: {
3772     // Generate a sequence for accessing addresses within the first 2 GiB of
3773     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3774     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3775     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3776     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3777     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3778   }
3779   case CodeModel::Medium: {
3780     // Generate a sequence for accessing addresses within any 2GiB range within
3781     // the address space. This generates the pattern (PseudoLLA sym), which
3782     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3783     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3784     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3785   }
3786   }
3787 }
3788 
3789 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3790     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3791 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3792     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3793 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3794     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3795 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3796     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3797 
3798 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3799                                                 SelectionDAG &DAG) const {
3800   SDLoc DL(Op);
3801   EVT Ty = Op.getValueType();
3802   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3803   int64_t Offset = N->getOffset();
3804   MVT XLenVT = Subtarget.getXLenVT();
3805 
3806   const GlobalValue *GV = N->getGlobal();
3807   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3808   SDValue Addr = getAddr(N, DAG, IsLocal);
3809 
3810   // In order to maximise the opportunity for common subexpression elimination,
3811   // emit a separate ADD node for the global address offset instead of folding
3812   // it in the global address node. Later peephole optimisations may choose to
3813   // fold it back in when profitable.
3814   if (Offset != 0)
3815     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3816                        DAG.getConstant(Offset, DL, XLenVT));
3817   return Addr;
3818 }
3819 
3820 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3821                                                SelectionDAG &DAG) const {
3822   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3823 
3824   return getAddr(N, DAG);
3825 }
3826 
3827 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3828                                                SelectionDAG &DAG) const {
3829   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3830 
3831   return getAddr(N, DAG);
3832 }
3833 
3834 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3835                                             SelectionDAG &DAG) const {
3836   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3837 
3838   return getAddr(N, DAG);
3839 }
3840 
3841 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3842                                               SelectionDAG &DAG,
3843                                               bool UseGOT) const {
3844   SDLoc DL(N);
3845   EVT Ty = getPointerTy(DAG.getDataLayout());
3846   const GlobalValue *GV = N->getGlobal();
3847   MVT XLenVT = Subtarget.getXLenVT();
3848 
3849   if (UseGOT) {
3850     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3851     // load the address from the GOT and add the thread pointer. This generates
3852     // the pattern (PseudoLA_TLS_IE sym), which expands to
3853     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3854     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3855     SDValue Load =
3856         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3857     MachineFunction &MF = DAG.getMachineFunction();
3858     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3859         MachinePointerInfo::getGOT(MF),
3860         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3861             MachineMemOperand::MOInvariant,
3862         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3863     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3864 
3865     // Add the thread pointer.
3866     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3867     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3868   }
3869 
3870   // Generate a sequence for accessing the address relative to the thread
3871   // pointer, with the appropriate adjustment for the thread pointer offset.
3872   // This generates the pattern
3873   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3874   SDValue AddrHi =
3875       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3876   SDValue AddrAdd =
3877       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3878   SDValue AddrLo =
3879       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3880 
3881   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3882   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3883   SDValue MNAdd = SDValue(
3884       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3885       0);
3886   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3887 }
3888 
3889 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3890                                                SelectionDAG &DAG) const {
3891   SDLoc DL(N);
3892   EVT Ty = getPointerTy(DAG.getDataLayout());
3893   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3894   const GlobalValue *GV = N->getGlobal();
3895 
3896   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3897   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3898   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3899   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3900   SDValue Load =
3901       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3902 
3903   // Prepare argument list to generate call.
3904   ArgListTy Args;
3905   ArgListEntry Entry;
3906   Entry.Node = Load;
3907   Entry.Ty = CallTy;
3908   Args.push_back(Entry);
3909 
3910   // Setup call to __tls_get_addr.
3911   TargetLowering::CallLoweringInfo CLI(DAG);
3912   CLI.setDebugLoc(DL)
3913       .setChain(DAG.getEntryNode())
3914       .setLibCallee(CallingConv::C, CallTy,
3915                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3916                     std::move(Args));
3917 
3918   return LowerCallTo(CLI).first;
3919 }
3920 
3921 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3922                                                    SelectionDAG &DAG) const {
3923   SDLoc DL(Op);
3924   EVT Ty = Op.getValueType();
3925   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3926   int64_t Offset = N->getOffset();
3927   MVT XLenVT = Subtarget.getXLenVT();
3928 
3929   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3930 
3931   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3932       CallingConv::GHC)
3933     report_fatal_error("In GHC calling convention TLS is not supported");
3934 
3935   SDValue Addr;
3936   switch (Model) {
3937   case TLSModel::LocalExec:
3938     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3939     break;
3940   case TLSModel::InitialExec:
3941     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3942     break;
3943   case TLSModel::LocalDynamic:
3944   case TLSModel::GeneralDynamic:
3945     Addr = getDynamicTLSAddr(N, DAG);
3946     break;
3947   }
3948 
3949   // In order to maximise the opportunity for common subexpression elimination,
3950   // emit a separate ADD node for the global address offset instead of folding
3951   // it in the global address node. Later peephole optimisations may choose to
3952   // fold it back in when profitable.
3953   if (Offset != 0)
3954     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3955                        DAG.getConstant(Offset, DL, XLenVT));
3956   return Addr;
3957 }
3958 
3959 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3960   SDValue CondV = Op.getOperand(0);
3961   SDValue TrueV = Op.getOperand(1);
3962   SDValue FalseV = Op.getOperand(2);
3963   SDLoc DL(Op);
3964   MVT VT = Op.getSimpleValueType();
3965   MVT XLenVT = Subtarget.getXLenVT();
3966 
3967   // Lower vector SELECTs to VSELECTs by splatting the condition.
3968   if (VT.isVector()) {
3969     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3970     SDValue CondSplat = VT.isScalableVector()
3971                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3972                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3973     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3974   }
3975 
3976   // If the result type is XLenVT and CondV is the output of a SETCC node
3977   // which also operated on XLenVT inputs, then merge the SETCC node into the
3978   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3979   // compare+branch instructions. i.e.:
3980   // (select (setcc lhs, rhs, cc), truev, falsev)
3981   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3982   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3983       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3984     SDValue LHS = CondV.getOperand(0);
3985     SDValue RHS = CondV.getOperand(1);
3986     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3987     ISD::CondCode CCVal = CC->get();
3988 
3989     // Special case for a select of 2 constants that have a diffence of 1.
3990     // Normally this is done by DAGCombine, but if the select is introduced by
3991     // type legalization or op legalization, we miss it. Restricting to SETLT
3992     // case for now because that is what signed saturating add/sub need.
3993     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3994     // but we would probably want to swap the true/false values if the condition
3995     // is SETGE/SETLE to avoid an XORI.
3996     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3997         CCVal == ISD::SETLT) {
3998       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3999       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
4000       if (TrueVal - 1 == FalseVal)
4001         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
4002       if (TrueVal + 1 == FalseVal)
4003         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
4004     }
4005 
4006     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4007 
4008     SDValue TargetCC = DAG.getCondCode(CCVal);
4009     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
4010     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4011   }
4012 
4013   // Otherwise:
4014   // (select condv, truev, falsev)
4015   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
4016   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4017   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
4018 
4019   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
4020 
4021   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4022 }
4023 
4024 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4025   SDValue CondV = Op.getOperand(1);
4026   SDLoc DL(Op);
4027   MVT XLenVT = Subtarget.getXLenVT();
4028 
4029   if (CondV.getOpcode() == ISD::SETCC &&
4030       CondV.getOperand(0).getValueType() == XLenVT) {
4031     SDValue LHS = CondV.getOperand(0);
4032     SDValue RHS = CondV.getOperand(1);
4033     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
4034 
4035     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4036 
4037     SDValue TargetCC = DAG.getCondCode(CCVal);
4038     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4039                        LHS, RHS, TargetCC, Op.getOperand(2));
4040   }
4041 
4042   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4043                      CondV, DAG.getConstant(0, DL, XLenVT),
4044                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4045 }
4046 
4047 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4048   MachineFunction &MF = DAG.getMachineFunction();
4049   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4050 
4051   SDLoc DL(Op);
4052   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4053                                  getPointerTy(MF.getDataLayout()));
4054 
4055   // vastart just stores the address of the VarArgsFrameIndex slot into the
4056   // memory location argument.
4057   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4058   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4059                       MachinePointerInfo(SV));
4060 }
4061 
4062 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4063                                             SelectionDAG &DAG) const {
4064   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4065   MachineFunction &MF = DAG.getMachineFunction();
4066   MachineFrameInfo &MFI = MF.getFrameInfo();
4067   MFI.setFrameAddressIsTaken(true);
4068   Register FrameReg = RI.getFrameRegister(MF);
4069   int XLenInBytes = Subtarget.getXLen() / 8;
4070 
4071   EVT VT = Op.getValueType();
4072   SDLoc DL(Op);
4073   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4074   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4075   while (Depth--) {
4076     int Offset = -(XLenInBytes * 2);
4077     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4078                               DAG.getIntPtrConstant(Offset, DL));
4079     FrameAddr =
4080         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4081   }
4082   return FrameAddr;
4083 }
4084 
4085 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4086                                              SelectionDAG &DAG) const {
4087   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4088   MachineFunction &MF = DAG.getMachineFunction();
4089   MachineFrameInfo &MFI = MF.getFrameInfo();
4090   MFI.setReturnAddressIsTaken(true);
4091   MVT XLenVT = Subtarget.getXLenVT();
4092   int XLenInBytes = Subtarget.getXLen() / 8;
4093 
4094   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4095     return SDValue();
4096 
4097   EVT VT = Op.getValueType();
4098   SDLoc DL(Op);
4099   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4100   if (Depth) {
4101     int Off = -XLenInBytes;
4102     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4103     SDValue Offset = DAG.getConstant(Off, DL, VT);
4104     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4105                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4106                        MachinePointerInfo());
4107   }
4108 
4109   // Return the value of the return address register, marking it an implicit
4110   // live-in.
4111   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4112   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4113 }
4114 
4115 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4116                                                  SelectionDAG &DAG) const {
4117   SDLoc DL(Op);
4118   SDValue Lo = Op.getOperand(0);
4119   SDValue Hi = Op.getOperand(1);
4120   SDValue Shamt = Op.getOperand(2);
4121   EVT VT = Lo.getValueType();
4122 
4123   // if Shamt-XLEN < 0: // Shamt < XLEN
4124   //   Lo = Lo << Shamt
4125   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4126   // else:
4127   //   Lo = 0
4128   //   Hi = Lo << (Shamt-XLEN)
4129 
4130   SDValue Zero = DAG.getConstant(0, DL, VT);
4131   SDValue One = DAG.getConstant(1, DL, VT);
4132   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4133   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4134   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4135   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4136 
4137   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4138   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4139   SDValue ShiftRightLo =
4140       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4141   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4142   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4143   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4144 
4145   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4146 
4147   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4148   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4149 
4150   SDValue Parts[2] = {Lo, Hi};
4151   return DAG.getMergeValues(Parts, DL);
4152 }
4153 
4154 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4155                                                   bool IsSRA) const {
4156   SDLoc DL(Op);
4157   SDValue Lo = Op.getOperand(0);
4158   SDValue Hi = Op.getOperand(1);
4159   SDValue Shamt = Op.getOperand(2);
4160   EVT VT = Lo.getValueType();
4161 
4162   // SRA expansion:
4163   //   if Shamt-XLEN < 0: // Shamt < XLEN
4164   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4165   //     Hi = Hi >>s Shamt
4166   //   else:
4167   //     Lo = Hi >>s (Shamt-XLEN);
4168   //     Hi = Hi >>s (XLEN-1)
4169   //
4170   // SRL expansion:
4171   //   if Shamt-XLEN < 0: // Shamt < XLEN
4172   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4173   //     Hi = Hi >>u Shamt
4174   //   else:
4175   //     Lo = Hi >>u (Shamt-XLEN);
4176   //     Hi = 0;
4177 
4178   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4179 
4180   SDValue Zero = DAG.getConstant(0, DL, VT);
4181   SDValue One = DAG.getConstant(1, DL, VT);
4182   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4183   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4184   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4185   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4186 
4187   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4188   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4189   SDValue ShiftLeftHi =
4190       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4191   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4192   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4193   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4194   SDValue HiFalse =
4195       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4196 
4197   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4198 
4199   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4200   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4201 
4202   SDValue Parts[2] = {Lo, Hi};
4203   return DAG.getMergeValues(Parts, DL);
4204 }
4205 
4206 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4207 // legal equivalently-sized i8 type, so we can use that as a go-between.
4208 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4209                                                   SelectionDAG &DAG) const {
4210   SDLoc DL(Op);
4211   MVT VT = Op.getSimpleValueType();
4212   SDValue SplatVal = Op.getOperand(0);
4213   // All-zeros or all-ones splats are handled specially.
4214   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4215     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4216     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4217   }
4218   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4219     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4220     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4221   }
4222   MVT XLenVT = Subtarget.getXLenVT();
4223   assert(SplatVal.getValueType() == XLenVT &&
4224          "Unexpected type for i1 splat value");
4225   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4226   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4227                          DAG.getConstant(1, DL, XLenVT));
4228   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4229   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4230   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4231 }
4232 
4233 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4234 // illegal (currently only vXi64 RV32).
4235 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4236 // them to VMV_V_X_VL.
4237 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4238                                                      SelectionDAG &DAG) const {
4239   SDLoc DL(Op);
4240   MVT VecVT = Op.getSimpleValueType();
4241   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4242          "Unexpected SPLAT_VECTOR_PARTS lowering");
4243 
4244   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4245   SDValue Lo = Op.getOperand(0);
4246   SDValue Hi = Op.getOperand(1);
4247 
4248   if (VecVT.isFixedLengthVector()) {
4249     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4250     SDLoc DL(Op);
4251     SDValue Mask, VL;
4252     std::tie(Mask, VL) =
4253         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4254 
4255     SDValue Res =
4256         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4257     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4258   }
4259 
4260   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4261     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4262     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4263     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4264     // node in order to try and match RVV vector/scalar instructions.
4265     if ((LoC >> 31) == HiC)
4266       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4267                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4268   }
4269 
4270   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4271   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4272       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4273       Hi.getConstantOperandVal(1) == 31)
4274     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4275                        DAG.getRegister(RISCV::X0, MVT::i32));
4276 
4277   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4278   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4279                      DAG.getUNDEF(VecVT), Lo, Hi,
4280                      DAG.getRegister(RISCV::X0, MVT::i32));
4281 }
4282 
4283 // Custom-lower extensions from mask vectors by using a vselect either with 1
4284 // for zero/any-extension or -1 for sign-extension:
4285 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4286 // Note that any-extension is lowered identically to zero-extension.
4287 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4288                                                 int64_t ExtTrueVal) const {
4289   SDLoc DL(Op);
4290   MVT VecVT = Op.getSimpleValueType();
4291   SDValue Src = Op.getOperand(0);
4292   // Only custom-lower extensions from mask types
4293   assert(Src.getValueType().isVector() &&
4294          Src.getValueType().getVectorElementType() == MVT::i1);
4295 
4296   if (VecVT.isScalableVector()) {
4297     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4298     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4299     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4300   }
4301 
4302   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4303   MVT I1ContainerVT =
4304       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4305 
4306   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4307 
4308   SDValue Mask, VL;
4309   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4310 
4311   MVT XLenVT = Subtarget.getXLenVT();
4312   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4313   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4314 
4315   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4316                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4317   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4318                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4319   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4320                                SplatTrueVal, SplatZero, VL);
4321 
4322   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4323 }
4324 
4325 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4326     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4327   MVT ExtVT = Op.getSimpleValueType();
4328   // Only custom-lower extensions from fixed-length vector types.
4329   if (!ExtVT.isFixedLengthVector())
4330     return Op;
4331   MVT VT = Op.getOperand(0).getSimpleValueType();
4332   // Grab the canonical container type for the extended type. Infer the smaller
4333   // type from that to ensure the same number of vector elements, as we know
4334   // the LMUL will be sufficient to hold the smaller type.
4335   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4336   // Get the extended container type manually to ensure the same number of
4337   // vector elements between source and dest.
4338   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4339                                      ContainerExtVT.getVectorElementCount());
4340 
4341   SDValue Op1 =
4342       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4343 
4344   SDLoc DL(Op);
4345   SDValue Mask, VL;
4346   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4347 
4348   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4349 
4350   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4351 }
4352 
4353 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4354 // setcc operation:
4355 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4356 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4357                                                   SelectionDAG &DAG) const {
4358   SDLoc DL(Op);
4359   EVT MaskVT = Op.getValueType();
4360   // Only expect to custom-lower truncations to mask types
4361   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4362          "Unexpected type for vector mask lowering");
4363   SDValue Src = Op.getOperand(0);
4364   MVT VecVT = Src.getSimpleValueType();
4365 
4366   // If this is a fixed vector, we need to convert it to a scalable vector.
4367   MVT ContainerVT = VecVT;
4368   if (VecVT.isFixedLengthVector()) {
4369     ContainerVT = getContainerForFixedLengthVector(VecVT);
4370     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4371   }
4372 
4373   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4374   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4375 
4376   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4377                          DAG.getUNDEF(ContainerVT), SplatOne);
4378   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4379                           DAG.getUNDEF(ContainerVT), SplatZero);
4380 
4381   if (VecVT.isScalableVector()) {
4382     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4383     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4384   }
4385 
4386   SDValue Mask, VL;
4387   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4388 
4389   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4390   SDValue Trunc =
4391       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4392   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4393                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4394   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4395 }
4396 
4397 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4398 // first position of a vector, and that vector is slid up to the insert index.
4399 // By limiting the active vector length to index+1 and merging with the
4400 // original vector (with an undisturbed tail policy for elements >= VL), we
4401 // achieve the desired result of leaving all elements untouched except the one
4402 // at VL-1, which is replaced with the desired value.
4403 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4404                                                     SelectionDAG &DAG) const {
4405   SDLoc DL(Op);
4406   MVT VecVT = Op.getSimpleValueType();
4407   SDValue Vec = Op.getOperand(0);
4408   SDValue Val = Op.getOperand(1);
4409   SDValue Idx = Op.getOperand(2);
4410 
4411   if (VecVT.getVectorElementType() == MVT::i1) {
4412     // FIXME: For now we just promote to an i8 vector and insert into that,
4413     // but this is probably not optimal.
4414     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4415     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4416     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4417     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4418   }
4419 
4420   MVT ContainerVT = VecVT;
4421   // If the operand is a fixed-length vector, convert to a scalable one.
4422   if (VecVT.isFixedLengthVector()) {
4423     ContainerVT = getContainerForFixedLengthVector(VecVT);
4424     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4425   }
4426 
4427   MVT XLenVT = Subtarget.getXLenVT();
4428 
4429   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4430   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4431   // Even i64-element vectors on RV32 can be lowered without scalar
4432   // legalization if the most-significant 32 bits of the value are not affected
4433   // by the sign-extension of the lower 32 bits.
4434   // TODO: We could also catch sign extensions of a 32-bit value.
4435   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4436     const auto *CVal = cast<ConstantSDNode>(Val);
4437     if (isInt<32>(CVal->getSExtValue())) {
4438       IsLegalInsert = true;
4439       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4440     }
4441   }
4442 
4443   SDValue Mask, VL;
4444   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4445 
4446   SDValue ValInVec;
4447 
4448   if (IsLegalInsert) {
4449     unsigned Opc =
4450         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4451     if (isNullConstant(Idx)) {
4452       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4453       if (!VecVT.isFixedLengthVector())
4454         return Vec;
4455       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4456     }
4457     ValInVec =
4458         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4459   } else {
4460     // On RV32, i64-element vectors must be specially handled to place the
4461     // value at element 0, by using two vslide1up instructions in sequence on
4462     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4463     // this.
4464     SDValue One = DAG.getConstant(1, DL, XLenVT);
4465     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4466     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4467     MVT I32ContainerVT =
4468         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4469     SDValue I32Mask =
4470         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4471     // Limit the active VL to two.
4472     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4473     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4474     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4475     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4476                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4477     // First slide in the hi value, then the lo in underneath it.
4478     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4479                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4480                            I32Mask, InsertI64VL);
4481     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4482                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4483                            I32Mask, InsertI64VL);
4484     // Bitcast back to the right container type.
4485     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4486   }
4487 
4488   // Now that the value is in a vector, slide it into position.
4489   SDValue InsertVL =
4490       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4491   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4492                                 ValInVec, Idx, Mask, InsertVL);
4493   if (!VecVT.isFixedLengthVector())
4494     return Slideup;
4495   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4496 }
4497 
4498 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4499 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4500 // types this is done using VMV_X_S to allow us to glean information about the
4501 // sign bits of the result.
4502 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4503                                                      SelectionDAG &DAG) const {
4504   SDLoc DL(Op);
4505   SDValue Idx = Op.getOperand(1);
4506   SDValue Vec = Op.getOperand(0);
4507   EVT EltVT = Op.getValueType();
4508   MVT VecVT = Vec.getSimpleValueType();
4509   MVT XLenVT = Subtarget.getXLenVT();
4510 
4511   if (VecVT.getVectorElementType() == MVT::i1) {
4512     if (VecVT.isFixedLengthVector()) {
4513       unsigned NumElts = VecVT.getVectorNumElements();
4514       if (NumElts >= 8) {
4515         MVT WideEltVT;
4516         unsigned WidenVecLen;
4517         SDValue ExtractElementIdx;
4518         SDValue ExtractBitIdx;
4519         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4520         MVT LargestEltVT = MVT::getIntegerVT(
4521             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4522         if (NumElts <= LargestEltVT.getSizeInBits()) {
4523           assert(isPowerOf2_32(NumElts) &&
4524                  "the number of elements should be power of 2");
4525           WideEltVT = MVT::getIntegerVT(NumElts);
4526           WidenVecLen = 1;
4527           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4528           ExtractBitIdx = Idx;
4529         } else {
4530           WideEltVT = LargestEltVT;
4531           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4532           // extract element index = index / element width
4533           ExtractElementIdx = DAG.getNode(
4534               ISD::SRL, DL, XLenVT, Idx,
4535               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4536           // mask bit index = index % element width
4537           ExtractBitIdx = DAG.getNode(
4538               ISD::AND, DL, XLenVT, Idx,
4539               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4540         }
4541         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4542         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4543         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4544                                          Vec, ExtractElementIdx);
4545         // Extract the bit from GPR.
4546         SDValue ShiftRight =
4547             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4548         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4549                            DAG.getConstant(1, DL, XLenVT));
4550       }
4551     }
4552     // Otherwise, promote to an i8 vector and extract from that.
4553     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4554     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4555     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4556   }
4557 
4558   // If this is a fixed vector, we need to convert it to a scalable vector.
4559   MVT ContainerVT = VecVT;
4560   if (VecVT.isFixedLengthVector()) {
4561     ContainerVT = getContainerForFixedLengthVector(VecVT);
4562     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4563   }
4564 
4565   // If the index is 0, the vector is already in the right position.
4566   if (!isNullConstant(Idx)) {
4567     // Use a VL of 1 to avoid processing more elements than we need.
4568     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4569     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4570     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4571     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4572                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4573   }
4574 
4575   if (!EltVT.isInteger()) {
4576     // Floating-point extracts are handled in TableGen.
4577     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4578                        DAG.getConstant(0, DL, XLenVT));
4579   }
4580 
4581   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4582   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4583 }
4584 
4585 // Some RVV intrinsics may claim that they want an integer operand to be
4586 // promoted or expanded.
4587 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4588                                            const RISCVSubtarget &Subtarget) {
4589   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4590           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4591          "Unexpected opcode");
4592 
4593   if (!Subtarget.hasVInstructions())
4594     return SDValue();
4595 
4596   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4597   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4598   SDLoc DL(Op);
4599 
4600   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4601       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4602   if (!II || !II->hasScalarOperand())
4603     return SDValue();
4604 
4605   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4606   assert(SplatOp < Op.getNumOperands());
4607 
4608   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4609   SDValue &ScalarOp = Operands[SplatOp];
4610   MVT OpVT = ScalarOp.getSimpleValueType();
4611   MVT XLenVT = Subtarget.getXLenVT();
4612 
4613   // If this isn't a scalar, or its type is XLenVT we're done.
4614   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4615     return SDValue();
4616 
4617   // Simplest case is that the operand needs to be promoted to XLenVT.
4618   if (OpVT.bitsLT(XLenVT)) {
4619     // If the operand is a constant, sign extend to increase our chances
4620     // of being able to use a .vi instruction. ANY_EXTEND would become a
4621     // a zero extend and the simm5 check in isel would fail.
4622     // FIXME: Should we ignore the upper bits in isel instead?
4623     unsigned ExtOpc =
4624         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4625     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4626     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4627   }
4628 
4629   // Use the previous operand to get the vXi64 VT. The result might be a mask
4630   // VT for compares. Using the previous operand assumes that the previous
4631   // operand will never have a smaller element size than a scalar operand and
4632   // that a widening operation never uses SEW=64.
4633   // NOTE: If this fails the below assert, we can probably just find the
4634   // element count from any operand or result and use it to construct the VT.
4635   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4636   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4637 
4638   // The more complex case is when the scalar is larger than XLenVT.
4639   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4640          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4641 
4642   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4643   // instruction to sign-extend since SEW>XLEN.
4644   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4645     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4646     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4647   }
4648 
4649   switch (IntNo) {
4650   case Intrinsic::riscv_vslide1up:
4651   case Intrinsic::riscv_vslide1down:
4652   case Intrinsic::riscv_vslide1up_mask:
4653   case Intrinsic::riscv_vslide1down_mask: {
4654     // We need to special case these when the scalar is larger than XLen.
4655     unsigned NumOps = Op.getNumOperands();
4656     bool IsMasked = NumOps == 7;
4657 
4658     // Convert the vector source to the equivalent nxvXi32 vector.
4659     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4660     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4661 
4662     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4663                                    DAG.getConstant(0, DL, XLenVT));
4664     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4665                                    DAG.getConstant(1, DL, XLenVT));
4666 
4667     // Double the VL since we halved SEW.
4668     SDValue AVL = getVLOperand(Op);
4669     SDValue I32VL;
4670 
4671     // Optimize for constant AVL
4672     if (isa<ConstantSDNode>(AVL)) {
4673       unsigned EltSize = VT.getScalarSizeInBits();
4674       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4675 
4676       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4677       unsigned MaxVLMAX =
4678           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4679 
4680       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4681       unsigned MinVLMAX =
4682           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4683 
4684       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4685       if (AVLInt <= MinVLMAX) {
4686         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4687       } else if (AVLInt >= 2 * MaxVLMAX) {
4688         // Just set vl to VLMAX in this situation
4689         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4690         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4691         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4692         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4693         SDValue SETVLMAX = DAG.getTargetConstant(
4694             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4695         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4696                             LMUL);
4697       } else {
4698         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4699         // is related to the hardware implementation.
4700         // So let the following code handle
4701       }
4702     }
4703     if (!I32VL) {
4704       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4705       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4706       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4707       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4708       SDValue SETVL =
4709           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4710       // Using vsetvli instruction to get actually used length which related to
4711       // the hardware implementation
4712       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4713                                SEW, LMUL);
4714       I32VL =
4715           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4716     }
4717 
4718     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4719     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4720 
4721     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4722     // instructions.
4723     SDValue Passthru;
4724     if (IsMasked)
4725       Passthru = DAG.getUNDEF(I32VT);
4726     else
4727       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4728 
4729     if (IntNo == Intrinsic::riscv_vslide1up ||
4730         IntNo == Intrinsic::riscv_vslide1up_mask) {
4731       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4732                         ScalarHi, I32Mask, I32VL);
4733       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4734                         ScalarLo, I32Mask, I32VL);
4735     } else {
4736       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4737                         ScalarLo, I32Mask, I32VL);
4738       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4739                         ScalarHi, I32Mask, I32VL);
4740     }
4741 
4742     // Convert back to nxvXi64.
4743     Vec = DAG.getBitcast(VT, Vec);
4744 
4745     if (!IsMasked)
4746       return Vec;
4747     // Apply mask after the operation.
4748     SDValue Mask = Operands[NumOps - 3];
4749     SDValue MaskedOff = Operands[1];
4750     // Assume Policy operand is the last operand.
4751     uint64_t Policy =
4752         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4753     // We don't need to select maskedoff if it's undef.
4754     if (MaskedOff.isUndef())
4755       return Vec;
4756     // TAMU
4757     if (Policy == RISCVII::TAIL_AGNOSTIC)
4758       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4759                          AVL);
4760     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4761     // It's fine because vmerge does not care mask policy.
4762     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4763                        AVL);
4764   }
4765   }
4766 
4767   // We need to convert the scalar to a splat vector.
4768   SDValue VL = getVLOperand(Op);
4769   assert(VL.getValueType() == XLenVT);
4770   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4771   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4772 }
4773 
4774 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4775                                                      SelectionDAG &DAG) const {
4776   unsigned IntNo = Op.getConstantOperandVal(0);
4777   SDLoc DL(Op);
4778   MVT XLenVT = Subtarget.getXLenVT();
4779 
4780   switch (IntNo) {
4781   default:
4782     break; // Don't custom lower most intrinsics.
4783   case Intrinsic::thread_pointer: {
4784     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4785     return DAG.getRegister(RISCV::X4, PtrVT);
4786   }
4787   case Intrinsic::riscv_orc_b:
4788   case Intrinsic::riscv_brev8: {
4789     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4790     unsigned Opc =
4791         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4792     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4793                        DAG.getConstant(7, DL, XLenVT));
4794   }
4795   case Intrinsic::riscv_grev:
4796   case Intrinsic::riscv_gorc: {
4797     unsigned Opc =
4798         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4799     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4800   }
4801   case Intrinsic::riscv_zip:
4802   case Intrinsic::riscv_unzip: {
4803     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4804     // For i32 the immediate is 15. For i64 the immediate is 31.
4805     unsigned Opc =
4806         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4807     unsigned BitWidth = Op.getValueSizeInBits();
4808     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4809     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4810                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4811   }
4812   case Intrinsic::riscv_shfl:
4813   case Intrinsic::riscv_unshfl: {
4814     unsigned Opc =
4815         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4816     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4817   }
4818   case Intrinsic::riscv_bcompress:
4819   case Intrinsic::riscv_bdecompress: {
4820     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4821                                                        : RISCVISD::BDECOMPRESS;
4822     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4823   }
4824   case Intrinsic::riscv_bfp:
4825     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4826                        Op.getOperand(2));
4827   case Intrinsic::riscv_fsl:
4828     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4829                        Op.getOperand(2), Op.getOperand(3));
4830   case Intrinsic::riscv_fsr:
4831     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4832                        Op.getOperand(2), Op.getOperand(3));
4833   case Intrinsic::riscv_vmv_x_s:
4834     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4835     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4836                        Op.getOperand(1));
4837   case Intrinsic::riscv_vmv_v_x:
4838     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4839                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4840                             Subtarget);
4841   case Intrinsic::riscv_vfmv_v_f:
4842     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4843                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4844   case Intrinsic::riscv_vmv_s_x: {
4845     SDValue Scalar = Op.getOperand(2);
4846 
4847     if (Scalar.getValueType().bitsLE(XLenVT)) {
4848       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4849       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4850                          Op.getOperand(1), Scalar, Op.getOperand(3));
4851     }
4852 
4853     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4854 
4855     // This is an i64 value that lives in two scalar registers. We have to
4856     // insert this in a convoluted way. First we build vXi64 splat containing
4857     // the two values that we assemble using some bit math. Next we'll use
4858     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4859     // to merge element 0 from our splat into the source vector.
4860     // FIXME: This is probably not the best way to do this, but it is
4861     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4862     // point.
4863     //   sw lo, (a0)
4864     //   sw hi, 4(a0)
4865     //   vlse vX, (a0)
4866     //
4867     //   vid.v      vVid
4868     //   vmseq.vx   mMask, vVid, 0
4869     //   vmerge.vvm vDest, vSrc, vVal, mMask
4870     MVT VT = Op.getSimpleValueType();
4871     SDValue Vec = Op.getOperand(1);
4872     SDValue VL = getVLOperand(Op);
4873 
4874     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4875     if (Op.getOperand(1).isUndef())
4876       return SplattedVal;
4877     SDValue SplattedIdx =
4878         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4879                     DAG.getConstant(0, DL, MVT::i32), VL);
4880 
4881     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4882     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4883     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4884     SDValue SelectCond =
4885         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4886                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4887     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4888                        Vec, VL);
4889   }
4890   }
4891 
4892   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4893 }
4894 
4895 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4896                                                     SelectionDAG &DAG) const {
4897   unsigned IntNo = Op.getConstantOperandVal(1);
4898   switch (IntNo) {
4899   default:
4900     break;
4901   case Intrinsic::riscv_masked_strided_load: {
4902     SDLoc DL(Op);
4903     MVT XLenVT = Subtarget.getXLenVT();
4904 
4905     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4906     // the selection of the masked intrinsics doesn't do this for us.
4907     SDValue Mask = Op.getOperand(5);
4908     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4909 
4910     MVT VT = Op->getSimpleValueType(0);
4911     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4912 
4913     SDValue PassThru = Op.getOperand(2);
4914     if (!IsUnmasked) {
4915       MVT MaskVT =
4916           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4917       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4918       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4919     }
4920 
4921     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4922 
4923     SDValue IntID = DAG.getTargetConstant(
4924         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4925         XLenVT);
4926 
4927     auto *Load = cast<MemIntrinsicSDNode>(Op);
4928     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4929     if (IsUnmasked)
4930       Ops.push_back(DAG.getUNDEF(ContainerVT));
4931     else
4932       Ops.push_back(PassThru);
4933     Ops.push_back(Op.getOperand(3)); // Ptr
4934     Ops.push_back(Op.getOperand(4)); // Stride
4935     if (!IsUnmasked)
4936       Ops.push_back(Mask);
4937     Ops.push_back(VL);
4938     if (!IsUnmasked) {
4939       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4940       Ops.push_back(Policy);
4941     }
4942 
4943     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4944     SDValue Result =
4945         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4946                                 Load->getMemoryVT(), Load->getMemOperand());
4947     SDValue Chain = Result.getValue(1);
4948     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4949     return DAG.getMergeValues({Result, Chain}, DL);
4950   }
4951   case Intrinsic::riscv_seg2_load:
4952   case Intrinsic::riscv_seg3_load:
4953   case Intrinsic::riscv_seg4_load:
4954   case Intrinsic::riscv_seg5_load:
4955   case Intrinsic::riscv_seg6_load:
4956   case Intrinsic::riscv_seg7_load:
4957   case Intrinsic::riscv_seg8_load: {
4958     SDLoc DL(Op);
4959     static const Intrinsic::ID VlsegInts[7] = {
4960         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4961         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4962         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4963         Intrinsic::riscv_vlseg8};
4964     unsigned NF = Op->getNumValues() - 1;
4965     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4966     MVT XLenVT = Subtarget.getXLenVT();
4967     MVT VT = Op->getSimpleValueType(0);
4968     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4969 
4970     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4971     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4972     auto *Load = cast<MemIntrinsicSDNode>(Op);
4973     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4974     ContainerVTs.push_back(MVT::Other);
4975     SDVTList VTs = DAG.getVTList(ContainerVTs);
4976     SDValue Result =
4977         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
4978                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
4979                                 Load->getMemoryVT(), Load->getMemOperand());
4980     SmallVector<SDValue, 9> Results;
4981     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4982       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4983                                                   DAG, Subtarget));
4984     Results.push_back(Result.getValue(NF));
4985     return DAG.getMergeValues(Results, DL);
4986   }
4987   }
4988 
4989   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4990 }
4991 
4992 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4993                                                  SelectionDAG &DAG) const {
4994   unsigned IntNo = Op.getConstantOperandVal(1);
4995   switch (IntNo) {
4996   default:
4997     break;
4998   case Intrinsic::riscv_masked_strided_store: {
4999     SDLoc DL(Op);
5000     MVT XLenVT = Subtarget.getXLenVT();
5001 
5002     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5003     // the selection of the masked intrinsics doesn't do this for us.
5004     SDValue Mask = Op.getOperand(5);
5005     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5006 
5007     SDValue Val = Op.getOperand(2);
5008     MVT VT = Val.getSimpleValueType();
5009     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5010 
5011     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5012     if (!IsUnmasked) {
5013       MVT MaskVT =
5014           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5015       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5016     }
5017 
5018     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5019 
5020     SDValue IntID = DAG.getTargetConstant(
5021         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5022         XLenVT);
5023 
5024     auto *Store = cast<MemIntrinsicSDNode>(Op);
5025     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5026     Ops.push_back(Val);
5027     Ops.push_back(Op.getOperand(3)); // Ptr
5028     Ops.push_back(Op.getOperand(4)); // Stride
5029     if (!IsUnmasked)
5030       Ops.push_back(Mask);
5031     Ops.push_back(VL);
5032 
5033     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5034                                    Ops, Store->getMemoryVT(),
5035                                    Store->getMemOperand());
5036   }
5037   }
5038 
5039   return SDValue();
5040 }
5041 
5042 static MVT getLMUL1VT(MVT VT) {
5043   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5044          "Unexpected vector MVT");
5045   return MVT::getScalableVectorVT(
5046       VT.getVectorElementType(),
5047       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5048 }
5049 
5050 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5051   switch (ISDOpcode) {
5052   default:
5053     llvm_unreachable("Unhandled reduction");
5054   case ISD::VECREDUCE_ADD:
5055     return RISCVISD::VECREDUCE_ADD_VL;
5056   case ISD::VECREDUCE_UMAX:
5057     return RISCVISD::VECREDUCE_UMAX_VL;
5058   case ISD::VECREDUCE_SMAX:
5059     return RISCVISD::VECREDUCE_SMAX_VL;
5060   case ISD::VECREDUCE_UMIN:
5061     return RISCVISD::VECREDUCE_UMIN_VL;
5062   case ISD::VECREDUCE_SMIN:
5063     return RISCVISD::VECREDUCE_SMIN_VL;
5064   case ISD::VECREDUCE_AND:
5065     return RISCVISD::VECREDUCE_AND_VL;
5066   case ISD::VECREDUCE_OR:
5067     return RISCVISD::VECREDUCE_OR_VL;
5068   case ISD::VECREDUCE_XOR:
5069     return RISCVISD::VECREDUCE_XOR_VL;
5070   }
5071 }
5072 
5073 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5074                                                          SelectionDAG &DAG,
5075                                                          bool IsVP) const {
5076   SDLoc DL(Op);
5077   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5078   MVT VecVT = Vec.getSimpleValueType();
5079   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5080           Op.getOpcode() == ISD::VECREDUCE_OR ||
5081           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5082           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5083           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5084           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5085          "Unexpected reduction lowering");
5086 
5087   MVT XLenVT = Subtarget.getXLenVT();
5088   assert(Op.getValueType() == XLenVT &&
5089          "Expected reduction output to be legalized to XLenVT");
5090 
5091   MVT ContainerVT = VecVT;
5092   if (VecVT.isFixedLengthVector()) {
5093     ContainerVT = getContainerForFixedLengthVector(VecVT);
5094     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5095   }
5096 
5097   SDValue Mask, VL;
5098   if (IsVP) {
5099     Mask = Op.getOperand(2);
5100     VL = Op.getOperand(3);
5101   } else {
5102     std::tie(Mask, VL) =
5103         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5104   }
5105 
5106   unsigned BaseOpc;
5107   ISD::CondCode CC;
5108   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5109 
5110   switch (Op.getOpcode()) {
5111   default:
5112     llvm_unreachable("Unhandled reduction");
5113   case ISD::VECREDUCE_AND:
5114   case ISD::VP_REDUCE_AND: {
5115     // vcpop ~x == 0
5116     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5117     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5118     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5119     CC = ISD::SETEQ;
5120     BaseOpc = ISD::AND;
5121     break;
5122   }
5123   case ISD::VECREDUCE_OR:
5124   case ISD::VP_REDUCE_OR:
5125     // vcpop x != 0
5126     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5127     CC = ISD::SETNE;
5128     BaseOpc = ISD::OR;
5129     break;
5130   case ISD::VECREDUCE_XOR:
5131   case ISD::VP_REDUCE_XOR: {
5132     // ((vcpop x) & 1) != 0
5133     SDValue One = DAG.getConstant(1, DL, XLenVT);
5134     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5135     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5136     CC = ISD::SETNE;
5137     BaseOpc = ISD::XOR;
5138     break;
5139   }
5140   }
5141 
5142   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5143 
5144   if (!IsVP)
5145     return SetCC;
5146 
5147   // Now include the start value in the operation.
5148   // Note that we must return the start value when no elements are operated
5149   // upon. The vcpop instructions we've emitted in each case above will return
5150   // 0 for an inactive vector, and so we've already received the neutral value:
5151   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5152   // can simply include the start value.
5153   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5154 }
5155 
5156 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5157                                             SelectionDAG &DAG) const {
5158   SDLoc DL(Op);
5159   SDValue Vec = Op.getOperand(0);
5160   EVT VecEVT = Vec.getValueType();
5161 
5162   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5163 
5164   // Due to ordering in legalize types we may have a vector type that needs to
5165   // be split. Do that manually so we can get down to a legal type.
5166   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5167          TargetLowering::TypeSplitVector) {
5168     SDValue Lo, Hi;
5169     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5170     VecEVT = Lo.getValueType();
5171     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5172   }
5173 
5174   // TODO: The type may need to be widened rather than split. Or widened before
5175   // it can be split.
5176   if (!isTypeLegal(VecEVT))
5177     return SDValue();
5178 
5179   MVT VecVT = VecEVT.getSimpleVT();
5180   MVT VecEltVT = VecVT.getVectorElementType();
5181   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5182 
5183   MVT ContainerVT = VecVT;
5184   if (VecVT.isFixedLengthVector()) {
5185     ContainerVT = getContainerForFixedLengthVector(VecVT);
5186     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5187   }
5188 
5189   MVT M1VT = getLMUL1VT(ContainerVT);
5190   MVT XLenVT = Subtarget.getXLenVT();
5191 
5192   SDValue Mask, VL;
5193   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5194 
5195   SDValue NeutralElem =
5196       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5197   SDValue IdentitySplat =
5198       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5199                        M1VT, DL, DAG, Subtarget);
5200   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5201                                   IdentitySplat, Mask, VL);
5202   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5203                              DAG.getConstant(0, DL, XLenVT));
5204   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5205 }
5206 
5207 // Given a reduction op, this function returns the matching reduction opcode,
5208 // the vector SDValue and the scalar SDValue required to lower this to a
5209 // RISCVISD node.
5210 static std::tuple<unsigned, SDValue, SDValue>
5211 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5212   SDLoc DL(Op);
5213   auto Flags = Op->getFlags();
5214   unsigned Opcode = Op.getOpcode();
5215   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5216   switch (Opcode) {
5217   default:
5218     llvm_unreachable("Unhandled reduction");
5219   case ISD::VECREDUCE_FADD: {
5220     // Use positive zero if we can. It is cheaper to materialize.
5221     SDValue Zero =
5222         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5223     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5224   }
5225   case ISD::VECREDUCE_SEQ_FADD:
5226     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5227                            Op.getOperand(0));
5228   case ISD::VECREDUCE_FMIN:
5229     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5230                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5231   case ISD::VECREDUCE_FMAX:
5232     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5233                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5234   }
5235 }
5236 
5237 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5238                                               SelectionDAG &DAG) const {
5239   SDLoc DL(Op);
5240   MVT VecEltVT = Op.getSimpleValueType();
5241 
5242   unsigned RVVOpcode;
5243   SDValue VectorVal, ScalarVal;
5244   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5245       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5246   MVT VecVT = VectorVal.getSimpleValueType();
5247 
5248   MVT ContainerVT = VecVT;
5249   if (VecVT.isFixedLengthVector()) {
5250     ContainerVT = getContainerForFixedLengthVector(VecVT);
5251     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5252   }
5253 
5254   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5255   MVT XLenVT = Subtarget.getXLenVT();
5256 
5257   SDValue Mask, VL;
5258   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5259 
5260   SDValue ScalarSplat =
5261       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5262                        M1VT, DL, DAG, Subtarget);
5263   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5264                                   VectorVal, ScalarSplat, Mask, VL);
5265   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5266                      DAG.getConstant(0, DL, XLenVT));
5267 }
5268 
5269 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5270   switch (ISDOpcode) {
5271   default:
5272     llvm_unreachable("Unhandled reduction");
5273   case ISD::VP_REDUCE_ADD:
5274     return RISCVISD::VECREDUCE_ADD_VL;
5275   case ISD::VP_REDUCE_UMAX:
5276     return RISCVISD::VECREDUCE_UMAX_VL;
5277   case ISD::VP_REDUCE_SMAX:
5278     return RISCVISD::VECREDUCE_SMAX_VL;
5279   case ISD::VP_REDUCE_UMIN:
5280     return RISCVISD::VECREDUCE_UMIN_VL;
5281   case ISD::VP_REDUCE_SMIN:
5282     return RISCVISD::VECREDUCE_SMIN_VL;
5283   case ISD::VP_REDUCE_AND:
5284     return RISCVISD::VECREDUCE_AND_VL;
5285   case ISD::VP_REDUCE_OR:
5286     return RISCVISD::VECREDUCE_OR_VL;
5287   case ISD::VP_REDUCE_XOR:
5288     return RISCVISD::VECREDUCE_XOR_VL;
5289   case ISD::VP_REDUCE_FADD:
5290     return RISCVISD::VECREDUCE_FADD_VL;
5291   case ISD::VP_REDUCE_SEQ_FADD:
5292     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5293   case ISD::VP_REDUCE_FMAX:
5294     return RISCVISD::VECREDUCE_FMAX_VL;
5295   case ISD::VP_REDUCE_FMIN:
5296     return RISCVISD::VECREDUCE_FMIN_VL;
5297   }
5298 }
5299 
5300 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5301                                            SelectionDAG &DAG) const {
5302   SDLoc DL(Op);
5303   SDValue Vec = Op.getOperand(1);
5304   EVT VecEVT = Vec.getValueType();
5305 
5306   // TODO: The type may need to be widened rather than split. Or widened before
5307   // it can be split.
5308   if (!isTypeLegal(VecEVT))
5309     return SDValue();
5310 
5311   MVT VecVT = VecEVT.getSimpleVT();
5312   MVT VecEltVT = VecVT.getVectorElementType();
5313   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5314 
5315   MVT ContainerVT = VecVT;
5316   if (VecVT.isFixedLengthVector()) {
5317     ContainerVT = getContainerForFixedLengthVector(VecVT);
5318     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5319   }
5320 
5321   SDValue VL = Op.getOperand(3);
5322   SDValue Mask = Op.getOperand(2);
5323 
5324   MVT M1VT = getLMUL1VT(ContainerVT);
5325   MVT XLenVT = Subtarget.getXLenVT();
5326   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5327 
5328   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5329                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5330                                         DL, DAG, Subtarget);
5331   SDValue Reduction =
5332       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5333   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5334                              DAG.getConstant(0, DL, XLenVT));
5335   if (!VecVT.isInteger())
5336     return Elt0;
5337   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5338 }
5339 
5340 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5341                                                    SelectionDAG &DAG) const {
5342   SDValue Vec = Op.getOperand(0);
5343   SDValue SubVec = Op.getOperand(1);
5344   MVT VecVT = Vec.getSimpleValueType();
5345   MVT SubVecVT = SubVec.getSimpleValueType();
5346 
5347   SDLoc DL(Op);
5348   MVT XLenVT = Subtarget.getXLenVT();
5349   unsigned OrigIdx = Op.getConstantOperandVal(2);
5350   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5351 
5352   // We don't have the ability to slide mask vectors up indexed by their i1
5353   // elements; the smallest we can do is i8. Often we are able to bitcast to
5354   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5355   // into a scalable one, we might not necessarily have enough scalable
5356   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5357   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5358       (OrigIdx != 0 || !Vec.isUndef())) {
5359     if (VecVT.getVectorMinNumElements() >= 8 &&
5360         SubVecVT.getVectorMinNumElements() >= 8) {
5361       assert(OrigIdx % 8 == 0 && "Invalid index");
5362       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5363              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5364              "Unexpected mask vector lowering");
5365       OrigIdx /= 8;
5366       SubVecVT =
5367           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5368                            SubVecVT.isScalableVector());
5369       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5370                                VecVT.isScalableVector());
5371       Vec = DAG.getBitcast(VecVT, Vec);
5372       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5373     } else {
5374       // We can't slide this mask vector up indexed by its i1 elements.
5375       // This poses a problem when we wish to insert a scalable vector which
5376       // can't be re-expressed as a larger type. Just choose the slow path and
5377       // extend to a larger type, then truncate back down.
5378       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5379       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5380       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5381       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5382       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5383                         Op.getOperand(2));
5384       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5385       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5386     }
5387   }
5388 
5389   // If the subvector vector is a fixed-length type, we cannot use subregister
5390   // manipulation to simplify the codegen; we don't know which register of a
5391   // LMUL group contains the specific subvector as we only know the minimum
5392   // register size. Therefore we must slide the vector group up the full
5393   // amount.
5394   if (SubVecVT.isFixedLengthVector()) {
5395     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5396       return Op;
5397     MVT ContainerVT = VecVT;
5398     if (VecVT.isFixedLengthVector()) {
5399       ContainerVT = getContainerForFixedLengthVector(VecVT);
5400       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5401     }
5402     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5403                          DAG.getUNDEF(ContainerVT), SubVec,
5404                          DAG.getConstant(0, DL, XLenVT));
5405     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5406       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5407       return DAG.getBitcast(Op.getValueType(), SubVec);
5408     }
5409     SDValue Mask =
5410         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5411     // Set the vector length to only the number of elements we care about. Note
5412     // that for slideup this includes the offset.
5413     SDValue VL =
5414         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5415     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5416     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5417                                   SubVec, SlideupAmt, Mask, VL);
5418     if (VecVT.isFixedLengthVector())
5419       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5420     return DAG.getBitcast(Op.getValueType(), Slideup);
5421   }
5422 
5423   unsigned SubRegIdx, RemIdx;
5424   std::tie(SubRegIdx, RemIdx) =
5425       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5426           VecVT, SubVecVT, OrigIdx, TRI);
5427 
5428   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5429   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5430                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5431                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5432 
5433   // 1. If the Idx has been completely eliminated and this subvector's size is
5434   // a vector register or a multiple thereof, or the surrounding elements are
5435   // undef, then this is a subvector insert which naturally aligns to a vector
5436   // register. These can easily be handled using subregister manipulation.
5437   // 2. If the subvector is smaller than a vector register, then the insertion
5438   // must preserve the undisturbed elements of the register. We do this by
5439   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5440   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5441   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5442   // LMUL=1 type back into the larger vector (resolving to another subregister
5443   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5444   // to avoid allocating a large register group to hold our subvector.
5445   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5446     return Op;
5447 
5448   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5449   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5450   // (in our case undisturbed). This means we can set up a subvector insertion
5451   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5452   // size of the subvector.
5453   MVT InterSubVT = VecVT;
5454   SDValue AlignedExtract = Vec;
5455   unsigned AlignedIdx = OrigIdx - RemIdx;
5456   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5457     InterSubVT = getLMUL1VT(VecVT);
5458     // Extract a subvector equal to the nearest full vector register type. This
5459     // should resolve to a EXTRACT_SUBREG instruction.
5460     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5461                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5462   }
5463 
5464   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5465   // For scalable vectors this must be further multiplied by vscale.
5466   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5467 
5468   SDValue Mask, VL;
5469   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5470 
5471   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5472   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5473   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5474   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5475 
5476   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5477                        DAG.getUNDEF(InterSubVT), SubVec,
5478                        DAG.getConstant(0, DL, XLenVT));
5479 
5480   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5481                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5482 
5483   // If required, insert this subvector back into the correct vector register.
5484   // This should resolve to an INSERT_SUBREG instruction.
5485   if (VecVT.bitsGT(InterSubVT))
5486     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5487                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5488 
5489   // We might have bitcast from a mask type: cast back to the original type if
5490   // required.
5491   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5492 }
5493 
5494 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5495                                                     SelectionDAG &DAG) const {
5496   SDValue Vec = Op.getOperand(0);
5497   MVT SubVecVT = Op.getSimpleValueType();
5498   MVT VecVT = Vec.getSimpleValueType();
5499 
5500   SDLoc DL(Op);
5501   MVT XLenVT = Subtarget.getXLenVT();
5502   unsigned OrigIdx = Op.getConstantOperandVal(1);
5503   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5504 
5505   // We don't have the ability to slide mask vectors down indexed by their i1
5506   // elements; the smallest we can do is i8. Often we are able to bitcast to
5507   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5508   // from a scalable one, we might not necessarily have enough scalable
5509   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5510   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5511     if (VecVT.getVectorMinNumElements() >= 8 &&
5512         SubVecVT.getVectorMinNumElements() >= 8) {
5513       assert(OrigIdx % 8 == 0 && "Invalid index");
5514       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5515              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5516              "Unexpected mask vector lowering");
5517       OrigIdx /= 8;
5518       SubVecVT =
5519           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5520                            SubVecVT.isScalableVector());
5521       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5522                                VecVT.isScalableVector());
5523       Vec = DAG.getBitcast(VecVT, Vec);
5524     } else {
5525       // We can't slide this mask vector down, indexed by its i1 elements.
5526       // This poses a problem when we wish to extract a scalable vector which
5527       // can't be re-expressed as a larger type. Just choose the slow path and
5528       // extend to a larger type, then truncate back down.
5529       // TODO: We could probably improve this when extracting certain fixed
5530       // from fixed, where we can extract as i8 and shift the correct element
5531       // right to reach the desired subvector?
5532       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5533       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5534       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5535       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5536                         Op.getOperand(1));
5537       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5538       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5539     }
5540   }
5541 
5542   // If the subvector vector is a fixed-length type, we cannot use subregister
5543   // manipulation to simplify the codegen; we don't know which register of a
5544   // LMUL group contains the specific subvector as we only know the minimum
5545   // register size. Therefore we must slide the vector group down the full
5546   // amount.
5547   if (SubVecVT.isFixedLengthVector()) {
5548     // With an index of 0 this is a cast-like subvector, which can be performed
5549     // with subregister operations.
5550     if (OrigIdx == 0)
5551       return Op;
5552     MVT ContainerVT = VecVT;
5553     if (VecVT.isFixedLengthVector()) {
5554       ContainerVT = getContainerForFixedLengthVector(VecVT);
5555       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5556     }
5557     SDValue Mask =
5558         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5559     // Set the vector length to only the number of elements we care about. This
5560     // avoids sliding down elements we're going to discard straight away.
5561     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5562     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5563     SDValue Slidedown =
5564         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5565                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5566     // Now we can use a cast-like subvector extract to get the result.
5567     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5568                             DAG.getConstant(0, DL, XLenVT));
5569     return DAG.getBitcast(Op.getValueType(), Slidedown);
5570   }
5571 
5572   unsigned SubRegIdx, RemIdx;
5573   std::tie(SubRegIdx, RemIdx) =
5574       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5575           VecVT, SubVecVT, OrigIdx, TRI);
5576 
5577   // If the Idx has been completely eliminated then this is a subvector extract
5578   // which naturally aligns to a vector register. These can easily be handled
5579   // using subregister manipulation.
5580   if (RemIdx == 0)
5581     return Op;
5582 
5583   // Else we must shift our vector register directly to extract the subvector.
5584   // Do this using VSLIDEDOWN.
5585 
5586   // If the vector type is an LMUL-group type, extract a subvector equal to the
5587   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5588   // instruction.
5589   MVT InterSubVT = VecVT;
5590   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5591     InterSubVT = getLMUL1VT(VecVT);
5592     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5593                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5594   }
5595 
5596   // Slide this vector register down by the desired number of elements in order
5597   // to place the desired subvector starting at element 0.
5598   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5599   // For scalable vectors this must be further multiplied by vscale.
5600   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5601 
5602   SDValue Mask, VL;
5603   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5604   SDValue Slidedown =
5605       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5606                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5607 
5608   // Now the vector is in the right position, extract our final subvector. This
5609   // should resolve to a COPY.
5610   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5611                           DAG.getConstant(0, DL, XLenVT));
5612 
5613   // We might have bitcast from a mask type: cast back to the original type if
5614   // required.
5615   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5616 }
5617 
5618 // Lower step_vector to the vid instruction. Any non-identity step value must
5619 // be accounted for my manual expansion.
5620 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5621                                               SelectionDAG &DAG) const {
5622   SDLoc DL(Op);
5623   MVT VT = Op.getSimpleValueType();
5624   MVT XLenVT = Subtarget.getXLenVT();
5625   SDValue Mask, VL;
5626   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5627   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5628   uint64_t StepValImm = Op.getConstantOperandVal(0);
5629   if (StepValImm != 1) {
5630     if (isPowerOf2_64(StepValImm)) {
5631       SDValue StepVal =
5632           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5633                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5634       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5635     } else {
5636       SDValue StepVal = lowerScalarSplat(
5637           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5638           VL, VT, DL, DAG, Subtarget);
5639       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5640     }
5641   }
5642   return StepVec;
5643 }
5644 
5645 // Implement vector_reverse using vrgather.vv with indices determined by
5646 // subtracting the id of each element from (VLMAX-1). This will convert
5647 // the indices like so:
5648 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5649 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5650 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5651                                                  SelectionDAG &DAG) const {
5652   SDLoc DL(Op);
5653   MVT VecVT = Op.getSimpleValueType();
5654   unsigned EltSize = VecVT.getScalarSizeInBits();
5655   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5656 
5657   unsigned MaxVLMAX = 0;
5658   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5659   if (VectorBitsMax != 0)
5660     MaxVLMAX =
5661         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5662 
5663   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5664   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5665 
5666   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5667   // to use vrgatherei16.vv.
5668   // TODO: It's also possible to use vrgatherei16.vv for other types to
5669   // decrease register width for the index calculation.
5670   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5671     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5672     // Reverse each half, then reassemble them in reverse order.
5673     // NOTE: It's also possible that after splitting that VLMAX no longer
5674     // requires vrgatherei16.vv.
5675     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5676       SDValue Lo, Hi;
5677       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5678       EVT LoVT, HiVT;
5679       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5680       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5681       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5682       // Reassemble the low and high pieces reversed.
5683       // FIXME: This is a CONCAT_VECTORS.
5684       SDValue Res =
5685           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5686                       DAG.getIntPtrConstant(0, DL));
5687       return DAG.getNode(
5688           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5689           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5690     }
5691 
5692     // Just promote the int type to i16 which will double the LMUL.
5693     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5694     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5695   }
5696 
5697   MVT XLenVT = Subtarget.getXLenVT();
5698   SDValue Mask, VL;
5699   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5700 
5701   // Calculate VLMAX-1 for the desired SEW.
5702   unsigned MinElts = VecVT.getVectorMinNumElements();
5703   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5704                               DAG.getConstant(MinElts, DL, XLenVT));
5705   SDValue VLMinus1 =
5706       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5707 
5708   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5709   bool IsRV32E64 =
5710       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5711   SDValue SplatVL;
5712   if (!IsRV32E64)
5713     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5714   else
5715     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5716                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5717 
5718   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5719   SDValue Indices =
5720       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5721 
5722   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5723 }
5724 
5725 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5726                                                 SelectionDAG &DAG) const {
5727   SDLoc DL(Op);
5728   SDValue V1 = Op.getOperand(0);
5729   SDValue V2 = Op.getOperand(1);
5730   MVT XLenVT = Subtarget.getXLenVT();
5731   MVT VecVT = Op.getSimpleValueType();
5732 
5733   unsigned MinElts = VecVT.getVectorMinNumElements();
5734   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5735                               DAG.getConstant(MinElts, DL, XLenVT));
5736 
5737   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5738   SDValue DownOffset, UpOffset;
5739   if (ImmValue >= 0) {
5740     // The operand is a TargetConstant, we need to rebuild it as a regular
5741     // constant.
5742     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5743     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5744   } else {
5745     // The operand is a TargetConstant, we need to rebuild it as a regular
5746     // constant rather than negating the original operand.
5747     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5748     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5749   }
5750 
5751   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5752   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5753 
5754   SDValue SlideDown =
5755       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5756                   DownOffset, TrueMask, UpOffset);
5757   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5758                      TrueMask,
5759                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5760 }
5761 
5762 SDValue
5763 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5764                                                      SelectionDAG &DAG) const {
5765   SDLoc DL(Op);
5766   auto *Load = cast<LoadSDNode>(Op);
5767 
5768   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5769                                         Load->getMemoryVT(),
5770                                         *Load->getMemOperand()) &&
5771          "Expecting a correctly-aligned load");
5772 
5773   MVT VT = Op.getSimpleValueType();
5774   MVT XLenVT = Subtarget.getXLenVT();
5775   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5776 
5777   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5778 
5779   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5780   SDValue IntID = DAG.getTargetConstant(
5781       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5782   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5783   if (!IsMaskOp)
5784     Ops.push_back(DAG.getUNDEF(ContainerVT));
5785   Ops.push_back(Load->getBasePtr());
5786   Ops.push_back(VL);
5787   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5788   SDValue NewLoad =
5789       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5790                               Load->getMemoryVT(), Load->getMemOperand());
5791 
5792   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5793   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5794 }
5795 
5796 SDValue
5797 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5798                                                       SelectionDAG &DAG) const {
5799   SDLoc DL(Op);
5800   auto *Store = cast<StoreSDNode>(Op);
5801 
5802   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5803                                         Store->getMemoryVT(),
5804                                         *Store->getMemOperand()) &&
5805          "Expecting a correctly-aligned store");
5806 
5807   SDValue StoreVal = Store->getValue();
5808   MVT VT = StoreVal.getSimpleValueType();
5809   MVT XLenVT = Subtarget.getXLenVT();
5810 
5811   // If the size less than a byte, we need to pad with zeros to make a byte.
5812   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5813     VT = MVT::v8i1;
5814     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5815                            DAG.getConstant(0, DL, VT), StoreVal,
5816                            DAG.getIntPtrConstant(0, DL));
5817   }
5818 
5819   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5820 
5821   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5822 
5823   SDValue NewValue =
5824       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5825 
5826   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5827   SDValue IntID = DAG.getTargetConstant(
5828       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5829   return DAG.getMemIntrinsicNode(
5830       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5831       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5832       Store->getMemoryVT(), Store->getMemOperand());
5833 }
5834 
5835 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5836                                              SelectionDAG &DAG) const {
5837   SDLoc DL(Op);
5838   MVT VT = Op.getSimpleValueType();
5839 
5840   const auto *MemSD = cast<MemSDNode>(Op);
5841   EVT MemVT = MemSD->getMemoryVT();
5842   MachineMemOperand *MMO = MemSD->getMemOperand();
5843   SDValue Chain = MemSD->getChain();
5844   SDValue BasePtr = MemSD->getBasePtr();
5845 
5846   SDValue Mask, PassThru, VL;
5847   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5848     Mask = VPLoad->getMask();
5849     PassThru = DAG.getUNDEF(VT);
5850     VL = VPLoad->getVectorLength();
5851   } else {
5852     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5853     Mask = MLoad->getMask();
5854     PassThru = MLoad->getPassThru();
5855   }
5856 
5857   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5858 
5859   MVT XLenVT = Subtarget.getXLenVT();
5860 
5861   MVT ContainerVT = VT;
5862   if (VT.isFixedLengthVector()) {
5863     ContainerVT = getContainerForFixedLengthVector(VT);
5864     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5865     if (!IsUnmasked) {
5866       MVT MaskVT =
5867           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5868       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5869     }
5870   }
5871 
5872   if (!VL)
5873     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5874 
5875   unsigned IntID =
5876       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5877   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5878   if (IsUnmasked)
5879     Ops.push_back(DAG.getUNDEF(ContainerVT));
5880   else
5881     Ops.push_back(PassThru);
5882   Ops.push_back(BasePtr);
5883   if (!IsUnmasked)
5884     Ops.push_back(Mask);
5885   Ops.push_back(VL);
5886   if (!IsUnmasked)
5887     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5888 
5889   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5890 
5891   SDValue Result =
5892       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5893   Chain = Result.getValue(1);
5894 
5895   if (VT.isFixedLengthVector())
5896     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5897 
5898   return DAG.getMergeValues({Result, Chain}, DL);
5899 }
5900 
5901 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5902                                               SelectionDAG &DAG) const {
5903   SDLoc DL(Op);
5904 
5905   const auto *MemSD = cast<MemSDNode>(Op);
5906   EVT MemVT = MemSD->getMemoryVT();
5907   MachineMemOperand *MMO = MemSD->getMemOperand();
5908   SDValue Chain = MemSD->getChain();
5909   SDValue BasePtr = MemSD->getBasePtr();
5910   SDValue Val, Mask, VL;
5911 
5912   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5913     Val = VPStore->getValue();
5914     Mask = VPStore->getMask();
5915     VL = VPStore->getVectorLength();
5916   } else {
5917     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5918     Val = MStore->getValue();
5919     Mask = MStore->getMask();
5920   }
5921 
5922   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5923 
5924   MVT VT = Val.getSimpleValueType();
5925   MVT XLenVT = Subtarget.getXLenVT();
5926 
5927   MVT ContainerVT = VT;
5928   if (VT.isFixedLengthVector()) {
5929     ContainerVT = getContainerForFixedLengthVector(VT);
5930 
5931     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5932     if (!IsUnmasked) {
5933       MVT MaskVT =
5934           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5935       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5936     }
5937   }
5938 
5939   if (!VL)
5940     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5941 
5942   unsigned IntID =
5943       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5944   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5945   Ops.push_back(Val);
5946   Ops.push_back(BasePtr);
5947   if (!IsUnmasked)
5948     Ops.push_back(Mask);
5949   Ops.push_back(VL);
5950 
5951   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5952                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5953 }
5954 
5955 SDValue
5956 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5957                                                       SelectionDAG &DAG) const {
5958   MVT InVT = Op.getOperand(0).getSimpleValueType();
5959   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5960 
5961   MVT VT = Op.getSimpleValueType();
5962 
5963   SDValue Op1 =
5964       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5965   SDValue Op2 =
5966       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5967 
5968   SDLoc DL(Op);
5969   SDValue VL =
5970       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5971 
5972   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5973   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5974 
5975   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5976                             Op.getOperand(2), Mask, VL);
5977 
5978   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5979 }
5980 
5981 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5982     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5983   MVT VT = Op.getSimpleValueType();
5984 
5985   if (VT.getVectorElementType() == MVT::i1)
5986     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5987 
5988   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5989 }
5990 
5991 SDValue
5992 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5993                                                       SelectionDAG &DAG) const {
5994   unsigned Opc;
5995   switch (Op.getOpcode()) {
5996   default: llvm_unreachable("Unexpected opcode!");
5997   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5998   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5999   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
6000   }
6001 
6002   return lowerToScalableOp(Op, DAG, Opc);
6003 }
6004 
6005 // Lower vector ABS to smax(X, sub(0, X)).
6006 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6007   SDLoc DL(Op);
6008   MVT VT = Op.getSimpleValueType();
6009   SDValue X = Op.getOperand(0);
6010 
6011   assert(VT.isFixedLengthVector() && "Unexpected type");
6012 
6013   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6014   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6015 
6016   SDValue Mask, VL;
6017   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6018 
6019   SDValue SplatZero = DAG.getNode(
6020       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6021       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6022   SDValue NegX =
6023       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6024   SDValue Max =
6025       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6026 
6027   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6028 }
6029 
6030 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6031     SDValue Op, SelectionDAG &DAG) const {
6032   SDLoc DL(Op);
6033   MVT VT = Op.getSimpleValueType();
6034   SDValue Mag = Op.getOperand(0);
6035   SDValue Sign = Op.getOperand(1);
6036   assert(Mag.getValueType() == Sign.getValueType() &&
6037          "Can only handle COPYSIGN with matching types.");
6038 
6039   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6040   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6041   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6042 
6043   SDValue Mask, VL;
6044   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6045 
6046   SDValue CopySign =
6047       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6048 
6049   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6050 }
6051 
6052 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6053     SDValue Op, SelectionDAG &DAG) const {
6054   MVT VT = Op.getSimpleValueType();
6055   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6056 
6057   MVT I1ContainerVT =
6058       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6059 
6060   SDValue CC =
6061       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6062   SDValue Op1 =
6063       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6064   SDValue Op2 =
6065       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6066 
6067   SDLoc DL(Op);
6068   SDValue Mask, VL;
6069   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6070 
6071   SDValue Select =
6072       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6073 
6074   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6075 }
6076 
6077 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6078                                                unsigned NewOpc,
6079                                                bool HasMask) const {
6080   MVT VT = Op.getSimpleValueType();
6081   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6082 
6083   // Create list of operands by converting existing ones to scalable types.
6084   SmallVector<SDValue, 6> Ops;
6085   for (const SDValue &V : Op->op_values()) {
6086     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6087 
6088     // Pass through non-vector operands.
6089     if (!V.getValueType().isVector()) {
6090       Ops.push_back(V);
6091       continue;
6092     }
6093 
6094     // "cast" fixed length vector to a scalable vector.
6095     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6096            "Only fixed length vectors are supported!");
6097     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6098   }
6099 
6100   SDLoc DL(Op);
6101   SDValue Mask, VL;
6102   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6103   if (HasMask)
6104     Ops.push_back(Mask);
6105   Ops.push_back(VL);
6106 
6107   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6108   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6109 }
6110 
6111 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6112 // * Operands of each node are assumed to be in the same order.
6113 // * The EVL operand is promoted from i32 to i64 on RV64.
6114 // * Fixed-length vectors are converted to their scalable-vector container
6115 //   types.
6116 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6117                                        unsigned RISCVISDOpc) const {
6118   SDLoc DL(Op);
6119   MVT VT = Op.getSimpleValueType();
6120   SmallVector<SDValue, 4> Ops;
6121 
6122   for (const auto &OpIdx : enumerate(Op->ops())) {
6123     SDValue V = OpIdx.value();
6124     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6125     // Pass through operands which aren't fixed-length vectors.
6126     if (!V.getValueType().isFixedLengthVector()) {
6127       Ops.push_back(V);
6128       continue;
6129     }
6130     // "cast" fixed length vector to a scalable vector.
6131     MVT OpVT = V.getSimpleValueType();
6132     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6133     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6134            "Only fixed length vectors are supported!");
6135     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6136   }
6137 
6138   if (!VT.isFixedLengthVector())
6139     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6140 
6141   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6142 
6143   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6144 
6145   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6146 }
6147 
6148 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6149                                               SelectionDAG &DAG) const {
6150   SDLoc DL(Op);
6151   MVT VT = Op.getSimpleValueType();
6152 
6153   SDValue Src = Op.getOperand(0);
6154   // NOTE: Mask is dropped.
6155   SDValue VL = Op.getOperand(2);
6156 
6157   MVT ContainerVT = VT;
6158   if (VT.isFixedLengthVector()) {
6159     ContainerVT = getContainerForFixedLengthVector(VT);
6160     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6161     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6162   }
6163 
6164   MVT XLenVT = Subtarget.getXLenVT();
6165   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6166   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6167                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6168 
6169   SDValue SplatValue =
6170       DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT);
6171   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6172                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6173 
6174   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6175                                Splat, ZeroSplat, VL);
6176   if (!VT.isFixedLengthVector())
6177     return Result;
6178   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6179 }
6180 
6181 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6182 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6183                                                 unsigned RISCVISDOpc) const {
6184   SDLoc DL(Op);
6185 
6186   SDValue Src = Op.getOperand(0);
6187   SDValue Mask = Op.getOperand(1);
6188   SDValue VL = Op.getOperand(2);
6189 
6190   MVT DstVT = Op.getSimpleValueType();
6191   MVT SrcVT = Src.getSimpleValueType();
6192   if (DstVT.isFixedLengthVector()) {
6193     DstVT = getContainerForFixedLengthVector(DstVT);
6194     SrcVT = getContainerForFixedLengthVector(SrcVT);
6195     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6196     MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount());
6197     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6198   }
6199 
6200   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6201                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6202                                 ? RISCVISD::VSEXT_VL
6203                                 : RISCVISD::VZEXT_VL;
6204 
6205   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6206   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6207 
6208   SDValue Result;
6209   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6210     if (SrcVT.isInteger()) {
6211       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6212 
6213       // Do we need to do any pre-widening before converting?
6214       if (SrcEltSize == 1) {
6215         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6216         MVT XLenVT = Subtarget.getXLenVT();
6217         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6218         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6219                                         DAG.getUNDEF(IntVT), Zero, VL);
6220         SDValue One = DAG.getConstant(
6221             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6222         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6223                                        DAG.getUNDEF(IntVT), One, VL);
6224         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6225                           ZeroSplat, VL);
6226       } else if (DstEltSize > (2 * SrcEltSize)) {
6227         // Widen before converting.
6228         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6229                                      DstVT.getVectorElementCount());
6230         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6231       }
6232 
6233       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6234     } else {
6235       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6236              "Wrong input/output vector types");
6237 
6238       // Convert f16 to f32 then convert f32 to i64.
6239       if (DstEltSize > (2 * SrcEltSize)) {
6240         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6241         MVT InterimFVT =
6242             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6243         Src =
6244             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6245       }
6246 
6247       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6248     }
6249   } else { // Narrowing + Conversion
6250     if (SrcVT.isInteger()) {
6251       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6252       // First do a narrowing convert to an FP type half the size, then round
6253       // the FP type to a small FP type if needed.
6254 
6255       MVT InterimFVT = DstVT;
6256       if (SrcEltSize > (2 * DstEltSize)) {
6257         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6258         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6259         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6260       }
6261 
6262       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6263 
6264       if (InterimFVT != DstVT) {
6265         Src = Result;
6266         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6267       }
6268     } else {
6269       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6270              "Wrong input/output vector types");
6271       // First do a narrowing conversion to an integer half the size, then
6272       // truncate if needed.
6273 
6274       if (DstEltSize == 1) {
6275         // First convert to the same size integer, then convert to mask using
6276         // setcc.
6277         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6278         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6279                                           DstVT.getVectorElementCount());
6280         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6281 
6282         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6283         // otherwise the conversion was undefined.
6284         MVT XLenVT = Subtarget.getXLenVT();
6285         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6286         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6287                                 DAG.getUNDEF(InterimIVT), SplatZero);
6288         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6289                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6290       } else {
6291         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6292                                           DstVT.getVectorElementCount());
6293 
6294         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6295 
6296         while (InterimIVT != DstVT) {
6297           SrcEltSize /= 2;
6298           Src = Result;
6299           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6300                                         DstVT.getVectorElementCount());
6301           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6302                                Src, Mask, VL);
6303         }
6304       }
6305     }
6306   }
6307 
6308   MVT VT = Op.getSimpleValueType();
6309   if (!VT.isFixedLengthVector())
6310     return Result;
6311   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6312 }
6313 
6314 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6315                                             unsigned MaskOpc,
6316                                             unsigned VecOpc) const {
6317   MVT VT = Op.getSimpleValueType();
6318   if (VT.getVectorElementType() != MVT::i1)
6319     return lowerVPOp(Op, DAG, VecOpc);
6320 
6321   // It is safe to drop mask parameter as masked-off elements are undef.
6322   SDValue Op1 = Op->getOperand(0);
6323   SDValue Op2 = Op->getOperand(1);
6324   SDValue VL = Op->getOperand(3);
6325 
6326   MVT ContainerVT = VT;
6327   const bool IsFixed = VT.isFixedLengthVector();
6328   if (IsFixed) {
6329     ContainerVT = getContainerForFixedLengthVector(VT);
6330     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6331     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6332   }
6333 
6334   SDLoc DL(Op);
6335   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6336   if (!IsFixed)
6337     return Val;
6338   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6339 }
6340 
6341 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6342 // matched to a RVV indexed load. The RVV indexed load instructions only
6343 // support the "unsigned unscaled" addressing mode; indices are implicitly
6344 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6345 // signed or scaled indexing is extended to the XLEN value type and scaled
6346 // accordingly.
6347 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6348                                                SelectionDAG &DAG) const {
6349   SDLoc DL(Op);
6350   MVT VT = Op.getSimpleValueType();
6351 
6352   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6353   EVT MemVT = MemSD->getMemoryVT();
6354   MachineMemOperand *MMO = MemSD->getMemOperand();
6355   SDValue Chain = MemSD->getChain();
6356   SDValue BasePtr = MemSD->getBasePtr();
6357 
6358   ISD::LoadExtType LoadExtType;
6359   SDValue Index, Mask, PassThru, VL;
6360 
6361   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6362     Index = VPGN->getIndex();
6363     Mask = VPGN->getMask();
6364     PassThru = DAG.getUNDEF(VT);
6365     VL = VPGN->getVectorLength();
6366     // VP doesn't support extending loads.
6367     LoadExtType = ISD::NON_EXTLOAD;
6368   } else {
6369     // Else it must be a MGATHER.
6370     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6371     Index = MGN->getIndex();
6372     Mask = MGN->getMask();
6373     PassThru = MGN->getPassThru();
6374     LoadExtType = MGN->getExtensionType();
6375   }
6376 
6377   MVT IndexVT = Index.getSimpleValueType();
6378   MVT XLenVT = Subtarget.getXLenVT();
6379 
6380   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6381          "Unexpected VTs!");
6382   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6383   // Targets have to explicitly opt-in for extending vector loads.
6384   assert(LoadExtType == ISD::NON_EXTLOAD &&
6385          "Unexpected extending MGATHER/VP_GATHER");
6386   (void)LoadExtType;
6387 
6388   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6389   // the selection of the masked intrinsics doesn't do this for us.
6390   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6391 
6392   MVT ContainerVT = VT;
6393   if (VT.isFixedLengthVector()) {
6394     // We need to use the larger of the result and index type to determine the
6395     // scalable type to use so we don't increase LMUL for any operand/result.
6396     if (VT.bitsGE(IndexVT)) {
6397       ContainerVT = getContainerForFixedLengthVector(VT);
6398       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6399                                  ContainerVT.getVectorElementCount());
6400     } else {
6401       IndexVT = getContainerForFixedLengthVector(IndexVT);
6402       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6403                                      IndexVT.getVectorElementCount());
6404     }
6405 
6406     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6407 
6408     if (!IsUnmasked) {
6409       MVT MaskVT =
6410           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6411       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6412       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6413     }
6414   }
6415 
6416   if (!VL)
6417     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6418 
6419   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6420     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6421     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6422                                    VL);
6423     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6424                         TrueMask, VL);
6425   }
6426 
6427   unsigned IntID =
6428       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6429   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6430   if (IsUnmasked)
6431     Ops.push_back(DAG.getUNDEF(ContainerVT));
6432   else
6433     Ops.push_back(PassThru);
6434   Ops.push_back(BasePtr);
6435   Ops.push_back(Index);
6436   if (!IsUnmasked)
6437     Ops.push_back(Mask);
6438   Ops.push_back(VL);
6439   if (!IsUnmasked)
6440     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6441 
6442   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6443   SDValue Result =
6444       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6445   Chain = Result.getValue(1);
6446 
6447   if (VT.isFixedLengthVector())
6448     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6449 
6450   return DAG.getMergeValues({Result, Chain}, DL);
6451 }
6452 
6453 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6454 // matched to a RVV indexed store. The RVV indexed store instructions only
6455 // support the "unsigned unscaled" addressing mode; indices are implicitly
6456 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6457 // signed or scaled indexing is extended to the XLEN value type and scaled
6458 // accordingly.
6459 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6460                                                 SelectionDAG &DAG) const {
6461   SDLoc DL(Op);
6462   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6463   EVT MemVT = MemSD->getMemoryVT();
6464   MachineMemOperand *MMO = MemSD->getMemOperand();
6465   SDValue Chain = MemSD->getChain();
6466   SDValue BasePtr = MemSD->getBasePtr();
6467 
6468   bool IsTruncatingStore = false;
6469   SDValue Index, Mask, Val, VL;
6470 
6471   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6472     Index = VPSN->getIndex();
6473     Mask = VPSN->getMask();
6474     Val = VPSN->getValue();
6475     VL = VPSN->getVectorLength();
6476     // VP doesn't support truncating stores.
6477     IsTruncatingStore = false;
6478   } else {
6479     // Else it must be a MSCATTER.
6480     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6481     Index = MSN->getIndex();
6482     Mask = MSN->getMask();
6483     Val = MSN->getValue();
6484     IsTruncatingStore = MSN->isTruncatingStore();
6485   }
6486 
6487   MVT VT = Val.getSimpleValueType();
6488   MVT IndexVT = Index.getSimpleValueType();
6489   MVT XLenVT = Subtarget.getXLenVT();
6490 
6491   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6492          "Unexpected VTs!");
6493   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6494   // Targets have to explicitly opt-in for extending vector loads and
6495   // truncating vector stores.
6496   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6497   (void)IsTruncatingStore;
6498 
6499   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6500   // the selection of the masked intrinsics doesn't do this for us.
6501   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6502 
6503   MVT ContainerVT = VT;
6504   if (VT.isFixedLengthVector()) {
6505     // We need to use the larger of the value and index type to determine the
6506     // scalable type to use so we don't increase LMUL for any operand/result.
6507     if (VT.bitsGE(IndexVT)) {
6508       ContainerVT = getContainerForFixedLengthVector(VT);
6509       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6510                                  ContainerVT.getVectorElementCount());
6511     } else {
6512       IndexVT = getContainerForFixedLengthVector(IndexVT);
6513       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6514                                      IndexVT.getVectorElementCount());
6515     }
6516 
6517     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6518     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6519 
6520     if (!IsUnmasked) {
6521       MVT MaskVT =
6522           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6523       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6524     }
6525   }
6526 
6527   if (!VL)
6528     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6529 
6530   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6531     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6532     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6533                                    VL);
6534     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6535                         TrueMask, VL);
6536   }
6537 
6538   unsigned IntID =
6539       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6540   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6541   Ops.push_back(Val);
6542   Ops.push_back(BasePtr);
6543   Ops.push_back(Index);
6544   if (!IsUnmasked)
6545     Ops.push_back(Mask);
6546   Ops.push_back(VL);
6547 
6548   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6549                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6550 }
6551 
6552 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6553                                                SelectionDAG &DAG) const {
6554   const MVT XLenVT = Subtarget.getXLenVT();
6555   SDLoc DL(Op);
6556   SDValue Chain = Op->getOperand(0);
6557   SDValue SysRegNo = DAG.getTargetConstant(
6558       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6559   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6560   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6561 
6562   // Encoding used for rounding mode in RISCV differs from that used in
6563   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6564   // table, which consists of a sequence of 4-bit fields, each representing
6565   // corresponding FLT_ROUNDS mode.
6566   static const int Table =
6567       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6568       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6569       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6570       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6571       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6572 
6573   SDValue Shift =
6574       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6575   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6576                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6577   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6578                                DAG.getConstant(7, DL, XLenVT));
6579 
6580   return DAG.getMergeValues({Masked, Chain}, DL);
6581 }
6582 
6583 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6584                                                SelectionDAG &DAG) const {
6585   const MVT XLenVT = Subtarget.getXLenVT();
6586   SDLoc DL(Op);
6587   SDValue Chain = Op->getOperand(0);
6588   SDValue RMValue = Op->getOperand(1);
6589   SDValue SysRegNo = DAG.getTargetConstant(
6590       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6591 
6592   // Encoding used for rounding mode in RISCV differs from that used in
6593   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6594   // a table, which consists of a sequence of 4-bit fields, each representing
6595   // corresponding RISCV mode.
6596   static const unsigned Table =
6597       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6598       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6599       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6600       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6601       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6602 
6603   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6604                               DAG.getConstant(2, DL, XLenVT));
6605   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6606                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6607   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6608                         DAG.getConstant(0x7, DL, XLenVT));
6609   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6610                      RMValue);
6611 }
6612 
6613 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6614   switch (IntNo) {
6615   default:
6616     llvm_unreachable("Unexpected Intrinsic");
6617   case Intrinsic::riscv_bcompress:
6618     return RISCVISD::BCOMPRESSW;
6619   case Intrinsic::riscv_bdecompress:
6620     return RISCVISD::BDECOMPRESSW;
6621   case Intrinsic::riscv_bfp:
6622     return RISCVISD::BFPW;
6623   case Intrinsic::riscv_fsl:
6624     return RISCVISD::FSLW;
6625   case Intrinsic::riscv_fsr:
6626     return RISCVISD::FSRW;
6627   }
6628 }
6629 
6630 // Converts the given intrinsic to a i64 operation with any extension.
6631 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6632                                          unsigned IntNo) {
6633   SDLoc DL(N);
6634   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6635   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6636   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6637   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6638   // ReplaceNodeResults requires we maintain the same type for the return value.
6639   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6640 }
6641 
6642 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6643 // form of the given Opcode.
6644 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6645   switch (Opcode) {
6646   default:
6647     llvm_unreachable("Unexpected opcode");
6648   case ISD::SHL:
6649     return RISCVISD::SLLW;
6650   case ISD::SRA:
6651     return RISCVISD::SRAW;
6652   case ISD::SRL:
6653     return RISCVISD::SRLW;
6654   case ISD::SDIV:
6655     return RISCVISD::DIVW;
6656   case ISD::UDIV:
6657     return RISCVISD::DIVUW;
6658   case ISD::UREM:
6659     return RISCVISD::REMUW;
6660   case ISD::ROTL:
6661     return RISCVISD::ROLW;
6662   case ISD::ROTR:
6663     return RISCVISD::RORW;
6664   }
6665 }
6666 
6667 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6668 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6669 // otherwise be promoted to i64, making it difficult to select the
6670 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6671 // type i8/i16/i32 is lost.
6672 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6673                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6674   SDLoc DL(N);
6675   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6676   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6677   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6678   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6679   // ReplaceNodeResults requires we maintain the same type for the return value.
6680   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6681 }
6682 
6683 // Converts the given 32-bit operation to a i64 operation with signed extension
6684 // semantic to reduce the signed extension instructions.
6685 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6686   SDLoc DL(N);
6687   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6688   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6689   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6690   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6691                                DAG.getValueType(MVT::i32));
6692   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6693 }
6694 
6695 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6696                                              SmallVectorImpl<SDValue> &Results,
6697                                              SelectionDAG &DAG) const {
6698   SDLoc DL(N);
6699   switch (N->getOpcode()) {
6700   default:
6701     llvm_unreachable("Don't know how to custom type legalize this operation!");
6702   case ISD::STRICT_FP_TO_SINT:
6703   case ISD::STRICT_FP_TO_UINT:
6704   case ISD::FP_TO_SINT:
6705   case ISD::FP_TO_UINT: {
6706     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6707            "Unexpected custom legalisation");
6708     bool IsStrict = N->isStrictFPOpcode();
6709     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6710                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6711     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6712     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6713         TargetLowering::TypeSoftenFloat) {
6714       if (!isTypeLegal(Op0.getValueType()))
6715         return;
6716       if (IsStrict) {
6717         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6718                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6719         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6720         SDValue Res = DAG.getNode(
6721             Opc, DL, VTs, N->getOperand(0), Op0,
6722             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6723         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6724         Results.push_back(Res.getValue(1));
6725         return;
6726       }
6727       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6728       SDValue Res =
6729           DAG.getNode(Opc, DL, MVT::i64, Op0,
6730                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6731       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6732       return;
6733     }
6734     // If the FP type needs to be softened, emit a library call using the 'si'
6735     // version. If we left it to default legalization we'd end up with 'di'. If
6736     // the FP type doesn't need to be softened just let generic type
6737     // legalization promote the result type.
6738     RTLIB::Libcall LC;
6739     if (IsSigned)
6740       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6741     else
6742       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6743     MakeLibCallOptions CallOptions;
6744     EVT OpVT = Op0.getValueType();
6745     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6746     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6747     SDValue Result;
6748     std::tie(Result, Chain) =
6749         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6750     Results.push_back(Result);
6751     if (IsStrict)
6752       Results.push_back(Chain);
6753     break;
6754   }
6755   case ISD::READCYCLECOUNTER: {
6756     assert(!Subtarget.is64Bit() &&
6757            "READCYCLECOUNTER only has custom type legalization on riscv32");
6758 
6759     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6760     SDValue RCW =
6761         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6762 
6763     Results.push_back(
6764         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6765     Results.push_back(RCW.getValue(2));
6766     break;
6767   }
6768   case ISD::MUL: {
6769     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6770     unsigned XLen = Subtarget.getXLen();
6771     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6772     if (Size > XLen) {
6773       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6774       SDValue LHS = N->getOperand(0);
6775       SDValue RHS = N->getOperand(1);
6776       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6777 
6778       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6779       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6780       // We need exactly one side to be unsigned.
6781       if (LHSIsU == RHSIsU)
6782         return;
6783 
6784       auto MakeMULPair = [&](SDValue S, SDValue U) {
6785         MVT XLenVT = Subtarget.getXLenVT();
6786         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6787         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6788         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6789         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6790         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6791       };
6792 
6793       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6794       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6795 
6796       // The other operand should be signed, but still prefer MULH when
6797       // possible.
6798       if (RHSIsU && LHSIsS && !RHSIsS)
6799         Results.push_back(MakeMULPair(LHS, RHS));
6800       else if (LHSIsU && RHSIsS && !LHSIsS)
6801         Results.push_back(MakeMULPair(RHS, LHS));
6802 
6803       return;
6804     }
6805     LLVM_FALLTHROUGH;
6806   }
6807   case ISD::ADD:
6808   case ISD::SUB:
6809     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6810            "Unexpected custom legalisation");
6811     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6812     break;
6813   case ISD::SHL:
6814   case ISD::SRA:
6815   case ISD::SRL:
6816     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6817            "Unexpected custom legalisation");
6818     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6819       Results.push_back(customLegalizeToWOp(N, DAG));
6820       break;
6821     }
6822 
6823     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6824     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6825     // shift amount.
6826     if (N->getOpcode() == ISD::SHL) {
6827       SDLoc DL(N);
6828       SDValue NewOp0 =
6829           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6830       SDValue NewOp1 =
6831           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6832       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6833       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6834                                    DAG.getValueType(MVT::i32));
6835       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6836     }
6837 
6838     break;
6839   case ISD::ROTL:
6840   case ISD::ROTR:
6841     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6842            "Unexpected custom legalisation");
6843     Results.push_back(customLegalizeToWOp(N, DAG));
6844     break;
6845   case ISD::CTTZ:
6846   case ISD::CTTZ_ZERO_UNDEF:
6847   case ISD::CTLZ:
6848   case ISD::CTLZ_ZERO_UNDEF: {
6849     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6850            "Unexpected custom legalisation");
6851 
6852     SDValue NewOp0 =
6853         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6854     bool IsCTZ =
6855         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6856     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6857     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6858     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6859     return;
6860   }
6861   case ISD::SDIV:
6862   case ISD::UDIV:
6863   case ISD::UREM: {
6864     MVT VT = N->getSimpleValueType(0);
6865     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6866            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6867            "Unexpected custom legalisation");
6868     // Don't promote division/remainder by constant since we should expand those
6869     // to multiply by magic constant.
6870     // FIXME: What if the expansion is disabled for minsize.
6871     if (N->getOperand(1).getOpcode() == ISD::Constant)
6872       return;
6873 
6874     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6875     // the upper 32 bits. For other types we need to sign or zero extend
6876     // based on the opcode.
6877     unsigned ExtOpc = ISD::ANY_EXTEND;
6878     if (VT != MVT::i32)
6879       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6880                                            : ISD::ZERO_EXTEND;
6881 
6882     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6883     break;
6884   }
6885   case ISD::UADDO:
6886   case ISD::USUBO: {
6887     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6888            "Unexpected custom legalisation");
6889     bool IsAdd = N->getOpcode() == ISD::UADDO;
6890     // Create an ADDW or SUBW.
6891     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6892     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6893     SDValue Res =
6894         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6895     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6896                       DAG.getValueType(MVT::i32));
6897 
6898     SDValue Overflow;
6899     if (IsAdd && isOneConstant(RHS)) {
6900       // Special case uaddo X, 1 overflowed if the addition result is 0.
6901       // FIXME: We can do this for any constant RHS by using (X + C) < C.
6902       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6903                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6904     } else {
6905       // Sign extend the LHS and perform an unsigned compare with the ADDW
6906       // result. Since the inputs are sign extended from i32, this is equivalent
6907       // to comparing the lower 32 bits.
6908       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6909       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6910                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6911     }
6912 
6913     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6914     Results.push_back(Overflow);
6915     return;
6916   }
6917   case ISD::UADDSAT:
6918   case ISD::USUBSAT: {
6919     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6920            "Unexpected custom legalisation");
6921     if (Subtarget.hasStdExtZbb()) {
6922       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6923       // sign extend allows overflow of the lower 32 bits to be detected on
6924       // the promoted size.
6925       SDValue LHS =
6926           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6927       SDValue RHS =
6928           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6929       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6930       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6931       return;
6932     }
6933 
6934     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6935     // promotion for UADDO/USUBO.
6936     Results.push_back(expandAddSubSat(N, DAG));
6937     return;
6938   }
6939   case ISD::ABS: {
6940     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6941            "Unexpected custom legalisation");
6942           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6943 
6944     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6945 
6946     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6947 
6948     // Freeze the source so we can increase it's use count.
6949     Src = DAG.getFreeze(Src);
6950 
6951     // Copy sign bit to all bits using the sraiw pattern.
6952     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6953                                    DAG.getValueType(MVT::i32));
6954     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6955                            DAG.getConstant(31, DL, MVT::i64));
6956 
6957     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6958     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6959 
6960     // NOTE: The result is only required to be anyextended, but sext is
6961     // consistent with type legalization of sub.
6962     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6963                          DAG.getValueType(MVT::i32));
6964     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6965     return;
6966   }
6967   case ISD::BITCAST: {
6968     EVT VT = N->getValueType(0);
6969     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6970     SDValue Op0 = N->getOperand(0);
6971     EVT Op0VT = Op0.getValueType();
6972     MVT XLenVT = Subtarget.getXLenVT();
6973     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6974       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6975       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6976     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6977                Subtarget.hasStdExtF()) {
6978       SDValue FPConv =
6979           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6980       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6981     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6982                isTypeLegal(Op0VT)) {
6983       // Custom-legalize bitcasts from fixed-length vector types to illegal
6984       // scalar types in order to improve codegen. Bitcast the vector to a
6985       // one-element vector type whose element type is the same as the result
6986       // type, and extract the first element.
6987       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6988       if (isTypeLegal(BVT)) {
6989         SDValue BVec = DAG.getBitcast(BVT, Op0);
6990         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6991                                       DAG.getConstant(0, DL, XLenVT)));
6992       }
6993     }
6994     break;
6995   }
6996   case RISCVISD::GREV:
6997   case RISCVISD::GORC:
6998   case RISCVISD::SHFL: {
6999     MVT VT = N->getSimpleValueType(0);
7000     MVT XLenVT = Subtarget.getXLenVT();
7001     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7002            "Unexpected custom legalisation");
7003     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7004     assert((Subtarget.hasStdExtZbp() ||
7005             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7006              N->getConstantOperandVal(1) == 7)) &&
7007            "Unexpected extension");
7008     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7009     SDValue NewOp1 =
7010         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7011     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7012     // ReplaceNodeResults requires we maintain the same type for the return
7013     // value.
7014     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7015     break;
7016   }
7017   case ISD::BSWAP:
7018   case ISD::BITREVERSE: {
7019     MVT VT = N->getSimpleValueType(0);
7020     MVT XLenVT = Subtarget.getXLenVT();
7021     assert((VT == MVT::i8 || VT == MVT::i16 ||
7022             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7023            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7024     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7025     unsigned Imm = VT.getSizeInBits() - 1;
7026     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7027     if (N->getOpcode() == ISD::BSWAP)
7028       Imm &= ~0x7U;
7029     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7030                                 DAG.getConstant(Imm, DL, XLenVT));
7031     // ReplaceNodeResults requires we maintain the same type for the return
7032     // value.
7033     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7034     break;
7035   }
7036   case ISD::FSHL:
7037   case ISD::FSHR: {
7038     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7039            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7040     SDValue NewOp0 =
7041         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7042     SDValue NewOp1 =
7043         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7044     SDValue NewShAmt =
7045         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7046     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7047     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7048     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7049                            DAG.getConstant(0x1f, DL, MVT::i64));
7050     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7051     // instruction use different orders. fshl will return its first operand for
7052     // shift of zero, fshr will return its second operand. fsl and fsr both
7053     // return rs1 so the ISD nodes need to have different operand orders.
7054     // Shift amount is in rs2.
7055     unsigned Opc = RISCVISD::FSLW;
7056     if (N->getOpcode() == ISD::FSHR) {
7057       std::swap(NewOp0, NewOp1);
7058       Opc = RISCVISD::FSRW;
7059     }
7060     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7061     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7062     break;
7063   }
7064   case ISD::EXTRACT_VECTOR_ELT: {
7065     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7066     // type is illegal (currently only vXi64 RV32).
7067     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7068     // transferred to the destination register. We issue two of these from the
7069     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7070     // first element.
7071     SDValue Vec = N->getOperand(0);
7072     SDValue Idx = N->getOperand(1);
7073 
7074     // The vector type hasn't been legalized yet so we can't issue target
7075     // specific nodes if it needs legalization.
7076     // FIXME: We would manually legalize if it's important.
7077     if (!isTypeLegal(Vec.getValueType()))
7078       return;
7079 
7080     MVT VecVT = Vec.getSimpleValueType();
7081 
7082     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7083            VecVT.getVectorElementType() == MVT::i64 &&
7084            "Unexpected EXTRACT_VECTOR_ELT legalization");
7085 
7086     // If this is a fixed vector, we need to convert it to a scalable vector.
7087     MVT ContainerVT = VecVT;
7088     if (VecVT.isFixedLengthVector()) {
7089       ContainerVT = getContainerForFixedLengthVector(VecVT);
7090       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7091     }
7092 
7093     MVT XLenVT = Subtarget.getXLenVT();
7094 
7095     // Use a VL of 1 to avoid processing more elements than we need.
7096     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
7097     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7098     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7099 
7100     // Unless the index is known to be 0, we must slide the vector down to get
7101     // the desired element into index 0.
7102     if (!isNullConstant(Idx)) {
7103       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7104                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7105     }
7106 
7107     // Extract the lower XLEN bits of the correct vector element.
7108     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7109 
7110     // To extract the upper XLEN bits of the vector element, shift the first
7111     // element right by 32 bits and re-extract the lower XLEN bits.
7112     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7113                                      DAG.getUNDEF(ContainerVT),
7114                                      DAG.getConstant(32, DL, XLenVT), VL);
7115     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7116                                  ThirtyTwoV, Mask, VL);
7117 
7118     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7119 
7120     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7121     break;
7122   }
7123   case ISD::INTRINSIC_WO_CHAIN: {
7124     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7125     switch (IntNo) {
7126     default:
7127       llvm_unreachable(
7128           "Don't know how to custom type legalize this intrinsic!");
7129     case Intrinsic::riscv_grev:
7130     case Intrinsic::riscv_gorc: {
7131       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7132              "Unexpected custom legalisation");
7133       SDValue NewOp1 =
7134           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7135       SDValue NewOp2 =
7136           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7137       unsigned Opc =
7138           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7139       // If the control is a constant, promote the node by clearing any extra
7140       // bits bits in the control. isel will form greviw/gorciw if the result is
7141       // sign extended.
7142       if (isa<ConstantSDNode>(NewOp2)) {
7143         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7144                              DAG.getConstant(0x1f, DL, MVT::i64));
7145         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7146       }
7147       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7148       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7149       break;
7150     }
7151     case Intrinsic::riscv_bcompress:
7152     case Intrinsic::riscv_bdecompress:
7153     case Intrinsic::riscv_bfp: {
7154       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7155              "Unexpected custom legalisation");
7156       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7157       break;
7158     }
7159     case Intrinsic::riscv_fsl:
7160     case Intrinsic::riscv_fsr: {
7161       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7162              "Unexpected custom legalisation");
7163       SDValue NewOp1 =
7164           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7165       SDValue NewOp2 =
7166           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7167       SDValue NewOp3 =
7168           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
7169       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
7170       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
7171       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7172       break;
7173     }
7174     case Intrinsic::riscv_orc_b: {
7175       // Lower to the GORCI encoding for orc.b with the operand extended.
7176       SDValue NewOp =
7177           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7178       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7179                                 DAG.getConstant(7, DL, MVT::i64));
7180       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7181       return;
7182     }
7183     case Intrinsic::riscv_shfl:
7184     case Intrinsic::riscv_unshfl: {
7185       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7186              "Unexpected custom legalisation");
7187       SDValue NewOp1 =
7188           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7189       SDValue NewOp2 =
7190           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7191       unsigned Opc =
7192           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7193       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7194       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7195       // will be shuffled the same way as the lower 32 bit half, but the two
7196       // halves won't cross.
7197       if (isa<ConstantSDNode>(NewOp2)) {
7198         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7199                              DAG.getConstant(0xf, DL, MVT::i64));
7200         Opc =
7201             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7202       }
7203       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7204       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7205       break;
7206     }
7207     case Intrinsic::riscv_vmv_x_s: {
7208       EVT VT = N->getValueType(0);
7209       MVT XLenVT = Subtarget.getXLenVT();
7210       if (VT.bitsLT(XLenVT)) {
7211         // Simple case just extract using vmv.x.s and truncate.
7212         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7213                                       Subtarget.getXLenVT(), N->getOperand(1));
7214         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7215         return;
7216       }
7217 
7218       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7219              "Unexpected custom legalization");
7220 
7221       // We need to do the move in two steps.
7222       SDValue Vec = N->getOperand(1);
7223       MVT VecVT = Vec.getSimpleValueType();
7224 
7225       // First extract the lower XLEN bits of the element.
7226       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7227 
7228       // To extract the upper XLEN bits of the vector element, shift the first
7229       // element right by 32 bits and re-extract the lower XLEN bits.
7230       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7231       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7232       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7233       SDValue ThirtyTwoV =
7234           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7235                       DAG.getConstant(32, DL, XLenVT), VL);
7236       SDValue LShr32 =
7237           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7238       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7239 
7240       Results.push_back(
7241           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7242       break;
7243     }
7244     }
7245     break;
7246   }
7247   case ISD::VECREDUCE_ADD:
7248   case ISD::VECREDUCE_AND:
7249   case ISD::VECREDUCE_OR:
7250   case ISD::VECREDUCE_XOR:
7251   case ISD::VECREDUCE_SMAX:
7252   case ISD::VECREDUCE_UMAX:
7253   case ISD::VECREDUCE_SMIN:
7254   case ISD::VECREDUCE_UMIN:
7255     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7256       Results.push_back(V);
7257     break;
7258   case ISD::VP_REDUCE_ADD:
7259   case ISD::VP_REDUCE_AND:
7260   case ISD::VP_REDUCE_OR:
7261   case ISD::VP_REDUCE_XOR:
7262   case ISD::VP_REDUCE_SMAX:
7263   case ISD::VP_REDUCE_UMAX:
7264   case ISD::VP_REDUCE_SMIN:
7265   case ISD::VP_REDUCE_UMIN:
7266     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7267       Results.push_back(V);
7268     break;
7269   case ISD::FLT_ROUNDS_: {
7270     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7271     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7272     Results.push_back(Res.getValue(0));
7273     Results.push_back(Res.getValue(1));
7274     break;
7275   }
7276   }
7277 }
7278 
7279 // A structure to hold one of the bit-manipulation patterns below. Together, a
7280 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7281 //   (or (and (shl x, 1), 0xAAAAAAAA),
7282 //       (and (srl x, 1), 0x55555555))
7283 struct RISCVBitmanipPat {
7284   SDValue Op;
7285   unsigned ShAmt;
7286   bool IsSHL;
7287 
7288   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7289     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7290   }
7291 };
7292 
7293 // Matches patterns of the form
7294 //   (and (shl x, C2), (C1 << C2))
7295 //   (and (srl x, C2), C1)
7296 //   (shl (and x, C1), C2)
7297 //   (srl (and x, (C1 << C2)), C2)
7298 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7299 // The expected masks for each shift amount are specified in BitmanipMasks where
7300 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7301 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7302 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7303 // XLen is 64.
7304 static Optional<RISCVBitmanipPat>
7305 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7306   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7307          "Unexpected number of masks");
7308   Optional<uint64_t> Mask;
7309   // Optionally consume a mask around the shift operation.
7310   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7311     Mask = Op.getConstantOperandVal(1);
7312     Op = Op.getOperand(0);
7313   }
7314   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7315     return None;
7316   bool IsSHL = Op.getOpcode() == ISD::SHL;
7317 
7318   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7319     return None;
7320   uint64_t ShAmt = Op.getConstantOperandVal(1);
7321 
7322   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7323   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7324     return None;
7325   // If we don't have enough masks for 64 bit, then we must be trying to
7326   // match SHFL so we're only allowed to shift 1/4 of the width.
7327   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7328     return None;
7329 
7330   SDValue Src = Op.getOperand(0);
7331 
7332   // The expected mask is shifted left when the AND is found around SHL
7333   // patterns.
7334   //   ((x >> 1) & 0x55555555)
7335   //   ((x << 1) & 0xAAAAAAAA)
7336   bool SHLExpMask = IsSHL;
7337 
7338   if (!Mask) {
7339     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7340     // the mask is all ones: consume that now.
7341     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7342       Mask = Src.getConstantOperandVal(1);
7343       Src = Src.getOperand(0);
7344       // The expected mask is now in fact shifted left for SRL, so reverse the
7345       // decision.
7346       //   ((x & 0xAAAAAAAA) >> 1)
7347       //   ((x & 0x55555555) << 1)
7348       SHLExpMask = !SHLExpMask;
7349     } else {
7350       // Use a default shifted mask of all-ones if there's no AND, truncated
7351       // down to the expected width. This simplifies the logic later on.
7352       Mask = maskTrailingOnes<uint64_t>(Width);
7353       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7354     }
7355   }
7356 
7357   unsigned MaskIdx = Log2_32(ShAmt);
7358   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7359 
7360   if (SHLExpMask)
7361     ExpMask <<= ShAmt;
7362 
7363   if (Mask != ExpMask)
7364     return None;
7365 
7366   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7367 }
7368 
7369 // Matches any of the following bit-manipulation patterns:
7370 //   (and (shl x, 1), (0x55555555 << 1))
7371 //   (and (srl x, 1), 0x55555555)
7372 //   (shl (and x, 0x55555555), 1)
7373 //   (srl (and x, (0x55555555 << 1)), 1)
7374 // where the shift amount and mask may vary thus:
7375 //   [1]  = 0x55555555 / 0xAAAAAAAA
7376 //   [2]  = 0x33333333 / 0xCCCCCCCC
7377 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7378 //   [8]  = 0x00FF00FF / 0xFF00FF00
7379 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7380 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7381 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7382   // These are the unshifted masks which we use to match bit-manipulation
7383   // patterns. They may be shifted left in certain circumstances.
7384   static const uint64_t BitmanipMasks[] = {
7385       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7386       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7387 
7388   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7389 }
7390 
7391 // Match the following pattern as a GREVI(W) operation
7392 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7393 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7394                                const RISCVSubtarget &Subtarget) {
7395   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7396   EVT VT = Op.getValueType();
7397 
7398   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7399     auto LHS = matchGREVIPat(Op.getOperand(0));
7400     auto RHS = matchGREVIPat(Op.getOperand(1));
7401     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7402       SDLoc DL(Op);
7403       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7404                          DAG.getConstant(LHS->ShAmt, DL, VT));
7405     }
7406   }
7407   return SDValue();
7408 }
7409 
7410 // Matches any the following pattern as a GORCI(W) operation
7411 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7412 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7413 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7414 // Note that with the variant of 3.,
7415 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7416 // the inner pattern will first be matched as GREVI and then the outer
7417 // pattern will be matched to GORC via the first rule above.
7418 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7419 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7420                                const RISCVSubtarget &Subtarget) {
7421   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7422   EVT VT = Op.getValueType();
7423 
7424   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7425     SDLoc DL(Op);
7426     SDValue Op0 = Op.getOperand(0);
7427     SDValue Op1 = Op.getOperand(1);
7428 
7429     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7430       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7431           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7432           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7433         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7434       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7435       if ((Reverse.getOpcode() == ISD::ROTL ||
7436            Reverse.getOpcode() == ISD::ROTR) &&
7437           Reverse.getOperand(0) == X &&
7438           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7439         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7440         if (RotAmt == (VT.getSizeInBits() / 2))
7441           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7442                              DAG.getConstant(RotAmt, DL, VT));
7443       }
7444       return SDValue();
7445     };
7446 
7447     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7448     if (SDValue V = MatchOROfReverse(Op0, Op1))
7449       return V;
7450     if (SDValue V = MatchOROfReverse(Op1, Op0))
7451       return V;
7452 
7453     // OR is commutable so canonicalize its OR operand to the left
7454     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7455       std::swap(Op0, Op1);
7456     if (Op0.getOpcode() != ISD::OR)
7457       return SDValue();
7458     SDValue OrOp0 = Op0.getOperand(0);
7459     SDValue OrOp1 = Op0.getOperand(1);
7460     auto LHS = matchGREVIPat(OrOp0);
7461     // OR is commutable so swap the operands and try again: x might have been
7462     // on the left
7463     if (!LHS) {
7464       std::swap(OrOp0, OrOp1);
7465       LHS = matchGREVIPat(OrOp0);
7466     }
7467     auto RHS = matchGREVIPat(Op1);
7468     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7469       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7470                          DAG.getConstant(LHS->ShAmt, DL, VT));
7471     }
7472   }
7473   return SDValue();
7474 }
7475 
7476 // Matches any of the following bit-manipulation patterns:
7477 //   (and (shl x, 1), (0x22222222 << 1))
7478 //   (and (srl x, 1), 0x22222222)
7479 //   (shl (and x, 0x22222222), 1)
7480 //   (srl (and x, (0x22222222 << 1)), 1)
7481 // where the shift amount and mask may vary thus:
7482 //   [1]  = 0x22222222 / 0x44444444
7483 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7484 //   [4]  = 0x00F000F0 / 0x0F000F00
7485 //   [8]  = 0x0000FF00 / 0x00FF0000
7486 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7487 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7488   // These are the unshifted masks which we use to match bit-manipulation
7489   // patterns. They may be shifted left in certain circumstances.
7490   static const uint64_t BitmanipMasks[] = {
7491       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7492       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7493 
7494   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7495 }
7496 
7497 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7498 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7499                                const RISCVSubtarget &Subtarget) {
7500   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7501   EVT VT = Op.getValueType();
7502 
7503   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7504     return SDValue();
7505 
7506   SDValue Op0 = Op.getOperand(0);
7507   SDValue Op1 = Op.getOperand(1);
7508 
7509   // Or is commutable so canonicalize the second OR to the LHS.
7510   if (Op0.getOpcode() != ISD::OR)
7511     std::swap(Op0, Op1);
7512   if (Op0.getOpcode() != ISD::OR)
7513     return SDValue();
7514 
7515   // We found an inner OR, so our operands are the operands of the inner OR
7516   // and the other operand of the outer OR.
7517   SDValue A = Op0.getOperand(0);
7518   SDValue B = Op0.getOperand(1);
7519   SDValue C = Op1;
7520 
7521   auto Match1 = matchSHFLPat(A);
7522   auto Match2 = matchSHFLPat(B);
7523 
7524   // If neither matched, we failed.
7525   if (!Match1 && !Match2)
7526     return SDValue();
7527 
7528   // We had at least one match. if one failed, try the remaining C operand.
7529   if (!Match1) {
7530     std::swap(A, C);
7531     Match1 = matchSHFLPat(A);
7532     if (!Match1)
7533       return SDValue();
7534   } else if (!Match2) {
7535     std::swap(B, C);
7536     Match2 = matchSHFLPat(B);
7537     if (!Match2)
7538       return SDValue();
7539   }
7540   assert(Match1 && Match2);
7541 
7542   // Make sure our matches pair up.
7543   if (!Match1->formsPairWith(*Match2))
7544     return SDValue();
7545 
7546   // All the remains is to make sure C is an AND with the same input, that masks
7547   // out the bits that are being shuffled.
7548   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7549       C.getOperand(0) != Match1->Op)
7550     return SDValue();
7551 
7552   uint64_t Mask = C.getConstantOperandVal(1);
7553 
7554   static const uint64_t BitmanipMasks[] = {
7555       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7556       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7557   };
7558 
7559   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7560   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7561   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7562 
7563   if (Mask != ExpMask)
7564     return SDValue();
7565 
7566   SDLoc DL(Op);
7567   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7568                      DAG.getConstant(Match1->ShAmt, DL, VT));
7569 }
7570 
7571 // Optimize (add (shl x, c0), (shl y, c1)) ->
7572 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7573 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7574                                   const RISCVSubtarget &Subtarget) {
7575   // Perform this optimization only in the zba extension.
7576   if (!Subtarget.hasStdExtZba())
7577     return SDValue();
7578 
7579   // Skip for vector types and larger types.
7580   EVT VT = N->getValueType(0);
7581   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7582     return SDValue();
7583 
7584   // The two operand nodes must be SHL and have no other use.
7585   SDValue N0 = N->getOperand(0);
7586   SDValue N1 = N->getOperand(1);
7587   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7588       !N0->hasOneUse() || !N1->hasOneUse())
7589     return SDValue();
7590 
7591   // Check c0 and c1.
7592   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7593   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7594   if (!N0C || !N1C)
7595     return SDValue();
7596   int64_t C0 = N0C->getSExtValue();
7597   int64_t C1 = N1C->getSExtValue();
7598   if (C0 <= 0 || C1 <= 0)
7599     return SDValue();
7600 
7601   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7602   int64_t Bits = std::min(C0, C1);
7603   int64_t Diff = std::abs(C0 - C1);
7604   if (Diff != 1 && Diff != 2 && Diff != 3)
7605     return SDValue();
7606 
7607   // Build nodes.
7608   SDLoc DL(N);
7609   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7610   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7611   SDValue NA0 =
7612       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7613   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7614   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7615 }
7616 
7617 // Combine
7618 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7619 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7620 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7621 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7622 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7623 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7624 // The grev patterns represents BSWAP.
7625 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7626 // off the grev.
7627 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7628                                           const RISCVSubtarget &Subtarget) {
7629   bool IsWInstruction =
7630       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7631   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7632           IsWInstruction) &&
7633          "Unexpected opcode!");
7634   SDValue Src = N->getOperand(0);
7635   EVT VT = N->getValueType(0);
7636   SDLoc DL(N);
7637 
7638   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7639     return SDValue();
7640 
7641   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7642       !isa<ConstantSDNode>(Src.getOperand(1)))
7643     return SDValue();
7644 
7645   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7646   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7647 
7648   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7649   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7650   unsigned ShAmt1 = N->getConstantOperandVal(1);
7651   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7652   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7653     return SDValue();
7654 
7655   Src = Src.getOperand(0);
7656 
7657   // Toggle bit the MSB of the shift.
7658   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7659   if (CombinedShAmt == 0)
7660     return Src;
7661 
7662   SDValue Res = DAG.getNode(
7663       RISCVISD::GREV, DL, VT, Src,
7664       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7665   if (!IsWInstruction)
7666     return Res;
7667 
7668   // Sign extend the result to match the behavior of the rotate. This will be
7669   // selected to GREVIW in isel.
7670   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7671                      DAG.getValueType(MVT::i32));
7672 }
7673 
7674 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7675 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7676 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7677 // not undo itself, but they are redundant.
7678 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7679   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7680   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7681   SDValue Src = N->getOperand(0);
7682 
7683   if (Src.getOpcode() != N->getOpcode())
7684     return SDValue();
7685 
7686   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7687       !isa<ConstantSDNode>(Src.getOperand(1)))
7688     return SDValue();
7689 
7690   unsigned ShAmt1 = N->getConstantOperandVal(1);
7691   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7692   Src = Src.getOperand(0);
7693 
7694   unsigned CombinedShAmt;
7695   if (IsGORC)
7696     CombinedShAmt = ShAmt1 | ShAmt2;
7697   else
7698     CombinedShAmt = ShAmt1 ^ ShAmt2;
7699 
7700   if (CombinedShAmt == 0)
7701     return Src;
7702 
7703   SDLoc DL(N);
7704   return DAG.getNode(
7705       N->getOpcode(), DL, N->getValueType(0), Src,
7706       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7707 }
7708 
7709 // Combine a constant select operand into its use:
7710 //
7711 // (and (select cond, -1, c), x)
7712 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7713 // (or  (select cond, 0, c), x)
7714 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7715 // (xor (select cond, 0, c), x)
7716 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7717 // (add (select cond, 0, c), x)
7718 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7719 // (sub x, (select cond, 0, c))
7720 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7721 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7722                                    SelectionDAG &DAG, bool AllOnes) {
7723   EVT VT = N->getValueType(0);
7724 
7725   // Skip vectors.
7726   if (VT.isVector())
7727     return SDValue();
7728 
7729   if ((Slct.getOpcode() != ISD::SELECT &&
7730        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7731       !Slct.hasOneUse())
7732     return SDValue();
7733 
7734   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7735     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7736   };
7737 
7738   bool SwapSelectOps;
7739   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7740   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7741   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7742   SDValue NonConstantVal;
7743   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7744     SwapSelectOps = false;
7745     NonConstantVal = FalseVal;
7746   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7747     SwapSelectOps = true;
7748     NonConstantVal = TrueVal;
7749   } else
7750     return SDValue();
7751 
7752   // Slct is now know to be the desired identity constant when CC is true.
7753   TrueVal = OtherOp;
7754   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7755   // Unless SwapSelectOps says the condition should be false.
7756   if (SwapSelectOps)
7757     std::swap(TrueVal, FalseVal);
7758 
7759   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7760     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7761                        {Slct.getOperand(0), Slct.getOperand(1),
7762                         Slct.getOperand(2), TrueVal, FalseVal});
7763 
7764   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7765                      {Slct.getOperand(0), TrueVal, FalseVal});
7766 }
7767 
7768 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7769 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7770                                               bool AllOnes) {
7771   SDValue N0 = N->getOperand(0);
7772   SDValue N1 = N->getOperand(1);
7773   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7774     return Result;
7775   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7776     return Result;
7777   return SDValue();
7778 }
7779 
7780 // Transform (add (mul x, c0), c1) ->
7781 //           (add (mul (add x, c1/c0), c0), c1%c0).
7782 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7783 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7784 // to an infinite loop in DAGCombine if transformed.
7785 // Or transform (add (mul x, c0), c1) ->
7786 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7787 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7788 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7789 // lead to an infinite loop in DAGCombine if transformed.
7790 // Or transform (add (mul x, c0), c1) ->
7791 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7792 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7793 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7794 // lead to an infinite loop in DAGCombine if transformed.
7795 // Or transform (add (mul x, c0), c1) ->
7796 //              (mul (add x, c1/c0), c0).
7797 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7798 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7799                                      const RISCVSubtarget &Subtarget) {
7800   // Skip for vector types and larger types.
7801   EVT VT = N->getValueType(0);
7802   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7803     return SDValue();
7804   // The first operand node must be a MUL and has no other use.
7805   SDValue N0 = N->getOperand(0);
7806   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7807     return SDValue();
7808   // Check if c0 and c1 match above conditions.
7809   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7810   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7811   if (!N0C || !N1C)
7812     return SDValue();
7813   // If N0C has multiple uses it's possible one of the cases in
7814   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7815   // in an infinite loop.
7816   if (!N0C->hasOneUse())
7817     return SDValue();
7818   int64_t C0 = N0C->getSExtValue();
7819   int64_t C1 = N1C->getSExtValue();
7820   int64_t CA, CB;
7821   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7822     return SDValue();
7823   // Search for proper CA (non-zero) and CB that both are simm12.
7824   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7825       !isInt<12>(C0 * (C1 / C0))) {
7826     CA = C1 / C0;
7827     CB = C1 % C0;
7828   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7829              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7830     CA = C1 / C0 + 1;
7831     CB = C1 % C0 - C0;
7832   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7833              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7834     CA = C1 / C0 - 1;
7835     CB = C1 % C0 + C0;
7836   } else
7837     return SDValue();
7838   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7839   SDLoc DL(N);
7840   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7841                              DAG.getConstant(CA, DL, VT));
7842   SDValue New1 =
7843       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7844   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7845 }
7846 
7847 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7848                                  const RISCVSubtarget &Subtarget) {
7849   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7850     return V;
7851   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7852     return V;
7853   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7854   //      (select lhs, rhs, cc, x, (add x, y))
7855   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7856 }
7857 
7858 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7859   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7860   //      (select lhs, rhs, cc, x, (sub x, y))
7861   SDValue N0 = N->getOperand(0);
7862   SDValue N1 = N->getOperand(1);
7863   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7864 }
7865 
7866 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7867   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7868   //      (select lhs, rhs, cc, x, (and x, y))
7869   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7870 }
7871 
7872 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7873                                 const RISCVSubtarget &Subtarget) {
7874   if (Subtarget.hasStdExtZbp()) {
7875     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7876       return GREV;
7877     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7878       return GORC;
7879     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7880       return SHFL;
7881   }
7882 
7883   // fold (or (select cond, 0, y), x) ->
7884   //      (select cond, x, (or x, y))
7885   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7886 }
7887 
7888 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7889   // fold (xor (select cond, 0, y), x) ->
7890   //      (select cond, x, (xor x, y))
7891   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7892 }
7893 
7894 static SDValue
7895 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7896                                 const RISCVSubtarget &Subtarget) {
7897   SDValue Src = N->getOperand(0);
7898   EVT VT = N->getValueType(0);
7899 
7900   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7901   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7902       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7903     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7904                        Src.getOperand(0));
7905 
7906   // Fold (i64 (sext_inreg (abs X), i32)) ->
7907   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7908   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7909   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7910   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7911   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7912   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7913   // may get combined into an earlier operation so we need to use
7914   // ComputeNumSignBits.
7915   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7916   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7917   // we can't assume that X has 33 sign bits. We must check.
7918   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7919       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7920       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7921       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7922     SDLoc DL(N);
7923     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7924     SDValue Neg =
7925         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7926     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7927                       DAG.getValueType(MVT::i32));
7928     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7929   }
7930 
7931   return SDValue();
7932 }
7933 
7934 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7935 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7936 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7937                                              bool Commute = false) {
7938   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7939           N->getOpcode() == RISCVISD::SUB_VL) &&
7940          "Unexpected opcode");
7941   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7942   SDValue Op0 = N->getOperand(0);
7943   SDValue Op1 = N->getOperand(1);
7944   if (Commute)
7945     std::swap(Op0, Op1);
7946 
7947   MVT VT = N->getSimpleValueType(0);
7948 
7949   // Determine the narrow size for a widening add/sub.
7950   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7951   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7952                                   VT.getVectorElementCount());
7953 
7954   SDValue Mask = N->getOperand(2);
7955   SDValue VL = N->getOperand(3);
7956 
7957   SDLoc DL(N);
7958 
7959   // If the RHS is a sext or zext, we can form a widening op.
7960   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7961        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7962       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7963     unsigned ExtOpc = Op1.getOpcode();
7964     Op1 = Op1.getOperand(0);
7965     // Re-introduce narrower extends if needed.
7966     if (Op1.getValueType() != NarrowVT)
7967       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7968 
7969     unsigned WOpc;
7970     if (ExtOpc == RISCVISD::VSEXT_VL)
7971       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7972     else
7973       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7974 
7975     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7976   }
7977 
7978   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7979   // sext/zext?
7980 
7981   return SDValue();
7982 }
7983 
7984 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7985 // vwsub(u).vv/vx.
7986 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7987   SDValue Op0 = N->getOperand(0);
7988   SDValue Op1 = N->getOperand(1);
7989   SDValue Mask = N->getOperand(2);
7990   SDValue VL = N->getOperand(3);
7991 
7992   MVT VT = N->getSimpleValueType(0);
7993   MVT NarrowVT = Op1.getSimpleValueType();
7994   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7995 
7996   unsigned VOpc;
7997   switch (N->getOpcode()) {
7998   default: llvm_unreachable("Unexpected opcode");
7999   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8000   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8001   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8002   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8003   }
8004 
8005   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8006                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8007 
8008   SDLoc DL(N);
8009 
8010   // If the LHS is a sext or zext, we can narrow this op to the same size as
8011   // the RHS.
8012   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8013        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8014       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8015     unsigned ExtOpc = Op0.getOpcode();
8016     Op0 = Op0.getOperand(0);
8017     // Re-introduce narrower extends if needed.
8018     if (Op0.getValueType() != NarrowVT)
8019       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8020     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8021   }
8022 
8023   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8024                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8025 
8026   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8027   // to commute and use a vwadd(u).vx instead.
8028   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8029       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8030     Op0 = Op0.getOperand(1);
8031 
8032     // See if have enough sign bits or zero bits in the scalar to use a
8033     // widening add/sub by splatting to smaller element size.
8034     unsigned EltBits = VT.getScalarSizeInBits();
8035     unsigned ScalarBits = Op0.getValueSizeInBits();
8036     // Make sure we're getting all element bits from the scalar register.
8037     // FIXME: Support implicit sign extension of vmv.v.x?
8038     if (ScalarBits < EltBits)
8039       return SDValue();
8040 
8041     if (IsSigned) {
8042       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8043         return SDValue();
8044     } else {
8045       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8046       if (!DAG.MaskedValueIsZero(Op0, Mask))
8047         return SDValue();
8048     }
8049 
8050     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8051                       DAG.getUNDEF(NarrowVT), Op0, VL);
8052     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8053   }
8054 
8055   return SDValue();
8056 }
8057 
8058 // Try to form VWMUL, VWMULU or VWMULSU.
8059 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8060 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8061                                        bool Commute) {
8062   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8063   SDValue Op0 = N->getOperand(0);
8064   SDValue Op1 = N->getOperand(1);
8065   if (Commute)
8066     std::swap(Op0, Op1);
8067 
8068   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8069   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8070   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8071   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8072     return SDValue();
8073 
8074   SDValue Mask = N->getOperand(2);
8075   SDValue VL = N->getOperand(3);
8076 
8077   // Make sure the mask and VL match.
8078   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8079     return SDValue();
8080 
8081   MVT VT = N->getSimpleValueType(0);
8082 
8083   // Determine the narrow size for a widening multiply.
8084   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8085   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8086                                   VT.getVectorElementCount());
8087 
8088   SDLoc DL(N);
8089 
8090   // See if the other operand is the same opcode.
8091   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8092     if (!Op1.hasOneUse())
8093       return SDValue();
8094 
8095     // Make sure the mask and VL match.
8096     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8097       return SDValue();
8098 
8099     Op1 = Op1.getOperand(0);
8100   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8101     // The operand is a splat of a scalar.
8102 
8103     // The pasthru must be undef for tail agnostic
8104     if (!Op1.getOperand(0).isUndef())
8105       return SDValue();
8106     // The VL must be the same.
8107     if (Op1.getOperand(2) != VL)
8108       return SDValue();
8109 
8110     // Get the scalar value.
8111     Op1 = Op1.getOperand(1);
8112 
8113     // See if have enough sign bits or zero bits in the scalar to use a
8114     // widening multiply by splatting to smaller element size.
8115     unsigned EltBits = VT.getScalarSizeInBits();
8116     unsigned ScalarBits = Op1.getValueSizeInBits();
8117     // Make sure we're getting all element bits from the scalar register.
8118     // FIXME: Support implicit sign extension of vmv.v.x?
8119     if (ScalarBits < EltBits)
8120       return SDValue();
8121 
8122     // If the LHS is a sign extend, try to use vwmul.
8123     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8124       // Can use vwmul.
8125     } else {
8126       // Otherwise try to use vwmulu or vwmulsu.
8127       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8128       if (DAG.MaskedValueIsZero(Op1, Mask))
8129         IsVWMULSU = IsSignExt;
8130       else
8131         return SDValue();
8132     }
8133 
8134     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8135                       DAG.getUNDEF(NarrowVT), Op1, VL);
8136   } else
8137     return SDValue();
8138 
8139   Op0 = Op0.getOperand(0);
8140 
8141   // Re-introduce narrower extends if needed.
8142   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8143   if (Op0.getValueType() != NarrowVT)
8144     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8145   // vwmulsu requires second operand to be zero extended.
8146   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8147   if (Op1.getValueType() != NarrowVT)
8148     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8149 
8150   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8151   if (!IsVWMULSU)
8152     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8153   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8154 }
8155 
8156 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8157   switch (Op.getOpcode()) {
8158   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8159   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8160   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8161   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8162   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8163   }
8164 
8165   return RISCVFPRndMode::Invalid;
8166 }
8167 
8168 // Fold
8169 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8170 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8171 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8172 //   (fp_to_int (fceil X))      -> fcvt X, rup
8173 //   (fp_to_int (fround X))     -> fcvt X, rmm
8174 static SDValue performFP_TO_INTCombine(SDNode *N,
8175                                        TargetLowering::DAGCombinerInfo &DCI,
8176                                        const RISCVSubtarget &Subtarget) {
8177   SelectionDAG &DAG = DCI.DAG;
8178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8179   MVT XLenVT = Subtarget.getXLenVT();
8180 
8181   // Only handle XLen or i32 types. Other types narrower than XLen will
8182   // eventually be legalized to XLenVT.
8183   EVT VT = N->getValueType(0);
8184   if (VT != MVT::i32 && VT != XLenVT)
8185     return SDValue();
8186 
8187   SDValue Src = N->getOperand(0);
8188 
8189   // Ensure the FP type is also legal.
8190   if (!TLI.isTypeLegal(Src.getValueType()))
8191     return SDValue();
8192 
8193   // Don't do this for f16 with Zfhmin and not Zfh.
8194   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8195     return SDValue();
8196 
8197   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8198   if (FRM == RISCVFPRndMode::Invalid)
8199     return SDValue();
8200 
8201   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8202 
8203   unsigned Opc;
8204   if (VT == XLenVT)
8205     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8206   else
8207     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8208 
8209   SDLoc DL(N);
8210   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8211                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8212   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8213 }
8214 
8215 // Fold
8216 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8217 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8218 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8219 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8220 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8221 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8222                                        TargetLowering::DAGCombinerInfo &DCI,
8223                                        const RISCVSubtarget &Subtarget) {
8224   SelectionDAG &DAG = DCI.DAG;
8225   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8226   MVT XLenVT = Subtarget.getXLenVT();
8227 
8228   // Only handle XLen types. Other types narrower than XLen will eventually be
8229   // legalized to XLenVT.
8230   EVT DstVT = N->getValueType(0);
8231   if (DstVT != XLenVT)
8232     return SDValue();
8233 
8234   SDValue Src = N->getOperand(0);
8235 
8236   // Ensure the FP type is also legal.
8237   if (!TLI.isTypeLegal(Src.getValueType()))
8238     return SDValue();
8239 
8240   // Don't do this for f16 with Zfhmin and not Zfh.
8241   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8242     return SDValue();
8243 
8244   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8245 
8246   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8247   if (FRM == RISCVFPRndMode::Invalid)
8248     return SDValue();
8249 
8250   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8251 
8252   unsigned Opc;
8253   if (SatVT == DstVT)
8254     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8255   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8256     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8257   else
8258     return SDValue();
8259   // FIXME: Support other SatVTs by clamping before or after the conversion.
8260 
8261   Src = Src.getOperand(0);
8262 
8263   SDLoc DL(N);
8264   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8265                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8266 
8267   // RISCV FP-to-int conversions saturate to the destination register size, but
8268   // don't produce 0 for nan.
8269   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8270   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8271 }
8272 
8273 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8274 // smaller than XLenVT.
8275 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8276                                         const RISCVSubtarget &Subtarget) {
8277   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8278 
8279   SDValue Src = N->getOperand(0);
8280   if (Src.getOpcode() != ISD::BSWAP)
8281     return SDValue();
8282 
8283   EVT VT = N->getValueType(0);
8284   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8285       !isPowerOf2_32(VT.getSizeInBits()))
8286     return SDValue();
8287 
8288   SDLoc DL(N);
8289   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8290                      DAG.getConstant(7, DL, VT));
8291 }
8292 
8293 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8294                                                DAGCombinerInfo &DCI) const {
8295   SelectionDAG &DAG = DCI.DAG;
8296 
8297   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8298   // bits are demanded. N will be added to the Worklist if it was not deleted.
8299   // Caller should return SDValue(N, 0) if this returns true.
8300   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8301     SDValue Op = N->getOperand(OpNo);
8302     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8303     if (!SimplifyDemandedBits(Op, Mask, DCI))
8304       return false;
8305 
8306     if (N->getOpcode() != ISD::DELETED_NODE)
8307       DCI.AddToWorklist(N);
8308     return true;
8309   };
8310 
8311   switch (N->getOpcode()) {
8312   default:
8313     break;
8314   case RISCVISD::SplitF64: {
8315     SDValue Op0 = N->getOperand(0);
8316     // If the input to SplitF64 is just BuildPairF64 then the operation is
8317     // redundant. Instead, use BuildPairF64's operands directly.
8318     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8319       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8320 
8321     if (Op0->isUndef()) {
8322       SDValue Lo = DAG.getUNDEF(MVT::i32);
8323       SDValue Hi = DAG.getUNDEF(MVT::i32);
8324       return DCI.CombineTo(N, Lo, Hi);
8325     }
8326 
8327     SDLoc DL(N);
8328 
8329     // It's cheaper to materialise two 32-bit integers than to load a double
8330     // from the constant pool and transfer it to integer registers through the
8331     // stack.
8332     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8333       APInt V = C->getValueAPF().bitcastToAPInt();
8334       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8335       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8336       return DCI.CombineTo(N, Lo, Hi);
8337     }
8338 
8339     // This is a target-specific version of a DAGCombine performed in
8340     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8341     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8342     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8343     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8344         !Op0.getNode()->hasOneUse())
8345       break;
8346     SDValue NewSplitF64 =
8347         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8348                     Op0.getOperand(0));
8349     SDValue Lo = NewSplitF64.getValue(0);
8350     SDValue Hi = NewSplitF64.getValue(1);
8351     APInt SignBit = APInt::getSignMask(32);
8352     if (Op0.getOpcode() == ISD::FNEG) {
8353       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8354                                   DAG.getConstant(SignBit, DL, MVT::i32));
8355       return DCI.CombineTo(N, Lo, NewHi);
8356     }
8357     assert(Op0.getOpcode() == ISD::FABS);
8358     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8359                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8360     return DCI.CombineTo(N, Lo, NewHi);
8361   }
8362   case RISCVISD::SLLW:
8363   case RISCVISD::SRAW:
8364   case RISCVISD::SRLW: {
8365     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8366     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8367         SimplifyDemandedLowBitsHelper(1, 5))
8368       return SDValue(N, 0);
8369 
8370     break;
8371   }
8372   case ISD::ROTR:
8373   case ISD::ROTL:
8374   case RISCVISD::RORW:
8375   case RISCVISD::ROLW: {
8376     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8377       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8378       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8379           SimplifyDemandedLowBitsHelper(1, 5))
8380         return SDValue(N, 0);
8381     }
8382 
8383     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8384   }
8385   case RISCVISD::CLZW:
8386   case RISCVISD::CTZW: {
8387     // Only the lower 32 bits of the first operand are read
8388     if (SimplifyDemandedLowBitsHelper(0, 32))
8389       return SDValue(N, 0);
8390     break;
8391   }
8392   case RISCVISD::GREV:
8393   case RISCVISD::GORC: {
8394     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8395     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8396     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8397     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8398       return SDValue(N, 0);
8399 
8400     return combineGREVI_GORCI(N, DAG);
8401   }
8402   case RISCVISD::GREVW:
8403   case RISCVISD::GORCW: {
8404     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8405     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8406         SimplifyDemandedLowBitsHelper(1, 5))
8407       return SDValue(N, 0);
8408 
8409     break;
8410   }
8411   case RISCVISD::SHFL:
8412   case RISCVISD::UNSHFL: {
8413     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8414     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8415     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8416     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8417       return SDValue(N, 0);
8418 
8419     break;
8420   }
8421   case RISCVISD::SHFLW:
8422   case RISCVISD::UNSHFLW: {
8423     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8424     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8425         SimplifyDemandedLowBitsHelper(1, 4))
8426       return SDValue(N, 0);
8427 
8428     break;
8429   }
8430   case RISCVISD::BCOMPRESSW:
8431   case RISCVISD::BDECOMPRESSW: {
8432     // Only the lower 32 bits of LHS and RHS are read.
8433     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8434         SimplifyDemandedLowBitsHelper(1, 32))
8435       return SDValue(N, 0);
8436 
8437     break;
8438   }
8439   case RISCVISD::FSR:
8440   case RISCVISD::FSL:
8441   case RISCVISD::FSRW:
8442   case RISCVISD::FSLW: {
8443     bool IsWInstruction =
8444         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8445     unsigned BitWidth =
8446         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8447     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8448     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8449     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8450       return SDValue(N, 0);
8451 
8452     break;
8453   }
8454   case RISCVISD::FMV_X_ANYEXTH:
8455   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8456     SDLoc DL(N);
8457     SDValue Op0 = N->getOperand(0);
8458     MVT VT = N->getSimpleValueType(0);
8459     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8460     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8461     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8462     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8463          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8464         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8465          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8466       assert(Op0.getOperand(0).getValueType() == VT &&
8467              "Unexpected value type!");
8468       return Op0.getOperand(0);
8469     }
8470 
8471     // This is a target-specific version of a DAGCombine performed in
8472     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8473     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8474     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8475     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8476         !Op0.getNode()->hasOneUse())
8477       break;
8478     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8479     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8480     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8481     if (Op0.getOpcode() == ISD::FNEG)
8482       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8483                          DAG.getConstant(SignBit, DL, VT));
8484 
8485     assert(Op0.getOpcode() == ISD::FABS);
8486     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8487                        DAG.getConstant(~SignBit, DL, VT));
8488   }
8489   case ISD::ADD:
8490     return performADDCombine(N, DAG, Subtarget);
8491   case ISD::SUB:
8492     return performSUBCombine(N, DAG);
8493   case ISD::AND:
8494     return performANDCombine(N, DAG);
8495   case ISD::OR:
8496     return performORCombine(N, DAG, Subtarget);
8497   case ISD::XOR:
8498     return performXORCombine(N, DAG);
8499   case ISD::SIGN_EXTEND_INREG:
8500     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8501   case ISD::ZERO_EXTEND:
8502     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8503     // type legalization. This is safe because fp_to_uint produces poison if
8504     // it overflows.
8505     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8506       SDValue Src = N->getOperand(0);
8507       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8508           isTypeLegal(Src.getOperand(0).getValueType()))
8509         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8510                            Src.getOperand(0));
8511       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8512           isTypeLegal(Src.getOperand(1).getValueType())) {
8513         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8514         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8515                                   Src.getOperand(0), Src.getOperand(1));
8516         DCI.CombineTo(N, Res);
8517         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8518         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8519         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8520       }
8521     }
8522     return SDValue();
8523   case RISCVISD::SELECT_CC: {
8524     // Transform
8525     SDValue LHS = N->getOperand(0);
8526     SDValue RHS = N->getOperand(1);
8527     SDValue TrueV = N->getOperand(3);
8528     SDValue FalseV = N->getOperand(4);
8529 
8530     // If the True and False values are the same, we don't need a select_cc.
8531     if (TrueV == FalseV)
8532       return TrueV;
8533 
8534     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8535     if (!ISD::isIntEqualitySetCC(CCVal))
8536       break;
8537 
8538     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8539     //      (select_cc X, Y, lt, trueV, falseV)
8540     // Sometimes the setcc is introduced after select_cc has been formed.
8541     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8542         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8543       // If we're looking for eq 0 instead of ne 0, we need to invert the
8544       // condition.
8545       bool Invert = CCVal == ISD::SETEQ;
8546       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8547       if (Invert)
8548         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8549 
8550       SDLoc DL(N);
8551       RHS = LHS.getOperand(1);
8552       LHS = LHS.getOperand(0);
8553       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8554 
8555       SDValue TargetCC = DAG.getCondCode(CCVal);
8556       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8557                          {LHS, RHS, TargetCC, TrueV, FalseV});
8558     }
8559 
8560     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8561     //      (select_cc X, Y, eq/ne, trueV, falseV)
8562     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8563       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8564                          {LHS.getOperand(0), LHS.getOperand(1),
8565                           N->getOperand(2), TrueV, FalseV});
8566     // (select_cc X, 1, setne, trueV, falseV) ->
8567     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8568     // This can occur when legalizing some floating point comparisons.
8569     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8570     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8571       SDLoc DL(N);
8572       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8573       SDValue TargetCC = DAG.getCondCode(CCVal);
8574       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8575       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8576                          {LHS, RHS, TargetCC, TrueV, FalseV});
8577     }
8578 
8579     break;
8580   }
8581   case RISCVISD::BR_CC: {
8582     SDValue LHS = N->getOperand(1);
8583     SDValue RHS = N->getOperand(2);
8584     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8585     if (!ISD::isIntEqualitySetCC(CCVal))
8586       break;
8587 
8588     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8589     //      (br_cc X, Y, lt, dest)
8590     // Sometimes the setcc is introduced after br_cc has been formed.
8591     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8592         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8593       // If we're looking for eq 0 instead of ne 0, we need to invert the
8594       // condition.
8595       bool Invert = CCVal == ISD::SETEQ;
8596       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8597       if (Invert)
8598         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8599 
8600       SDLoc DL(N);
8601       RHS = LHS.getOperand(1);
8602       LHS = LHS.getOperand(0);
8603       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8604 
8605       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8606                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8607                          N->getOperand(4));
8608     }
8609 
8610     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8611     //      (br_cc X, Y, eq/ne, trueV, falseV)
8612     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8613       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8614                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8615                          N->getOperand(3), N->getOperand(4));
8616 
8617     // (br_cc X, 1, setne, br_cc) ->
8618     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8619     // This can occur when legalizing some floating point comparisons.
8620     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8621     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8622       SDLoc DL(N);
8623       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8624       SDValue TargetCC = DAG.getCondCode(CCVal);
8625       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8626       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8627                          N->getOperand(0), LHS, RHS, TargetCC,
8628                          N->getOperand(4));
8629     }
8630     break;
8631   }
8632   case ISD::BITREVERSE:
8633     return performBITREVERSECombine(N, DAG, Subtarget);
8634   case ISD::FP_TO_SINT:
8635   case ISD::FP_TO_UINT:
8636     return performFP_TO_INTCombine(N, DCI, Subtarget);
8637   case ISD::FP_TO_SINT_SAT:
8638   case ISD::FP_TO_UINT_SAT:
8639     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8640   case ISD::FCOPYSIGN: {
8641     EVT VT = N->getValueType(0);
8642     if (!VT.isVector())
8643       break;
8644     // There is a form of VFSGNJ which injects the negated sign of its second
8645     // operand. Try and bubble any FNEG up after the extend/round to produce
8646     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8647     // TRUNC=1.
8648     SDValue In2 = N->getOperand(1);
8649     // Avoid cases where the extend/round has multiple uses, as duplicating
8650     // those is typically more expensive than removing a fneg.
8651     if (!In2.hasOneUse())
8652       break;
8653     if (In2.getOpcode() != ISD::FP_EXTEND &&
8654         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8655       break;
8656     In2 = In2.getOperand(0);
8657     if (In2.getOpcode() != ISD::FNEG)
8658       break;
8659     SDLoc DL(N);
8660     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8661     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8662                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8663   }
8664   case ISD::MGATHER:
8665   case ISD::MSCATTER:
8666   case ISD::VP_GATHER:
8667   case ISD::VP_SCATTER: {
8668     if (!DCI.isBeforeLegalize())
8669       break;
8670     SDValue Index, ScaleOp;
8671     bool IsIndexScaled = false;
8672     bool IsIndexSigned = false;
8673     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8674       Index = VPGSN->getIndex();
8675       ScaleOp = VPGSN->getScale();
8676       IsIndexScaled = VPGSN->isIndexScaled();
8677       IsIndexSigned = VPGSN->isIndexSigned();
8678     } else {
8679       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8680       Index = MGSN->getIndex();
8681       ScaleOp = MGSN->getScale();
8682       IsIndexScaled = MGSN->isIndexScaled();
8683       IsIndexSigned = MGSN->isIndexSigned();
8684     }
8685     EVT IndexVT = Index.getValueType();
8686     MVT XLenVT = Subtarget.getXLenVT();
8687     // RISCV indexed loads only support the "unsigned unscaled" addressing
8688     // mode, so anything else must be manually legalized.
8689     bool NeedsIdxLegalization =
8690         IsIndexScaled ||
8691         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8692     if (!NeedsIdxLegalization)
8693       break;
8694 
8695     SDLoc DL(N);
8696 
8697     // Any index legalization should first promote to XLenVT, so we don't lose
8698     // bits when scaling. This may create an illegal index type so we let
8699     // LLVM's legalization take care of the splitting.
8700     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8701     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8702       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8703       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8704                           DL, IndexVT, Index);
8705     }
8706 
8707     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8708     if (IsIndexScaled && Scale != 1) {
8709       // Manually scale the indices by the element size.
8710       // TODO: Sanitize the scale operand here?
8711       // TODO: For VP nodes, should we use VP_SHL here?
8712       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8713       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8714       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8715     }
8716 
8717     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8718     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8719       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8720                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8721                               VPGN->getScale(), VPGN->getMask(),
8722                               VPGN->getVectorLength()},
8723                              VPGN->getMemOperand(), NewIndexTy);
8724     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8725       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8726                               {VPSN->getChain(), VPSN->getValue(),
8727                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8728                                VPSN->getMask(), VPSN->getVectorLength()},
8729                               VPSN->getMemOperand(), NewIndexTy);
8730     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8731       return DAG.getMaskedGather(
8732           N->getVTList(), MGN->getMemoryVT(), DL,
8733           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8734            MGN->getBasePtr(), Index, MGN->getScale()},
8735           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8736     const auto *MSN = cast<MaskedScatterSDNode>(N);
8737     return DAG.getMaskedScatter(
8738         N->getVTList(), MSN->getMemoryVT(), DL,
8739         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8740          Index, MSN->getScale()},
8741         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8742   }
8743   case RISCVISD::SRA_VL:
8744   case RISCVISD::SRL_VL:
8745   case RISCVISD::SHL_VL: {
8746     SDValue ShAmt = N->getOperand(1);
8747     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8748       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8749       SDLoc DL(N);
8750       SDValue VL = N->getOperand(3);
8751       EVT VT = N->getValueType(0);
8752       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8753                           ShAmt.getOperand(1), VL);
8754       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8755                          N->getOperand(2), N->getOperand(3));
8756     }
8757     break;
8758   }
8759   case ISD::SRA:
8760   case ISD::SRL:
8761   case ISD::SHL: {
8762     SDValue ShAmt = N->getOperand(1);
8763     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8764       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8765       SDLoc DL(N);
8766       EVT VT = N->getValueType(0);
8767       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8768                           ShAmt.getOperand(1),
8769                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8770       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8771     }
8772     break;
8773   }
8774   case RISCVISD::ADD_VL:
8775     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8776       return V;
8777     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8778   case RISCVISD::SUB_VL:
8779     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8780   case RISCVISD::VWADD_W_VL:
8781   case RISCVISD::VWADDU_W_VL:
8782   case RISCVISD::VWSUB_W_VL:
8783   case RISCVISD::VWSUBU_W_VL:
8784     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8785   case RISCVISD::MUL_VL:
8786     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8787       return V;
8788     // Mul is commutative.
8789     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8790   case ISD::STORE: {
8791     auto *Store = cast<StoreSDNode>(N);
8792     SDValue Val = Store->getValue();
8793     // Combine store of vmv.x.s to vse with VL of 1.
8794     // FIXME: Support FP.
8795     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8796       SDValue Src = Val.getOperand(0);
8797       EVT VecVT = Src.getValueType();
8798       EVT MemVT = Store->getMemoryVT();
8799       // The memory VT and the element type must match.
8800       if (VecVT.getVectorElementType() == MemVT) {
8801         SDLoc DL(N);
8802         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8803         return DAG.getStoreVP(
8804             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8805             DAG.getConstant(1, DL, MaskVT),
8806             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8807             Store->getMemOperand(), Store->getAddressingMode(),
8808             Store->isTruncatingStore(), /*IsCompress*/ false);
8809       }
8810     }
8811 
8812     break;
8813   }
8814   case ISD::SPLAT_VECTOR: {
8815     EVT VT = N->getValueType(0);
8816     // Only perform this combine on legal MVT types.
8817     if (!isTypeLegal(VT))
8818       break;
8819     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8820                                          DAG, Subtarget))
8821       return Gather;
8822     break;
8823   }
8824   case RISCVISD::VMV_V_X_VL: {
8825     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8826     // scalar input.
8827     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8828     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8829     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8830       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8831         return SDValue(N, 0);
8832 
8833     break;
8834   }
8835   case ISD::INTRINSIC_WO_CHAIN: {
8836     unsigned IntNo = N->getConstantOperandVal(0);
8837     switch (IntNo) {
8838       // By default we do not combine any intrinsic.
8839     default:
8840       return SDValue();
8841     case Intrinsic::riscv_vcpop:
8842     case Intrinsic::riscv_vcpop_mask:
8843     case Intrinsic::riscv_vfirst:
8844     case Intrinsic::riscv_vfirst_mask: {
8845       SDValue VL = N->getOperand(2);
8846       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8847           IntNo == Intrinsic::riscv_vfirst_mask)
8848         VL = N->getOperand(3);
8849       if (!isNullConstant(VL))
8850         return SDValue();
8851       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8852       SDLoc DL(N);
8853       EVT VT = N->getValueType(0);
8854       if (IntNo == Intrinsic::riscv_vfirst ||
8855           IntNo == Intrinsic::riscv_vfirst_mask)
8856         return DAG.getConstant(-1, DL, VT);
8857       return DAG.getConstant(0, DL, VT);
8858     }
8859     }
8860   }
8861   }
8862 
8863   return SDValue();
8864 }
8865 
8866 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8867     const SDNode *N, CombineLevel Level) const {
8868   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8869   // materialised in fewer instructions than `(OP _, c1)`:
8870   //
8871   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8872   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8873   SDValue N0 = N->getOperand(0);
8874   EVT Ty = N0.getValueType();
8875   if (Ty.isScalarInteger() &&
8876       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8877     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8878     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8879     if (C1 && C2) {
8880       const APInt &C1Int = C1->getAPIntValue();
8881       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8882 
8883       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8884       // and the combine should happen, to potentially allow further combines
8885       // later.
8886       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8887           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8888         return true;
8889 
8890       // We can materialise `c1` in an add immediate, so it's "free", and the
8891       // combine should be prevented.
8892       if (C1Int.getMinSignedBits() <= 64 &&
8893           isLegalAddImmediate(C1Int.getSExtValue()))
8894         return false;
8895 
8896       // Neither constant will fit into an immediate, so find materialisation
8897       // costs.
8898       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8899                                               Subtarget.getFeatureBits(),
8900                                               /*CompressionCost*/true);
8901       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8902           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8903           /*CompressionCost*/true);
8904 
8905       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8906       // combine should be prevented.
8907       if (C1Cost < ShiftedC1Cost)
8908         return false;
8909     }
8910   }
8911   return true;
8912 }
8913 
8914 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8915     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8916     TargetLoweringOpt &TLO) const {
8917   // Delay this optimization as late as possible.
8918   if (!TLO.LegalOps)
8919     return false;
8920 
8921   EVT VT = Op.getValueType();
8922   if (VT.isVector())
8923     return false;
8924 
8925   // Only handle AND for now.
8926   if (Op.getOpcode() != ISD::AND)
8927     return false;
8928 
8929   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8930   if (!C)
8931     return false;
8932 
8933   const APInt &Mask = C->getAPIntValue();
8934 
8935   // Clear all non-demanded bits initially.
8936   APInt ShrunkMask = Mask & DemandedBits;
8937 
8938   // Try to make a smaller immediate by setting undemanded bits.
8939 
8940   APInt ExpandedMask = Mask | ~DemandedBits;
8941 
8942   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8943     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8944   };
8945   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8946     if (NewMask == Mask)
8947       return true;
8948     SDLoc DL(Op);
8949     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8950     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8951     return TLO.CombineTo(Op, NewOp);
8952   };
8953 
8954   // If the shrunk mask fits in sign extended 12 bits, let the target
8955   // independent code apply it.
8956   if (ShrunkMask.isSignedIntN(12))
8957     return false;
8958 
8959   // Preserve (and X, 0xffff) when zext.h is supported.
8960   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8961     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8962     if (IsLegalMask(NewMask))
8963       return UseMask(NewMask);
8964   }
8965 
8966   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8967   if (VT == MVT::i64) {
8968     APInt NewMask = APInt(64, 0xffffffff);
8969     if (IsLegalMask(NewMask))
8970       return UseMask(NewMask);
8971   }
8972 
8973   // For the remaining optimizations, we need to be able to make a negative
8974   // number through a combination of mask and undemanded bits.
8975   if (!ExpandedMask.isNegative())
8976     return false;
8977 
8978   // What is the fewest number of bits we need to represent the negative number.
8979   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8980 
8981   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8982   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8983   APInt NewMask = ShrunkMask;
8984   if (MinSignedBits <= 12)
8985     NewMask.setBitsFrom(11);
8986   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8987     NewMask.setBitsFrom(31);
8988   else
8989     return false;
8990 
8991   // Check that our new mask is a subset of the demanded mask.
8992   assert(IsLegalMask(NewMask));
8993   return UseMask(NewMask);
8994 }
8995 
8996 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
8997   static const uint64_t GREVMasks[] = {
8998       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
8999       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9000 
9001   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9002     unsigned Shift = 1 << Stage;
9003     if (ShAmt & Shift) {
9004       uint64_t Mask = GREVMasks[Stage];
9005       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9006       if (IsGORC)
9007         Res |= x;
9008       x = Res;
9009     }
9010   }
9011 
9012   return x;
9013 }
9014 
9015 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9016                                                         KnownBits &Known,
9017                                                         const APInt &DemandedElts,
9018                                                         const SelectionDAG &DAG,
9019                                                         unsigned Depth) const {
9020   unsigned BitWidth = Known.getBitWidth();
9021   unsigned Opc = Op.getOpcode();
9022   assert((Opc >= ISD::BUILTIN_OP_END ||
9023           Opc == ISD::INTRINSIC_WO_CHAIN ||
9024           Opc == ISD::INTRINSIC_W_CHAIN ||
9025           Opc == ISD::INTRINSIC_VOID) &&
9026          "Should use MaskedValueIsZero if you don't know whether Op"
9027          " is a target node!");
9028 
9029   Known.resetAll();
9030   switch (Opc) {
9031   default: break;
9032   case RISCVISD::SELECT_CC: {
9033     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9034     // If we don't know any bits, early out.
9035     if (Known.isUnknown())
9036       break;
9037     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9038 
9039     // Only known if known in both the LHS and RHS.
9040     Known = KnownBits::commonBits(Known, Known2);
9041     break;
9042   }
9043   case RISCVISD::REMUW: {
9044     KnownBits Known2;
9045     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9046     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9047     // We only care about the lower 32 bits.
9048     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9049     // Restore the original width by sign extending.
9050     Known = Known.sext(BitWidth);
9051     break;
9052   }
9053   case RISCVISD::DIVUW: {
9054     KnownBits Known2;
9055     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9056     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9057     // We only care about the lower 32 bits.
9058     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9059     // Restore the original width by sign extending.
9060     Known = Known.sext(BitWidth);
9061     break;
9062   }
9063   case RISCVISD::CTZW: {
9064     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9065     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9066     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9067     Known.Zero.setBitsFrom(LowBits);
9068     break;
9069   }
9070   case RISCVISD::CLZW: {
9071     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9072     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9073     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9074     Known.Zero.setBitsFrom(LowBits);
9075     break;
9076   }
9077   case RISCVISD::GREV:
9078   case RISCVISD::GORC: {
9079     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9080       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9081       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9082       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9083       // To compute zeros, we need to invert the value and invert it back after.
9084       Known.Zero =
9085           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9086       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9087     }
9088     break;
9089   }
9090   case RISCVISD::READ_VLENB: {
9091     // If we know the minimum VLen from Zvl extensions, we can use that to
9092     // determine the trailing zeros of VLENB.
9093     // FIXME: Limit to 128 bit vectors until we have more testing.
9094     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9095     if (MinVLenB > 0)
9096       Known.Zero.setLowBits(Log2_32(MinVLenB));
9097     // We assume VLENB is no more than 65536 / 8 bytes.
9098     Known.Zero.setBitsFrom(14);
9099     break;
9100   }
9101   case ISD::INTRINSIC_W_CHAIN:
9102   case ISD::INTRINSIC_WO_CHAIN: {
9103     unsigned IntNo =
9104         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9105     switch (IntNo) {
9106     default:
9107       // We can't do anything for most intrinsics.
9108       break;
9109     case Intrinsic::riscv_vsetvli:
9110     case Intrinsic::riscv_vsetvlimax:
9111     case Intrinsic::riscv_vsetvli_opt:
9112     case Intrinsic::riscv_vsetvlimax_opt:
9113       // Assume that VL output is positive and would fit in an int32_t.
9114       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9115       if (BitWidth >= 32)
9116         Known.Zero.setBitsFrom(31);
9117       break;
9118     }
9119     break;
9120   }
9121   }
9122 }
9123 
9124 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9125     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9126     unsigned Depth) const {
9127   switch (Op.getOpcode()) {
9128   default:
9129     break;
9130   case RISCVISD::SELECT_CC: {
9131     unsigned Tmp =
9132         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9133     if (Tmp == 1) return 1;  // Early out.
9134     unsigned Tmp2 =
9135         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9136     return std::min(Tmp, Tmp2);
9137   }
9138   case RISCVISD::SLLW:
9139   case RISCVISD::SRAW:
9140   case RISCVISD::SRLW:
9141   case RISCVISD::DIVW:
9142   case RISCVISD::DIVUW:
9143   case RISCVISD::REMUW:
9144   case RISCVISD::ROLW:
9145   case RISCVISD::RORW:
9146   case RISCVISD::GREVW:
9147   case RISCVISD::GORCW:
9148   case RISCVISD::FSLW:
9149   case RISCVISD::FSRW:
9150   case RISCVISD::SHFLW:
9151   case RISCVISD::UNSHFLW:
9152   case RISCVISD::BCOMPRESSW:
9153   case RISCVISD::BDECOMPRESSW:
9154   case RISCVISD::BFPW:
9155   case RISCVISD::FCVT_W_RV64:
9156   case RISCVISD::FCVT_WU_RV64:
9157   case RISCVISD::STRICT_FCVT_W_RV64:
9158   case RISCVISD::STRICT_FCVT_WU_RV64:
9159     // TODO: As the result is sign-extended, this is conservatively correct. A
9160     // more precise answer could be calculated for SRAW depending on known
9161     // bits in the shift amount.
9162     return 33;
9163   case RISCVISD::SHFL:
9164   case RISCVISD::UNSHFL: {
9165     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9166     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9167     // will stay within the upper 32 bits. If there were more than 32 sign bits
9168     // before there will be at least 33 sign bits after.
9169     if (Op.getValueType() == MVT::i64 &&
9170         isa<ConstantSDNode>(Op.getOperand(1)) &&
9171         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9172       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9173       if (Tmp > 32)
9174         return 33;
9175     }
9176     break;
9177   }
9178   case RISCVISD::VMV_X_S: {
9179     // The number of sign bits of the scalar result is computed by obtaining the
9180     // element type of the input vector operand, subtracting its width from the
9181     // XLEN, and then adding one (sign bit within the element type). If the
9182     // element type is wider than XLen, the least-significant XLEN bits are
9183     // taken.
9184     unsigned XLen = Subtarget.getXLen();
9185     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9186     if (EltBits <= XLen)
9187       return XLen - EltBits + 1;
9188     break;
9189   }
9190   }
9191 
9192   return 1;
9193 }
9194 
9195 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9196                                                   MachineBasicBlock *BB) {
9197   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9198 
9199   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9200   // Should the count have wrapped while it was being read, we need to try
9201   // again.
9202   // ...
9203   // read:
9204   // rdcycleh x3 # load high word of cycle
9205   // rdcycle  x2 # load low word of cycle
9206   // rdcycleh x4 # load high word of cycle
9207   // bne x3, x4, read # check if high word reads match, otherwise try again
9208   // ...
9209 
9210   MachineFunction &MF = *BB->getParent();
9211   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9212   MachineFunction::iterator It = ++BB->getIterator();
9213 
9214   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9215   MF.insert(It, LoopMBB);
9216 
9217   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9218   MF.insert(It, DoneMBB);
9219 
9220   // Transfer the remainder of BB and its successor edges to DoneMBB.
9221   DoneMBB->splice(DoneMBB->begin(), BB,
9222                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9223   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9224 
9225   BB->addSuccessor(LoopMBB);
9226 
9227   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9228   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9229   Register LoReg = MI.getOperand(0).getReg();
9230   Register HiReg = MI.getOperand(1).getReg();
9231   DebugLoc DL = MI.getDebugLoc();
9232 
9233   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9234   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9235       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9236       .addReg(RISCV::X0);
9237   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9238       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9239       .addReg(RISCV::X0);
9240   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9241       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9242       .addReg(RISCV::X0);
9243 
9244   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9245       .addReg(HiReg)
9246       .addReg(ReadAgainReg)
9247       .addMBB(LoopMBB);
9248 
9249   LoopMBB->addSuccessor(LoopMBB);
9250   LoopMBB->addSuccessor(DoneMBB);
9251 
9252   MI.eraseFromParent();
9253 
9254   return DoneMBB;
9255 }
9256 
9257 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9258                                              MachineBasicBlock *BB) {
9259   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9260 
9261   MachineFunction &MF = *BB->getParent();
9262   DebugLoc DL = MI.getDebugLoc();
9263   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9264   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9265   Register LoReg = MI.getOperand(0).getReg();
9266   Register HiReg = MI.getOperand(1).getReg();
9267   Register SrcReg = MI.getOperand(2).getReg();
9268   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9269   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9270 
9271   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9272                           RI);
9273   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9274   MachineMemOperand *MMOLo =
9275       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9276   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9277       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9278   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9279       .addFrameIndex(FI)
9280       .addImm(0)
9281       .addMemOperand(MMOLo);
9282   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9283       .addFrameIndex(FI)
9284       .addImm(4)
9285       .addMemOperand(MMOHi);
9286   MI.eraseFromParent(); // The pseudo instruction is gone now.
9287   return BB;
9288 }
9289 
9290 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9291                                                  MachineBasicBlock *BB) {
9292   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9293          "Unexpected instruction");
9294 
9295   MachineFunction &MF = *BB->getParent();
9296   DebugLoc DL = MI.getDebugLoc();
9297   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9298   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9299   Register DstReg = MI.getOperand(0).getReg();
9300   Register LoReg = MI.getOperand(1).getReg();
9301   Register HiReg = MI.getOperand(2).getReg();
9302   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9303   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9304 
9305   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9306   MachineMemOperand *MMOLo =
9307       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9308   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9309       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9310   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9311       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9312       .addFrameIndex(FI)
9313       .addImm(0)
9314       .addMemOperand(MMOLo);
9315   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9316       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9317       .addFrameIndex(FI)
9318       .addImm(4)
9319       .addMemOperand(MMOHi);
9320   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9321   MI.eraseFromParent(); // The pseudo instruction is gone now.
9322   return BB;
9323 }
9324 
9325 static bool isSelectPseudo(MachineInstr &MI) {
9326   switch (MI.getOpcode()) {
9327   default:
9328     return false;
9329   case RISCV::Select_GPR_Using_CC_GPR:
9330   case RISCV::Select_FPR16_Using_CC_GPR:
9331   case RISCV::Select_FPR32_Using_CC_GPR:
9332   case RISCV::Select_FPR64_Using_CC_GPR:
9333     return true;
9334   }
9335 }
9336 
9337 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9338                                         unsigned RelOpcode, unsigned EqOpcode,
9339                                         const RISCVSubtarget &Subtarget) {
9340   DebugLoc DL = MI.getDebugLoc();
9341   Register DstReg = MI.getOperand(0).getReg();
9342   Register Src1Reg = MI.getOperand(1).getReg();
9343   Register Src2Reg = MI.getOperand(2).getReg();
9344   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9345   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9346   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9347 
9348   // Save the current FFLAGS.
9349   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9350 
9351   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9352                  .addReg(Src1Reg)
9353                  .addReg(Src2Reg);
9354   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9355     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9356 
9357   // Restore the FFLAGS.
9358   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9359       .addReg(SavedFFlags, RegState::Kill);
9360 
9361   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9362   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9363                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9364                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9365   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9366     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9367 
9368   // Erase the pseudoinstruction.
9369   MI.eraseFromParent();
9370   return BB;
9371 }
9372 
9373 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9374                                            MachineBasicBlock *BB,
9375                                            const RISCVSubtarget &Subtarget) {
9376   // To "insert" Select_* instructions, we actually have to insert the triangle
9377   // control-flow pattern.  The incoming instructions know the destination vreg
9378   // to set, the condition code register to branch on, the true/false values to
9379   // select between, and the condcode to use to select the appropriate branch.
9380   //
9381   // We produce the following control flow:
9382   //     HeadMBB
9383   //     |  \
9384   //     |  IfFalseMBB
9385   //     | /
9386   //    TailMBB
9387   //
9388   // When we find a sequence of selects we attempt to optimize their emission
9389   // by sharing the control flow. Currently we only handle cases where we have
9390   // multiple selects with the exact same condition (same LHS, RHS and CC).
9391   // The selects may be interleaved with other instructions if the other
9392   // instructions meet some requirements we deem safe:
9393   // - They are debug instructions. Otherwise,
9394   // - They do not have side-effects, do not access memory and their inputs do
9395   //   not depend on the results of the select pseudo-instructions.
9396   // The TrueV/FalseV operands of the selects cannot depend on the result of
9397   // previous selects in the sequence.
9398   // These conditions could be further relaxed. See the X86 target for a
9399   // related approach and more information.
9400   Register LHS = MI.getOperand(1).getReg();
9401   Register RHS = MI.getOperand(2).getReg();
9402   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9403 
9404   SmallVector<MachineInstr *, 4> SelectDebugValues;
9405   SmallSet<Register, 4> SelectDests;
9406   SelectDests.insert(MI.getOperand(0).getReg());
9407 
9408   MachineInstr *LastSelectPseudo = &MI;
9409 
9410   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9411        SequenceMBBI != E; ++SequenceMBBI) {
9412     if (SequenceMBBI->isDebugInstr())
9413       continue;
9414     else if (isSelectPseudo(*SequenceMBBI)) {
9415       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9416           SequenceMBBI->getOperand(2).getReg() != RHS ||
9417           SequenceMBBI->getOperand(3).getImm() != CC ||
9418           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9419           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9420         break;
9421       LastSelectPseudo = &*SequenceMBBI;
9422       SequenceMBBI->collectDebugValues(SelectDebugValues);
9423       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9424     } else {
9425       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9426           SequenceMBBI->mayLoadOrStore())
9427         break;
9428       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9429             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9430           }))
9431         break;
9432     }
9433   }
9434 
9435   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9436   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9437   DebugLoc DL = MI.getDebugLoc();
9438   MachineFunction::iterator I = ++BB->getIterator();
9439 
9440   MachineBasicBlock *HeadMBB = BB;
9441   MachineFunction *F = BB->getParent();
9442   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9443   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9444 
9445   F->insert(I, IfFalseMBB);
9446   F->insert(I, TailMBB);
9447 
9448   // Transfer debug instructions associated with the selects to TailMBB.
9449   for (MachineInstr *DebugInstr : SelectDebugValues) {
9450     TailMBB->push_back(DebugInstr->removeFromParent());
9451   }
9452 
9453   // Move all instructions after the sequence to TailMBB.
9454   TailMBB->splice(TailMBB->end(), HeadMBB,
9455                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9456   // Update machine-CFG edges by transferring all successors of the current
9457   // block to the new block which will contain the Phi nodes for the selects.
9458   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9459   // Set the successors for HeadMBB.
9460   HeadMBB->addSuccessor(IfFalseMBB);
9461   HeadMBB->addSuccessor(TailMBB);
9462 
9463   // Insert appropriate branch.
9464   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9465     .addReg(LHS)
9466     .addReg(RHS)
9467     .addMBB(TailMBB);
9468 
9469   // IfFalseMBB just falls through to TailMBB.
9470   IfFalseMBB->addSuccessor(TailMBB);
9471 
9472   // Create PHIs for all of the select pseudo-instructions.
9473   auto SelectMBBI = MI.getIterator();
9474   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9475   auto InsertionPoint = TailMBB->begin();
9476   while (SelectMBBI != SelectEnd) {
9477     auto Next = std::next(SelectMBBI);
9478     if (isSelectPseudo(*SelectMBBI)) {
9479       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9480       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9481               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9482           .addReg(SelectMBBI->getOperand(4).getReg())
9483           .addMBB(HeadMBB)
9484           .addReg(SelectMBBI->getOperand(5).getReg())
9485           .addMBB(IfFalseMBB);
9486       SelectMBBI->eraseFromParent();
9487     }
9488     SelectMBBI = Next;
9489   }
9490 
9491   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9492   return TailMBB;
9493 }
9494 
9495 MachineBasicBlock *
9496 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9497                                                  MachineBasicBlock *BB) const {
9498   switch (MI.getOpcode()) {
9499   default:
9500     llvm_unreachable("Unexpected instr type to insert");
9501   case RISCV::ReadCycleWide:
9502     assert(!Subtarget.is64Bit() &&
9503            "ReadCycleWrite is only to be used on riscv32");
9504     return emitReadCycleWidePseudo(MI, BB);
9505   case RISCV::Select_GPR_Using_CC_GPR:
9506   case RISCV::Select_FPR16_Using_CC_GPR:
9507   case RISCV::Select_FPR32_Using_CC_GPR:
9508   case RISCV::Select_FPR64_Using_CC_GPR:
9509     return emitSelectPseudo(MI, BB, Subtarget);
9510   case RISCV::BuildPairF64Pseudo:
9511     return emitBuildPairF64Pseudo(MI, BB);
9512   case RISCV::SplitF64Pseudo:
9513     return emitSplitF64Pseudo(MI, BB);
9514   case RISCV::PseudoQuietFLE_H:
9515     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9516   case RISCV::PseudoQuietFLT_H:
9517     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9518   case RISCV::PseudoQuietFLE_S:
9519     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9520   case RISCV::PseudoQuietFLT_S:
9521     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9522   case RISCV::PseudoQuietFLE_D:
9523     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9524   case RISCV::PseudoQuietFLT_D:
9525     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9526   }
9527 }
9528 
9529 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9530                                                         SDNode *Node) const {
9531   // Add FRM dependency to any instructions with dynamic rounding mode.
9532   unsigned Opc = MI.getOpcode();
9533   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9534   if (Idx < 0)
9535     return;
9536   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9537     return;
9538   // If the instruction already reads FRM, don't add another read.
9539   if (MI.readsRegister(RISCV::FRM))
9540     return;
9541   MI.addOperand(
9542       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9543 }
9544 
9545 // Calling Convention Implementation.
9546 // The expectations for frontend ABI lowering vary from target to target.
9547 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9548 // details, but this is a longer term goal. For now, we simply try to keep the
9549 // role of the frontend as simple and well-defined as possible. The rules can
9550 // be summarised as:
9551 // * Never split up large scalar arguments. We handle them here.
9552 // * If a hardfloat calling convention is being used, and the struct may be
9553 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9554 // available, then pass as two separate arguments. If either the GPRs or FPRs
9555 // are exhausted, then pass according to the rule below.
9556 // * If a struct could never be passed in registers or directly in a stack
9557 // slot (as it is larger than 2*XLEN and the floating point rules don't
9558 // apply), then pass it using a pointer with the byval attribute.
9559 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9560 // word-sized array or a 2*XLEN scalar (depending on alignment).
9561 // * The frontend can determine whether a struct is returned by reference or
9562 // not based on its size and fields. If it will be returned by reference, the
9563 // frontend must modify the prototype so a pointer with the sret annotation is
9564 // passed as the first argument. This is not necessary for large scalar
9565 // returns.
9566 // * Struct return values and varargs should be coerced to structs containing
9567 // register-size fields in the same situations they would be for fixed
9568 // arguments.
9569 
9570 static const MCPhysReg ArgGPRs[] = {
9571   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9572   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9573 };
9574 static const MCPhysReg ArgFPR16s[] = {
9575   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9576   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9577 };
9578 static const MCPhysReg ArgFPR32s[] = {
9579   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9580   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9581 };
9582 static const MCPhysReg ArgFPR64s[] = {
9583   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9584   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9585 };
9586 // This is an interim calling convention and it may be changed in the future.
9587 static const MCPhysReg ArgVRs[] = {
9588     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9589     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9590     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9591 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9592                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9593                                      RISCV::V20M2, RISCV::V22M2};
9594 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9595                                      RISCV::V20M4};
9596 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9597 
9598 // Pass a 2*XLEN argument that has been split into two XLEN values through
9599 // registers or the stack as necessary.
9600 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9601                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9602                                 MVT ValVT2, MVT LocVT2,
9603                                 ISD::ArgFlagsTy ArgFlags2) {
9604   unsigned XLenInBytes = XLen / 8;
9605   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9606     // At least one half can be passed via register.
9607     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9608                                      VA1.getLocVT(), CCValAssign::Full));
9609   } else {
9610     // Both halves must be passed on the stack, with proper alignment.
9611     Align StackAlign =
9612         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9613     State.addLoc(
9614         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9615                             State.AllocateStack(XLenInBytes, StackAlign),
9616                             VA1.getLocVT(), CCValAssign::Full));
9617     State.addLoc(CCValAssign::getMem(
9618         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9619         LocVT2, CCValAssign::Full));
9620     return false;
9621   }
9622 
9623   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9624     // The second half can also be passed via register.
9625     State.addLoc(
9626         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9627   } else {
9628     // The second half is passed via the stack, without additional alignment.
9629     State.addLoc(CCValAssign::getMem(
9630         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9631         LocVT2, CCValAssign::Full));
9632   }
9633 
9634   return false;
9635 }
9636 
9637 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9638                                Optional<unsigned> FirstMaskArgument,
9639                                CCState &State, const RISCVTargetLowering &TLI) {
9640   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9641   if (RC == &RISCV::VRRegClass) {
9642     // Assign the first mask argument to V0.
9643     // This is an interim calling convention and it may be changed in the
9644     // future.
9645     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9646       return State.AllocateReg(RISCV::V0);
9647     return State.AllocateReg(ArgVRs);
9648   }
9649   if (RC == &RISCV::VRM2RegClass)
9650     return State.AllocateReg(ArgVRM2s);
9651   if (RC == &RISCV::VRM4RegClass)
9652     return State.AllocateReg(ArgVRM4s);
9653   if (RC == &RISCV::VRM8RegClass)
9654     return State.AllocateReg(ArgVRM8s);
9655   llvm_unreachable("Unhandled register class for ValueType");
9656 }
9657 
9658 // Implements the RISC-V calling convention. Returns true upon failure.
9659 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9660                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9661                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9662                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9663                      Optional<unsigned> FirstMaskArgument) {
9664   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9665   assert(XLen == 32 || XLen == 64);
9666   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9667 
9668   // Any return value split in to more than two values can't be returned
9669   // directly. Vectors are returned via the available vector registers.
9670   if (!LocVT.isVector() && IsRet && ValNo > 1)
9671     return true;
9672 
9673   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9674   // variadic argument, or if no F16/F32 argument registers are available.
9675   bool UseGPRForF16_F32 = true;
9676   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9677   // variadic argument, or if no F64 argument registers are available.
9678   bool UseGPRForF64 = true;
9679 
9680   switch (ABI) {
9681   default:
9682     llvm_unreachable("Unexpected ABI");
9683   case RISCVABI::ABI_ILP32:
9684   case RISCVABI::ABI_LP64:
9685     break;
9686   case RISCVABI::ABI_ILP32F:
9687   case RISCVABI::ABI_LP64F:
9688     UseGPRForF16_F32 = !IsFixed;
9689     break;
9690   case RISCVABI::ABI_ILP32D:
9691   case RISCVABI::ABI_LP64D:
9692     UseGPRForF16_F32 = !IsFixed;
9693     UseGPRForF64 = !IsFixed;
9694     break;
9695   }
9696 
9697   // FPR16, FPR32, and FPR64 alias each other.
9698   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9699     UseGPRForF16_F32 = true;
9700     UseGPRForF64 = true;
9701   }
9702 
9703   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9704   // similar local variables rather than directly checking against the target
9705   // ABI.
9706 
9707   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9708     LocVT = XLenVT;
9709     LocInfo = CCValAssign::BCvt;
9710   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9711     LocVT = MVT::i64;
9712     LocInfo = CCValAssign::BCvt;
9713   }
9714 
9715   // If this is a variadic argument, the RISC-V calling convention requires
9716   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9717   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9718   // be used regardless of whether the original argument was split during
9719   // legalisation or not. The argument will not be passed by registers if the
9720   // original type is larger than 2*XLEN, so the register alignment rule does
9721   // not apply.
9722   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9723   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9724       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9725     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9726     // Skip 'odd' register if necessary.
9727     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9728       State.AllocateReg(ArgGPRs);
9729   }
9730 
9731   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9732   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9733       State.getPendingArgFlags();
9734 
9735   assert(PendingLocs.size() == PendingArgFlags.size() &&
9736          "PendingLocs and PendingArgFlags out of sync");
9737 
9738   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9739   // registers are exhausted.
9740   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9741     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9742            "Can't lower f64 if it is split");
9743     // Depending on available argument GPRS, f64 may be passed in a pair of
9744     // GPRs, split between a GPR and the stack, or passed completely on the
9745     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9746     // cases.
9747     Register Reg = State.AllocateReg(ArgGPRs);
9748     LocVT = MVT::i32;
9749     if (!Reg) {
9750       unsigned StackOffset = State.AllocateStack(8, Align(8));
9751       State.addLoc(
9752           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9753       return false;
9754     }
9755     if (!State.AllocateReg(ArgGPRs))
9756       State.AllocateStack(4, Align(4));
9757     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9758     return false;
9759   }
9760 
9761   // Fixed-length vectors are located in the corresponding scalable-vector
9762   // container types.
9763   if (ValVT.isFixedLengthVector())
9764     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9765 
9766   // Split arguments might be passed indirectly, so keep track of the pending
9767   // values. Split vectors are passed via a mix of registers and indirectly, so
9768   // treat them as we would any other argument.
9769   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9770     LocVT = XLenVT;
9771     LocInfo = CCValAssign::Indirect;
9772     PendingLocs.push_back(
9773         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9774     PendingArgFlags.push_back(ArgFlags);
9775     if (!ArgFlags.isSplitEnd()) {
9776       return false;
9777     }
9778   }
9779 
9780   // If the split argument only had two elements, it should be passed directly
9781   // in registers or on the stack.
9782   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9783       PendingLocs.size() <= 2) {
9784     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9785     // Apply the normal calling convention rules to the first half of the
9786     // split argument.
9787     CCValAssign VA = PendingLocs[0];
9788     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9789     PendingLocs.clear();
9790     PendingArgFlags.clear();
9791     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9792                                ArgFlags);
9793   }
9794 
9795   // Allocate to a register if possible, or else a stack slot.
9796   Register Reg;
9797   unsigned StoreSizeBytes = XLen / 8;
9798   Align StackAlign = Align(XLen / 8);
9799 
9800   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9801     Reg = State.AllocateReg(ArgFPR16s);
9802   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9803     Reg = State.AllocateReg(ArgFPR32s);
9804   else if (ValVT == MVT::f64 && !UseGPRForF64)
9805     Reg = State.AllocateReg(ArgFPR64s);
9806   else if (ValVT.isVector()) {
9807     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9808     if (!Reg) {
9809       // For return values, the vector must be passed fully via registers or
9810       // via the stack.
9811       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9812       // but we're using all of them.
9813       if (IsRet)
9814         return true;
9815       // Try using a GPR to pass the address
9816       if ((Reg = State.AllocateReg(ArgGPRs))) {
9817         LocVT = XLenVT;
9818         LocInfo = CCValAssign::Indirect;
9819       } else if (ValVT.isScalableVector()) {
9820         LocVT = XLenVT;
9821         LocInfo = CCValAssign::Indirect;
9822       } else {
9823         // Pass fixed-length vectors on the stack.
9824         LocVT = ValVT;
9825         StoreSizeBytes = ValVT.getStoreSize();
9826         // Align vectors to their element sizes, being careful for vXi1
9827         // vectors.
9828         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9829       }
9830     }
9831   } else {
9832     Reg = State.AllocateReg(ArgGPRs);
9833   }
9834 
9835   unsigned StackOffset =
9836       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9837 
9838   // If we reach this point and PendingLocs is non-empty, we must be at the
9839   // end of a split argument that must be passed indirectly.
9840   if (!PendingLocs.empty()) {
9841     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9842     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9843 
9844     for (auto &It : PendingLocs) {
9845       if (Reg)
9846         It.convertToReg(Reg);
9847       else
9848         It.convertToMem(StackOffset);
9849       State.addLoc(It);
9850     }
9851     PendingLocs.clear();
9852     PendingArgFlags.clear();
9853     return false;
9854   }
9855 
9856   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9857           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9858          "Expected an XLenVT or vector types at this stage");
9859 
9860   if (Reg) {
9861     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9862     return false;
9863   }
9864 
9865   // When a floating-point value is passed on the stack, no bit-conversion is
9866   // needed.
9867   if (ValVT.isFloatingPoint()) {
9868     LocVT = ValVT;
9869     LocInfo = CCValAssign::Full;
9870   }
9871   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9872   return false;
9873 }
9874 
9875 template <typename ArgTy>
9876 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9877   for (const auto &ArgIdx : enumerate(Args)) {
9878     MVT ArgVT = ArgIdx.value().VT;
9879     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9880       return ArgIdx.index();
9881   }
9882   return None;
9883 }
9884 
9885 void RISCVTargetLowering::analyzeInputArgs(
9886     MachineFunction &MF, CCState &CCInfo,
9887     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9888     RISCVCCAssignFn Fn) const {
9889   unsigned NumArgs = Ins.size();
9890   FunctionType *FType = MF.getFunction().getFunctionType();
9891 
9892   Optional<unsigned> FirstMaskArgument;
9893   if (Subtarget.hasVInstructions())
9894     FirstMaskArgument = preAssignMask(Ins);
9895 
9896   for (unsigned i = 0; i != NumArgs; ++i) {
9897     MVT ArgVT = Ins[i].VT;
9898     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9899 
9900     Type *ArgTy = nullptr;
9901     if (IsRet)
9902       ArgTy = FType->getReturnType();
9903     else if (Ins[i].isOrigArg())
9904       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9905 
9906     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9907     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9908            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9909            FirstMaskArgument)) {
9910       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9911                         << EVT(ArgVT).getEVTString() << '\n');
9912       llvm_unreachable(nullptr);
9913     }
9914   }
9915 }
9916 
9917 void RISCVTargetLowering::analyzeOutputArgs(
9918     MachineFunction &MF, CCState &CCInfo,
9919     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9920     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9921   unsigned NumArgs = Outs.size();
9922 
9923   Optional<unsigned> FirstMaskArgument;
9924   if (Subtarget.hasVInstructions())
9925     FirstMaskArgument = preAssignMask(Outs);
9926 
9927   for (unsigned i = 0; i != NumArgs; i++) {
9928     MVT ArgVT = Outs[i].VT;
9929     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9930     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9931 
9932     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9933     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9934            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9935            FirstMaskArgument)) {
9936       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9937                         << EVT(ArgVT).getEVTString() << "\n");
9938       llvm_unreachable(nullptr);
9939     }
9940   }
9941 }
9942 
9943 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9944 // values.
9945 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9946                                    const CCValAssign &VA, const SDLoc &DL,
9947                                    const RISCVSubtarget &Subtarget) {
9948   switch (VA.getLocInfo()) {
9949   default:
9950     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9951   case CCValAssign::Full:
9952     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9953       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9954     break;
9955   case CCValAssign::BCvt:
9956     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9957       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9958     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9959       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9960     else
9961       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9962     break;
9963   }
9964   return Val;
9965 }
9966 
9967 // The caller is responsible for loading the full value if the argument is
9968 // passed with CCValAssign::Indirect.
9969 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9970                                 const CCValAssign &VA, const SDLoc &DL,
9971                                 const RISCVTargetLowering &TLI) {
9972   MachineFunction &MF = DAG.getMachineFunction();
9973   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9974   EVT LocVT = VA.getLocVT();
9975   SDValue Val;
9976   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9977   Register VReg = RegInfo.createVirtualRegister(RC);
9978   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9979   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9980 
9981   if (VA.getLocInfo() == CCValAssign::Indirect)
9982     return Val;
9983 
9984   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9985 }
9986 
9987 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9988                                    const CCValAssign &VA, const SDLoc &DL,
9989                                    const RISCVSubtarget &Subtarget) {
9990   EVT LocVT = VA.getLocVT();
9991 
9992   switch (VA.getLocInfo()) {
9993   default:
9994     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9995   case CCValAssign::Full:
9996     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9997       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9998     break;
9999   case CCValAssign::BCvt:
10000     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10001       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10002     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10003       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10004     else
10005       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10006     break;
10007   }
10008   return Val;
10009 }
10010 
10011 // The caller is responsible for loading the full value if the argument is
10012 // passed with CCValAssign::Indirect.
10013 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10014                                 const CCValAssign &VA, const SDLoc &DL) {
10015   MachineFunction &MF = DAG.getMachineFunction();
10016   MachineFrameInfo &MFI = MF.getFrameInfo();
10017   EVT LocVT = VA.getLocVT();
10018   EVT ValVT = VA.getValVT();
10019   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10020   if (ValVT.isScalableVector()) {
10021     // When the value is a scalable vector, we save the pointer which points to
10022     // the scalable vector value in the stack. The ValVT will be the pointer
10023     // type, instead of the scalable vector type.
10024     ValVT = LocVT;
10025   }
10026   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10027                                  /*IsImmutable=*/true);
10028   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10029   SDValue Val;
10030 
10031   ISD::LoadExtType ExtType;
10032   switch (VA.getLocInfo()) {
10033   default:
10034     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10035   case CCValAssign::Full:
10036   case CCValAssign::Indirect:
10037   case CCValAssign::BCvt:
10038     ExtType = ISD::NON_EXTLOAD;
10039     break;
10040   }
10041   Val = DAG.getExtLoad(
10042       ExtType, DL, LocVT, Chain, FIN,
10043       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10044   return Val;
10045 }
10046 
10047 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10048                                        const CCValAssign &VA, const SDLoc &DL) {
10049   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10050          "Unexpected VA");
10051   MachineFunction &MF = DAG.getMachineFunction();
10052   MachineFrameInfo &MFI = MF.getFrameInfo();
10053   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10054 
10055   if (VA.isMemLoc()) {
10056     // f64 is passed on the stack.
10057     int FI =
10058         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10059     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10060     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10061                        MachinePointerInfo::getFixedStack(MF, FI));
10062   }
10063 
10064   assert(VA.isRegLoc() && "Expected register VA assignment");
10065 
10066   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10067   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10068   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10069   SDValue Hi;
10070   if (VA.getLocReg() == RISCV::X17) {
10071     // Second half of f64 is passed on the stack.
10072     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10073     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10074     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10075                      MachinePointerInfo::getFixedStack(MF, FI));
10076   } else {
10077     // Second half of f64 is passed in another GPR.
10078     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10079     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10080     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10081   }
10082   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10083 }
10084 
10085 // FastCC has less than 1% performance improvement for some particular
10086 // benchmark. But theoretically, it may has benenfit for some cases.
10087 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10088                             unsigned ValNo, MVT ValVT, MVT LocVT,
10089                             CCValAssign::LocInfo LocInfo,
10090                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10091                             bool IsFixed, bool IsRet, Type *OrigTy,
10092                             const RISCVTargetLowering &TLI,
10093                             Optional<unsigned> FirstMaskArgument) {
10094 
10095   // X5 and X6 might be used for save-restore libcall.
10096   static const MCPhysReg GPRList[] = {
10097       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10098       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10099       RISCV::X29, RISCV::X30, RISCV::X31};
10100 
10101   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10102     if (unsigned Reg = State.AllocateReg(GPRList)) {
10103       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10104       return false;
10105     }
10106   }
10107 
10108   if (LocVT == MVT::f16) {
10109     static const MCPhysReg FPR16List[] = {
10110         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10111         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10112         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10113         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10114     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10115       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10116       return false;
10117     }
10118   }
10119 
10120   if (LocVT == MVT::f32) {
10121     static const MCPhysReg FPR32List[] = {
10122         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10123         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10124         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10125         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10126     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10127       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10128       return false;
10129     }
10130   }
10131 
10132   if (LocVT == MVT::f64) {
10133     static const MCPhysReg FPR64List[] = {
10134         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10135         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10136         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10137         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10138     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10139       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10140       return false;
10141     }
10142   }
10143 
10144   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10145     unsigned Offset4 = State.AllocateStack(4, Align(4));
10146     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10147     return false;
10148   }
10149 
10150   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10151     unsigned Offset5 = State.AllocateStack(8, Align(8));
10152     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10153     return false;
10154   }
10155 
10156   if (LocVT.isVector()) {
10157     if (unsigned Reg =
10158             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10159       // Fixed-length vectors are located in the corresponding scalable-vector
10160       // container types.
10161       if (ValVT.isFixedLengthVector())
10162         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10163       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10164     } else {
10165       // Try and pass the address via a "fast" GPR.
10166       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10167         LocInfo = CCValAssign::Indirect;
10168         LocVT = TLI.getSubtarget().getXLenVT();
10169         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10170       } else if (ValVT.isFixedLengthVector()) {
10171         auto StackAlign =
10172             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10173         unsigned StackOffset =
10174             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10175         State.addLoc(
10176             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10177       } else {
10178         // Can't pass scalable vectors on the stack.
10179         return true;
10180       }
10181     }
10182 
10183     return false;
10184   }
10185 
10186   return true; // CC didn't match.
10187 }
10188 
10189 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10190                          CCValAssign::LocInfo LocInfo,
10191                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10192 
10193   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10194     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10195     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10196     static const MCPhysReg GPRList[] = {
10197         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10198         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10199     if (unsigned Reg = State.AllocateReg(GPRList)) {
10200       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10201       return false;
10202     }
10203   }
10204 
10205   if (LocVT == MVT::f32) {
10206     // Pass in STG registers: F1, ..., F6
10207     //                        fs0 ... fs5
10208     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10209                                           RISCV::F18_F, RISCV::F19_F,
10210                                           RISCV::F20_F, RISCV::F21_F};
10211     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10212       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10213       return false;
10214     }
10215   }
10216 
10217   if (LocVT == MVT::f64) {
10218     // Pass in STG registers: D1, ..., D6
10219     //                        fs6 ... fs11
10220     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10221                                           RISCV::F24_D, RISCV::F25_D,
10222                                           RISCV::F26_D, RISCV::F27_D};
10223     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10224       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10225       return false;
10226     }
10227   }
10228 
10229   report_fatal_error("No registers left in GHC calling convention");
10230   return true;
10231 }
10232 
10233 // Transform physical registers into virtual registers.
10234 SDValue RISCVTargetLowering::LowerFormalArguments(
10235     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10236     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10237     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10238 
10239   MachineFunction &MF = DAG.getMachineFunction();
10240 
10241   switch (CallConv) {
10242   default:
10243     report_fatal_error("Unsupported calling convention");
10244   case CallingConv::C:
10245   case CallingConv::Fast:
10246     break;
10247   case CallingConv::GHC:
10248     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10249         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10250       report_fatal_error(
10251         "GHC calling convention requires the F and D instruction set extensions");
10252   }
10253 
10254   const Function &Func = MF.getFunction();
10255   if (Func.hasFnAttribute("interrupt")) {
10256     if (!Func.arg_empty())
10257       report_fatal_error(
10258         "Functions with the interrupt attribute cannot have arguments!");
10259 
10260     StringRef Kind =
10261       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10262 
10263     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10264       report_fatal_error(
10265         "Function interrupt attribute argument not supported!");
10266   }
10267 
10268   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10269   MVT XLenVT = Subtarget.getXLenVT();
10270   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10271   // Used with vargs to acumulate store chains.
10272   std::vector<SDValue> OutChains;
10273 
10274   // Assign locations to all of the incoming arguments.
10275   SmallVector<CCValAssign, 16> ArgLocs;
10276   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10277 
10278   if (CallConv == CallingConv::GHC)
10279     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10280   else
10281     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10282                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10283                                                    : CC_RISCV);
10284 
10285   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10286     CCValAssign &VA = ArgLocs[i];
10287     SDValue ArgValue;
10288     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10289     // case.
10290     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10291       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10292     else if (VA.isRegLoc())
10293       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10294     else
10295       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10296 
10297     if (VA.getLocInfo() == CCValAssign::Indirect) {
10298       // If the original argument was split and passed by reference (e.g. i128
10299       // on RV32), we need to load all parts of it here (using the same
10300       // address). Vectors may be partly split to registers and partly to the
10301       // stack, in which case the base address is partly offset and subsequent
10302       // stores are relative to that.
10303       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10304                                    MachinePointerInfo()));
10305       unsigned ArgIndex = Ins[i].OrigArgIndex;
10306       unsigned ArgPartOffset = Ins[i].PartOffset;
10307       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10308       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10309         CCValAssign &PartVA = ArgLocs[i + 1];
10310         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10311         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10312         if (PartVA.getValVT().isScalableVector())
10313           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10314         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10315         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10316                                      MachinePointerInfo()));
10317         ++i;
10318       }
10319       continue;
10320     }
10321     InVals.push_back(ArgValue);
10322   }
10323 
10324   if (IsVarArg) {
10325     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10326     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10327     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10328     MachineFrameInfo &MFI = MF.getFrameInfo();
10329     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10330     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10331 
10332     // Offset of the first variable argument from stack pointer, and size of
10333     // the vararg save area. For now, the varargs save area is either zero or
10334     // large enough to hold a0-a7.
10335     int VaArgOffset, VarArgsSaveSize;
10336 
10337     // If all registers are allocated, then all varargs must be passed on the
10338     // stack and we don't need to save any argregs.
10339     if (ArgRegs.size() == Idx) {
10340       VaArgOffset = CCInfo.getNextStackOffset();
10341       VarArgsSaveSize = 0;
10342     } else {
10343       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10344       VaArgOffset = -VarArgsSaveSize;
10345     }
10346 
10347     // Record the frame index of the first variable argument
10348     // which is a value necessary to VASTART.
10349     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10350     RVFI->setVarArgsFrameIndex(FI);
10351 
10352     // If saving an odd number of registers then create an extra stack slot to
10353     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10354     // offsets to even-numbered registered remain 2*XLEN-aligned.
10355     if (Idx % 2) {
10356       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10357       VarArgsSaveSize += XLenInBytes;
10358     }
10359 
10360     // Copy the integer registers that may have been used for passing varargs
10361     // to the vararg save area.
10362     for (unsigned I = Idx; I < ArgRegs.size();
10363          ++I, VaArgOffset += XLenInBytes) {
10364       const Register Reg = RegInfo.createVirtualRegister(RC);
10365       RegInfo.addLiveIn(ArgRegs[I], Reg);
10366       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10367       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10368       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10369       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10370                                    MachinePointerInfo::getFixedStack(MF, FI));
10371       cast<StoreSDNode>(Store.getNode())
10372           ->getMemOperand()
10373           ->setValue((Value *)nullptr);
10374       OutChains.push_back(Store);
10375     }
10376     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10377   }
10378 
10379   // All stores are grouped in one node to allow the matching between
10380   // the size of Ins and InVals. This only happens for vararg functions.
10381   if (!OutChains.empty()) {
10382     OutChains.push_back(Chain);
10383     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10384   }
10385 
10386   return Chain;
10387 }
10388 
10389 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10390 /// for tail call optimization.
10391 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10392 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10393     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10394     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10395 
10396   auto &Callee = CLI.Callee;
10397   auto CalleeCC = CLI.CallConv;
10398   auto &Outs = CLI.Outs;
10399   auto &Caller = MF.getFunction();
10400   auto CallerCC = Caller.getCallingConv();
10401 
10402   // Exception-handling functions need a special set of instructions to
10403   // indicate a return to the hardware. Tail-calling another function would
10404   // probably break this.
10405   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10406   // should be expanded as new function attributes are introduced.
10407   if (Caller.hasFnAttribute("interrupt"))
10408     return false;
10409 
10410   // Do not tail call opt if the stack is used to pass parameters.
10411   if (CCInfo.getNextStackOffset() != 0)
10412     return false;
10413 
10414   // Do not tail call opt if any parameters need to be passed indirectly.
10415   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10416   // passed indirectly. So the address of the value will be passed in a
10417   // register, or if not available, then the address is put on the stack. In
10418   // order to pass indirectly, space on the stack often needs to be allocated
10419   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10420   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10421   // are passed CCValAssign::Indirect.
10422   for (auto &VA : ArgLocs)
10423     if (VA.getLocInfo() == CCValAssign::Indirect)
10424       return false;
10425 
10426   // Do not tail call opt if either caller or callee uses struct return
10427   // semantics.
10428   auto IsCallerStructRet = Caller.hasStructRetAttr();
10429   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10430   if (IsCallerStructRet || IsCalleeStructRet)
10431     return false;
10432 
10433   // Externally-defined functions with weak linkage should not be
10434   // tail-called. The behaviour of branch instructions in this situation (as
10435   // used for tail calls) is implementation-defined, so we cannot rely on the
10436   // linker replacing the tail call with a return.
10437   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10438     const GlobalValue *GV = G->getGlobal();
10439     if (GV->hasExternalWeakLinkage())
10440       return false;
10441   }
10442 
10443   // The callee has to preserve all registers the caller needs to preserve.
10444   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10445   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10446   if (CalleeCC != CallerCC) {
10447     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10448     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10449       return false;
10450   }
10451 
10452   // Byval parameters hand the function a pointer directly into the stack area
10453   // we want to reuse during a tail call. Working around this *is* possible
10454   // but less efficient and uglier in LowerCall.
10455   for (auto &Arg : Outs)
10456     if (Arg.Flags.isByVal())
10457       return false;
10458 
10459   return true;
10460 }
10461 
10462 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10463   return DAG.getDataLayout().getPrefTypeAlign(
10464       VT.getTypeForEVT(*DAG.getContext()));
10465 }
10466 
10467 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10468 // and output parameter nodes.
10469 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10470                                        SmallVectorImpl<SDValue> &InVals) const {
10471   SelectionDAG &DAG = CLI.DAG;
10472   SDLoc &DL = CLI.DL;
10473   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10474   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10475   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10476   SDValue Chain = CLI.Chain;
10477   SDValue Callee = CLI.Callee;
10478   bool &IsTailCall = CLI.IsTailCall;
10479   CallingConv::ID CallConv = CLI.CallConv;
10480   bool IsVarArg = CLI.IsVarArg;
10481   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10482   MVT XLenVT = Subtarget.getXLenVT();
10483 
10484   MachineFunction &MF = DAG.getMachineFunction();
10485 
10486   // Analyze the operands of the call, assigning locations to each operand.
10487   SmallVector<CCValAssign, 16> ArgLocs;
10488   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10489 
10490   if (CallConv == CallingConv::GHC)
10491     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10492   else
10493     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10494                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10495                                                     : CC_RISCV);
10496 
10497   // Check if it's really possible to do a tail call.
10498   if (IsTailCall)
10499     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10500 
10501   if (IsTailCall)
10502     ++NumTailCalls;
10503   else if (CLI.CB && CLI.CB->isMustTailCall())
10504     report_fatal_error("failed to perform tail call elimination on a call "
10505                        "site marked musttail");
10506 
10507   // Get a count of how many bytes are to be pushed on the stack.
10508   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10509 
10510   // Create local copies for byval args
10511   SmallVector<SDValue, 8> ByValArgs;
10512   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10513     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10514     if (!Flags.isByVal())
10515       continue;
10516 
10517     SDValue Arg = OutVals[i];
10518     unsigned Size = Flags.getByValSize();
10519     Align Alignment = Flags.getNonZeroByValAlign();
10520 
10521     int FI =
10522         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10523     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10524     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10525 
10526     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10527                           /*IsVolatile=*/false,
10528                           /*AlwaysInline=*/false, IsTailCall,
10529                           MachinePointerInfo(), MachinePointerInfo());
10530     ByValArgs.push_back(FIPtr);
10531   }
10532 
10533   if (!IsTailCall)
10534     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10535 
10536   // Copy argument values to their designated locations.
10537   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10538   SmallVector<SDValue, 8> MemOpChains;
10539   SDValue StackPtr;
10540   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10541     CCValAssign &VA = ArgLocs[i];
10542     SDValue ArgValue = OutVals[i];
10543     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10544 
10545     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10546     bool IsF64OnRV32DSoftABI =
10547         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10548     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10549       SDValue SplitF64 = DAG.getNode(
10550           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10551       SDValue Lo = SplitF64.getValue(0);
10552       SDValue Hi = SplitF64.getValue(1);
10553 
10554       Register RegLo = VA.getLocReg();
10555       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10556 
10557       if (RegLo == RISCV::X17) {
10558         // Second half of f64 is passed on the stack.
10559         // Work out the address of the stack slot.
10560         if (!StackPtr.getNode())
10561           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10562         // Emit the store.
10563         MemOpChains.push_back(
10564             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10565       } else {
10566         // Second half of f64 is passed in another GPR.
10567         assert(RegLo < RISCV::X31 && "Invalid register pair");
10568         Register RegHigh = RegLo + 1;
10569         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10570       }
10571       continue;
10572     }
10573 
10574     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10575     // as any other MemLoc.
10576 
10577     // Promote the value if needed.
10578     // For now, only handle fully promoted and indirect arguments.
10579     if (VA.getLocInfo() == CCValAssign::Indirect) {
10580       // Store the argument in a stack slot and pass its address.
10581       Align StackAlign =
10582           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10583                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10584       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10585       // If the original argument was split (e.g. i128), we need
10586       // to store the required parts of it here (and pass just one address).
10587       // Vectors may be partly split to registers and partly to the stack, in
10588       // which case the base address is partly offset and subsequent stores are
10589       // relative to that.
10590       unsigned ArgIndex = Outs[i].OrigArgIndex;
10591       unsigned ArgPartOffset = Outs[i].PartOffset;
10592       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10593       // Calculate the total size to store. We don't have access to what we're
10594       // actually storing other than performing the loop and collecting the
10595       // info.
10596       SmallVector<std::pair<SDValue, SDValue>> Parts;
10597       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10598         SDValue PartValue = OutVals[i + 1];
10599         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10600         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10601         EVT PartVT = PartValue.getValueType();
10602         if (PartVT.isScalableVector())
10603           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10604         StoredSize += PartVT.getStoreSize();
10605         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10606         Parts.push_back(std::make_pair(PartValue, Offset));
10607         ++i;
10608       }
10609       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10610       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10611       MemOpChains.push_back(
10612           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10613                        MachinePointerInfo::getFixedStack(MF, FI)));
10614       for (const auto &Part : Parts) {
10615         SDValue PartValue = Part.first;
10616         SDValue PartOffset = Part.second;
10617         SDValue Address =
10618             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10619         MemOpChains.push_back(
10620             DAG.getStore(Chain, DL, PartValue, Address,
10621                          MachinePointerInfo::getFixedStack(MF, FI)));
10622       }
10623       ArgValue = SpillSlot;
10624     } else {
10625       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10626     }
10627 
10628     // Use local copy if it is a byval arg.
10629     if (Flags.isByVal())
10630       ArgValue = ByValArgs[j++];
10631 
10632     if (VA.isRegLoc()) {
10633       // Queue up the argument copies and emit them at the end.
10634       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10635     } else {
10636       assert(VA.isMemLoc() && "Argument not register or memory");
10637       assert(!IsTailCall && "Tail call not allowed if stack is used "
10638                             "for passing parameters");
10639 
10640       // Work out the address of the stack slot.
10641       if (!StackPtr.getNode())
10642         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10643       SDValue Address =
10644           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10645                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10646 
10647       // Emit the store.
10648       MemOpChains.push_back(
10649           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10650     }
10651   }
10652 
10653   // Join the stores, which are independent of one another.
10654   if (!MemOpChains.empty())
10655     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10656 
10657   SDValue Glue;
10658 
10659   // Build a sequence of copy-to-reg nodes, chained and glued together.
10660   for (auto &Reg : RegsToPass) {
10661     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10662     Glue = Chain.getValue(1);
10663   }
10664 
10665   // Validate that none of the argument registers have been marked as
10666   // reserved, if so report an error. Do the same for the return address if this
10667   // is not a tailcall.
10668   validateCCReservedRegs(RegsToPass, MF);
10669   if (!IsTailCall &&
10670       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10671     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10672         MF.getFunction(),
10673         "Return address register required, but has been reserved."});
10674 
10675   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10676   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10677   // split it and then direct call can be matched by PseudoCALL.
10678   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10679     const GlobalValue *GV = S->getGlobal();
10680 
10681     unsigned OpFlags = RISCVII::MO_CALL;
10682     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10683       OpFlags = RISCVII::MO_PLT;
10684 
10685     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10686   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10687     unsigned OpFlags = RISCVII::MO_CALL;
10688 
10689     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10690                                                  nullptr))
10691       OpFlags = RISCVII::MO_PLT;
10692 
10693     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10694   }
10695 
10696   // The first call operand is the chain and the second is the target address.
10697   SmallVector<SDValue, 8> Ops;
10698   Ops.push_back(Chain);
10699   Ops.push_back(Callee);
10700 
10701   // Add argument registers to the end of the list so that they are
10702   // known live into the call.
10703   for (auto &Reg : RegsToPass)
10704     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10705 
10706   if (!IsTailCall) {
10707     // Add a register mask operand representing the call-preserved registers.
10708     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10709     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10710     assert(Mask && "Missing call preserved mask for calling convention");
10711     Ops.push_back(DAG.getRegisterMask(Mask));
10712   }
10713 
10714   // Glue the call to the argument copies, if any.
10715   if (Glue.getNode())
10716     Ops.push_back(Glue);
10717 
10718   // Emit the call.
10719   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10720 
10721   if (IsTailCall) {
10722     MF.getFrameInfo().setHasTailCall();
10723     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10724   }
10725 
10726   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10727   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10728   Glue = Chain.getValue(1);
10729 
10730   // Mark the end of the call, which is glued to the call itself.
10731   Chain = DAG.getCALLSEQ_END(Chain,
10732                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10733                              DAG.getConstant(0, DL, PtrVT, true),
10734                              Glue, DL);
10735   Glue = Chain.getValue(1);
10736 
10737   // Assign locations to each value returned by this call.
10738   SmallVector<CCValAssign, 16> RVLocs;
10739   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10740   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10741 
10742   // Copy all of the result registers out of their specified physreg.
10743   for (auto &VA : RVLocs) {
10744     // Copy the value out
10745     SDValue RetValue =
10746         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10747     // Glue the RetValue to the end of the call sequence
10748     Chain = RetValue.getValue(1);
10749     Glue = RetValue.getValue(2);
10750 
10751     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10752       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10753       SDValue RetValue2 =
10754           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10755       Chain = RetValue2.getValue(1);
10756       Glue = RetValue2.getValue(2);
10757       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10758                              RetValue2);
10759     }
10760 
10761     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10762 
10763     InVals.push_back(RetValue);
10764   }
10765 
10766   return Chain;
10767 }
10768 
10769 bool RISCVTargetLowering::CanLowerReturn(
10770     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10771     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10772   SmallVector<CCValAssign, 16> RVLocs;
10773   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10774 
10775   Optional<unsigned> FirstMaskArgument;
10776   if (Subtarget.hasVInstructions())
10777     FirstMaskArgument = preAssignMask(Outs);
10778 
10779   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10780     MVT VT = Outs[i].VT;
10781     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10782     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10783     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10784                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10785                  *this, FirstMaskArgument))
10786       return false;
10787   }
10788   return true;
10789 }
10790 
10791 SDValue
10792 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10793                                  bool IsVarArg,
10794                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10795                                  const SmallVectorImpl<SDValue> &OutVals,
10796                                  const SDLoc &DL, SelectionDAG &DAG) const {
10797   const MachineFunction &MF = DAG.getMachineFunction();
10798   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10799 
10800   // Stores the assignment of the return value to a location.
10801   SmallVector<CCValAssign, 16> RVLocs;
10802 
10803   // Info about the registers and stack slot.
10804   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10805                  *DAG.getContext());
10806 
10807   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10808                     nullptr, CC_RISCV);
10809 
10810   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10811     report_fatal_error("GHC functions return void only");
10812 
10813   SDValue Glue;
10814   SmallVector<SDValue, 4> RetOps(1, Chain);
10815 
10816   // Copy the result values into the output registers.
10817   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10818     SDValue Val = OutVals[i];
10819     CCValAssign &VA = RVLocs[i];
10820     assert(VA.isRegLoc() && "Can only return in registers!");
10821 
10822     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10823       // Handle returning f64 on RV32D with a soft float ABI.
10824       assert(VA.isRegLoc() && "Expected return via registers");
10825       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10826                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10827       SDValue Lo = SplitF64.getValue(0);
10828       SDValue Hi = SplitF64.getValue(1);
10829       Register RegLo = VA.getLocReg();
10830       assert(RegLo < RISCV::X31 && "Invalid register pair");
10831       Register RegHi = RegLo + 1;
10832 
10833       if (STI.isRegisterReservedByUser(RegLo) ||
10834           STI.isRegisterReservedByUser(RegHi))
10835         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10836             MF.getFunction(),
10837             "Return value register required, but has been reserved."});
10838 
10839       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10840       Glue = Chain.getValue(1);
10841       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10842       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10843       Glue = Chain.getValue(1);
10844       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10845     } else {
10846       // Handle a 'normal' return.
10847       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10848       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10849 
10850       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10851         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10852             MF.getFunction(),
10853             "Return value register required, but has been reserved."});
10854 
10855       // Guarantee that all emitted copies are stuck together.
10856       Glue = Chain.getValue(1);
10857       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10858     }
10859   }
10860 
10861   RetOps[0] = Chain; // Update chain.
10862 
10863   // Add the glue node if we have it.
10864   if (Glue.getNode()) {
10865     RetOps.push_back(Glue);
10866   }
10867 
10868   unsigned RetOpc = RISCVISD::RET_FLAG;
10869   // Interrupt service routines use different return instructions.
10870   const Function &Func = DAG.getMachineFunction().getFunction();
10871   if (Func.hasFnAttribute("interrupt")) {
10872     if (!Func.getReturnType()->isVoidTy())
10873       report_fatal_error(
10874           "Functions with the interrupt attribute must have void return type!");
10875 
10876     MachineFunction &MF = DAG.getMachineFunction();
10877     StringRef Kind =
10878       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10879 
10880     if (Kind == "user")
10881       RetOpc = RISCVISD::URET_FLAG;
10882     else if (Kind == "supervisor")
10883       RetOpc = RISCVISD::SRET_FLAG;
10884     else
10885       RetOpc = RISCVISD::MRET_FLAG;
10886   }
10887 
10888   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10889 }
10890 
10891 void RISCVTargetLowering::validateCCReservedRegs(
10892     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10893     MachineFunction &MF) const {
10894   const Function &F = MF.getFunction();
10895   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10896 
10897   if (llvm::any_of(Regs, [&STI](auto Reg) {
10898         return STI.isRegisterReservedByUser(Reg.first);
10899       }))
10900     F.getContext().diagnose(DiagnosticInfoUnsupported{
10901         F, "Argument register required, but has been reserved."});
10902 }
10903 
10904 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10905   return CI->isTailCall();
10906 }
10907 
10908 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10909 #define NODE_NAME_CASE(NODE)                                                   \
10910   case RISCVISD::NODE:                                                         \
10911     return "RISCVISD::" #NODE;
10912   // clang-format off
10913   switch ((RISCVISD::NodeType)Opcode) {
10914   case RISCVISD::FIRST_NUMBER:
10915     break;
10916   NODE_NAME_CASE(RET_FLAG)
10917   NODE_NAME_CASE(URET_FLAG)
10918   NODE_NAME_CASE(SRET_FLAG)
10919   NODE_NAME_CASE(MRET_FLAG)
10920   NODE_NAME_CASE(CALL)
10921   NODE_NAME_CASE(SELECT_CC)
10922   NODE_NAME_CASE(BR_CC)
10923   NODE_NAME_CASE(BuildPairF64)
10924   NODE_NAME_CASE(SplitF64)
10925   NODE_NAME_CASE(TAIL)
10926   NODE_NAME_CASE(MULHSU)
10927   NODE_NAME_CASE(SLLW)
10928   NODE_NAME_CASE(SRAW)
10929   NODE_NAME_CASE(SRLW)
10930   NODE_NAME_CASE(DIVW)
10931   NODE_NAME_CASE(DIVUW)
10932   NODE_NAME_CASE(REMUW)
10933   NODE_NAME_CASE(ROLW)
10934   NODE_NAME_CASE(RORW)
10935   NODE_NAME_CASE(CLZW)
10936   NODE_NAME_CASE(CTZW)
10937   NODE_NAME_CASE(FSLW)
10938   NODE_NAME_CASE(FSRW)
10939   NODE_NAME_CASE(FSL)
10940   NODE_NAME_CASE(FSR)
10941   NODE_NAME_CASE(FMV_H_X)
10942   NODE_NAME_CASE(FMV_X_ANYEXTH)
10943   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10944   NODE_NAME_CASE(FMV_W_X_RV64)
10945   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10946   NODE_NAME_CASE(FCVT_X)
10947   NODE_NAME_CASE(FCVT_XU)
10948   NODE_NAME_CASE(FCVT_W_RV64)
10949   NODE_NAME_CASE(FCVT_WU_RV64)
10950   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10951   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10952   NODE_NAME_CASE(READ_CYCLE_WIDE)
10953   NODE_NAME_CASE(GREV)
10954   NODE_NAME_CASE(GREVW)
10955   NODE_NAME_CASE(GORC)
10956   NODE_NAME_CASE(GORCW)
10957   NODE_NAME_CASE(SHFL)
10958   NODE_NAME_CASE(SHFLW)
10959   NODE_NAME_CASE(UNSHFL)
10960   NODE_NAME_CASE(UNSHFLW)
10961   NODE_NAME_CASE(BFP)
10962   NODE_NAME_CASE(BFPW)
10963   NODE_NAME_CASE(BCOMPRESS)
10964   NODE_NAME_CASE(BCOMPRESSW)
10965   NODE_NAME_CASE(BDECOMPRESS)
10966   NODE_NAME_CASE(BDECOMPRESSW)
10967   NODE_NAME_CASE(VMV_V_X_VL)
10968   NODE_NAME_CASE(VFMV_V_F_VL)
10969   NODE_NAME_CASE(VMV_X_S)
10970   NODE_NAME_CASE(VMV_S_X_VL)
10971   NODE_NAME_CASE(VFMV_S_F_VL)
10972   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10973   NODE_NAME_CASE(READ_VLENB)
10974   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10975   NODE_NAME_CASE(VSLIDEUP_VL)
10976   NODE_NAME_CASE(VSLIDE1UP_VL)
10977   NODE_NAME_CASE(VSLIDEDOWN_VL)
10978   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10979   NODE_NAME_CASE(VID_VL)
10980   NODE_NAME_CASE(VFNCVT_ROD_VL)
10981   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10982   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10983   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10984   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10985   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10986   NODE_NAME_CASE(VECREDUCE_AND_VL)
10987   NODE_NAME_CASE(VECREDUCE_OR_VL)
10988   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10989   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10990   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10991   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10992   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10993   NODE_NAME_CASE(ADD_VL)
10994   NODE_NAME_CASE(AND_VL)
10995   NODE_NAME_CASE(MUL_VL)
10996   NODE_NAME_CASE(OR_VL)
10997   NODE_NAME_CASE(SDIV_VL)
10998   NODE_NAME_CASE(SHL_VL)
10999   NODE_NAME_CASE(SREM_VL)
11000   NODE_NAME_CASE(SRA_VL)
11001   NODE_NAME_CASE(SRL_VL)
11002   NODE_NAME_CASE(SUB_VL)
11003   NODE_NAME_CASE(UDIV_VL)
11004   NODE_NAME_CASE(UREM_VL)
11005   NODE_NAME_CASE(XOR_VL)
11006   NODE_NAME_CASE(SADDSAT_VL)
11007   NODE_NAME_CASE(UADDSAT_VL)
11008   NODE_NAME_CASE(SSUBSAT_VL)
11009   NODE_NAME_CASE(USUBSAT_VL)
11010   NODE_NAME_CASE(FADD_VL)
11011   NODE_NAME_CASE(FSUB_VL)
11012   NODE_NAME_CASE(FMUL_VL)
11013   NODE_NAME_CASE(FDIV_VL)
11014   NODE_NAME_CASE(FNEG_VL)
11015   NODE_NAME_CASE(FABS_VL)
11016   NODE_NAME_CASE(FSQRT_VL)
11017   NODE_NAME_CASE(FMA_VL)
11018   NODE_NAME_CASE(FCOPYSIGN_VL)
11019   NODE_NAME_CASE(SMIN_VL)
11020   NODE_NAME_CASE(SMAX_VL)
11021   NODE_NAME_CASE(UMIN_VL)
11022   NODE_NAME_CASE(UMAX_VL)
11023   NODE_NAME_CASE(FMINNUM_VL)
11024   NODE_NAME_CASE(FMAXNUM_VL)
11025   NODE_NAME_CASE(MULHS_VL)
11026   NODE_NAME_CASE(MULHU_VL)
11027   NODE_NAME_CASE(FP_TO_SINT_VL)
11028   NODE_NAME_CASE(FP_TO_UINT_VL)
11029   NODE_NAME_CASE(SINT_TO_FP_VL)
11030   NODE_NAME_CASE(UINT_TO_FP_VL)
11031   NODE_NAME_CASE(FP_EXTEND_VL)
11032   NODE_NAME_CASE(FP_ROUND_VL)
11033   NODE_NAME_CASE(VWMUL_VL)
11034   NODE_NAME_CASE(VWMULU_VL)
11035   NODE_NAME_CASE(VWMULSU_VL)
11036   NODE_NAME_CASE(VWADD_VL)
11037   NODE_NAME_CASE(VWADDU_VL)
11038   NODE_NAME_CASE(VWSUB_VL)
11039   NODE_NAME_CASE(VWSUBU_VL)
11040   NODE_NAME_CASE(VWADD_W_VL)
11041   NODE_NAME_CASE(VWADDU_W_VL)
11042   NODE_NAME_CASE(VWSUB_W_VL)
11043   NODE_NAME_CASE(VWSUBU_W_VL)
11044   NODE_NAME_CASE(SETCC_VL)
11045   NODE_NAME_CASE(VSELECT_VL)
11046   NODE_NAME_CASE(VP_MERGE_VL)
11047   NODE_NAME_CASE(VMAND_VL)
11048   NODE_NAME_CASE(VMOR_VL)
11049   NODE_NAME_CASE(VMXOR_VL)
11050   NODE_NAME_CASE(VMCLR_VL)
11051   NODE_NAME_CASE(VMSET_VL)
11052   NODE_NAME_CASE(VRGATHER_VX_VL)
11053   NODE_NAME_CASE(VRGATHER_VV_VL)
11054   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11055   NODE_NAME_CASE(VSEXT_VL)
11056   NODE_NAME_CASE(VZEXT_VL)
11057   NODE_NAME_CASE(VCPOP_VL)
11058   NODE_NAME_CASE(READ_CSR)
11059   NODE_NAME_CASE(WRITE_CSR)
11060   NODE_NAME_CASE(SWAP_CSR)
11061   }
11062   // clang-format on
11063   return nullptr;
11064 #undef NODE_NAME_CASE
11065 }
11066 
11067 /// getConstraintType - Given a constraint letter, return the type of
11068 /// constraint it is for this target.
11069 RISCVTargetLowering::ConstraintType
11070 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11071   if (Constraint.size() == 1) {
11072     switch (Constraint[0]) {
11073     default:
11074       break;
11075     case 'f':
11076       return C_RegisterClass;
11077     case 'I':
11078     case 'J':
11079     case 'K':
11080       return C_Immediate;
11081     case 'A':
11082       return C_Memory;
11083     case 'S': // A symbolic address
11084       return C_Other;
11085     }
11086   } else {
11087     if (Constraint == "vr" || Constraint == "vm")
11088       return C_RegisterClass;
11089   }
11090   return TargetLowering::getConstraintType(Constraint);
11091 }
11092 
11093 std::pair<unsigned, const TargetRegisterClass *>
11094 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11095                                                   StringRef Constraint,
11096                                                   MVT VT) const {
11097   // First, see if this is a constraint that directly corresponds to a
11098   // RISCV register class.
11099   if (Constraint.size() == 1) {
11100     switch (Constraint[0]) {
11101     case 'r':
11102       // TODO: Support fixed vectors up to XLen for P extension?
11103       if (VT.isVector())
11104         break;
11105       return std::make_pair(0U, &RISCV::GPRRegClass);
11106     case 'f':
11107       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11108         return std::make_pair(0U, &RISCV::FPR16RegClass);
11109       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11110         return std::make_pair(0U, &RISCV::FPR32RegClass);
11111       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11112         return std::make_pair(0U, &RISCV::FPR64RegClass);
11113       break;
11114     default:
11115       break;
11116     }
11117   } else if (Constraint == "vr") {
11118     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11119                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11120       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11121         return std::make_pair(0U, RC);
11122     }
11123   } else if (Constraint == "vm") {
11124     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11125       return std::make_pair(0U, &RISCV::VMV0RegClass);
11126   }
11127 
11128   // Clang will correctly decode the usage of register name aliases into their
11129   // official names. However, other frontends like `rustc` do not. This allows
11130   // users of these frontends to use the ABI names for registers in LLVM-style
11131   // register constraints.
11132   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11133                                .Case("{zero}", RISCV::X0)
11134                                .Case("{ra}", RISCV::X1)
11135                                .Case("{sp}", RISCV::X2)
11136                                .Case("{gp}", RISCV::X3)
11137                                .Case("{tp}", RISCV::X4)
11138                                .Case("{t0}", RISCV::X5)
11139                                .Case("{t1}", RISCV::X6)
11140                                .Case("{t2}", RISCV::X7)
11141                                .Cases("{s0}", "{fp}", RISCV::X8)
11142                                .Case("{s1}", RISCV::X9)
11143                                .Case("{a0}", RISCV::X10)
11144                                .Case("{a1}", RISCV::X11)
11145                                .Case("{a2}", RISCV::X12)
11146                                .Case("{a3}", RISCV::X13)
11147                                .Case("{a4}", RISCV::X14)
11148                                .Case("{a5}", RISCV::X15)
11149                                .Case("{a6}", RISCV::X16)
11150                                .Case("{a7}", RISCV::X17)
11151                                .Case("{s2}", RISCV::X18)
11152                                .Case("{s3}", RISCV::X19)
11153                                .Case("{s4}", RISCV::X20)
11154                                .Case("{s5}", RISCV::X21)
11155                                .Case("{s6}", RISCV::X22)
11156                                .Case("{s7}", RISCV::X23)
11157                                .Case("{s8}", RISCV::X24)
11158                                .Case("{s9}", RISCV::X25)
11159                                .Case("{s10}", RISCV::X26)
11160                                .Case("{s11}", RISCV::X27)
11161                                .Case("{t3}", RISCV::X28)
11162                                .Case("{t4}", RISCV::X29)
11163                                .Case("{t5}", RISCV::X30)
11164                                .Case("{t6}", RISCV::X31)
11165                                .Default(RISCV::NoRegister);
11166   if (XRegFromAlias != RISCV::NoRegister)
11167     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11168 
11169   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11170   // TableGen record rather than the AsmName to choose registers for InlineAsm
11171   // constraints, plus we want to match those names to the widest floating point
11172   // register type available, manually select floating point registers here.
11173   //
11174   // The second case is the ABI name of the register, so that frontends can also
11175   // use the ABI names in register constraint lists.
11176   if (Subtarget.hasStdExtF()) {
11177     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11178                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11179                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11180                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11181                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11182                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11183                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11184                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11185                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11186                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11187                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11188                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11189                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11190                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11191                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11192                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11193                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11194                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11195                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11196                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11197                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11198                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11199                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11200                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11201                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11202                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11203                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11204                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11205                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11206                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11207                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11208                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11209                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11210                         .Default(RISCV::NoRegister);
11211     if (FReg != RISCV::NoRegister) {
11212       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11213       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11214         unsigned RegNo = FReg - RISCV::F0_F;
11215         unsigned DReg = RISCV::F0_D + RegNo;
11216         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11217       }
11218       if (VT == MVT::f32 || VT == MVT::Other)
11219         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11220       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11221         unsigned RegNo = FReg - RISCV::F0_F;
11222         unsigned HReg = RISCV::F0_H + RegNo;
11223         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11224       }
11225     }
11226   }
11227 
11228   if (Subtarget.hasVInstructions()) {
11229     Register VReg = StringSwitch<Register>(Constraint.lower())
11230                         .Case("{v0}", RISCV::V0)
11231                         .Case("{v1}", RISCV::V1)
11232                         .Case("{v2}", RISCV::V2)
11233                         .Case("{v3}", RISCV::V3)
11234                         .Case("{v4}", RISCV::V4)
11235                         .Case("{v5}", RISCV::V5)
11236                         .Case("{v6}", RISCV::V6)
11237                         .Case("{v7}", RISCV::V7)
11238                         .Case("{v8}", RISCV::V8)
11239                         .Case("{v9}", RISCV::V9)
11240                         .Case("{v10}", RISCV::V10)
11241                         .Case("{v11}", RISCV::V11)
11242                         .Case("{v12}", RISCV::V12)
11243                         .Case("{v13}", RISCV::V13)
11244                         .Case("{v14}", RISCV::V14)
11245                         .Case("{v15}", RISCV::V15)
11246                         .Case("{v16}", RISCV::V16)
11247                         .Case("{v17}", RISCV::V17)
11248                         .Case("{v18}", RISCV::V18)
11249                         .Case("{v19}", RISCV::V19)
11250                         .Case("{v20}", RISCV::V20)
11251                         .Case("{v21}", RISCV::V21)
11252                         .Case("{v22}", RISCV::V22)
11253                         .Case("{v23}", RISCV::V23)
11254                         .Case("{v24}", RISCV::V24)
11255                         .Case("{v25}", RISCV::V25)
11256                         .Case("{v26}", RISCV::V26)
11257                         .Case("{v27}", RISCV::V27)
11258                         .Case("{v28}", RISCV::V28)
11259                         .Case("{v29}", RISCV::V29)
11260                         .Case("{v30}", RISCV::V30)
11261                         .Case("{v31}", RISCV::V31)
11262                         .Default(RISCV::NoRegister);
11263     if (VReg != RISCV::NoRegister) {
11264       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11265         return std::make_pair(VReg, &RISCV::VMRegClass);
11266       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11267         return std::make_pair(VReg, &RISCV::VRRegClass);
11268       for (const auto *RC :
11269            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11270         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11271           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11272           return std::make_pair(VReg, RC);
11273         }
11274       }
11275     }
11276   }
11277 
11278   std::pair<Register, const TargetRegisterClass *> Res =
11279       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11280 
11281   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11282   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11283   // Subtarget into account.
11284   if (Res.second == &RISCV::GPRF16RegClass ||
11285       Res.second == &RISCV::GPRF32RegClass ||
11286       Res.second == &RISCV::GPRF64RegClass)
11287     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11288 
11289   return Res;
11290 }
11291 
11292 unsigned
11293 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11294   // Currently only support length 1 constraints.
11295   if (ConstraintCode.size() == 1) {
11296     switch (ConstraintCode[0]) {
11297     case 'A':
11298       return InlineAsm::Constraint_A;
11299     default:
11300       break;
11301     }
11302   }
11303 
11304   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11305 }
11306 
11307 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11308     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11309     SelectionDAG &DAG) const {
11310   // Currently only support length 1 constraints.
11311   if (Constraint.length() == 1) {
11312     switch (Constraint[0]) {
11313     case 'I':
11314       // Validate & create a 12-bit signed immediate operand.
11315       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11316         uint64_t CVal = C->getSExtValue();
11317         if (isInt<12>(CVal))
11318           Ops.push_back(
11319               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11320       }
11321       return;
11322     case 'J':
11323       // Validate & create an integer zero operand.
11324       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11325         if (C->getZExtValue() == 0)
11326           Ops.push_back(
11327               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11328       return;
11329     case 'K':
11330       // Validate & create a 5-bit unsigned immediate operand.
11331       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11332         uint64_t CVal = C->getZExtValue();
11333         if (isUInt<5>(CVal))
11334           Ops.push_back(
11335               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11336       }
11337       return;
11338     case 'S':
11339       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11340         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11341                                                  GA->getValueType(0)));
11342       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11343         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11344                                                 BA->getValueType(0)));
11345       }
11346       return;
11347     default:
11348       break;
11349     }
11350   }
11351   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11352 }
11353 
11354 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11355                                                    Instruction *Inst,
11356                                                    AtomicOrdering Ord) const {
11357   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11358     return Builder.CreateFence(Ord);
11359   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11360     return Builder.CreateFence(AtomicOrdering::Release);
11361   return nullptr;
11362 }
11363 
11364 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11365                                                     Instruction *Inst,
11366                                                     AtomicOrdering Ord) const {
11367   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11368     return Builder.CreateFence(AtomicOrdering::Acquire);
11369   return nullptr;
11370 }
11371 
11372 TargetLowering::AtomicExpansionKind
11373 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11374   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11375   // point operations can't be used in an lr/sc sequence without breaking the
11376   // forward-progress guarantee.
11377   if (AI->isFloatingPointOperation())
11378     return AtomicExpansionKind::CmpXChg;
11379 
11380   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11381   if (Size == 8 || Size == 16)
11382     return AtomicExpansionKind::MaskedIntrinsic;
11383   return AtomicExpansionKind::None;
11384 }
11385 
11386 static Intrinsic::ID
11387 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11388   if (XLen == 32) {
11389     switch (BinOp) {
11390     default:
11391       llvm_unreachable("Unexpected AtomicRMW BinOp");
11392     case AtomicRMWInst::Xchg:
11393       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11394     case AtomicRMWInst::Add:
11395       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11396     case AtomicRMWInst::Sub:
11397       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11398     case AtomicRMWInst::Nand:
11399       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11400     case AtomicRMWInst::Max:
11401       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11402     case AtomicRMWInst::Min:
11403       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11404     case AtomicRMWInst::UMax:
11405       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11406     case AtomicRMWInst::UMin:
11407       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11408     }
11409   }
11410 
11411   if (XLen == 64) {
11412     switch (BinOp) {
11413     default:
11414       llvm_unreachable("Unexpected AtomicRMW BinOp");
11415     case AtomicRMWInst::Xchg:
11416       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11417     case AtomicRMWInst::Add:
11418       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11419     case AtomicRMWInst::Sub:
11420       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11421     case AtomicRMWInst::Nand:
11422       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11423     case AtomicRMWInst::Max:
11424       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11425     case AtomicRMWInst::Min:
11426       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11427     case AtomicRMWInst::UMax:
11428       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11429     case AtomicRMWInst::UMin:
11430       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11431     }
11432   }
11433 
11434   llvm_unreachable("Unexpected XLen\n");
11435 }
11436 
11437 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11438     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11439     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11440   unsigned XLen = Subtarget.getXLen();
11441   Value *Ordering =
11442       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11443   Type *Tys[] = {AlignedAddr->getType()};
11444   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11445       AI->getModule(),
11446       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11447 
11448   if (XLen == 64) {
11449     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11450     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11451     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11452   }
11453 
11454   Value *Result;
11455 
11456   // Must pass the shift amount needed to sign extend the loaded value prior
11457   // to performing a signed comparison for min/max. ShiftAmt is the number of
11458   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11459   // is the number of bits to left+right shift the value in order to
11460   // sign-extend.
11461   if (AI->getOperation() == AtomicRMWInst::Min ||
11462       AI->getOperation() == AtomicRMWInst::Max) {
11463     const DataLayout &DL = AI->getModule()->getDataLayout();
11464     unsigned ValWidth =
11465         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11466     Value *SextShamt =
11467         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11468     Result = Builder.CreateCall(LrwOpScwLoop,
11469                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11470   } else {
11471     Result =
11472         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11473   }
11474 
11475   if (XLen == 64)
11476     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11477   return Result;
11478 }
11479 
11480 TargetLowering::AtomicExpansionKind
11481 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11482     AtomicCmpXchgInst *CI) const {
11483   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11484   if (Size == 8 || Size == 16)
11485     return AtomicExpansionKind::MaskedIntrinsic;
11486   return AtomicExpansionKind::None;
11487 }
11488 
11489 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11490     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11491     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11492   unsigned XLen = Subtarget.getXLen();
11493   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11494   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11495   if (XLen == 64) {
11496     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11497     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11498     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11499     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11500   }
11501   Type *Tys[] = {AlignedAddr->getType()};
11502   Function *MaskedCmpXchg =
11503       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11504   Value *Result = Builder.CreateCall(
11505       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11506   if (XLen == 64)
11507     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11508   return Result;
11509 }
11510 
11511 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11512   return false;
11513 }
11514 
11515 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11516                                                EVT VT) const {
11517   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11518     return false;
11519 
11520   switch (FPVT.getSimpleVT().SimpleTy) {
11521   case MVT::f16:
11522     return Subtarget.hasStdExtZfh();
11523   case MVT::f32:
11524     return Subtarget.hasStdExtF();
11525   case MVT::f64:
11526     return Subtarget.hasStdExtD();
11527   default:
11528     return false;
11529   }
11530 }
11531 
11532 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11533   // If we are using the small code model, we can reduce size of jump table
11534   // entry to 4 bytes.
11535   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11536       getTargetMachine().getCodeModel() == CodeModel::Small) {
11537     return MachineJumpTableInfo::EK_Custom32;
11538   }
11539   return TargetLowering::getJumpTableEncoding();
11540 }
11541 
11542 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11543     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11544     unsigned uid, MCContext &Ctx) const {
11545   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11546          getTargetMachine().getCodeModel() == CodeModel::Small);
11547   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11548 }
11549 
11550 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11551                                                      EVT VT) const {
11552   VT = VT.getScalarType();
11553 
11554   if (!VT.isSimple())
11555     return false;
11556 
11557   switch (VT.getSimpleVT().SimpleTy) {
11558   case MVT::f16:
11559     return Subtarget.hasStdExtZfh();
11560   case MVT::f32:
11561     return Subtarget.hasStdExtF();
11562   case MVT::f64:
11563     return Subtarget.hasStdExtD();
11564   default:
11565     break;
11566   }
11567 
11568   return false;
11569 }
11570 
11571 Register RISCVTargetLowering::getExceptionPointerRegister(
11572     const Constant *PersonalityFn) const {
11573   return RISCV::X10;
11574 }
11575 
11576 Register RISCVTargetLowering::getExceptionSelectorRegister(
11577     const Constant *PersonalityFn) const {
11578   return RISCV::X11;
11579 }
11580 
11581 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11582   // Return false to suppress the unnecessary extensions if the LibCall
11583   // arguments or return value is f32 type for LP64 ABI.
11584   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11585   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11586     return false;
11587 
11588   return true;
11589 }
11590 
11591 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11592   if (Subtarget.is64Bit() && Type == MVT::i32)
11593     return true;
11594 
11595   return IsSigned;
11596 }
11597 
11598 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11599                                                  SDValue C) const {
11600   // Check integral scalar types.
11601   if (VT.isScalarInteger()) {
11602     // Omit the optimization if the sub target has the M extension and the data
11603     // size exceeds XLen.
11604     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11605       return false;
11606     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11607       // Break the MUL to a SLLI and an ADD/SUB.
11608       const APInt &Imm = ConstNode->getAPIntValue();
11609       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11610           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11611         return true;
11612       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11613       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11614           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11615            (Imm - 8).isPowerOf2()))
11616         return true;
11617       // Omit the following optimization if the sub target has the M extension
11618       // and the data size >= XLen.
11619       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11620         return false;
11621       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11622       // a pair of LUI/ADDI.
11623       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11624         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11625         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11626             (1 - ImmS).isPowerOf2())
11627         return true;
11628       }
11629     }
11630   }
11631 
11632   return false;
11633 }
11634 
11635 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11636                                                       SDValue ConstNode) const {
11637   // Let the DAGCombiner decide for vectors.
11638   EVT VT = AddNode.getValueType();
11639   if (VT.isVector())
11640     return true;
11641 
11642   // Let the DAGCombiner decide for larger types.
11643   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11644     return true;
11645 
11646   // It is worse if c1 is simm12 while c1*c2 is not.
11647   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11648   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11649   const APInt &C1 = C1Node->getAPIntValue();
11650   const APInt &C2 = C2Node->getAPIntValue();
11651   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11652     return false;
11653 
11654   // Default to true and let the DAGCombiner decide.
11655   return true;
11656 }
11657 
11658 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11659     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11660     bool *Fast) const {
11661   if (!VT.isVector())
11662     return false;
11663 
11664   EVT ElemVT = VT.getVectorElementType();
11665   if (Alignment >= ElemVT.getStoreSize()) {
11666     if (Fast)
11667       *Fast = true;
11668     return true;
11669   }
11670 
11671   return false;
11672 }
11673 
11674 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11675     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11676     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11677   bool IsABIRegCopy = CC.hasValue();
11678   EVT ValueVT = Val.getValueType();
11679   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11680     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11681     // and cast to f32.
11682     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11683     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11684     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11685                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11686     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11687     Parts[0] = Val;
11688     return true;
11689   }
11690 
11691   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11692     LLVMContext &Context = *DAG.getContext();
11693     EVT ValueEltVT = ValueVT.getVectorElementType();
11694     EVT PartEltVT = PartVT.getVectorElementType();
11695     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11696     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11697     if (PartVTBitSize % ValueVTBitSize == 0) {
11698       assert(PartVTBitSize >= ValueVTBitSize);
11699       // If the element types are different, bitcast to the same element type of
11700       // PartVT first.
11701       // Give an example here, we want copy a <vscale x 1 x i8> value to
11702       // <vscale x 4 x i16>.
11703       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11704       // subvector, then we can bitcast to <vscale x 4 x i16>.
11705       if (ValueEltVT != PartEltVT) {
11706         if (PartVTBitSize > ValueVTBitSize) {
11707           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11708           assert(Count != 0 && "The number of element should not be zero.");
11709           EVT SameEltTypeVT =
11710               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11711           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11712                             DAG.getUNDEF(SameEltTypeVT), Val,
11713                             DAG.getVectorIdxConstant(0, DL));
11714         }
11715         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11716       } else {
11717         Val =
11718             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11719                         Val, DAG.getVectorIdxConstant(0, DL));
11720       }
11721       Parts[0] = Val;
11722       return true;
11723     }
11724   }
11725   return false;
11726 }
11727 
11728 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11729     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11730     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11731   bool IsABIRegCopy = CC.hasValue();
11732   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11733     SDValue Val = Parts[0];
11734 
11735     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11736     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11737     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11738     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11739     return Val;
11740   }
11741 
11742   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11743     LLVMContext &Context = *DAG.getContext();
11744     SDValue Val = Parts[0];
11745     EVT ValueEltVT = ValueVT.getVectorElementType();
11746     EVT PartEltVT = PartVT.getVectorElementType();
11747     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11748     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11749     if (PartVTBitSize % ValueVTBitSize == 0) {
11750       assert(PartVTBitSize >= ValueVTBitSize);
11751       EVT SameEltTypeVT = ValueVT;
11752       // If the element types are different, convert it to the same element type
11753       // of PartVT.
11754       // Give an example here, we want copy a <vscale x 1 x i8> value from
11755       // <vscale x 4 x i16>.
11756       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11757       // then we can extract <vscale x 1 x i8>.
11758       if (ValueEltVT != PartEltVT) {
11759         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11760         assert(Count != 0 && "The number of element should not be zero.");
11761         SameEltTypeVT =
11762             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11763         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11764       }
11765       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11766                         DAG.getVectorIdxConstant(0, DL));
11767       return Val;
11768     }
11769   }
11770   return SDValue();
11771 }
11772 
11773 SDValue
11774 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11775                                    SelectionDAG &DAG,
11776                                    SmallVectorImpl<SDNode *> &Created) const {
11777   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11778   if (isIntDivCheap(N->getValueType(0), Attr))
11779     return SDValue(N, 0); // Lower SDIV as SDIV
11780 
11781   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11782          "Unexpected divisor!");
11783 
11784   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11785   if (!Subtarget.hasStdExtZbt())
11786     return SDValue();
11787 
11788   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11789   // Besides, more critical path instructions will be generated when dividing
11790   // by 2. So we keep using the original DAGs for these cases.
11791   unsigned Lg2 = Divisor.countTrailingZeros();
11792   if (Lg2 == 1 || Lg2 >= 12)
11793     return SDValue();
11794 
11795   // fold (sdiv X, pow2)
11796   EVT VT = N->getValueType(0);
11797   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11798     return SDValue();
11799 
11800   SDLoc DL(N);
11801   SDValue N0 = N->getOperand(0);
11802   SDValue Zero = DAG.getConstant(0, DL, VT);
11803   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11804 
11805   // Add (N0 < 0) ? Pow2 - 1 : 0;
11806   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11807   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11808   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11809 
11810   Created.push_back(Cmp.getNode());
11811   Created.push_back(Add.getNode());
11812   Created.push_back(Sel.getNode());
11813 
11814   // Divide by pow2.
11815   SDValue SRA =
11816       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11817 
11818   // If we're dividing by a positive value, we're done.  Otherwise, we must
11819   // negate the result.
11820   if (Divisor.isNonNegative())
11821     return SRA;
11822 
11823   Created.push_back(SRA.getNode());
11824   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11825 }
11826 
11827 #define GET_REGISTER_MATCHER
11828 #include "RISCVGenAsmMatcher.inc"
11829 
11830 Register
11831 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11832                                        const MachineFunction &MF) const {
11833   Register Reg = MatchRegisterAltName(RegName);
11834   if (Reg == RISCV::NoRegister)
11835     Reg = MatchRegisterName(RegName);
11836   if (Reg == RISCV::NoRegister)
11837     report_fatal_error(
11838         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11839   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11840   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11841     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11842                              StringRef(RegName) + "\"."));
11843   return Reg;
11844 }
11845 
11846 namespace llvm {
11847 namespace RISCVVIntrinsicsTable {
11848 
11849 #define GET_RISCVVIntrinsicsTable_IMPL
11850 #include "RISCVGenSearchableTables.inc"
11851 
11852 } // namespace RISCVVIntrinsicsTable
11853 
11854 } // namespace llvm
11855