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/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IntrinsicsRISCV.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "riscv-lower"
42 
43 STATISTIC(NumTailCalls, "Number of tail calls");
44 
45 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
46                                          const RISCVSubtarget &STI)
47     : TargetLowering(TM), Subtarget(STI) {
48 
49   if (Subtarget.isRV32E())
50     report_fatal_error("Codegen not yet implemented for RV32E");
51 
52   RISCVABI::ABI ABI = Subtarget.getTargetABI();
53   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
54 
55   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
56       !Subtarget.hasStdExtF()) {
57     errs() << "Hard-float 'f' ABI can't be used for a target that "
58                 "doesn't support the F instruction set extension (ignoring "
59                           "target-abi)\n";
60     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
61   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
62              !Subtarget.hasStdExtD()) {
63     errs() << "Hard-float 'd' ABI can't be used for a target that "
64               "doesn't support the D instruction set extension (ignoring "
65               "target-abi)\n";
66     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
67   }
68 
69   switch (ABI) {
70   default:
71     report_fatal_error("Don't know how to lower this ABI");
72   case RISCVABI::ABI_ILP32:
73   case RISCVABI::ABI_ILP32F:
74   case RISCVABI::ABI_ILP32D:
75   case RISCVABI::ABI_LP64:
76   case RISCVABI::ABI_LP64F:
77   case RISCVABI::ABI_LP64D:
78     break;
79   }
80 
81   MVT XLenVT = Subtarget.getXLenVT();
82 
83   // Set up the register classes.
84   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
85 
86   if (Subtarget.hasStdExtZfh())
87     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
88   if (Subtarget.hasStdExtF())
89     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
90   if (Subtarget.hasStdExtD())
91     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
92 
93   static const MVT::SimpleValueType BoolVecVTs[] = {
94       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
95       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
96   static const MVT::SimpleValueType IntVecVTs[] = {
97       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
98       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
99       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
100       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
101       MVT::nxv4i64, MVT::nxv8i64};
102   static const MVT::SimpleValueType F16VecVTs[] = {
103       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
104       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
105   static const MVT::SimpleValueType F32VecVTs[] = {
106       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
107   static const MVT::SimpleValueType F64VecVTs[] = {
108       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
109 
110   if (Subtarget.hasStdExtV()) {
111     auto addRegClassForRVV = [this](MVT VT) {
112       unsigned Size = VT.getSizeInBits().getKnownMinValue();
113       assert(Size <= 512 && isPowerOf2_32(Size));
114       const TargetRegisterClass *RC;
115       if (Size <= 64)
116         RC = &RISCV::VRRegClass;
117       else if (Size == 128)
118         RC = &RISCV::VRM2RegClass;
119       else if (Size == 256)
120         RC = &RISCV::VRM4RegClass;
121       else
122         RC = &RISCV::VRM8RegClass;
123 
124       addRegisterClass(VT, RC);
125     };
126 
127     for (MVT VT : BoolVecVTs)
128       addRegClassForRVV(VT);
129     for (MVT VT : IntVecVTs)
130       addRegClassForRVV(VT);
131 
132     if (Subtarget.hasStdExtZfh())
133       for (MVT VT : F16VecVTs)
134         addRegClassForRVV(VT);
135 
136     if (Subtarget.hasStdExtF())
137       for (MVT VT : F32VecVTs)
138         addRegClassForRVV(VT);
139 
140     if (Subtarget.hasStdExtD())
141       for (MVT VT : F64VecVTs)
142         addRegClassForRVV(VT);
143 
144     if (Subtarget.useRVVForFixedLengthVectors()) {
145       auto addRegClassForFixedVectors = [this](MVT VT) {
146         unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT);
147         const TargetRegisterClass *RC;
148         if (LMul == 1)
149           RC = &RISCV::VRRegClass;
150         else if (LMul == 2)
151           RC = &RISCV::VRM2RegClass;
152         else if (LMul == 4)
153           RC = &RISCV::VRM4RegClass;
154         else if (LMul == 8)
155           RC = &RISCV::VRM8RegClass;
156         else
157           llvm_unreachable("Unexpected LMul!");
158 
159         addRegisterClass(VT, RC);
160       };
161       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
162         if (useRVVForFixedLengthVectorVT(VT))
163           addRegClassForFixedVectors(VT);
164 
165       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
166         if (useRVVForFixedLengthVectorVT(VT))
167           addRegClassForFixedVectors(VT);
168     }
169   }
170 
171   // Compute derived properties from the register classes.
172   computeRegisterProperties(STI.getRegisterInfo());
173 
174   setStackPointerRegisterToSaveRestore(RISCV::X2);
175 
176   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
177     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
178 
179   // TODO: add all necessary setOperationAction calls.
180   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
181 
182   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
183   setOperationAction(ISD::BR_CC, XLenVT, Expand);
184   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
185 
186   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
187   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
188 
189   setOperationAction(ISD::VASTART, MVT::Other, Custom);
190   setOperationAction(ISD::VAARG, MVT::Other, Expand);
191   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
192   setOperationAction(ISD::VAEND, MVT::Other, Expand);
193 
194   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
195   if (!Subtarget.hasStdExtZbb()) {
196     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
197     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
198   }
199 
200   if (Subtarget.is64Bit()) {
201     setOperationAction(ISD::ADD, MVT::i32, Custom);
202     setOperationAction(ISD::SUB, MVT::i32, Custom);
203     setOperationAction(ISD::SHL, MVT::i32, Custom);
204     setOperationAction(ISD::SRA, MVT::i32, Custom);
205     setOperationAction(ISD::SRL, MVT::i32, Custom);
206   }
207 
208   if (!Subtarget.hasStdExtM()) {
209     setOperationAction(ISD::MUL, XLenVT, Expand);
210     setOperationAction(ISD::MULHS, XLenVT, Expand);
211     setOperationAction(ISD::MULHU, XLenVT, Expand);
212     setOperationAction(ISD::SDIV, XLenVT, Expand);
213     setOperationAction(ISD::UDIV, XLenVT, Expand);
214     setOperationAction(ISD::SREM, XLenVT, Expand);
215     setOperationAction(ISD::UREM, XLenVT, Expand);
216   }
217 
218   if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) {
219     setOperationAction(ISD::MUL, MVT::i32, Custom);
220 
221     setOperationAction(ISD::SDIV, MVT::i8, Custom);
222     setOperationAction(ISD::UDIV, MVT::i8, Custom);
223     setOperationAction(ISD::UREM, MVT::i8, Custom);
224     setOperationAction(ISD::SDIV, MVT::i16, Custom);
225     setOperationAction(ISD::UDIV, MVT::i16, Custom);
226     setOperationAction(ISD::UREM, MVT::i16, Custom);
227     setOperationAction(ISD::SDIV, MVT::i32, Custom);
228     setOperationAction(ISD::UDIV, MVT::i32, Custom);
229     setOperationAction(ISD::UREM, MVT::i32, Custom);
230   }
231 
232   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
233   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
234   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
235   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
236 
237   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
238   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
239   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
240 
241   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
242     if (Subtarget.is64Bit()) {
243       setOperationAction(ISD::ROTL, MVT::i32, Custom);
244       setOperationAction(ISD::ROTR, MVT::i32, Custom);
245     }
246   } else {
247     setOperationAction(ISD::ROTL, XLenVT, Expand);
248     setOperationAction(ISD::ROTR, XLenVT, Expand);
249   }
250 
251   if (Subtarget.hasStdExtZbp()) {
252     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
253     // more combining.
254     setOperationAction(ISD::BITREVERSE, XLenVT, Custom);
255     setOperationAction(ISD::BSWAP, XLenVT, Custom);
256 
257     if (Subtarget.is64Bit()) {
258       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
259       setOperationAction(ISD::BSWAP, MVT::i32, Custom);
260     }
261   } else {
262     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
263     // pattern match it directly in isel.
264     setOperationAction(ISD::BSWAP, XLenVT,
265                        Subtarget.hasStdExtZbb() ? Legal : Expand);
266   }
267 
268   if (Subtarget.hasStdExtZbb()) {
269     setOperationAction(ISD::SMIN, XLenVT, Legal);
270     setOperationAction(ISD::SMAX, XLenVT, Legal);
271     setOperationAction(ISD::UMIN, XLenVT, Legal);
272     setOperationAction(ISD::UMAX, XLenVT, Legal);
273   } else {
274     setOperationAction(ISD::CTTZ, XLenVT, Expand);
275     setOperationAction(ISD::CTLZ, XLenVT, Expand);
276     setOperationAction(ISD::CTPOP, XLenVT, Expand);
277   }
278 
279   if (Subtarget.hasStdExtZbt()) {
280     setOperationAction(ISD::FSHL, XLenVT, Custom);
281     setOperationAction(ISD::FSHR, XLenVT, Custom);
282     setOperationAction(ISD::SELECT, XLenVT, Legal);
283 
284     if (Subtarget.is64Bit()) {
285       setOperationAction(ISD::FSHL, MVT::i32, Custom);
286       setOperationAction(ISD::FSHR, MVT::i32, Custom);
287     }
288   } else {
289     setOperationAction(ISD::SELECT, XLenVT, Custom);
290   }
291 
292   ISD::CondCode FPCCToExpand[] = {
293       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
294       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
295       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
296 
297   ISD::NodeType FPOpToExpand[] = {
298       ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP,
299       ISD::FP_TO_FP16};
300 
301   if (Subtarget.hasStdExtZfh())
302     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
303 
304   if (Subtarget.hasStdExtZfh()) {
305     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
306     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
307     for (auto CC : FPCCToExpand)
308       setCondCodeAction(CC, MVT::f16, Expand);
309     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
310     setOperationAction(ISD::SELECT, MVT::f16, Custom);
311     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
312     for (auto Op : FPOpToExpand)
313       setOperationAction(Op, MVT::f16, Expand);
314   }
315 
316   if (Subtarget.hasStdExtF()) {
317     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
318     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
319     for (auto CC : FPCCToExpand)
320       setCondCodeAction(CC, MVT::f32, Expand);
321     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
322     setOperationAction(ISD::SELECT, MVT::f32, Custom);
323     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
324     for (auto Op : FPOpToExpand)
325       setOperationAction(Op, MVT::f32, Expand);
326     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
327     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
328   }
329 
330   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
331     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
332 
333   if (Subtarget.hasStdExtD()) {
334     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
335     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
336     for (auto CC : FPCCToExpand)
337       setCondCodeAction(CC, MVT::f64, Expand);
338     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
339     setOperationAction(ISD::SELECT, MVT::f64, Custom);
340     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
341     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
342     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
343     for (auto Op : FPOpToExpand)
344       setOperationAction(Op, MVT::f64, Expand);
345     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
346     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
347   }
348 
349   if (Subtarget.is64Bit()) {
350     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
351     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
352     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
353     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
354   }
355 
356   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
357   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
358   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
359   setOperationAction(ISD::JumpTable, XLenVT, Custom);
360 
361   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
362 
363   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
364   // Unfortunately this can't be determined just from the ISA naming string.
365   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
366                      Subtarget.is64Bit() ? Legal : Custom);
367 
368   setOperationAction(ISD::TRAP, MVT::Other, Legal);
369   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
370   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
371 
372   if (Subtarget.hasStdExtA()) {
373     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
374     setMinCmpXchgSizeInBits(32);
375   } else {
376     setMaxAtomicSizeInBitsSupported(0);
377   }
378 
379   setBooleanContents(ZeroOrOneBooleanContent);
380 
381   if (Subtarget.hasStdExtV()) {
382     setBooleanVectorContents(ZeroOrOneBooleanContent);
383 
384     setOperationAction(ISD::VSCALE, XLenVT, Custom);
385 
386     // RVV intrinsics may have illegal operands.
387     // We also need to custom legalize vmv.x.s.
388     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
389     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
390     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
391     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
392     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
393     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
394 
395     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
396 
397     if (Subtarget.is64Bit()) {
398       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
399       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
400     } else {
401       // We must custom-lower certain vXi64 operations on RV32 due to the vector
402       // element type being illegal.
403       setOperationAction(ISD::SPLAT_VECTOR, MVT::i64, Custom);
404       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
405       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
406 
407       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
408       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
409       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
410       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
411       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
412       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
413       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
414       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
415     }
416 
417     for (MVT VT : BoolVecVTs) {
418       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
419 
420       // Mask VTs are custom-expanded into a series of standard nodes
421       setOperationAction(ISD::TRUNCATE, VT, Custom);
422       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
423       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
424     }
425 
426     for (MVT VT : IntVecVTs) {
427       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
428 
429       setOperationAction(ISD::SMIN, VT, Legal);
430       setOperationAction(ISD::SMAX, VT, Legal);
431       setOperationAction(ISD::UMIN, VT, Legal);
432       setOperationAction(ISD::UMAX, VT, Legal);
433 
434       if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64)
435         setOperationAction(ISD::ABS, VT, Custom);
436 
437       setOperationAction(ISD::ROTL, VT, Expand);
438       setOperationAction(ISD::ROTR, VT, Expand);
439 
440       // Custom-lower extensions and truncations from/to mask types.
441       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
442       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
443       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
444 
445       // RVV has native int->float & float->int conversions where the
446       // element type sizes are within one power-of-two of each other. Any
447       // wider distances between type sizes have to be lowered as sequences
448       // which progressively narrow the gap in stages.
449       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
450       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
451       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
452       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
453 
454       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
455       // nodes which truncate by one power of two at a time.
456       setOperationAction(ISD::TRUNCATE, VT, Custom);
457 
458       // Custom-lower insert/extract operations to simplify patterns.
459       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
460       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
461 
462       // Custom-lower reduction operations to set up the corresponding custom
463       // nodes' operands.
464       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
465       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
466       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
467       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
468       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
469       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
470       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
471       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
472 
473       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
474       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
475 
476       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
477     }
478 
479     // Expand various CCs to best match the RVV ISA, which natively supports UNE
480     // but no other unordered comparisons, and supports all ordered comparisons
481     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
482     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
483     // and we pattern-match those back to the "original", swapping operands once
484     // more. This way we catch both operations and both "vf" and "fv" forms with
485     // fewer patterns.
486     ISD::CondCode VFPCCToExpand[] = {
487         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
488         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
489         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
490     };
491 
492     // Sets common operation actions on RVV floating-point vector types.
493     const auto SetCommonVFPActions = [&](MVT VT) {
494       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
495       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
496       // sizes are within one power-of-two of each other. Therefore conversions
497       // between vXf16 and vXf64 must be lowered as sequences which convert via
498       // vXf32.
499       setOperationAction(ISD::FP_ROUND, VT, Custom);
500       setOperationAction(ISD::FP_EXTEND, VT, Custom);
501       // Custom-lower insert/extract operations to simplify patterns.
502       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
503       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
504       // Expand various condition codes (explained above).
505       for (auto CC : VFPCCToExpand)
506         setCondCodeAction(CC, VT, Expand);
507 
508       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
509       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
510       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
511 
512       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
513       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
514 
515       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
516     };
517 
518     if (Subtarget.hasStdExtZfh())
519       for (MVT VT : F16VecVTs)
520         SetCommonVFPActions(VT);
521 
522     if (Subtarget.hasStdExtF())
523       for (MVT VT : F32VecVTs)
524         SetCommonVFPActions(VT);
525 
526     if (Subtarget.hasStdExtD())
527       for (MVT VT : F64VecVTs)
528         SetCommonVFPActions(VT);
529 
530     if (Subtarget.useRVVForFixedLengthVectors()) {
531       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
532         if (!useRVVForFixedLengthVectorVT(VT))
533           continue;
534 
535         // By default everything must be expanded.
536         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
537           setOperationAction(Op, VT, Expand);
538         for (MVT OtherVT : MVT::fixedlen_vector_valuetypes())
539           setTruncStoreAction(VT, OtherVT, Expand);
540 
541         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
542         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
543         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
544 
545         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
546         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
547 
548         setOperationAction(ISD::LOAD, VT, Custom);
549         setOperationAction(ISD::STORE, VT, Custom);
550 
551         setOperationAction(ISD::SETCC, VT, Custom);
552 
553         setOperationAction(ISD::TRUNCATE, VT, Custom);
554 
555         // Operations below are different for between masks and other vectors.
556         if (VT.getVectorElementType() == MVT::i1) {
557           setOperationAction(ISD::AND, VT, Custom);
558           setOperationAction(ISD::OR, VT, Custom);
559           setOperationAction(ISD::XOR, VT, Custom);
560           continue;
561         }
562 
563         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
564         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
565         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
566 
567         setOperationAction(ISD::ADD, VT, Custom);
568         setOperationAction(ISD::MUL, VT, Custom);
569         setOperationAction(ISD::SUB, VT, Custom);
570         setOperationAction(ISD::AND, VT, Custom);
571         setOperationAction(ISD::OR, VT, Custom);
572         setOperationAction(ISD::XOR, VT, Custom);
573         setOperationAction(ISD::SDIV, VT, Custom);
574         setOperationAction(ISD::SREM, VT, Custom);
575         setOperationAction(ISD::UDIV, VT, Custom);
576         setOperationAction(ISD::UREM, VT, Custom);
577         setOperationAction(ISD::SHL, VT, Custom);
578         setOperationAction(ISD::SRA, VT, Custom);
579         setOperationAction(ISD::SRL, VT, Custom);
580 
581         setOperationAction(ISD::SMIN, VT, Custom);
582         setOperationAction(ISD::SMAX, VT, Custom);
583         setOperationAction(ISD::UMIN, VT, Custom);
584         setOperationAction(ISD::UMAX, VT, Custom);
585         setOperationAction(ISD::ABS,  VT, Custom);
586 
587         setOperationAction(ISD::MULHS, VT, Custom);
588         setOperationAction(ISD::MULHU, VT, Custom);
589 
590         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
591         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
592         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
593         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
594 
595         setOperationAction(ISD::VSELECT, VT, Custom);
596 
597         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
598         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
599         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
600 
601         setOperationAction(ISD::BITCAST, VT, Custom);
602 
603         // Custom-lower reduction operations to set up the corresponding custom
604         // nodes' operands.
605         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
606         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
607         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
608         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
609         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
610         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
611         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
612         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
613       }
614 
615       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
616         if (!useRVVForFixedLengthVectorVT(VT))
617           continue;
618 
619         // By default everything must be expanded.
620         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
621           setOperationAction(Op, VT, Expand);
622         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
623           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
624           setTruncStoreAction(VT, OtherVT, Expand);
625         }
626 
627         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
628         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
629         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
630 
631         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
632         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
633         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
634         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
635 
636         setOperationAction(ISD::LOAD, VT, Custom);
637         setOperationAction(ISD::STORE, VT, Custom);
638         setOperationAction(ISD::FADD, VT, Custom);
639         setOperationAction(ISD::FSUB, VT, Custom);
640         setOperationAction(ISD::FMUL, VT, Custom);
641         setOperationAction(ISD::FDIV, VT, Custom);
642         setOperationAction(ISD::FNEG, VT, Custom);
643         setOperationAction(ISD::FABS, VT, Custom);
644         setOperationAction(ISD::FSQRT, VT, Custom);
645         setOperationAction(ISD::FMA, VT, Custom);
646 
647         setOperationAction(ISD::FP_ROUND, VT, Custom);
648         setOperationAction(ISD::FP_EXTEND, VT, Custom);
649 
650         for (auto CC : VFPCCToExpand)
651           setCondCodeAction(CC, VT, Expand);
652 
653         setOperationAction(ISD::VSELECT, VT, Custom);
654 
655         setOperationAction(ISD::BITCAST, VT, Custom);
656 
657         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
658         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
659       }
660     }
661   }
662 
663   // Function alignments.
664   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
665   setMinFunctionAlignment(FunctionAlignment);
666   setPrefFunctionAlignment(FunctionAlignment);
667 
668   setMinimumJumpTableEntries(5);
669 
670   // Jumps are expensive, compared to logic
671   setJumpIsExpensive();
672 
673   // We can use any register for comparisons
674   setHasMultipleConditionRegisters();
675 
676   setTargetDAGCombine(ISD::SETCC);
677   if (Subtarget.hasStdExtZbp()) {
678     setTargetDAGCombine(ISD::OR);
679   }
680   if (Subtarget.hasStdExtV())
681     setTargetDAGCombine(ISD::FCOPYSIGN);
682 }
683 
684 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
685                                             LLVMContext &Context,
686                                             EVT VT) const {
687   if (!VT.isVector())
688     return getPointerTy(DL);
689   if (Subtarget.hasStdExtV() &&
690       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
691     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
692   return VT.changeVectorElementTypeToInteger();
693 }
694 
695 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
696                                              const CallInst &I,
697                                              MachineFunction &MF,
698                                              unsigned Intrinsic) const {
699   switch (Intrinsic) {
700   default:
701     return false;
702   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
703   case Intrinsic::riscv_masked_atomicrmw_add_i32:
704   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
705   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
706   case Intrinsic::riscv_masked_atomicrmw_max_i32:
707   case Intrinsic::riscv_masked_atomicrmw_min_i32:
708   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
709   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
710   case Intrinsic::riscv_masked_cmpxchg_i32:
711     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
712     Info.opc = ISD::INTRINSIC_W_CHAIN;
713     Info.memVT = MVT::getVT(PtrTy->getElementType());
714     Info.ptrVal = I.getArgOperand(0);
715     Info.offset = 0;
716     Info.align = Align(4);
717     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
718                  MachineMemOperand::MOVolatile;
719     return true;
720   }
721 }
722 
723 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
724                                                 const AddrMode &AM, Type *Ty,
725                                                 unsigned AS,
726                                                 Instruction *I) const {
727   // No global is ever allowed as a base.
728   if (AM.BaseGV)
729     return false;
730 
731   // Require a 12-bit signed offset.
732   if (!isInt<12>(AM.BaseOffs))
733     return false;
734 
735   switch (AM.Scale) {
736   case 0: // "r+i" or just "i", depending on HasBaseReg.
737     break;
738   case 1:
739     if (!AM.HasBaseReg) // allow "r+i".
740       break;
741     return false; // disallow "r+r" or "r+r+i".
742   default:
743     return false;
744   }
745 
746   return true;
747 }
748 
749 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
750   return isInt<12>(Imm);
751 }
752 
753 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
754   return isInt<12>(Imm);
755 }
756 
757 // On RV32, 64-bit integers are split into their high and low parts and held
758 // in two different registers, so the trunc is free since the low register can
759 // just be used.
760 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
761   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
762     return false;
763   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
764   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
765   return (SrcBits == 64 && DestBits == 32);
766 }
767 
768 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
769   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
770       !SrcVT.isInteger() || !DstVT.isInteger())
771     return false;
772   unsigned SrcBits = SrcVT.getSizeInBits();
773   unsigned DestBits = DstVT.getSizeInBits();
774   return (SrcBits == 64 && DestBits == 32);
775 }
776 
777 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
778   // Zexts are free if they can be combined with a load.
779   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
780     EVT MemVT = LD->getMemoryVT();
781     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
782          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
783         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
784          LD->getExtensionType() == ISD::ZEXTLOAD))
785       return true;
786   }
787 
788   return TargetLowering::isZExtFree(Val, VT2);
789 }
790 
791 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
792   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
793 }
794 
795 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
796   return Subtarget.hasStdExtZbb();
797 }
798 
799 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
800   return Subtarget.hasStdExtZbb();
801 }
802 
803 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
804                                        bool ForCodeSize) const {
805   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
806     return false;
807   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
808     return false;
809   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
810     return false;
811   if (Imm.isNegZero())
812     return false;
813   return Imm.isZero();
814 }
815 
816 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
817   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
818          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
819          (VT == MVT::f64 && Subtarget.hasStdExtD());
820 }
821 
822 // Changes the condition code and swaps operands if necessary, so the SetCC
823 // operation matches one of the comparisons supported directly in the RISC-V
824 // ISA.
825 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
826   switch (CC) {
827   default:
828     break;
829   case ISD::SETGT:
830   case ISD::SETLE:
831   case ISD::SETUGT:
832   case ISD::SETULE:
833     CC = ISD::getSetCCSwappedOperands(CC);
834     std::swap(LHS, RHS);
835     break;
836   }
837 }
838 
839 // Return the RISC-V branch opcode that matches the given DAG integer
840 // condition code. The CondCode must be one of those supported by the RISC-V
841 // ISA (see normaliseSetCC).
842 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
843   switch (CC) {
844   default:
845     llvm_unreachable("Unsupported CondCode");
846   case ISD::SETEQ:
847     return RISCV::BEQ;
848   case ISD::SETNE:
849     return RISCV::BNE;
850   case ISD::SETLT:
851     return RISCV::BLT;
852   case ISD::SETGE:
853     return RISCV::BGE;
854   case ISD::SETULT:
855     return RISCV::BLTU;
856   case ISD::SETUGE:
857     return RISCV::BGEU;
858   }
859 }
860 
861 RISCVVLMUL RISCVTargetLowering::getLMUL(MVT VT) {
862   assert(VT.isScalableVector() && "Expecting a scalable vector type");
863   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
864   if (VT.getVectorElementType() == MVT::i1)
865     KnownSize *= 8;
866 
867   switch (KnownSize) {
868   default:
869     llvm_unreachable("Invalid LMUL.");
870   case 8:
871     return RISCVVLMUL::LMUL_F8;
872   case 16:
873     return RISCVVLMUL::LMUL_F4;
874   case 32:
875     return RISCVVLMUL::LMUL_F2;
876   case 64:
877     return RISCVVLMUL::LMUL_1;
878   case 128:
879     return RISCVVLMUL::LMUL_2;
880   case 256:
881     return RISCVVLMUL::LMUL_4;
882   case 512:
883     return RISCVVLMUL::LMUL_8;
884   }
885 }
886 
887 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVVLMUL LMul) {
888   switch (LMul) {
889   default:
890     llvm_unreachable("Invalid LMUL.");
891   case RISCVVLMUL::LMUL_F8:
892   case RISCVVLMUL::LMUL_F4:
893   case RISCVVLMUL::LMUL_F2:
894   case RISCVVLMUL::LMUL_1:
895     return RISCV::VRRegClassID;
896   case RISCVVLMUL::LMUL_2:
897     return RISCV::VRM2RegClassID;
898   case RISCVVLMUL::LMUL_4:
899     return RISCV::VRM4RegClassID;
900   case RISCVVLMUL::LMUL_8:
901     return RISCV::VRM8RegClassID;
902   }
903 }
904 
905 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
906   RISCVVLMUL LMUL = getLMUL(VT);
907   if (LMUL == RISCVVLMUL::LMUL_F8 || LMUL == RISCVVLMUL::LMUL_F4 ||
908       LMUL == RISCVVLMUL::LMUL_F2 || LMUL == RISCVVLMUL::LMUL_1) {
909     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
910                   "Unexpected subreg numbering");
911     return RISCV::sub_vrm1_0 + Index;
912   }
913   if (LMUL == RISCVVLMUL::LMUL_2) {
914     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
915                   "Unexpected subreg numbering");
916     return RISCV::sub_vrm2_0 + Index;
917   }
918   if (LMUL == RISCVVLMUL::LMUL_4) {
919     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
920                   "Unexpected subreg numbering");
921     return RISCV::sub_vrm4_0 + Index;
922   }
923   llvm_unreachable("Invalid vector type.");
924 }
925 
926 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
927   if (VT.getVectorElementType() == MVT::i1)
928     return RISCV::VRRegClassID;
929   return getRegClassIDForLMUL(getLMUL(VT));
930 }
931 
932 // Attempt to decompose a subvector insert/extract between VecVT and
933 // SubVecVT via subregister indices. Returns the subregister index that
934 // can perform the subvector insert/extract with the given element index, as
935 // well as the index corresponding to any leftover subvectors that must be
936 // further inserted/extracted within the register class for SubVecVT.
937 std::pair<unsigned, unsigned>
938 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
939     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
940     const RISCVRegisterInfo *TRI) {
941   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
942                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
943                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
944                 "Register classes not ordered");
945   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
946   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
947   // Try to compose a subregister index that takes us from the incoming
948   // LMUL>1 register class down to the outgoing one. At each step we half
949   // the LMUL:
950   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
951   // Note that this is not guaranteed to find a subregister index, such as
952   // when we are extracting from one VR type to another.
953   unsigned SubRegIdx = RISCV::NoSubRegister;
954   for (const unsigned RCID :
955        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
956     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
957       VecVT = VecVT.getHalfNumVectorElementsVT();
958       bool IsHi =
959           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
960       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
961                                             getSubregIndexByMVT(VecVT, IsHi));
962       if (IsHi)
963         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
964     }
965   return {SubRegIdx, InsertExtractIdx};
966 }
967 
968 // Return the largest legal scalable vector type that matches VT's element type.
969 MVT RISCVTargetLowering::getContainerForFixedLengthVector(
970     const TargetLowering &TLI, MVT VT, const RISCVSubtarget &Subtarget) {
971   assert(VT.isFixedLengthVector() && TLI.isTypeLegal(VT) &&
972          "Expected legal fixed length vector!");
973 
974   unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT);
975   assert(LMul <= 8 && isPowerOf2_32(LMul) && "Unexpected LMUL!");
976 
977   MVT EltVT = VT.getVectorElementType();
978   switch (EltVT.SimpleTy) {
979   default:
980     llvm_unreachable("unexpected element type for RVV container");
981   case MVT::i1: {
982     // Masks are calculated assuming 8-bit elements since that's when we need
983     // the most elements.
984     unsigned EltsPerBlock = RISCV::RVVBitsPerBlock / 8;
985     return MVT::getScalableVectorVT(MVT::i1, LMul * EltsPerBlock);
986   }
987   case MVT::i8:
988   case MVT::i16:
989   case MVT::i32:
990   case MVT::i64:
991   case MVT::f16:
992   case MVT::f32:
993   case MVT::f64: {
994     unsigned EltsPerBlock = RISCV::RVVBitsPerBlock / EltVT.getSizeInBits();
995     return MVT::getScalableVectorVT(EltVT, LMul * EltsPerBlock);
996   }
997   }
998 }
999 
1000 MVT RISCVTargetLowering::getContainerForFixedLengthVector(
1001     SelectionDAG &DAG, MVT VT, const RISCVSubtarget &Subtarget) {
1002   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1003                                           Subtarget);
1004 }
1005 
1006 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1007   return getContainerForFixedLengthVector(*this, VT, getSubtarget());
1008 }
1009 
1010 // Grow V to consume an entire RVV register.
1011 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1012                                        const RISCVSubtarget &Subtarget) {
1013   assert(VT.isScalableVector() &&
1014          "Expected to convert into a scalable vector!");
1015   assert(V.getValueType().isFixedLengthVector() &&
1016          "Expected a fixed length vector operand!");
1017   SDLoc DL(V);
1018   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1019   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1020 }
1021 
1022 // Shrink V so it's just big enough to maintain a VT's worth of data.
1023 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1024                                          const RISCVSubtarget &Subtarget) {
1025   assert(VT.isFixedLengthVector() &&
1026          "Expected to convert into a fixed length vector!");
1027   assert(V.getValueType().isScalableVector() &&
1028          "Expected a scalable vector operand!");
1029   SDLoc DL(V);
1030   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1031   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1032 }
1033 
1034 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1035 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1036 // the vector type that it is contained in.
1037 static std::pair<SDValue, SDValue>
1038 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1039                 const RISCVSubtarget &Subtarget) {
1040   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1041   MVT XLenVT = Subtarget.getXLenVT();
1042   SDValue VL = VecVT.isFixedLengthVector()
1043                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1044                    : DAG.getRegister(RISCV::X0, XLenVT);
1045   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1046   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1047   return {Mask, VL};
1048 }
1049 
1050 // As above but assuming the given type is a scalable vector type.
1051 static std::pair<SDValue, SDValue>
1052 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1053                         const RISCVSubtarget &Subtarget) {
1054   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1055   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1056 }
1057 
1058 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1059 // of either is (currently) supported. This can get us into an infinite loop
1060 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1061 // as a ..., etc.
1062 // Until either (or both) of these can reliably lower any node, reporting that
1063 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1064 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1065 // which is not desirable.
1066 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1067     EVT VT, unsigned DefinedValues) const {
1068   return false;
1069 }
1070 
1071 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1072                                  const RISCVSubtarget &Subtarget) {
1073   MVT VT = Op.getSimpleValueType();
1074   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1075 
1076   MVT ContainerVT =
1077       RISCVTargetLowering::getContainerForFixedLengthVector(DAG, VT, Subtarget);
1078 
1079   SDLoc DL(Op);
1080   SDValue Mask, VL;
1081   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1082 
1083   if (VT.getVectorElementType() == MVT::i1) {
1084     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1085       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1086       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1087     }
1088 
1089     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1090       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1091       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1092     }
1093 
1094     return SDValue();
1095   }
1096 
1097   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1098     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1099                                         : RISCVISD::VMV_V_X_VL;
1100     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1101     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1102   }
1103 
1104   // Try and match an index sequence, which we can lower directly to the vid
1105   // instruction. An all-undef vector is matched by getSplatValue, above.
1106   if (VT.isInteger()) {
1107     bool IsVID = true;
1108     for (unsigned i = 0, e = Op.getNumOperands(); i < e && IsVID; i++)
1109       IsVID &= Op.getOperand(i).isUndef() ||
1110                (isa<ConstantSDNode>(Op.getOperand(i)) &&
1111                 Op.getConstantOperandVal(i) == i);
1112 
1113     if (IsVID) {
1114       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1115       return convertFromScalableVector(VT, VID, DAG, Subtarget);
1116     }
1117   }
1118 
1119   return SDValue();
1120 }
1121 
1122 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
1123                                    const RISCVSubtarget &Subtarget) {
1124   SDValue V1 = Op.getOperand(0);
1125   SDLoc DL(Op);
1126   MVT VT = Op.getSimpleValueType();
1127   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
1128 
1129   if (SVN->isSplat()) {
1130     int Lane = SVN->getSplatIndex();
1131     if (Lane >= 0) {
1132       MVT ContainerVT = RISCVTargetLowering::getContainerForFixedLengthVector(
1133           DAG, VT, Subtarget);
1134 
1135       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
1136       assert(Lane < (int)VT.getVectorNumElements() && "Unexpected lane!");
1137 
1138       SDValue Mask, VL;
1139       std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1140       MVT XLenVT = Subtarget.getXLenVT();
1141       SDValue Gather =
1142           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
1143                       DAG.getConstant(Lane, DL, XLenVT), Mask, VL);
1144       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1145     }
1146   }
1147 
1148   return SDValue();
1149 }
1150 
1151 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
1152                                      SDLoc DL, SelectionDAG &DAG,
1153                                      const RISCVSubtarget &Subtarget) {
1154   if (VT.isScalableVector())
1155     return DAG.getFPExtendOrRound(Op, DL, VT);
1156   assert(VT.isFixedLengthVector() &&
1157          "Unexpected value type for RVV FP extend/round lowering");
1158   SDValue Mask, VL;
1159   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1160   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
1161                         ? RISCVISD::FP_EXTEND_VL
1162                         : RISCVISD::FP_ROUND_VL;
1163   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
1164 }
1165 
1166 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
1167                                             SelectionDAG &DAG) const {
1168   switch (Op.getOpcode()) {
1169   default:
1170     report_fatal_error("unimplemented operand");
1171   case ISD::GlobalAddress:
1172     return lowerGlobalAddress(Op, DAG);
1173   case ISD::BlockAddress:
1174     return lowerBlockAddress(Op, DAG);
1175   case ISD::ConstantPool:
1176     return lowerConstantPool(Op, DAG);
1177   case ISD::JumpTable:
1178     return lowerJumpTable(Op, DAG);
1179   case ISD::GlobalTLSAddress:
1180     return lowerGlobalTLSAddress(Op, DAG);
1181   case ISD::SELECT:
1182     return lowerSELECT(Op, DAG);
1183   case ISD::VASTART:
1184     return lowerVASTART(Op, DAG);
1185   case ISD::FRAMEADDR:
1186     return lowerFRAMEADDR(Op, DAG);
1187   case ISD::RETURNADDR:
1188     return lowerRETURNADDR(Op, DAG);
1189   case ISD::SHL_PARTS:
1190     return lowerShiftLeftParts(Op, DAG);
1191   case ISD::SRA_PARTS:
1192     return lowerShiftRightParts(Op, DAG, true);
1193   case ISD::SRL_PARTS:
1194     return lowerShiftRightParts(Op, DAG, false);
1195   case ISD::BITCAST: {
1196     SDValue Op0 = Op.getOperand(0);
1197     // We can handle fixed length vector bitcasts with a simple replacement
1198     // in isel.
1199     if (Op.getValueType().isFixedLengthVector()) {
1200       if (Op0.getValueType().isFixedLengthVector())
1201         return Op;
1202       return SDValue();
1203     }
1204     assert(((Subtarget.is64Bit() && Subtarget.hasStdExtF()) ||
1205             Subtarget.hasStdExtZfh()) &&
1206            "Unexpected custom legalisation");
1207     SDLoc DL(Op);
1208     if (Op.getValueType() == MVT::f16 && Subtarget.hasStdExtZfh()) {
1209       if (Op0.getValueType() != MVT::i16)
1210         return SDValue();
1211       SDValue NewOp0 =
1212           DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Op0);
1213       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
1214       return FPConv;
1215     } else if (Op.getValueType() == MVT::f32 && Subtarget.is64Bit() &&
1216                Subtarget.hasStdExtF()) {
1217       if (Op0.getValueType() != MVT::i32)
1218         return SDValue();
1219       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
1220       SDValue FPConv =
1221           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
1222       return FPConv;
1223     }
1224     return SDValue();
1225   }
1226   case ISD::INTRINSIC_WO_CHAIN:
1227     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1228   case ISD::INTRINSIC_W_CHAIN:
1229     return LowerINTRINSIC_W_CHAIN(Op, DAG);
1230   case ISD::BSWAP:
1231   case ISD::BITREVERSE: {
1232     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
1233     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
1234     MVT VT = Op.getSimpleValueType();
1235     SDLoc DL(Op);
1236     // Start with the maximum immediate value which is the bitwidth - 1.
1237     unsigned Imm = VT.getSizeInBits() - 1;
1238     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
1239     if (Op.getOpcode() == ISD::BSWAP)
1240       Imm &= ~0x7U;
1241     return DAG.getNode(RISCVISD::GREVI, DL, VT, Op.getOperand(0),
1242                        DAG.getTargetConstant(Imm, DL, Subtarget.getXLenVT()));
1243   }
1244   case ISD::FSHL:
1245   case ISD::FSHR: {
1246     MVT VT = Op.getSimpleValueType();
1247     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
1248     SDLoc DL(Op);
1249     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
1250     // use log(XLen) bits. Mask the shift amount accordingly.
1251     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
1252     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
1253                                 DAG.getConstant(ShAmtWidth, DL, VT));
1254     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
1255     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
1256   }
1257   case ISD::TRUNCATE: {
1258     SDLoc DL(Op);
1259     MVT VT = Op.getSimpleValueType();
1260     // Only custom-lower vector truncates
1261     if (!VT.isVector())
1262       return Op;
1263 
1264     // Truncates to mask types are handled differently
1265     if (VT.getVectorElementType() == MVT::i1)
1266       return lowerVectorMaskTrunc(Op, DAG);
1267 
1268     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
1269     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
1270     // truncate by one power of two at a time.
1271     MVT DstEltVT = VT.getVectorElementType();
1272 
1273     SDValue Src = Op.getOperand(0);
1274     MVT SrcVT = Src.getSimpleValueType();
1275     MVT SrcEltVT = SrcVT.getVectorElementType();
1276 
1277     assert(DstEltVT.bitsLT(SrcEltVT) &&
1278            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
1279            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
1280            "Unexpected vector truncate lowering");
1281 
1282     MVT ContainerVT = SrcVT;
1283     if (SrcVT.isFixedLengthVector()) {
1284       ContainerVT = getContainerForFixedLengthVector(SrcVT);
1285       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
1286     }
1287 
1288     SDValue Result = Src;
1289     SDValue Mask, VL;
1290     std::tie(Mask, VL) =
1291         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
1292     LLVMContext &Context = *DAG.getContext();
1293     const ElementCount Count = ContainerVT.getVectorElementCount();
1294     do {
1295       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
1296       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
1297       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
1298                            Mask, VL);
1299     } while (SrcEltVT != DstEltVT);
1300 
1301     if (SrcVT.isFixedLengthVector())
1302       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
1303 
1304     return Result;
1305   }
1306   case ISD::ANY_EXTEND:
1307   case ISD::ZERO_EXTEND:
1308     if (Op.getOperand(0).getValueType().isVector() &&
1309         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
1310       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
1311     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
1312   case ISD::SIGN_EXTEND:
1313     if (Op.getOperand(0).getValueType().isVector() &&
1314         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
1315       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
1316     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
1317   case ISD::SPLAT_VECTOR:
1318     return lowerSPLATVECTOR(Op, DAG);
1319   case ISD::INSERT_VECTOR_ELT:
1320     return lowerINSERT_VECTOR_ELT(Op, DAG);
1321   case ISD::EXTRACT_VECTOR_ELT:
1322     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
1323   case ISD::VSCALE: {
1324     MVT VT = Op.getSimpleValueType();
1325     SDLoc DL(Op);
1326     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
1327     // We define our scalable vector types for lmul=1 to use a 64 bit known
1328     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
1329     // vscale as VLENB / 8.
1330     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
1331                                  DAG.getConstant(3, DL, VT));
1332     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
1333   }
1334   case ISD::FP_EXTEND: {
1335     // RVV can only do fp_extend to types double the size as the source. We
1336     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
1337     // via f32.
1338     SDLoc DL(Op);
1339     MVT VT = Op.getSimpleValueType();
1340     SDValue Src = Op.getOperand(0);
1341     MVT SrcVT = Src.getSimpleValueType();
1342 
1343     // Prepare any fixed-length vector operands.
1344     MVT ContainerVT = VT;
1345     if (SrcVT.isFixedLengthVector()) {
1346       ContainerVT = getContainerForFixedLengthVector(VT);
1347       MVT SrcContainerVT =
1348           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
1349       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
1350     }
1351 
1352     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
1353         SrcVT.getVectorElementType() != MVT::f16) {
1354       // For scalable vectors, we only need to close the gap between
1355       // vXf16->vXf64.
1356       if (!VT.isFixedLengthVector())
1357         return Op;
1358       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
1359       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
1360       return convertFromScalableVector(VT, Src, DAG, Subtarget);
1361     }
1362 
1363     MVT InterVT = VT.changeVectorElementType(MVT::f32);
1364     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
1365     SDValue IntermediateExtend = getRVVFPExtendOrRound(
1366         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
1367 
1368     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
1369                                            DL, DAG, Subtarget);
1370     if (VT.isFixedLengthVector())
1371       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
1372     return Extend;
1373   }
1374   case ISD::FP_ROUND: {
1375     // RVV can only do fp_round to types half the size as the source. We
1376     // custom-lower f64->f16 rounds via RVV's round-to-odd float
1377     // conversion instruction.
1378     SDLoc DL(Op);
1379     MVT VT = Op.getSimpleValueType();
1380     SDValue Src = Op.getOperand(0);
1381     MVT SrcVT = Src.getSimpleValueType();
1382 
1383     // Prepare any fixed-length vector operands.
1384     MVT ContainerVT = VT;
1385     if (VT.isFixedLengthVector()) {
1386       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
1387       ContainerVT =
1388           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
1389       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
1390     }
1391 
1392     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
1393         SrcVT.getVectorElementType() != MVT::f64) {
1394       // For scalable vectors, we only need to close the gap between
1395       // vXf64<->vXf16.
1396       if (!VT.isFixedLengthVector())
1397         return Op;
1398       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
1399       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
1400       return convertFromScalableVector(VT, Src, DAG, Subtarget);
1401     }
1402 
1403     SDValue Mask, VL;
1404     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1405 
1406     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
1407     SDValue IntermediateRound =
1408         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
1409     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
1410                                           DL, DAG, Subtarget);
1411 
1412     if (VT.isFixedLengthVector())
1413       return convertFromScalableVector(VT, Round, DAG, Subtarget);
1414     return Round;
1415   }
1416   case ISD::FP_TO_SINT:
1417   case ISD::FP_TO_UINT:
1418   case ISD::SINT_TO_FP:
1419   case ISD::UINT_TO_FP: {
1420     // RVV can only do fp<->int conversions to types half/double the size as
1421     // the source. We custom-lower any conversions that do two hops into
1422     // sequences.
1423     MVT VT = Op.getSimpleValueType();
1424     if (!VT.isVector())
1425       return Op;
1426     SDLoc DL(Op);
1427     SDValue Src = Op.getOperand(0);
1428     MVT EltVT = VT.getVectorElementType();
1429     MVT SrcVT = Src.getSimpleValueType();
1430     MVT SrcEltVT = SrcVT.getVectorElementType();
1431     unsigned EltSize = EltVT.getSizeInBits();
1432     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
1433     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
1434            "Unexpected vector element types");
1435 
1436     bool IsInt2FP = SrcEltVT.isInteger();
1437     // Widening conversions
1438     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
1439       if (IsInt2FP) {
1440         // Do a regular integer sign/zero extension then convert to float.
1441         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
1442                                       VT.getVectorElementCount());
1443         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
1444                                  ? ISD::ZERO_EXTEND
1445                                  : ISD::SIGN_EXTEND;
1446         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
1447         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
1448       }
1449       // FP2Int
1450       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
1451       // Do one doubling fp_extend then complete the operation by converting
1452       // to int.
1453       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1454       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
1455       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
1456     }
1457 
1458     // Narrowing conversions
1459     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
1460       if (IsInt2FP) {
1461         // One narrowing int_to_fp, then an fp_round.
1462         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
1463         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1464         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
1465         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
1466       }
1467       // FP2Int
1468       // One narrowing fp_to_int, then truncate the integer. If the float isn't
1469       // representable by the integer, the result is poison.
1470       MVT IVecVT =
1471           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
1472                            VT.getVectorElementCount());
1473       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
1474       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
1475     }
1476 
1477     // Scalable vectors can exit here. Patterns will handle equally-sized
1478     // conversions halving/doubling ones.
1479     if (!VT.isFixedLengthVector())
1480       return Op;
1481 
1482     // For fixed-length vectors we lower to a custom "VL" node.
1483     unsigned RVVOpc = 0;
1484     switch (Op.getOpcode()) {
1485     default:
1486       llvm_unreachable("Impossible opcode");
1487     case ISD::FP_TO_SINT:
1488       RVVOpc = RISCVISD::FP_TO_SINT_VL;
1489       break;
1490     case ISD::FP_TO_UINT:
1491       RVVOpc = RISCVISD::FP_TO_UINT_VL;
1492       break;
1493     case ISD::SINT_TO_FP:
1494       RVVOpc = RISCVISD::SINT_TO_FP_VL;
1495       break;
1496     case ISD::UINT_TO_FP:
1497       RVVOpc = RISCVISD::UINT_TO_FP_VL;
1498       break;
1499     }
1500 
1501     MVT ContainerVT, SrcContainerVT;
1502     // Derive the reference container type from the larger vector type.
1503     if (SrcEltSize > EltSize) {
1504       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
1505       ContainerVT =
1506           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
1507     } else {
1508       ContainerVT = getContainerForFixedLengthVector(VT);
1509       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
1510     }
1511 
1512     SDValue Mask, VL;
1513     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1514 
1515     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
1516     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
1517     return convertFromScalableVector(VT, Src, DAG, Subtarget);
1518   }
1519   case ISD::VECREDUCE_ADD:
1520   case ISD::VECREDUCE_UMAX:
1521   case ISD::VECREDUCE_SMAX:
1522   case ISD::VECREDUCE_UMIN:
1523   case ISD::VECREDUCE_SMIN:
1524   case ISD::VECREDUCE_AND:
1525   case ISD::VECREDUCE_OR:
1526   case ISD::VECREDUCE_XOR:
1527     return lowerVECREDUCE(Op, DAG);
1528   case ISD::VECREDUCE_FADD:
1529   case ISD::VECREDUCE_SEQ_FADD:
1530     return lowerFPVECREDUCE(Op, DAG);
1531   case ISD::INSERT_SUBVECTOR:
1532     return lowerINSERT_SUBVECTOR(Op, DAG);
1533   case ISD::EXTRACT_SUBVECTOR:
1534     return lowerEXTRACT_SUBVECTOR(Op, DAG);
1535   case ISD::VECTOR_REVERSE:
1536     return lowerVECTOR_REVERSE(Op, DAG);
1537   case ISD::BUILD_VECTOR:
1538     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
1539   case ISD::VECTOR_SHUFFLE:
1540     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
1541   case ISD::CONCAT_VECTORS: {
1542     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
1543     // better than going through the stack, as the default expansion does.
1544     SDLoc DL(Op);
1545     MVT VT = Op.getSimpleValueType();
1546     assert(VT.isFixedLengthVector() && "Unexpected CONCAT_VECTORS lowering");
1547     unsigned NumOpElts =
1548         Op.getOperand(0).getSimpleValueType().getVectorNumElements();
1549     SDValue Vec = DAG.getUNDEF(VT);
1550     for (const auto &OpIdx : enumerate(Op->ops()))
1551       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
1552                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
1553     return Vec;
1554   }
1555   case ISD::LOAD:
1556     return lowerFixedLengthVectorLoadToRVV(Op, DAG);
1557   case ISD::STORE:
1558     return lowerFixedLengthVectorStoreToRVV(Op, DAG);
1559   case ISD::SETCC:
1560     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
1561   case ISD::ADD:
1562     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
1563   case ISD::SUB:
1564     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
1565   case ISD::MUL:
1566     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
1567   case ISD::MULHS:
1568     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
1569   case ISD::MULHU:
1570     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
1571   case ISD::AND:
1572     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
1573                                               RISCVISD::AND_VL);
1574   case ISD::OR:
1575     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
1576                                               RISCVISD::OR_VL);
1577   case ISD::XOR:
1578     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
1579                                               RISCVISD::XOR_VL);
1580   case ISD::SDIV:
1581     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
1582   case ISD::SREM:
1583     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
1584   case ISD::UDIV:
1585     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
1586   case ISD::UREM:
1587     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
1588   case ISD::SHL:
1589     return lowerToScalableOp(Op, DAG, RISCVISD::SHL_VL);
1590   case ISD::SRA:
1591     return lowerToScalableOp(Op, DAG, RISCVISD::SRA_VL);
1592   case ISD::SRL:
1593     return lowerToScalableOp(Op, DAG, RISCVISD::SRL_VL);
1594   case ISD::FADD:
1595     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
1596   case ISD::FSUB:
1597     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
1598   case ISD::FMUL:
1599     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
1600   case ISD::FDIV:
1601     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
1602   case ISD::FNEG:
1603     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
1604   case ISD::FABS:
1605     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
1606   case ISD::FSQRT:
1607     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
1608   case ISD::FMA:
1609     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
1610   case ISD::SMIN:
1611     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
1612   case ISD::SMAX:
1613     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
1614   case ISD::UMIN:
1615     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
1616   case ISD::UMAX:
1617     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
1618   case ISD::ABS:
1619     return lowerABS(Op, DAG);
1620   case ISD::VSELECT:
1621     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
1622   }
1623 }
1624 
1625 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
1626                              SelectionDAG &DAG, unsigned Flags) {
1627   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
1628 }
1629 
1630 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
1631                              SelectionDAG &DAG, unsigned Flags) {
1632   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
1633                                    Flags);
1634 }
1635 
1636 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
1637                              SelectionDAG &DAG, unsigned Flags) {
1638   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
1639                                    N->getOffset(), Flags);
1640 }
1641 
1642 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
1643                              SelectionDAG &DAG, unsigned Flags) {
1644   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
1645 }
1646 
1647 template <class NodeTy>
1648 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
1649                                      bool IsLocal) const {
1650   SDLoc DL(N);
1651   EVT Ty = getPointerTy(DAG.getDataLayout());
1652 
1653   if (isPositionIndependent()) {
1654     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
1655     if (IsLocal)
1656       // Use PC-relative addressing to access the symbol. This generates the
1657       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
1658       // %pcrel_lo(auipc)).
1659       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
1660 
1661     // Use PC-relative addressing to access the GOT for this symbol, then load
1662     // the address from the GOT. This generates the pattern (PseudoLA sym),
1663     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
1664     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
1665   }
1666 
1667   switch (getTargetMachine().getCodeModel()) {
1668   default:
1669     report_fatal_error("Unsupported code model for lowering");
1670   case CodeModel::Small: {
1671     // Generate a sequence for accessing addresses within the first 2 GiB of
1672     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
1673     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
1674     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
1675     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
1676     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
1677   }
1678   case CodeModel::Medium: {
1679     // Generate a sequence for accessing addresses within any 2GiB range within
1680     // the address space. This generates the pattern (PseudoLLA sym), which
1681     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
1682     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
1683     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
1684   }
1685   }
1686 }
1687 
1688 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
1689                                                 SelectionDAG &DAG) const {
1690   SDLoc DL(Op);
1691   EVT Ty = Op.getValueType();
1692   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1693   int64_t Offset = N->getOffset();
1694   MVT XLenVT = Subtarget.getXLenVT();
1695 
1696   const GlobalValue *GV = N->getGlobal();
1697   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
1698   SDValue Addr = getAddr(N, DAG, IsLocal);
1699 
1700   // In order to maximise the opportunity for common subexpression elimination,
1701   // emit a separate ADD node for the global address offset instead of folding
1702   // it in the global address node. Later peephole optimisations may choose to
1703   // fold it back in when profitable.
1704   if (Offset != 0)
1705     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
1706                        DAG.getConstant(Offset, DL, XLenVT));
1707   return Addr;
1708 }
1709 
1710 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
1711                                                SelectionDAG &DAG) const {
1712   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1713 
1714   return getAddr(N, DAG);
1715 }
1716 
1717 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
1718                                                SelectionDAG &DAG) const {
1719   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1720 
1721   return getAddr(N, DAG);
1722 }
1723 
1724 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
1725                                             SelectionDAG &DAG) const {
1726   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1727 
1728   return getAddr(N, DAG);
1729 }
1730 
1731 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
1732                                               SelectionDAG &DAG,
1733                                               bool UseGOT) const {
1734   SDLoc DL(N);
1735   EVT Ty = getPointerTy(DAG.getDataLayout());
1736   const GlobalValue *GV = N->getGlobal();
1737   MVT XLenVT = Subtarget.getXLenVT();
1738 
1739   if (UseGOT) {
1740     // Use PC-relative addressing to access the GOT for this TLS symbol, then
1741     // load the address from the GOT and add the thread pointer. This generates
1742     // the pattern (PseudoLA_TLS_IE sym), which expands to
1743     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
1744     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
1745     SDValue Load =
1746         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
1747 
1748     // Add the thread pointer.
1749     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
1750     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
1751   }
1752 
1753   // Generate a sequence for accessing the address relative to the thread
1754   // pointer, with the appropriate adjustment for the thread pointer offset.
1755   // This generates the pattern
1756   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
1757   SDValue AddrHi =
1758       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
1759   SDValue AddrAdd =
1760       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
1761   SDValue AddrLo =
1762       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
1763 
1764   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
1765   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
1766   SDValue MNAdd = SDValue(
1767       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
1768       0);
1769   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
1770 }
1771 
1772 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
1773                                                SelectionDAG &DAG) const {
1774   SDLoc DL(N);
1775   EVT Ty = getPointerTy(DAG.getDataLayout());
1776   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
1777   const GlobalValue *GV = N->getGlobal();
1778 
1779   // Use a PC-relative addressing mode to access the global dynamic GOT address.
1780   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
1781   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
1782   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
1783   SDValue Load =
1784       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
1785 
1786   // Prepare argument list to generate call.
1787   ArgListTy Args;
1788   ArgListEntry Entry;
1789   Entry.Node = Load;
1790   Entry.Ty = CallTy;
1791   Args.push_back(Entry);
1792 
1793   // Setup call to __tls_get_addr.
1794   TargetLowering::CallLoweringInfo CLI(DAG);
1795   CLI.setDebugLoc(DL)
1796       .setChain(DAG.getEntryNode())
1797       .setLibCallee(CallingConv::C, CallTy,
1798                     DAG.getExternalSymbol("__tls_get_addr", Ty),
1799                     std::move(Args));
1800 
1801   return LowerCallTo(CLI).first;
1802 }
1803 
1804 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
1805                                                    SelectionDAG &DAG) const {
1806   SDLoc DL(Op);
1807   EVT Ty = Op.getValueType();
1808   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1809   int64_t Offset = N->getOffset();
1810   MVT XLenVT = Subtarget.getXLenVT();
1811 
1812   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
1813 
1814   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
1815       CallingConv::GHC)
1816     report_fatal_error("In GHC calling convention TLS is not supported");
1817 
1818   SDValue Addr;
1819   switch (Model) {
1820   case TLSModel::LocalExec:
1821     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
1822     break;
1823   case TLSModel::InitialExec:
1824     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
1825     break;
1826   case TLSModel::LocalDynamic:
1827   case TLSModel::GeneralDynamic:
1828     Addr = getDynamicTLSAddr(N, DAG);
1829     break;
1830   }
1831 
1832   // In order to maximise the opportunity for common subexpression elimination,
1833   // emit a separate ADD node for the global address offset instead of folding
1834   // it in the global address node. Later peephole optimisations may choose to
1835   // fold it back in when profitable.
1836   if (Offset != 0)
1837     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
1838                        DAG.getConstant(Offset, DL, XLenVT));
1839   return Addr;
1840 }
1841 
1842 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1843   SDValue CondV = Op.getOperand(0);
1844   SDValue TrueV = Op.getOperand(1);
1845   SDValue FalseV = Op.getOperand(2);
1846   SDLoc DL(Op);
1847   MVT XLenVT = Subtarget.getXLenVT();
1848 
1849   // If the result type is XLenVT and CondV is the output of a SETCC node
1850   // which also operated on XLenVT inputs, then merge the SETCC node into the
1851   // lowered RISCVISD::SELECT_CC to take advantage of the integer
1852   // compare+branch instructions. i.e.:
1853   // (select (setcc lhs, rhs, cc), truev, falsev)
1854   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
1855   if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
1856       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
1857     SDValue LHS = CondV.getOperand(0);
1858     SDValue RHS = CondV.getOperand(1);
1859     auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
1860     ISD::CondCode CCVal = CC->get();
1861 
1862     normaliseSetCC(LHS, RHS, CCVal);
1863 
1864     SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
1865     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
1866     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
1867   }
1868 
1869   // Otherwise:
1870   // (select condv, truev, falsev)
1871   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
1872   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
1873   SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
1874 
1875   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
1876 
1877   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
1878 }
1879 
1880 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1881   MachineFunction &MF = DAG.getMachineFunction();
1882   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
1883 
1884   SDLoc DL(Op);
1885   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1886                                  getPointerTy(MF.getDataLayout()));
1887 
1888   // vastart just stores the address of the VarArgsFrameIndex slot into the
1889   // memory location argument.
1890   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1891   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1892                       MachinePointerInfo(SV));
1893 }
1894 
1895 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
1896                                             SelectionDAG &DAG) const {
1897   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
1898   MachineFunction &MF = DAG.getMachineFunction();
1899   MachineFrameInfo &MFI = MF.getFrameInfo();
1900   MFI.setFrameAddressIsTaken(true);
1901   Register FrameReg = RI.getFrameRegister(MF);
1902   int XLenInBytes = Subtarget.getXLen() / 8;
1903 
1904   EVT VT = Op.getValueType();
1905   SDLoc DL(Op);
1906   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
1907   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1908   while (Depth--) {
1909     int Offset = -(XLenInBytes * 2);
1910     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
1911                               DAG.getIntPtrConstant(Offset, DL));
1912     FrameAddr =
1913         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
1914   }
1915   return FrameAddr;
1916 }
1917 
1918 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
1919                                              SelectionDAG &DAG) const {
1920   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
1921   MachineFunction &MF = DAG.getMachineFunction();
1922   MachineFrameInfo &MFI = MF.getFrameInfo();
1923   MFI.setReturnAddressIsTaken(true);
1924   MVT XLenVT = Subtarget.getXLenVT();
1925   int XLenInBytes = Subtarget.getXLen() / 8;
1926 
1927   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1928     return SDValue();
1929 
1930   EVT VT = Op.getValueType();
1931   SDLoc DL(Op);
1932   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1933   if (Depth) {
1934     int Off = -XLenInBytes;
1935     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
1936     SDValue Offset = DAG.getConstant(Off, DL, VT);
1937     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
1938                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
1939                        MachinePointerInfo());
1940   }
1941 
1942   // Return the value of the return address register, marking it an implicit
1943   // live-in.
1944   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
1945   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
1946 }
1947 
1948 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
1949                                                  SelectionDAG &DAG) const {
1950   SDLoc DL(Op);
1951   SDValue Lo = Op.getOperand(0);
1952   SDValue Hi = Op.getOperand(1);
1953   SDValue Shamt = Op.getOperand(2);
1954   EVT VT = Lo.getValueType();
1955 
1956   // if Shamt-XLEN < 0: // Shamt < XLEN
1957   //   Lo = Lo << Shamt
1958   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
1959   // else:
1960   //   Lo = 0
1961   //   Hi = Lo << (Shamt-XLEN)
1962 
1963   SDValue Zero = DAG.getConstant(0, DL, VT);
1964   SDValue One = DAG.getConstant(1, DL, VT);
1965   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
1966   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
1967   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
1968   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
1969 
1970   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
1971   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
1972   SDValue ShiftRightLo =
1973       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
1974   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
1975   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
1976   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
1977 
1978   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
1979 
1980   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
1981   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
1982 
1983   SDValue Parts[2] = {Lo, Hi};
1984   return DAG.getMergeValues(Parts, DL);
1985 }
1986 
1987 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1988                                                   bool IsSRA) const {
1989   SDLoc DL(Op);
1990   SDValue Lo = Op.getOperand(0);
1991   SDValue Hi = Op.getOperand(1);
1992   SDValue Shamt = Op.getOperand(2);
1993   EVT VT = Lo.getValueType();
1994 
1995   // SRA expansion:
1996   //   if Shamt-XLEN < 0: // Shamt < XLEN
1997   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
1998   //     Hi = Hi >>s Shamt
1999   //   else:
2000   //     Lo = Hi >>s (Shamt-XLEN);
2001   //     Hi = Hi >>s (XLEN-1)
2002   //
2003   // SRL expansion:
2004   //   if Shamt-XLEN < 0: // Shamt < XLEN
2005   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
2006   //     Hi = Hi >>u Shamt
2007   //   else:
2008   //     Lo = Hi >>u (Shamt-XLEN);
2009   //     Hi = 0;
2010 
2011   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
2012 
2013   SDValue Zero = DAG.getConstant(0, DL, VT);
2014   SDValue One = DAG.getConstant(1, DL, VT);
2015   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
2016   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
2017   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
2018   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
2019 
2020   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2021   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
2022   SDValue ShiftLeftHi =
2023       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
2024   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
2025   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
2026   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
2027   SDValue HiFalse =
2028       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
2029 
2030   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
2031 
2032   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
2033   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
2034 
2035   SDValue Parts[2] = {Lo, Hi};
2036   return DAG.getMergeValues(Parts, DL);
2037 }
2038 
2039 // Custom-lower a SPLAT_VECTOR where XLEN<SEW, as the SEW element type is
2040 // illegal (currently only vXi64 RV32).
2041 // FIXME: We could also catch non-constant sign-extended i32 values and lower
2042 // them to SPLAT_VECTOR_I64
2043 SDValue RISCVTargetLowering::lowerSPLATVECTOR(SDValue Op,
2044                                               SelectionDAG &DAG) const {
2045   SDLoc DL(Op);
2046   EVT VecVT = Op.getValueType();
2047   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
2048          "Unexpected SPLAT_VECTOR lowering");
2049   SDValue SplatVal = Op.getOperand(0);
2050 
2051   // If we can prove that the value is a sign-extended 32-bit value, lower this
2052   // as a custom node in order to try and match RVV vector/scalar instructions.
2053   if (auto *CVal = dyn_cast<ConstantSDNode>(SplatVal)) {
2054     if (isInt<32>(CVal->getSExtValue()))
2055       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT,
2056                          DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32));
2057   }
2058 
2059   if (SplatVal.getOpcode() == ISD::SIGN_EXTEND &&
2060       SplatVal.getOperand(0).getValueType() == MVT::i32) {
2061     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT,
2062                        SplatVal.getOperand(0));
2063   }
2064 
2065   // Else, on RV32 we lower an i64-element SPLAT_VECTOR thus, being careful not
2066   // to accidentally sign-extend the 32-bit halves to the e64 SEW:
2067   // vmv.v.x vX, hi
2068   // vsll.vx vX, vX, /*32*/
2069   // vmv.v.x vY, lo
2070   // vsll.vx vY, vY, /*32*/
2071   // vsrl.vx vY, vY, /*32*/
2072   // vor.vv vX, vX, vY
2073   SDValue One = DAG.getConstant(1, DL, MVT::i32);
2074   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2075   SDValue ThirtyTwoV = DAG.getConstant(32, DL, VecVT);
2076   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, Zero);
2077   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, One);
2078 
2079   Lo = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
2080   Lo = DAG.getNode(ISD::SHL, DL, VecVT, Lo, ThirtyTwoV);
2081   Lo = DAG.getNode(ISD::SRL, DL, VecVT, Lo, ThirtyTwoV);
2082 
2083   if (isNullConstant(Hi))
2084     return Lo;
2085 
2086   Hi = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Hi);
2087   Hi = DAG.getNode(ISD::SHL, DL, VecVT, Hi, ThirtyTwoV);
2088 
2089   return DAG.getNode(ISD::OR, DL, VecVT, Lo, Hi);
2090 }
2091 
2092 // Custom-lower extensions from mask vectors by using a vselect either with 1
2093 // for zero/any-extension or -1 for sign-extension:
2094 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
2095 // Note that any-extension is lowered identically to zero-extension.
2096 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
2097                                                 int64_t ExtTrueVal) const {
2098   SDLoc DL(Op);
2099   MVT VecVT = Op.getSimpleValueType();
2100   SDValue Src = Op.getOperand(0);
2101   // Only custom-lower extensions from mask types
2102   assert(Src.getValueType().isVector() &&
2103          Src.getValueType().getVectorElementType() == MVT::i1);
2104 
2105   MVT XLenVT = Subtarget.getXLenVT();
2106   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
2107   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
2108 
2109   if (VecVT.isScalableVector()) {
2110     // Be careful not to introduce illegal scalar types at this stage, and be
2111     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
2112     // illegal and must be expanded. Since we know that the constants are
2113     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
2114     bool IsRV32E64 =
2115         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
2116 
2117     if (!IsRV32E64) {
2118       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
2119       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
2120     } else {
2121       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
2122       SplatTrueVal =
2123           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
2124     }
2125 
2126     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
2127   }
2128 
2129   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
2130   MVT I1ContainerVT =
2131       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
2132 
2133   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
2134 
2135   SDValue Mask, VL;
2136   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
2137 
2138   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
2139   SplatTrueVal =
2140       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
2141   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
2142                                SplatTrueVal, SplatZero, VL);
2143 
2144   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
2145 }
2146 
2147 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
2148     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
2149   MVT ExtVT = Op.getSimpleValueType();
2150   // Only custom-lower extensions from fixed-length vector types.
2151   if (!ExtVT.isFixedLengthVector())
2152     return Op;
2153   MVT VT = Op.getOperand(0).getSimpleValueType();
2154   // Grab the canonical container type for the extended type. Infer the smaller
2155   // type from that to ensure the same number of vector elements, as we know
2156   // the LMUL will be sufficient to hold the smaller type.
2157   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
2158   // Get the extended container type manually to ensure the same number of
2159   // vector elements between source and dest.
2160   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
2161                                      ContainerExtVT.getVectorElementCount());
2162 
2163   SDValue Op1 =
2164       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
2165 
2166   SDLoc DL(Op);
2167   SDValue Mask, VL;
2168   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2169 
2170   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
2171 
2172   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
2173 }
2174 
2175 // Custom-lower truncations from vectors to mask vectors by using a mask and a
2176 // setcc operation:
2177 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
2178 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
2179                                                   SelectionDAG &DAG) const {
2180   SDLoc DL(Op);
2181   EVT MaskVT = Op.getValueType();
2182   // Only expect to custom-lower truncations to mask types
2183   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
2184          "Unexpected type for vector mask lowering");
2185   SDValue Src = Op.getOperand(0);
2186   MVT VecVT = Src.getSimpleValueType();
2187 
2188   // If this is a fixed vector, we need to convert it to a scalable vector.
2189   MVT ContainerVT = VecVT;
2190   if (VecVT.isFixedLengthVector()) {
2191     ContainerVT = getContainerForFixedLengthVector(VecVT);
2192     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2193   }
2194 
2195   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
2196   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
2197 
2198   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
2199   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
2200 
2201   if (VecVT.isScalableVector()) {
2202     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
2203     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
2204   }
2205 
2206   SDValue Mask, VL;
2207   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
2208 
2209   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2210   SDValue Trunc =
2211       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
2212   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
2213                       DAG.getCondCode(ISD::SETNE), Mask, VL);
2214   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
2215 }
2216 
2217 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2218                                                     SelectionDAG &DAG) const {
2219   SDLoc DL(Op);
2220   MVT VecVT = Op.getSimpleValueType();
2221   SDValue Vec = Op.getOperand(0);
2222   SDValue Val = Op.getOperand(1);
2223   SDValue Idx = Op.getOperand(2);
2224 
2225   MVT ContainerVT = VecVT;
2226   // If the operand is a fixed-length vector, convert to a scalable one.
2227   if (VecVT.isFixedLengthVector()) {
2228     ContainerVT = getContainerForFixedLengthVector(VecVT);
2229     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2230   }
2231 
2232   SDValue Mask, VL;
2233   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
2234 
2235   // Custom-legalize INSERT_VECTOR_ELT where XLEN>=SEW, so that the vector is
2236   // first slid down into position, the value is inserted into the first
2237   // position, and the vector is slid back up. We do this to simplify patterns.
2238   //   (slideup vec, (insertelt (slidedown impdef, vec, idx), val, 0), idx),
2239   if (Subtarget.is64Bit() || Val.getValueType() != MVT::i64) {
2240     if (isNullConstant(Idx))
2241       return DAG.getNode(RISCVISD::VMV_S_XF_VL, DL, ContainerVT, Vec, Val, VL);
2242     SDValue Slidedown =
2243         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2244                     DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
2245     SDValue InsertElt0 =
2246         DAG.getNode(RISCVISD::VMV_S_XF_VL, DL, ContainerVT, Slidedown, Val, VL);
2247     return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, InsertElt0,
2248                        Idx, Mask, VL);
2249   }
2250 
2251   // Custom-legalize INSERT_VECTOR_ELT where XLEN<SEW, as the SEW element type
2252   // is illegal (currently only vXi64 RV32).
2253   // Since there is no easy way of getting a single element into a vector when
2254   // XLEN<SEW, we lower the operation to the following sequence:
2255   //   splat      vVal, rVal
2256   //   vid.v      vVid
2257   //   vmseq.vx   mMask, vVid, rIdx
2258   //   vmerge.vvm vDest, vSrc, vVal, mMask
2259   // This essentially merges the original vector with the inserted element by
2260   // using a mask whose only set bit is that corresponding to the insert
2261   // index.
2262   SDValue SplattedVal = DAG.getSplatVector(ContainerVT, DL, Val);
2263   SDValue SplattedIdx =
2264       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, Idx, VL);
2265 
2266   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2267   auto SetCCVT =
2268       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ContainerVT);
2269   SDValue SelectCond =
2270       DAG.getNode(RISCVISD::SETCC_VL, DL, SetCCVT, VID, SplattedIdx,
2271                   DAG.getCondCode(ISD::SETEQ), Mask, VL);
2272   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT,
2273                                SelectCond, SplattedVal, Vec, VL);
2274   if (!VecVT.isFixedLengthVector())
2275     return Select;
2276   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
2277 }
2278 
2279 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
2280 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
2281 // types this is done using VMV_X_S to allow us to glean information about the
2282 // sign bits of the result.
2283 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2284                                                      SelectionDAG &DAG) const {
2285   SDLoc DL(Op);
2286   SDValue Idx = Op.getOperand(1);
2287   SDValue Vec = Op.getOperand(0);
2288   EVT EltVT = Op.getValueType();
2289   MVT VecVT = Vec.getSimpleValueType();
2290   MVT XLenVT = Subtarget.getXLenVT();
2291 
2292   // If this is a fixed vector, we need to convert it to a scalable vector.
2293   MVT ContainerVT = VecVT;
2294   if (VecVT.isFixedLengthVector()) {
2295     ContainerVT = getContainerForFixedLengthVector(VecVT);
2296     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2297   }
2298 
2299   // If the index is 0, the vector is already in the right position.
2300   if (!isNullConstant(Idx)) {
2301     // Use a VL of 1 to avoid processing more elements than we need.
2302     SDValue VL = DAG.getConstant(1, DL, XLenVT);
2303     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
2304     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2305     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2306                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
2307   }
2308 
2309   if (!EltVT.isInteger()) {
2310     // Floating-point extracts are handled in TableGen.
2311     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
2312                        DAG.getConstant(0, DL, XLenVT));
2313   }
2314 
2315   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
2316   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
2317 }
2318 
2319 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2320                                                      SelectionDAG &DAG) const {
2321   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2322   SDLoc DL(Op);
2323 
2324   if (Subtarget.hasStdExtV()) {
2325     // Some RVV intrinsics may claim that they want an integer operand to be
2326     // extended.
2327     if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
2328             RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) {
2329       if (II->ExtendedOperand) {
2330         assert(II->ExtendedOperand < Op.getNumOperands());
2331         SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
2332         SDValue &ScalarOp = Operands[II->ExtendedOperand];
2333         EVT OpVT = ScalarOp.getValueType();
2334         if (OpVT == MVT::i8 || OpVT == MVT::i16 ||
2335             (OpVT == MVT::i32 && Subtarget.is64Bit())) {
2336           // If the operand is a constant, sign extend to increase our chances
2337           // of being able to use a .vi instruction. ANY_EXTEND would become a
2338           // a zero extend and the simm5 check in isel would fail.
2339           // FIXME: Should we ignore the upper bits in isel instead?
2340           unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND
2341                                                           : ISD::ANY_EXTEND;
2342           ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp);
2343           return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
2344                              Operands);
2345         }
2346       }
2347     }
2348   }
2349 
2350   switch (IntNo) {
2351   default:
2352     return SDValue();    // Don't custom lower most intrinsics.
2353   case Intrinsic::thread_pointer: {
2354     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2355     return DAG.getRegister(RISCV::X4, PtrVT);
2356   }
2357   case Intrinsic::riscv_vmv_x_s:
2358     assert(Op.getValueType() == Subtarget.getXLenVT() && "Unexpected VT!");
2359     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
2360                        Op.getOperand(1));
2361   case Intrinsic::riscv_vmv_v_x: {
2362     SDValue Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(),
2363                                  Op.getOperand(1));
2364     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, Op.getValueType(),
2365                        Scalar, Op.getOperand(2));
2366   }
2367   case Intrinsic::riscv_vfmv_v_f:
2368     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
2369                        Op.getOperand(1), Op.getOperand(2));
2370   }
2371 }
2372 
2373 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2374                                                     SelectionDAG &DAG) const {
2375   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2376   SDLoc DL(Op);
2377 
2378   if (Subtarget.hasStdExtV()) {
2379     // Some RVV intrinsics may claim that they want an integer operand to be
2380     // extended.
2381     if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
2382             RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) {
2383       if (II->ExtendedOperand) {
2384         // The operands start from the second argument in INTRINSIC_W_CHAIN.
2385         unsigned ExtendOp = II->ExtendedOperand + 1;
2386         assert(ExtendOp < Op.getNumOperands());
2387         SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
2388         SDValue &ScalarOp = Operands[ExtendOp];
2389         EVT OpVT = ScalarOp.getValueType();
2390         if (OpVT == MVT::i8 || OpVT == MVT::i16 ||
2391             (OpVT == MVT::i32 && Subtarget.is64Bit())) {
2392           // If the operand is a constant, sign extend to increase our chances
2393           // of being able to use a .vi instruction. ANY_EXTEND would become a
2394           // a zero extend and the simm5 check in isel would fail.
2395           // FIXME: Should we ignore the upper bits in isel instead?
2396           unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND
2397                                                           : ISD::ANY_EXTEND;
2398           ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp);
2399           return DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, Op->getVTList(),
2400                              Operands);
2401         }
2402       }
2403     }
2404   }
2405 
2406   return SDValue(); // Don't custom lower most intrinsics.
2407 }
2408 
2409 static MVT getLMUL1VT(MVT VT) {
2410   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
2411          "Unexpected vector MVT");
2412   return MVT::getScalableVectorVT(
2413       VT.getVectorElementType(),
2414       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
2415 }
2416 
2417 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
2418   switch (ISDOpcode) {
2419   default:
2420     llvm_unreachable("Unhandled reduction");
2421   case ISD::VECREDUCE_ADD:
2422     return RISCVISD::VECREDUCE_ADD_VL;
2423   case ISD::VECREDUCE_UMAX:
2424     return RISCVISD::VECREDUCE_UMAX_VL;
2425   case ISD::VECREDUCE_SMAX:
2426     return RISCVISD::VECREDUCE_SMAX_VL;
2427   case ISD::VECREDUCE_UMIN:
2428     return RISCVISD::VECREDUCE_UMIN_VL;
2429   case ISD::VECREDUCE_SMIN:
2430     return RISCVISD::VECREDUCE_SMIN_VL;
2431   case ISD::VECREDUCE_AND:
2432     return RISCVISD::VECREDUCE_AND_VL;
2433   case ISD::VECREDUCE_OR:
2434     return RISCVISD::VECREDUCE_OR_VL;
2435   case ISD::VECREDUCE_XOR:
2436     return RISCVISD::VECREDUCE_XOR_VL;
2437   }
2438 }
2439 
2440 // Take a (supported) standard ISD reduction opcode and transform it to a RISCV
2441 // reduction opcode. Note that this returns a vector type, which must be
2442 // further processed to access the scalar result in element 0.
2443 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
2444                                             SelectionDAG &DAG) const {
2445   SDLoc DL(Op);
2446   SDValue Vec = Op.getOperand(0);
2447   EVT VecEVT = Vec.getValueType();
2448 
2449   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
2450 
2451   // Due to ordering in legalize types we may have a vector type that needs to
2452   // be split. Do that manually so we can get down to a legal type.
2453   while (getTypeAction(*DAG.getContext(), VecEVT) ==
2454          TargetLowering::TypeSplitVector) {
2455     SDValue Lo, Hi;
2456     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
2457     VecEVT = Lo.getValueType();
2458     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
2459   }
2460 
2461   // TODO: The type may need to be widened rather than split. Or widened before
2462   // it can be split.
2463   if (!isTypeLegal(VecEVT))
2464     return SDValue();
2465 
2466   MVT VecVT = VecEVT.getSimpleVT();
2467   MVT VecEltVT = VecVT.getVectorElementType();
2468   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
2469 
2470   MVT ContainerVT = VecVT;
2471   if (VecVT.isFixedLengthVector()) {
2472     ContainerVT = getContainerForFixedLengthVector(VecVT);
2473     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2474   }
2475 
2476   MVT M1VT = getLMUL1VT(ContainerVT);
2477 
2478   SDValue Mask, VL;
2479   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
2480 
2481   // FIXME: This is a VLMAX splat which might be too large and can prevent
2482   // vsetvli removal.
2483   SDValue NeutralElem =
2484       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
2485   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
2486   SDValue Reduction =
2487       DAG.getNode(RVVOpcode, DL, M1VT, Vec, IdentitySplat, Mask, VL);
2488   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
2489                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
2490   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
2491 }
2492 
2493 // Given a reduction op, this function returns the matching reduction opcode,
2494 // the vector SDValue and the scalar SDValue required to lower this to a
2495 // RISCVISD node.
2496 static std::tuple<unsigned, SDValue, SDValue>
2497 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
2498   SDLoc DL(Op);
2499   switch (Op.getOpcode()) {
2500   default:
2501     llvm_unreachable("Unhandled reduction");
2502   case ISD::VECREDUCE_FADD:
2503     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
2504                            DAG.getConstantFP(0.0, DL, EltVT));
2505   case ISD::VECREDUCE_SEQ_FADD:
2506     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
2507                            Op.getOperand(0));
2508   }
2509 }
2510 
2511 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
2512                                               SelectionDAG &DAG) const {
2513   SDLoc DL(Op);
2514   MVT VecEltVT = Op.getSimpleValueType();
2515 
2516   unsigned RVVOpcode;
2517   SDValue VectorVal, ScalarVal;
2518   std::tie(RVVOpcode, VectorVal, ScalarVal) =
2519       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
2520   MVT VecVT = VectorVal.getSimpleValueType();
2521 
2522   MVT ContainerVT = VecVT;
2523   if (VecVT.isFixedLengthVector()) {
2524     ContainerVT = getContainerForFixedLengthVector(VecVT);
2525     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
2526   }
2527 
2528   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
2529 
2530   SDValue Mask, VL;
2531   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
2532 
2533   // FIXME: This is a VLMAX splat which might be too large and can prevent
2534   // vsetvli removal.
2535   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
2536   SDValue Reduction =
2537       DAG.getNode(RVVOpcode, DL, M1VT, VectorVal, ScalarSplat, Mask, VL);
2538   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
2539                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
2540 }
2541 
2542 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
2543                                                    SelectionDAG &DAG) const {
2544   SDValue Vec = Op.getOperand(0);
2545   SDValue SubVec = Op.getOperand(1);
2546   MVT VecVT = Vec.getSimpleValueType();
2547   MVT SubVecVT = SubVec.getSimpleValueType();
2548 
2549   SDLoc DL(Op);
2550   MVT XLenVT = Subtarget.getXLenVT();
2551   unsigned OrigIdx = Op.getConstantOperandVal(2);
2552   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
2553 
2554   // We don't have the ability to slide mask vectors up indexed by their i1
2555   // elements; the smallest we can do is i8. Often we are able to bitcast to
2556   // equivalent i8 vectors. Note that when inserting a fixed-length vector
2557   // into a scalable one, we might not necessarily have enough scalable
2558   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
2559   if (SubVecVT.getVectorElementType() == MVT::i1 &&
2560       (OrigIdx != 0 || !Vec.isUndef())) {
2561     if (VecVT.getVectorMinNumElements() >= 8 &&
2562         SubVecVT.getVectorMinNumElements() >= 8) {
2563       assert(OrigIdx % 8 == 0 && "Invalid index");
2564       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
2565              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
2566              "Unexpected mask vector lowering");
2567       OrigIdx /= 8;
2568       SubVecVT =
2569           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
2570                            SubVecVT.isScalableVector());
2571       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
2572                                VecVT.isScalableVector());
2573       Vec = DAG.getBitcast(VecVT, Vec);
2574       SubVec = DAG.getBitcast(SubVecVT, SubVec);
2575     } else {
2576       // We can't slide this mask vector up indexed by its i1 elements.
2577       // This poses a problem when we wish to insert a scalable vector which
2578       // can't be re-expressed as a larger type. Just choose the slow path and
2579       // extend to a larger type, then truncate back down.
2580       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
2581       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
2582       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
2583       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
2584       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
2585                         Op.getOperand(2));
2586       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
2587       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
2588     }
2589   }
2590 
2591   // If the subvector vector is a fixed-length type, we cannot use subregister
2592   // manipulation to simplify the codegen; we don't know which register of a
2593   // LMUL group contains the specific subvector as we only know the minimum
2594   // register size. Therefore we must slide the vector group up the full
2595   // amount.
2596   if (SubVecVT.isFixedLengthVector()) {
2597     if (OrigIdx == 0 && Vec.isUndef())
2598       return Op;
2599     MVT ContainerVT = VecVT;
2600     if (VecVT.isFixedLengthVector()) {
2601       ContainerVT = getContainerForFixedLengthVector(VecVT);
2602       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2603     }
2604     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
2605                          DAG.getUNDEF(ContainerVT), SubVec,
2606                          DAG.getConstant(0, DL, XLenVT));
2607     SDValue Mask =
2608         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
2609     // Set the vector length to only the number of elements we care about. Note
2610     // that for slideup this includes the offset.
2611     SDValue VL =
2612         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
2613     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
2614     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
2615                                   SubVec, SlideupAmt, Mask, VL);
2616     if (!VecVT.isFixedLengthVector())
2617       return Slideup;
2618     return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
2619   }
2620 
2621   unsigned SubRegIdx, RemIdx;
2622   std::tie(SubRegIdx, RemIdx) =
2623       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
2624           VecVT, SubVecVT, OrigIdx, TRI);
2625 
2626   RISCVVLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
2627   bool IsSubVecPartReg = SubVecLMUL == RISCVVLMUL::LMUL_F2 ||
2628                          SubVecLMUL == RISCVVLMUL::LMUL_F4 ||
2629                          SubVecLMUL == RISCVVLMUL::LMUL_F8;
2630 
2631   // 1. If the Idx has been completely eliminated and this subvector's size is
2632   // a vector register or a multiple thereof, or the surrounding elements are
2633   // undef, then this is a subvector insert which naturally aligns to a vector
2634   // register. These can easily be handled using subregister manipulation.
2635   // 2. If the subvector is smaller than a vector register, then the insertion
2636   // must preserve the undisturbed elements of the register. We do this by
2637   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
2638   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
2639   // subvector within the vector register, and an INSERT_SUBVECTOR of that
2640   // LMUL=1 type back into the larger vector (resolving to another subregister
2641   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
2642   // to avoid allocating a large register group to hold our subvector.
2643   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
2644     return Op;
2645 
2646   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
2647   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
2648   // (in our case undisturbed). This means we can set up a subvector insertion
2649   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
2650   // size of the subvector.
2651   MVT InterSubVT = VecVT;
2652   SDValue AlignedExtract = Vec;
2653   unsigned AlignedIdx = OrigIdx - RemIdx;
2654   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
2655     InterSubVT = getLMUL1VT(VecVT);
2656     // Extract a subvector equal to the nearest full vector register type. This
2657     // should resolve to a EXTRACT_SUBREG instruction.
2658     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
2659                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
2660   }
2661 
2662   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
2663   // For scalable vectors this must be further multiplied by vscale.
2664   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
2665 
2666   SDValue Mask, VL;
2667   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
2668 
2669   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
2670   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
2671   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
2672   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
2673 
2674   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
2675                        DAG.getUNDEF(InterSubVT), SubVec,
2676                        DAG.getConstant(0, DL, XLenVT));
2677 
2678   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
2679                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
2680 
2681   // If required, insert this subvector back into the correct vector register.
2682   // This should resolve to an INSERT_SUBREG instruction.
2683   if (VecVT.bitsGT(InterSubVT))
2684     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
2685                           DAG.getConstant(AlignedIdx, DL, XLenVT));
2686 
2687   // We might have bitcast from a mask type: cast back to the original type if
2688   // required.
2689   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
2690 }
2691 
2692 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
2693                                                     SelectionDAG &DAG) const {
2694   SDValue Vec = Op.getOperand(0);
2695   MVT SubVecVT = Op.getSimpleValueType();
2696   MVT VecVT = Vec.getSimpleValueType();
2697 
2698   SDLoc DL(Op);
2699   MVT XLenVT = Subtarget.getXLenVT();
2700   unsigned OrigIdx = Op.getConstantOperandVal(1);
2701   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
2702 
2703   // We don't have the ability to slide mask vectors down indexed by their i1
2704   // elements; the smallest we can do is i8. Often we are able to bitcast to
2705   // equivalent i8 vectors. Note that when extracting a fixed-length vector
2706   // from a scalable one, we might not necessarily have enough scalable
2707   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
2708   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
2709     if (VecVT.getVectorMinNumElements() >= 8 &&
2710         SubVecVT.getVectorMinNumElements() >= 8) {
2711       assert(OrigIdx % 8 == 0 && "Invalid index");
2712       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
2713              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
2714              "Unexpected mask vector lowering");
2715       OrigIdx /= 8;
2716       SubVecVT =
2717           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
2718                            SubVecVT.isScalableVector());
2719       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
2720                                VecVT.isScalableVector());
2721       Vec = DAG.getBitcast(VecVT, Vec);
2722     } else {
2723       // We can't slide this mask vector down, indexed by its i1 elements.
2724       // This poses a problem when we wish to extract a scalable vector which
2725       // can't be re-expressed as a larger type. Just choose the slow path and
2726       // extend to a larger type, then truncate back down.
2727       // TODO: We could probably improve this when extracting certain fixed
2728       // from fixed, where we can extract as i8 and shift the correct element
2729       // right to reach the desired subvector?
2730       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
2731       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
2732       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
2733       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
2734                         Op.getOperand(1));
2735       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
2736       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
2737     }
2738   }
2739 
2740   // If the subvector vector is a fixed-length type, we cannot use subregister
2741   // manipulation to simplify the codegen; we don't know which register of a
2742   // LMUL group contains the specific subvector as we only know the minimum
2743   // register size. Therefore we must slide the vector group down the full
2744   // amount.
2745   if (SubVecVT.isFixedLengthVector()) {
2746     // With an index of 0 this is a cast-like subvector, which can be performed
2747     // with subregister operations.
2748     if (OrigIdx == 0)
2749       return Op;
2750     MVT ContainerVT = VecVT;
2751     if (VecVT.isFixedLengthVector()) {
2752       ContainerVT = getContainerForFixedLengthVector(VecVT);
2753       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2754     }
2755     SDValue Mask =
2756         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
2757     // Set the vector length to only the number of elements we care about. This
2758     // avoids sliding down elements we're going to discard straight away.
2759     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
2760     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
2761     SDValue Slidedown =
2762         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2763                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
2764     // Now we can use a cast-like subvector extract to get the result.
2765     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
2766                        DAG.getConstant(0, DL, XLenVT));
2767   }
2768 
2769   unsigned SubRegIdx, RemIdx;
2770   std::tie(SubRegIdx, RemIdx) =
2771       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
2772           VecVT, SubVecVT, OrigIdx, TRI);
2773 
2774   // If the Idx has been completely eliminated then this is a subvector extract
2775   // which naturally aligns to a vector register. These can easily be handled
2776   // using subregister manipulation.
2777   if (RemIdx == 0)
2778     return Op;
2779 
2780   // Else we must shift our vector register directly to extract the subvector.
2781   // Do this using VSLIDEDOWN.
2782 
2783   // If the vector type is an LMUL-group type, extract a subvector equal to the
2784   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
2785   // instruction.
2786   MVT InterSubVT = VecVT;
2787   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
2788     InterSubVT = getLMUL1VT(VecVT);
2789     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
2790                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
2791   }
2792 
2793   // Slide this vector register down by the desired number of elements in order
2794   // to place the desired subvector starting at element 0.
2795   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
2796   // For scalable vectors this must be further multiplied by vscale.
2797   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
2798 
2799   SDValue Mask, VL;
2800   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
2801   SDValue Slidedown =
2802       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
2803                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
2804 
2805   // Now the vector is in the right position, extract our final subvector. This
2806   // should resolve to a COPY.
2807   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
2808                           DAG.getConstant(0, DL, XLenVT));
2809 
2810   // We might have bitcast from a mask type: cast back to the original type if
2811   // required.
2812   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
2813 }
2814 
2815 // Implement vector_reverse using vrgather.vv with indices determined by
2816 // subtracting the id of each element from (VLMAX-1). This will convert
2817 // the indices like so:
2818 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
2819 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
2820 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
2821                                                  SelectionDAG &DAG) const {
2822   SDLoc DL(Op);
2823   MVT VecVT = Op.getSimpleValueType();
2824   unsigned EltSize = VecVT.getScalarSizeInBits();
2825   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
2826 
2827   unsigned MaxVLMAX = 0;
2828   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
2829   if (VectorBitsMax != 0)
2830     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
2831 
2832   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
2833   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
2834 
2835   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
2836   // to use vrgatherei16.vv.
2837   // TODO: It's also possible to use vrgatherei16.vv for other types to
2838   // decrease register width for the index calculation.
2839   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
2840     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
2841     // Reverse each half, then reassemble them in reverse order.
2842     // NOTE: It's also possible that after splitting that VLMAX no longer
2843     // requires vrgatherei16.vv.
2844     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
2845       SDValue Lo, Hi;
2846       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
2847       EVT LoVT, HiVT;
2848       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
2849       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
2850       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
2851       // Reassemble the low and high pieces reversed.
2852       // FIXME: This is a CONCAT_VECTORS.
2853       SDValue Res =
2854           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
2855                       DAG.getIntPtrConstant(0, DL));
2856       return DAG.getNode(
2857           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
2858           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
2859     }
2860 
2861     // Just promote the int type to i16 which will double the LMUL.
2862     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
2863     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
2864   }
2865 
2866   MVT XLenVT = Subtarget.getXLenVT();
2867   SDValue Mask, VL;
2868   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
2869 
2870   // Calculate VLMAX-1 for the desired SEW.
2871   unsigned MinElts = VecVT.getVectorMinNumElements();
2872   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
2873                               DAG.getConstant(MinElts, DL, XLenVT));
2874   SDValue VLMinus1 =
2875       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
2876 
2877   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
2878   bool IsRV32E64 =
2879       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
2880   SDValue SplatVL;
2881   if (!IsRV32E64)
2882     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
2883   else
2884     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
2885 
2886   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
2887   SDValue Indices =
2888       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
2889 
2890   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
2891 }
2892 
2893 SDValue
2894 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
2895                                                      SelectionDAG &DAG) const {
2896   auto *Load = cast<LoadSDNode>(Op);
2897 
2898   SDLoc DL(Op);
2899   MVT VT = Op.getSimpleValueType();
2900   MVT ContainerVT = getContainerForFixedLengthVector(VT);
2901 
2902   SDValue VL =
2903       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
2904 
2905   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2906   SDValue NewLoad = DAG.getMemIntrinsicNode(
2907       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
2908       Load->getMemoryVT(), Load->getMemOperand());
2909 
2910   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2911   return DAG.getMergeValues({Result, Load->getChain()}, DL);
2912 }
2913 
2914 SDValue
2915 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
2916                                                       SelectionDAG &DAG) const {
2917   auto *Store = cast<StoreSDNode>(Op);
2918 
2919   SDLoc DL(Op);
2920   MVT VT = Store->getValue().getSimpleValueType();
2921 
2922   // FIXME: We probably need to zero any extra bits in a byte for mask stores.
2923   // This is tricky to do.
2924 
2925   MVT ContainerVT = getContainerForFixedLengthVector(VT);
2926 
2927   SDValue VL =
2928       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
2929 
2930   SDValue NewValue =
2931       convertToScalableVector(ContainerVT, Store->getValue(), DAG, Subtarget);
2932   return DAG.getMemIntrinsicNode(
2933       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
2934       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
2935       Store->getMemoryVT(), Store->getMemOperand());
2936 }
2937 
2938 SDValue
2939 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
2940                                                       SelectionDAG &DAG) const {
2941   MVT InVT = Op.getOperand(0).getSimpleValueType();
2942   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
2943 
2944   MVT VT = Op.getSimpleValueType();
2945 
2946   SDValue Op1 =
2947       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
2948   SDValue Op2 =
2949       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
2950 
2951   SDLoc DL(Op);
2952   SDValue VL =
2953       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
2954 
2955   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2956 
2957   bool Invert = false;
2958   Optional<unsigned> LogicOpc;
2959   if (ContainerVT.isFloatingPoint()) {
2960     bool Swap = false;
2961     switch (CC) {
2962     default:
2963       break;
2964     case ISD::SETULE:
2965     case ISD::SETULT:
2966       Swap = true;
2967       LLVM_FALLTHROUGH;
2968     case ISD::SETUGE:
2969     case ISD::SETUGT:
2970       CC = getSetCCInverse(CC, ContainerVT);
2971       Invert = true;
2972       break;
2973     case ISD::SETOGE:
2974     case ISD::SETOGT:
2975     case ISD::SETGE:
2976     case ISD::SETGT:
2977       Swap = true;
2978       break;
2979     case ISD::SETUEQ:
2980       // Use !((OLT Op1, Op2) || (OLT Op2, Op1))
2981       Invert = true;
2982       LogicOpc = RISCVISD::VMOR_VL;
2983       CC = ISD::SETOLT;
2984       break;
2985     case ISD::SETONE:
2986       // Use ((OLT Op1, Op2) || (OLT Op2, Op1))
2987       LogicOpc = RISCVISD::VMOR_VL;
2988       CC = ISD::SETOLT;
2989       break;
2990     case ISD::SETO:
2991       // Use (OEQ Op1, Op1) && (OEQ Op2, Op2)
2992       LogicOpc = RISCVISD::VMAND_VL;
2993       CC = ISD::SETOEQ;
2994       break;
2995     case ISD::SETUO:
2996       // Use (UNE Op1, Op1) || (UNE Op2, Op2)
2997       LogicOpc = RISCVISD::VMOR_VL;
2998       CC = ISD::SETUNE;
2999       break;
3000     }
3001 
3002     if (Swap) {
3003       CC = getSetCCSwappedOperands(CC);
3004       std::swap(Op1, Op2);
3005     }
3006   }
3007 
3008   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3009   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3010 
3011   // There are 3 cases we need to emit.
3012   // 1. For (OEQ Op1, Op1) && (OEQ Op2, Op2) or (UNE Op1, Op1) || (UNE Op2, Op2)
3013   //    we need to compare each operand with itself.
3014   // 2. For (OLT Op1, Op2) || (OLT Op2, Op1) we need to compare Op1 and Op2 in
3015   //    both orders.
3016   // 3. For any other case we just need one compare with Op1 and Op2.
3017   SDValue Cmp;
3018   if (LogicOpc && (CC == ISD::SETOEQ || CC == ISD::SETUNE)) {
3019     Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op1,
3020                       DAG.getCondCode(CC), Mask, VL);
3021     SDValue Cmp2 = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op2, Op2,
3022                                DAG.getCondCode(CC), Mask, VL);
3023     Cmp = DAG.getNode(*LogicOpc, DL, MaskVT, Cmp, Cmp2, VL);
3024   } else {
3025     Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
3026                       DAG.getCondCode(CC), Mask, VL);
3027     if (LogicOpc) {
3028       SDValue Cmp2 = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op2, Op1,
3029                                  DAG.getCondCode(CC), Mask, VL);
3030       Cmp = DAG.getNode(*LogicOpc, DL, MaskVT, Cmp, Cmp2, VL);
3031     }
3032   }
3033 
3034   if (Invert) {
3035     SDValue AllOnes = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3036     Cmp = DAG.getNode(RISCVISD::VMXOR_VL, DL, MaskVT, Cmp, AllOnes, VL);
3037   }
3038 
3039   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
3040 }
3041 
3042 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
3043     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
3044   MVT VT = Op.getSimpleValueType();
3045 
3046   if (VT.getVectorElementType() == MVT::i1)
3047     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
3048 
3049   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
3050 }
3051 
3052 // Lower vector ABS to smax(X, sub(0, X)).
3053 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
3054   SDLoc DL(Op);
3055   MVT VT = Op.getSimpleValueType();
3056   SDValue X = Op.getOperand(0);
3057 
3058   // For scalable vectors we just need to deal with i64 on RV32 since the
3059   // default expansion crashes in getConstant.
3060   if (VT.isScalableVector()) {
3061     assert(!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64 &&
3062            "Unexpected custom lowering!");
3063     SDValue SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT,
3064                                     DAG.getConstant(0, DL, MVT::i32));
3065     SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, SplatZero, X);
3066     return DAG.getNode(ISD::SMAX, DL, VT, X, NegX);
3067   }
3068 
3069   assert(VT.isFixedLengthVector() && "Unexpected type");
3070 
3071   MVT ContainerVT =
3072       RISCVTargetLowering::getContainerForFixedLengthVector(DAG, VT, Subtarget);
3073   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
3074 
3075   SDValue Mask, VL;
3076   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3077 
3078   SDValue SplatZero =
3079       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
3080                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
3081   SDValue NegX =
3082       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
3083   SDValue Max =
3084       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
3085 
3086   return convertFromScalableVector(VT, Max, DAG, Subtarget);
3087 }
3088 
3089 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
3090     SDValue Op, SelectionDAG &DAG) const {
3091   MVT VT = Op.getSimpleValueType();
3092   MVT ContainerVT = getContainerForFixedLengthVector(VT);
3093 
3094   MVT I1ContainerVT =
3095       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3096 
3097   SDValue CC =
3098       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
3099   SDValue Op1 =
3100       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
3101   SDValue Op2 =
3102       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
3103 
3104   SDLoc DL(Op);
3105   SDValue Mask, VL;
3106   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3107 
3108   SDValue Select =
3109       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
3110 
3111   return convertFromScalableVector(VT, Select, DAG, Subtarget);
3112 }
3113 
3114 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
3115                                                unsigned NewOpc,
3116                                                bool HasMask) const {
3117   MVT VT = Op.getSimpleValueType();
3118   assert(useRVVForFixedLengthVectorVT(VT) &&
3119          "Only expected to lower fixed length vector operation!");
3120   MVT ContainerVT = getContainerForFixedLengthVector(VT);
3121 
3122   // Create list of operands by converting existing ones to scalable types.
3123   SmallVector<SDValue, 6> Ops;
3124   for (const SDValue &V : Op->op_values()) {
3125     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
3126 
3127     // Pass through non-vector operands.
3128     if (!V.getValueType().isVector()) {
3129       Ops.push_back(V);
3130       continue;
3131     }
3132 
3133     // "cast" fixed length vector to a scalable vector.
3134     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
3135            "Only fixed length vectors are supported!");
3136     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
3137   }
3138 
3139   SDLoc DL(Op);
3140   SDValue Mask, VL;
3141   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3142   if (HasMask)
3143     Ops.push_back(Mask);
3144   Ops.push_back(VL);
3145 
3146   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
3147   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
3148 }
3149 
3150 // Returns the opcode of the target-specific SDNode that implements the 32-bit
3151 // form of the given Opcode.
3152 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
3153   switch (Opcode) {
3154   default:
3155     llvm_unreachable("Unexpected opcode");
3156   case ISD::SHL:
3157     return RISCVISD::SLLW;
3158   case ISD::SRA:
3159     return RISCVISD::SRAW;
3160   case ISD::SRL:
3161     return RISCVISD::SRLW;
3162   case ISD::SDIV:
3163     return RISCVISD::DIVW;
3164   case ISD::UDIV:
3165     return RISCVISD::DIVUW;
3166   case ISD::UREM:
3167     return RISCVISD::REMUW;
3168   case ISD::ROTL:
3169     return RISCVISD::ROLW;
3170   case ISD::ROTR:
3171     return RISCVISD::RORW;
3172   case RISCVISD::GREVI:
3173     return RISCVISD::GREVIW;
3174   case RISCVISD::GORCI:
3175     return RISCVISD::GORCIW;
3176   }
3177 }
3178 
3179 // Converts the given 32-bit operation to a target-specific SelectionDAG node.
3180 // Because i32 isn't a legal type for RV64, these operations would otherwise
3181 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
3182 // later one because the fact the operation was originally of type i32 is
3183 // lost.
3184 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
3185                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
3186   SDLoc DL(N);
3187   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
3188   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
3189   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
3190   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
3191   // ReplaceNodeResults requires we maintain the same type for the return value.
3192   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
3193 }
3194 
3195 // Converts the given 32-bit operation to a i64 operation with signed extension
3196 // semantic to reduce the signed extension instructions.
3197 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
3198   SDLoc DL(N);
3199   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
3200   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
3201   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
3202   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
3203                                DAG.getValueType(MVT::i32));
3204   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
3205 }
3206 
3207 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
3208                                              SmallVectorImpl<SDValue> &Results,
3209                                              SelectionDAG &DAG) const {
3210   SDLoc DL(N);
3211   switch (N->getOpcode()) {
3212   default:
3213     llvm_unreachable("Don't know how to custom type legalize this operation!");
3214   case ISD::STRICT_FP_TO_SINT:
3215   case ISD::STRICT_FP_TO_UINT:
3216   case ISD::FP_TO_SINT:
3217   case ISD::FP_TO_UINT: {
3218     bool IsStrict = N->isStrictFPOpcode();
3219     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3220            "Unexpected custom legalisation");
3221     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
3222     // If the FP type needs to be softened, emit a library call using the 'si'
3223     // version. If we left it to default legalization we'd end up with 'di'. If
3224     // the FP type doesn't need to be softened just let generic type
3225     // legalization promote the result type.
3226     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
3227         TargetLowering::TypeSoftenFloat)
3228       return;
3229     RTLIB::Libcall LC;
3230     if (N->getOpcode() == ISD::FP_TO_SINT ||
3231         N->getOpcode() == ISD::STRICT_FP_TO_SINT)
3232       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
3233     else
3234       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
3235     MakeLibCallOptions CallOptions;
3236     EVT OpVT = Op0.getValueType();
3237     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
3238     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
3239     SDValue Result;
3240     std::tie(Result, Chain) =
3241         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
3242     Results.push_back(Result);
3243     if (IsStrict)
3244       Results.push_back(Chain);
3245     break;
3246   }
3247   case ISD::READCYCLECOUNTER: {
3248     assert(!Subtarget.is64Bit() &&
3249            "READCYCLECOUNTER only has custom type legalization on riscv32");
3250 
3251     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
3252     SDValue RCW =
3253         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
3254 
3255     Results.push_back(
3256         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
3257     Results.push_back(RCW.getValue(2));
3258     break;
3259   }
3260   case ISD::ADD:
3261   case ISD::SUB:
3262   case ISD::MUL:
3263     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3264            "Unexpected custom legalisation");
3265     if (N->getOperand(1).getOpcode() == ISD::Constant)
3266       return;
3267     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
3268     break;
3269   case ISD::SHL:
3270   case ISD::SRA:
3271   case ISD::SRL:
3272     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3273            "Unexpected custom legalisation");
3274     if (N->getOperand(1).getOpcode() == ISD::Constant)
3275       return;
3276     Results.push_back(customLegalizeToWOp(N, DAG));
3277     break;
3278   case ISD::ROTL:
3279   case ISD::ROTR:
3280     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3281            "Unexpected custom legalisation");
3282     Results.push_back(customLegalizeToWOp(N, DAG));
3283     break;
3284   case ISD::SDIV:
3285   case ISD::UDIV:
3286   case ISD::UREM: {
3287     MVT VT = N->getSimpleValueType(0);
3288     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
3289            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
3290            "Unexpected custom legalisation");
3291     if (N->getOperand(0).getOpcode() == ISD::Constant ||
3292         N->getOperand(1).getOpcode() == ISD::Constant)
3293       return;
3294 
3295     // If the input is i32, use ANY_EXTEND since the W instructions don't read
3296     // the upper 32 bits. For other types we need to sign or zero extend
3297     // based on the opcode.
3298     unsigned ExtOpc = ISD::ANY_EXTEND;
3299     if (VT != MVT::i32)
3300       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
3301                                            : ISD::ZERO_EXTEND;
3302 
3303     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
3304     break;
3305   }
3306   case ISD::BITCAST: {
3307     assert(((N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3308              Subtarget.hasStdExtF()) ||
3309             (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh())) &&
3310            "Unexpected custom legalisation");
3311     SDValue Op0 = N->getOperand(0);
3312     if (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh()) {
3313       if (Op0.getValueType() != MVT::f16)
3314         return;
3315       SDValue FPConv =
3316           DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(), Op0);
3317       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
3318     } else if (N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3319                Subtarget.hasStdExtF()) {
3320       if (Op0.getValueType() != MVT::f32)
3321         return;
3322       SDValue FPConv =
3323           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
3324       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
3325     }
3326     break;
3327   }
3328   case RISCVISD::GREVI:
3329   case RISCVISD::GORCI: {
3330     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3331            "Unexpected custom legalisation");
3332     // This is similar to customLegalizeToWOp, except that we pass the second
3333     // operand (a TargetConstant) straight through: it is already of type
3334     // XLenVT.
3335     SDLoc DL(N);
3336     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
3337     SDValue NewOp0 =
3338         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
3339     SDValue NewRes =
3340         DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, N->getOperand(1));
3341     // ReplaceNodeResults requires we maintain the same type for the return
3342     // value.
3343     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
3344     break;
3345   }
3346   case RISCVISD::SHFLI: {
3347     // There is no SHFLIW instruction, but we can just promote the operation.
3348     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3349            "Unexpected custom legalisation");
3350     SDLoc DL(N);
3351     SDValue NewOp0 =
3352         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
3353     SDValue NewRes =
3354         DAG.getNode(RISCVISD::SHFLI, DL, MVT::i64, NewOp0, N->getOperand(1));
3355     // ReplaceNodeResults requires we maintain the same type for the return
3356     // value.
3357     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
3358     break;
3359   }
3360   case ISD::BSWAP:
3361   case ISD::BITREVERSE: {
3362     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3363            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
3364     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
3365                                  N->getOperand(0));
3366     unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24;
3367     SDValue GREVIW = DAG.getNode(RISCVISD::GREVIW, DL, MVT::i64, NewOp0,
3368                                  DAG.getTargetConstant(Imm, DL,
3369                                                        Subtarget.getXLenVT()));
3370     // ReplaceNodeResults requires we maintain the same type for the return
3371     // value.
3372     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW));
3373     break;
3374   }
3375   case ISD::FSHL:
3376   case ISD::FSHR: {
3377     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
3378            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
3379     SDValue NewOp0 =
3380         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
3381     SDValue NewOp1 =
3382         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
3383     SDValue NewOp2 =
3384         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
3385     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
3386     // Mask the shift amount to 5 bits.
3387     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
3388                          DAG.getConstant(0x1f, DL, MVT::i64));
3389     unsigned Opc =
3390         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
3391     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
3392     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
3393     break;
3394   }
3395   case ISD::EXTRACT_VECTOR_ELT: {
3396     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
3397     // type is illegal (currently only vXi64 RV32).
3398     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
3399     // transferred to the destination register. We issue two of these from the
3400     // upper- and lower- halves of the SEW-bit vector element, slid down to the
3401     // first element.
3402     SDLoc DL(N);
3403     SDValue Vec = N->getOperand(0);
3404     SDValue Idx = N->getOperand(1);
3405 
3406     // The vector type hasn't been legalized yet so we can't issue target
3407     // specific nodes if it needs legalization.
3408     // FIXME: We would manually legalize if it's important.
3409     if (!isTypeLegal(Vec.getValueType()))
3410       return;
3411 
3412     MVT VecVT = Vec.getSimpleValueType();
3413 
3414     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
3415            VecVT.getVectorElementType() == MVT::i64 &&
3416            "Unexpected EXTRACT_VECTOR_ELT legalization");
3417 
3418     // If this is a fixed vector, we need to convert it to a scalable vector.
3419     MVT ContainerVT = VecVT;
3420     if (VecVT.isFixedLengthVector()) {
3421       ContainerVT = getContainerForFixedLengthVector(VecVT);
3422       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3423     }
3424 
3425     MVT XLenVT = Subtarget.getXLenVT();
3426 
3427     // Use a VL of 1 to avoid processing more elements than we need.
3428     MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
3429     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3430     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3431 
3432     // Unless the index is known to be 0, we must slide the vector down to get
3433     // the desired element into index 0.
3434     if (!isNullConstant(Idx)) {
3435       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3436                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3437     }
3438 
3439     // Extract the lower XLEN bits of the correct vector element.
3440     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3441 
3442     // To extract the upper XLEN bits of the vector element, shift the first
3443     // element right by 32 bits and re-extract the lower XLEN bits.
3444     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
3445                                      DAG.getConstant(32, DL, XLenVT), VL);
3446     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
3447                                  ThirtyTwoV, Mask, VL);
3448 
3449     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
3450 
3451     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
3452     break;
3453   }
3454   case ISD::INTRINSIC_WO_CHAIN: {
3455     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3456     switch (IntNo) {
3457     default:
3458       llvm_unreachable(
3459           "Don't know how to custom type legalize this intrinsic!");
3460     case Intrinsic::riscv_vmv_x_s: {
3461       EVT VT = N->getValueType(0);
3462       assert((VT == MVT::i8 || VT == MVT::i16 ||
3463               (Subtarget.is64Bit() && VT == MVT::i32)) &&
3464              "Unexpected custom legalisation!");
3465       SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
3466                                     Subtarget.getXLenVT(), N->getOperand(1));
3467       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
3468       break;
3469     }
3470     }
3471     break;
3472   }
3473   case ISD::VECREDUCE_ADD:
3474   case ISD::VECREDUCE_AND:
3475   case ISD::VECREDUCE_OR:
3476   case ISD::VECREDUCE_XOR:
3477   case ISD::VECREDUCE_SMAX:
3478   case ISD::VECREDUCE_UMAX:
3479   case ISD::VECREDUCE_SMIN:
3480   case ISD::VECREDUCE_UMIN:
3481     // The custom-lowering for these nodes returns a vector whose first element
3482     // is the result of the reduction. Extract its first element and let the
3483     // legalization for EXTRACT_VECTOR_ELT do the rest of the job.
3484     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
3485       Results.push_back(V);
3486     break;
3487   }
3488 }
3489 
3490 // A structure to hold one of the bit-manipulation patterns below. Together, a
3491 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
3492 //   (or (and (shl x, 1), 0xAAAAAAAA),
3493 //       (and (srl x, 1), 0x55555555))
3494 struct RISCVBitmanipPat {
3495   SDValue Op;
3496   unsigned ShAmt;
3497   bool IsSHL;
3498 
3499   bool formsPairWith(const RISCVBitmanipPat &Other) const {
3500     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
3501   }
3502 };
3503 
3504 // Matches patterns of the form
3505 //   (and (shl x, C2), (C1 << C2))
3506 //   (and (srl x, C2), C1)
3507 //   (shl (and x, C1), C2)
3508 //   (srl (and x, (C1 << C2)), C2)
3509 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
3510 // The expected masks for each shift amount are specified in BitmanipMasks where
3511 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
3512 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
3513 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
3514 // XLen is 64.
3515 static Optional<RISCVBitmanipPat>
3516 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
3517   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
3518          "Unexpected number of masks");
3519   Optional<uint64_t> Mask;
3520   // Optionally consume a mask around the shift operation.
3521   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
3522     Mask = Op.getConstantOperandVal(1);
3523     Op = Op.getOperand(0);
3524   }
3525   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
3526     return None;
3527   bool IsSHL = Op.getOpcode() == ISD::SHL;
3528 
3529   if (!isa<ConstantSDNode>(Op.getOperand(1)))
3530     return None;
3531   uint64_t ShAmt = Op.getConstantOperandVal(1);
3532 
3533   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
3534   if (ShAmt >= Width && !isPowerOf2_64(ShAmt))
3535     return None;
3536   // If we don't have enough masks for 64 bit, then we must be trying to
3537   // match SHFL so we're only allowed to shift 1/4 of the width.
3538   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
3539     return None;
3540 
3541   SDValue Src = Op.getOperand(0);
3542 
3543   // The expected mask is shifted left when the AND is found around SHL
3544   // patterns.
3545   //   ((x >> 1) & 0x55555555)
3546   //   ((x << 1) & 0xAAAAAAAA)
3547   bool SHLExpMask = IsSHL;
3548 
3549   if (!Mask) {
3550     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
3551     // the mask is all ones: consume that now.
3552     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
3553       Mask = Src.getConstantOperandVal(1);
3554       Src = Src.getOperand(0);
3555       // The expected mask is now in fact shifted left for SRL, so reverse the
3556       // decision.
3557       //   ((x & 0xAAAAAAAA) >> 1)
3558       //   ((x & 0x55555555) << 1)
3559       SHLExpMask = !SHLExpMask;
3560     } else {
3561       // Use a default shifted mask of all-ones if there's no AND, truncated
3562       // down to the expected width. This simplifies the logic later on.
3563       Mask = maskTrailingOnes<uint64_t>(Width);
3564       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
3565     }
3566   }
3567 
3568   unsigned MaskIdx = Log2_32(ShAmt);
3569   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
3570 
3571   if (SHLExpMask)
3572     ExpMask <<= ShAmt;
3573 
3574   if (Mask != ExpMask)
3575     return None;
3576 
3577   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
3578 }
3579 
3580 // Matches any of the following bit-manipulation patterns:
3581 //   (and (shl x, 1), (0x55555555 << 1))
3582 //   (and (srl x, 1), 0x55555555)
3583 //   (shl (and x, 0x55555555), 1)
3584 //   (srl (and x, (0x55555555 << 1)), 1)
3585 // where the shift amount and mask may vary thus:
3586 //   [1]  = 0x55555555 / 0xAAAAAAAA
3587 //   [2]  = 0x33333333 / 0xCCCCCCCC
3588 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
3589 //   [8]  = 0x00FF00FF / 0xFF00FF00
3590 //   [16] = 0x0000FFFF / 0xFFFFFFFF
3591 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
3592 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
3593   // These are the unshifted masks which we use to match bit-manipulation
3594   // patterns. They may be shifted left in certain circumstances.
3595   static const uint64_t BitmanipMasks[] = {
3596       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
3597       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
3598 
3599   return matchRISCVBitmanipPat(Op, BitmanipMasks);
3600 }
3601 
3602 // Match the following pattern as a GREVI(W) operation
3603 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
3604 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
3605                                const RISCVSubtarget &Subtarget) {
3606   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
3607   EVT VT = Op.getValueType();
3608 
3609   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
3610     auto LHS = matchGREVIPat(Op.getOperand(0));
3611     auto RHS = matchGREVIPat(Op.getOperand(1));
3612     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
3613       SDLoc DL(Op);
3614       return DAG.getNode(
3615           RISCVISD::GREVI, DL, VT, LHS->Op,
3616           DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT()));
3617     }
3618   }
3619   return SDValue();
3620 }
3621 
3622 // Matches any the following pattern as a GORCI(W) operation
3623 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
3624 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
3625 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
3626 // Note that with the variant of 3.,
3627 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
3628 // the inner pattern will first be matched as GREVI and then the outer
3629 // pattern will be matched to GORC via the first rule above.
3630 // 4.  (or (rotl/rotr x, bitwidth/2), x)
3631 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
3632                                const RISCVSubtarget &Subtarget) {
3633   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
3634   EVT VT = Op.getValueType();
3635 
3636   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
3637     SDLoc DL(Op);
3638     SDValue Op0 = Op.getOperand(0);
3639     SDValue Op1 = Op.getOperand(1);
3640 
3641     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
3642       if (Reverse.getOpcode() == RISCVISD::GREVI && Reverse.getOperand(0) == X &&
3643           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
3644         return DAG.getNode(RISCVISD::GORCI, DL, VT, X, Reverse.getOperand(1));
3645       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
3646       if ((Reverse.getOpcode() == ISD::ROTL ||
3647            Reverse.getOpcode() == ISD::ROTR) &&
3648           Reverse.getOperand(0) == X &&
3649           isa<ConstantSDNode>(Reverse.getOperand(1))) {
3650         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
3651         if (RotAmt == (VT.getSizeInBits() / 2))
3652           return DAG.getNode(
3653               RISCVISD::GORCI, DL, VT, X,
3654               DAG.getTargetConstant(RotAmt, DL, Subtarget.getXLenVT()));
3655       }
3656       return SDValue();
3657     };
3658 
3659     // Check for either commutable permutation of (or (GREVI x, shamt), x)
3660     if (SDValue V = MatchOROfReverse(Op0, Op1))
3661       return V;
3662     if (SDValue V = MatchOROfReverse(Op1, Op0))
3663       return V;
3664 
3665     // OR is commutable so canonicalize its OR operand to the left
3666     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
3667       std::swap(Op0, Op1);
3668     if (Op0.getOpcode() != ISD::OR)
3669       return SDValue();
3670     SDValue OrOp0 = Op0.getOperand(0);
3671     SDValue OrOp1 = Op0.getOperand(1);
3672     auto LHS = matchGREVIPat(OrOp0);
3673     // OR is commutable so swap the operands and try again: x might have been
3674     // on the left
3675     if (!LHS) {
3676       std::swap(OrOp0, OrOp1);
3677       LHS = matchGREVIPat(OrOp0);
3678     }
3679     auto RHS = matchGREVIPat(Op1);
3680     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
3681       return DAG.getNode(
3682           RISCVISD::GORCI, DL, VT, LHS->Op,
3683           DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT()));
3684     }
3685   }
3686   return SDValue();
3687 }
3688 
3689 // Matches any of the following bit-manipulation patterns:
3690 //   (and (shl x, 1), (0x22222222 << 1))
3691 //   (and (srl x, 1), 0x22222222)
3692 //   (shl (and x, 0x22222222), 1)
3693 //   (srl (and x, (0x22222222 << 1)), 1)
3694 // where the shift amount and mask may vary thus:
3695 //   [1]  = 0x22222222 / 0x44444444
3696 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
3697 //   [4]  = 0x00F000F0 / 0x0F000F00
3698 //   [8]  = 0x0000FF00 / 0x00FF0000
3699 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
3700 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
3701   // These are the unshifted masks which we use to match bit-manipulation
3702   // patterns. They may be shifted left in certain circumstances.
3703   static const uint64_t BitmanipMasks[] = {
3704       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
3705       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
3706 
3707   return matchRISCVBitmanipPat(Op, BitmanipMasks);
3708 }
3709 
3710 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
3711 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
3712                                const RISCVSubtarget &Subtarget) {
3713   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
3714   EVT VT = Op.getValueType();
3715 
3716   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
3717     return SDValue();
3718 
3719   SDValue Op0 = Op.getOperand(0);
3720   SDValue Op1 = Op.getOperand(1);
3721 
3722   // Or is commutable so canonicalize the second OR to the LHS.
3723   if (Op0.getOpcode() != ISD::OR)
3724     std::swap(Op0, Op1);
3725   if (Op0.getOpcode() != ISD::OR)
3726     return SDValue();
3727 
3728   // We found an inner OR, so our operands are the operands of the inner OR
3729   // and the other operand of the outer OR.
3730   SDValue A = Op0.getOperand(0);
3731   SDValue B = Op0.getOperand(1);
3732   SDValue C = Op1;
3733 
3734   auto Match1 = matchSHFLPat(A);
3735   auto Match2 = matchSHFLPat(B);
3736 
3737   // If neither matched, we failed.
3738   if (!Match1 && !Match2)
3739     return SDValue();
3740 
3741   // We had at least one match. if one failed, try the remaining C operand.
3742   if (!Match1) {
3743     std::swap(A, C);
3744     Match1 = matchSHFLPat(A);
3745     if (!Match1)
3746       return SDValue();
3747   } else if (!Match2) {
3748     std::swap(B, C);
3749     Match2 = matchSHFLPat(B);
3750     if (!Match2)
3751       return SDValue();
3752   }
3753   assert(Match1 && Match2);
3754 
3755   // Make sure our matches pair up.
3756   if (!Match1->formsPairWith(*Match2))
3757     return SDValue();
3758 
3759   // All the remains is to make sure C is an AND with the same input, that masks
3760   // out the bits that are being shuffled.
3761   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
3762       C.getOperand(0) != Match1->Op)
3763     return SDValue();
3764 
3765   uint64_t Mask = C.getConstantOperandVal(1);
3766 
3767   static const uint64_t BitmanipMasks[] = {
3768       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
3769       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
3770   };
3771 
3772   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
3773   unsigned MaskIdx = Log2_32(Match1->ShAmt);
3774   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
3775 
3776   if (Mask != ExpMask)
3777     return SDValue();
3778 
3779   SDLoc DL(Op);
3780   return DAG.getNode(
3781       RISCVISD::SHFLI, DL, VT, Match1->Op,
3782       DAG.getTargetConstant(Match1->ShAmt, DL, Subtarget.getXLenVT()));
3783 }
3784 
3785 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
3786 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
3787 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
3788 // not undo itself, but they are redundant.
3789 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
3790   unsigned ShAmt1 = N->getConstantOperandVal(1);
3791   SDValue Src = N->getOperand(0);
3792 
3793   if (Src.getOpcode() != N->getOpcode())
3794     return SDValue();
3795 
3796   unsigned ShAmt2 = Src.getConstantOperandVal(1);
3797   Src = Src.getOperand(0);
3798 
3799   unsigned CombinedShAmt;
3800   if (N->getOpcode() == RISCVISD::GORCI || N->getOpcode() == RISCVISD::GORCIW)
3801     CombinedShAmt = ShAmt1 | ShAmt2;
3802   else
3803     CombinedShAmt = ShAmt1 ^ ShAmt2;
3804 
3805   if (CombinedShAmt == 0)
3806     return Src;
3807 
3808   SDLoc DL(N);
3809   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), Src,
3810                      DAG.getTargetConstant(CombinedShAmt, DL,
3811                                            N->getOperand(1).getValueType()));
3812 }
3813 
3814 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
3815                                                DAGCombinerInfo &DCI) const {
3816   SelectionDAG &DAG = DCI.DAG;
3817 
3818   switch (N->getOpcode()) {
3819   default:
3820     break;
3821   case RISCVISD::SplitF64: {
3822     SDValue Op0 = N->getOperand(0);
3823     // If the input to SplitF64 is just BuildPairF64 then the operation is
3824     // redundant. Instead, use BuildPairF64's operands directly.
3825     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
3826       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
3827 
3828     SDLoc DL(N);
3829 
3830     // It's cheaper to materialise two 32-bit integers than to load a double
3831     // from the constant pool and transfer it to integer registers through the
3832     // stack.
3833     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
3834       APInt V = C->getValueAPF().bitcastToAPInt();
3835       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
3836       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
3837       return DCI.CombineTo(N, Lo, Hi);
3838     }
3839 
3840     // This is a target-specific version of a DAGCombine performed in
3841     // DAGCombiner::visitBITCAST. It performs the equivalent of:
3842     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
3843     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
3844     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
3845         !Op0.getNode()->hasOneUse())
3846       break;
3847     SDValue NewSplitF64 =
3848         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
3849                     Op0.getOperand(0));
3850     SDValue Lo = NewSplitF64.getValue(0);
3851     SDValue Hi = NewSplitF64.getValue(1);
3852     APInt SignBit = APInt::getSignMask(32);
3853     if (Op0.getOpcode() == ISD::FNEG) {
3854       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
3855                                   DAG.getConstant(SignBit, DL, MVT::i32));
3856       return DCI.CombineTo(N, Lo, NewHi);
3857     }
3858     assert(Op0.getOpcode() == ISD::FABS);
3859     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
3860                                 DAG.getConstant(~SignBit, DL, MVT::i32));
3861     return DCI.CombineTo(N, Lo, NewHi);
3862   }
3863   case RISCVISD::SLLW:
3864   case RISCVISD::SRAW:
3865   case RISCVISD::SRLW:
3866   case RISCVISD::ROLW:
3867   case RISCVISD::RORW: {
3868     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
3869     SDValue LHS = N->getOperand(0);
3870     SDValue RHS = N->getOperand(1);
3871     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
3872     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
3873     if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) ||
3874         SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) {
3875       if (N->getOpcode() != ISD::DELETED_NODE)
3876         DCI.AddToWorklist(N);
3877       return SDValue(N, 0);
3878     }
3879     break;
3880   }
3881   case RISCVISD::FSL:
3882   case RISCVISD::FSR: {
3883     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
3884     SDValue ShAmt = N->getOperand(2);
3885     unsigned BitWidth = ShAmt.getValueSizeInBits();
3886     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
3887     APInt ShAmtMask(BitWidth, (BitWidth * 2) - 1);
3888     if (SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
3889       if (N->getOpcode() != ISD::DELETED_NODE)
3890         DCI.AddToWorklist(N);
3891       return SDValue(N, 0);
3892     }
3893     break;
3894   }
3895   case RISCVISD::FSLW:
3896   case RISCVISD::FSRW: {
3897     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
3898     // read.
3899     SDValue Op0 = N->getOperand(0);
3900     SDValue Op1 = N->getOperand(1);
3901     SDValue ShAmt = N->getOperand(2);
3902     APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
3903     APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6);
3904     if (SimplifyDemandedBits(Op0, OpMask, DCI) ||
3905         SimplifyDemandedBits(Op1, OpMask, DCI) ||
3906         SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
3907       if (N->getOpcode() != ISD::DELETED_NODE)
3908         DCI.AddToWorklist(N);
3909       return SDValue(N, 0);
3910     }
3911     break;
3912   }
3913   case RISCVISD::GREVIW:
3914   case RISCVISD::GORCIW: {
3915     // Only the lower 32 bits of the first operand are read
3916     SDValue Op0 = N->getOperand(0);
3917     APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
3918     if (SimplifyDemandedBits(Op0, Mask, DCI)) {
3919       if (N->getOpcode() != ISD::DELETED_NODE)
3920         DCI.AddToWorklist(N);
3921       return SDValue(N, 0);
3922     }
3923 
3924     return combineGREVI_GORCI(N, DCI.DAG);
3925   }
3926   case RISCVISD::FMV_X_ANYEXTW_RV64: {
3927     SDLoc DL(N);
3928     SDValue Op0 = N->getOperand(0);
3929     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
3930     // conversion is unnecessary and can be replaced with an ANY_EXTEND
3931     // of the FMV_W_X_RV64 operand.
3932     if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
3933       assert(Op0.getOperand(0).getValueType() == MVT::i64 &&
3934              "Unexpected value type!");
3935       return Op0.getOperand(0);
3936     }
3937 
3938     // This is a target-specific version of a DAGCombine performed in
3939     // DAGCombiner::visitBITCAST. It performs the equivalent of:
3940     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
3941     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
3942     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
3943         !Op0.getNode()->hasOneUse())
3944       break;
3945     SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64,
3946                                  Op0.getOperand(0));
3947     APInt SignBit = APInt::getSignMask(32).sext(64);
3948     if (Op0.getOpcode() == ISD::FNEG)
3949       return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
3950                          DAG.getConstant(SignBit, DL, MVT::i64));
3951 
3952     assert(Op0.getOpcode() == ISD::FABS);
3953     return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
3954                        DAG.getConstant(~SignBit, DL, MVT::i64));
3955   }
3956   case RISCVISD::GREVI:
3957   case RISCVISD::GORCI:
3958     return combineGREVI_GORCI(N, DCI.DAG);
3959   case ISD::OR:
3960     if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget))
3961       return GREV;
3962     if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget))
3963       return GORC;
3964     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DCI.DAG, Subtarget))
3965       return SHFL;
3966     break;
3967   case RISCVISD::SELECT_CC: {
3968     // Transform
3969     SDValue LHS = N->getOperand(0);
3970     SDValue RHS = N->getOperand(1);
3971     auto CCVal = static_cast<ISD::CondCode>(N->getConstantOperandVal(2));
3972     if (!ISD::isIntEqualitySetCC(CCVal))
3973       break;
3974 
3975     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
3976     //      (select_cc X, Y, lt, trueV, falseV)
3977     // Sometimes the setcc is introduced after select_cc has been formed.
3978     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
3979         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
3980       // If we're looking for eq 0 instead of ne 0, we need to invert the
3981       // condition.
3982       bool Invert = CCVal == ISD::SETEQ;
3983       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
3984       if (Invert)
3985         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
3986 
3987       RHS = LHS.getOperand(1);
3988       LHS = LHS.getOperand(0);
3989       normaliseSetCC(LHS, RHS, CCVal);
3990 
3991       SDLoc DL(N);
3992       SDValue TargetCC = DAG.getConstant(CCVal, DL, Subtarget.getXLenVT());
3993       return DAG.getNode(
3994           RISCVISD::SELECT_CC, DL, N->getValueType(0),
3995           {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)});
3996     }
3997 
3998     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
3999     //      (select_cc X, Y, eq/ne, trueV, falseV)
4000     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
4001       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
4002                          {LHS.getOperand(0), LHS.getOperand(1),
4003                           N->getOperand(2), N->getOperand(3),
4004                           N->getOperand(4)});
4005     // (select_cc X, 1, setne, trueV, falseV) ->
4006     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
4007     // This can occur when legalizing some floating point comparisons.
4008     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
4009     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
4010       SDLoc DL(N);
4011       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
4012       SDValue TargetCC = DAG.getConstant(CCVal, DL, Subtarget.getXLenVT());
4013       RHS = DAG.getConstant(0, DL, LHS.getValueType());
4014       return DAG.getNode(
4015           RISCVISD::SELECT_CC, DL, N->getValueType(0),
4016           {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)});
4017     }
4018 
4019     break;
4020   }
4021   case ISD::SETCC: {
4022     // (setcc X, 1, setne) -> (setcc X, 0, seteq) if we can prove X is 0/1.
4023     // Comparing with 0 may allow us to fold into bnez/beqz.
4024     SDValue LHS = N->getOperand(0);
4025     SDValue RHS = N->getOperand(1);
4026     if (LHS.getValueType().isScalableVector())
4027       break;
4028     auto CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4029     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
4030     if (isOneConstant(RHS) && ISD::isIntEqualitySetCC(CC) &&
4031         DAG.MaskedValueIsZero(LHS, Mask)) {
4032       SDLoc DL(N);
4033       SDValue Zero = DAG.getConstant(0, DL, LHS.getValueType());
4034       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
4035       return DAG.getSetCC(DL, N->getValueType(0), LHS, Zero, CC);
4036     }
4037     break;
4038   }
4039   case ISD::FCOPYSIGN: {
4040     EVT VT = N->getValueType(0);
4041     if (!VT.isVector())
4042       break;
4043     // There is a form of VFSGNJ which injects the negated sign of its second
4044     // operand. Try and bubble any FNEG up after the extend/round to produce
4045     // this optimized pattern. Avoid modifying cases where FP_ROUND and
4046     // TRUNC=1.
4047     SDValue In2 = N->getOperand(1);
4048     // Avoid cases where the extend/round has multiple uses, as duplicating
4049     // those is typically more expensive than removing a fneg.
4050     if (!In2.hasOneUse())
4051       break;
4052     if (In2.getOpcode() != ISD::FP_EXTEND &&
4053         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
4054       break;
4055     In2 = In2.getOperand(0);
4056     if (In2.getOpcode() != ISD::FNEG)
4057       break;
4058     SDLoc DL(N);
4059     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
4060     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
4061                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
4062   }
4063   }
4064 
4065   return SDValue();
4066 }
4067 
4068 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
4069     const SDNode *N, CombineLevel Level) const {
4070   // The following folds are only desirable if `(OP _, c1 << c2)` can be
4071   // materialised in fewer instructions than `(OP _, c1)`:
4072   //
4073   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4074   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
4075   SDValue N0 = N->getOperand(0);
4076   EVT Ty = N0.getValueType();
4077   if (Ty.isScalarInteger() &&
4078       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
4079     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
4080     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
4081     if (C1 && C2) {
4082       const APInt &C1Int = C1->getAPIntValue();
4083       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
4084 
4085       // We can materialise `c1 << c2` into an add immediate, so it's "free",
4086       // and the combine should happen, to potentially allow further combines
4087       // later.
4088       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
4089           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
4090         return true;
4091 
4092       // We can materialise `c1` in an add immediate, so it's "free", and the
4093       // combine should be prevented.
4094       if (C1Int.getMinSignedBits() <= 64 &&
4095           isLegalAddImmediate(C1Int.getSExtValue()))
4096         return false;
4097 
4098       // Neither constant will fit into an immediate, so find materialisation
4099       // costs.
4100       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
4101                                               Subtarget.is64Bit());
4102       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
4103           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit());
4104 
4105       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
4106       // combine should be prevented.
4107       if (C1Cost < ShiftedC1Cost)
4108         return false;
4109     }
4110   }
4111   return true;
4112 }
4113 
4114 bool RISCVTargetLowering::targetShrinkDemandedConstant(
4115     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4116     TargetLoweringOpt &TLO) const {
4117   // Delay this optimization as late as possible.
4118   if (!TLO.LegalOps)
4119     return false;
4120 
4121   EVT VT = Op.getValueType();
4122   if (VT.isVector())
4123     return false;
4124 
4125   // Only handle AND for now.
4126   if (Op.getOpcode() != ISD::AND)
4127     return false;
4128 
4129   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4130   if (!C)
4131     return false;
4132 
4133   const APInt &Mask = C->getAPIntValue();
4134 
4135   // Clear all non-demanded bits initially.
4136   APInt ShrunkMask = Mask & DemandedBits;
4137 
4138   // If the shrunk mask fits in sign extended 12 bits, let the target
4139   // independent code apply it.
4140   if (ShrunkMask.isSignedIntN(12))
4141     return false;
4142 
4143   // Try to make a smaller immediate by setting undemanded bits.
4144 
4145   // We need to be able to make a negative number through a combination of mask
4146   // and undemanded bits.
4147   APInt ExpandedMask = Mask | ~DemandedBits;
4148   if (!ExpandedMask.isNegative())
4149     return false;
4150 
4151   // What is the fewest number of bits we need to represent the negative number.
4152   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
4153 
4154   // Try to make a 12 bit negative immediate. If that fails try to make a 32
4155   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
4156   APInt NewMask = ShrunkMask;
4157   if (MinSignedBits <= 12)
4158     NewMask.setBitsFrom(11);
4159   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
4160     NewMask.setBitsFrom(31);
4161   else
4162     return false;
4163 
4164   // Sanity check that our new mask is a subset of the demanded mask.
4165   assert(NewMask.isSubsetOf(ExpandedMask));
4166 
4167   // If we aren't changing the mask, just return true to keep it and prevent
4168   // the caller from optimizing.
4169   if (NewMask == Mask)
4170     return true;
4171 
4172   // Replace the constant with the new mask.
4173   SDLoc DL(Op);
4174   SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
4175   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
4176   return TLO.CombineTo(Op, NewOp);
4177 }
4178 
4179 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
4180                                                         KnownBits &Known,
4181                                                         const APInt &DemandedElts,
4182                                                         const SelectionDAG &DAG,
4183                                                         unsigned Depth) const {
4184   unsigned BitWidth = Known.getBitWidth();
4185   unsigned Opc = Op.getOpcode();
4186   assert((Opc >= ISD::BUILTIN_OP_END ||
4187           Opc == ISD::INTRINSIC_WO_CHAIN ||
4188           Opc == ISD::INTRINSIC_W_CHAIN ||
4189           Opc == ISD::INTRINSIC_VOID) &&
4190          "Should use MaskedValueIsZero if you don't know whether Op"
4191          " is a target node!");
4192 
4193   Known.resetAll();
4194   switch (Opc) {
4195   default: break;
4196   case RISCVISD::REMUW: {
4197     KnownBits Known2;
4198     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4199     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4200     // We only care about the lower 32 bits.
4201     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
4202     // Restore the original width by sign extending.
4203     Known = Known.sext(BitWidth);
4204     break;
4205   }
4206   case RISCVISD::DIVUW: {
4207     KnownBits Known2;
4208     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4209     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4210     // We only care about the lower 32 bits.
4211     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
4212     // Restore the original width by sign extending.
4213     Known = Known.sext(BitWidth);
4214     break;
4215   }
4216   case RISCVISD::READ_VLENB:
4217     // We assume VLENB is at least 8 bytes.
4218     // FIXME: The 1.0 draft spec defines minimum VLEN as 128 bits.
4219     Known.Zero.setLowBits(3);
4220     break;
4221   }
4222 }
4223 
4224 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
4225     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4226     unsigned Depth) const {
4227   switch (Op.getOpcode()) {
4228   default:
4229     break;
4230   case RISCVISD::SLLW:
4231   case RISCVISD::SRAW:
4232   case RISCVISD::SRLW:
4233   case RISCVISD::DIVW:
4234   case RISCVISD::DIVUW:
4235   case RISCVISD::REMUW:
4236   case RISCVISD::ROLW:
4237   case RISCVISD::RORW:
4238   case RISCVISD::GREVIW:
4239   case RISCVISD::GORCIW:
4240   case RISCVISD::FSLW:
4241   case RISCVISD::FSRW:
4242     // TODO: As the result is sign-extended, this is conservatively correct. A
4243     // more precise answer could be calculated for SRAW depending on known
4244     // bits in the shift amount.
4245     return 33;
4246   case RISCVISD::SHFLI: {
4247     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
4248     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
4249     // will stay within the upper 32 bits. If there were more than 32 sign bits
4250     // before there will be at least 33 sign bits after.
4251     if (Op.getValueType() == MVT::i64 &&
4252         (Op.getConstantOperandVal(1) & 0x10) == 0) {
4253       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4254       if (Tmp > 32)
4255         return 33;
4256     }
4257     break;
4258   }
4259   case RISCVISD::VMV_X_S:
4260     // The number of sign bits of the scalar result is computed by obtaining the
4261     // element type of the input vector operand, subtracting its width from the
4262     // XLEN, and then adding one (sign bit within the element type). If the
4263     // element type is wider than XLen, the least-significant XLEN bits are
4264     // taken.
4265     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
4266       return 1;
4267     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
4268   }
4269 
4270   return 1;
4271 }
4272 
4273 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
4274                                                   MachineBasicBlock *BB) {
4275   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
4276 
4277   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
4278   // Should the count have wrapped while it was being read, we need to try
4279   // again.
4280   // ...
4281   // read:
4282   // rdcycleh x3 # load high word of cycle
4283   // rdcycle  x2 # load low word of cycle
4284   // rdcycleh x4 # load high word of cycle
4285   // bne x3, x4, read # check if high word reads match, otherwise try again
4286   // ...
4287 
4288   MachineFunction &MF = *BB->getParent();
4289   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4290   MachineFunction::iterator It = ++BB->getIterator();
4291 
4292   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
4293   MF.insert(It, LoopMBB);
4294 
4295   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
4296   MF.insert(It, DoneMBB);
4297 
4298   // Transfer the remainder of BB and its successor edges to DoneMBB.
4299   DoneMBB->splice(DoneMBB->begin(), BB,
4300                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
4301   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
4302 
4303   BB->addSuccessor(LoopMBB);
4304 
4305   MachineRegisterInfo &RegInfo = MF.getRegInfo();
4306   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
4307   Register LoReg = MI.getOperand(0).getReg();
4308   Register HiReg = MI.getOperand(1).getReg();
4309   DebugLoc DL = MI.getDebugLoc();
4310 
4311   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
4312   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
4313       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
4314       .addReg(RISCV::X0);
4315   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
4316       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
4317       .addReg(RISCV::X0);
4318   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
4319       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
4320       .addReg(RISCV::X0);
4321 
4322   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
4323       .addReg(HiReg)
4324       .addReg(ReadAgainReg)
4325       .addMBB(LoopMBB);
4326 
4327   LoopMBB->addSuccessor(LoopMBB);
4328   LoopMBB->addSuccessor(DoneMBB);
4329 
4330   MI.eraseFromParent();
4331 
4332   return DoneMBB;
4333 }
4334 
4335 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
4336                                              MachineBasicBlock *BB) {
4337   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
4338 
4339   MachineFunction &MF = *BB->getParent();
4340   DebugLoc DL = MI.getDebugLoc();
4341   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
4342   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
4343   Register LoReg = MI.getOperand(0).getReg();
4344   Register HiReg = MI.getOperand(1).getReg();
4345   Register SrcReg = MI.getOperand(2).getReg();
4346   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
4347   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
4348 
4349   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
4350                           RI);
4351   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
4352   MachineMemOperand *MMOLo =
4353       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
4354   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
4355       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
4356   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
4357       .addFrameIndex(FI)
4358       .addImm(0)
4359       .addMemOperand(MMOLo);
4360   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
4361       .addFrameIndex(FI)
4362       .addImm(4)
4363       .addMemOperand(MMOHi);
4364   MI.eraseFromParent(); // The pseudo instruction is gone now.
4365   return BB;
4366 }
4367 
4368 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
4369                                                  MachineBasicBlock *BB) {
4370   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
4371          "Unexpected instruction");
4372 
4373   MachineFunction &MF = *BB->getParent();
4374   DebugLoc DL = MI.getDebugLoc();
4375   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
4376   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
4377   Register DstReg = MI.getOperand(0).getReg();
4378   Register LoReg = MI.getOperand(1).getReg();
4379   Register HiReg = MI.getOperand(2).getReg();
4380   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
4381   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
4382 
4383   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
4384   MachineMemOperand *MMOLo =
4385       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
4386   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
4387       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
4388   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
4389       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
4390       .addFrameIndex(FI)
4391       .addImm(0)
4392       .addMemOperand(MMOLo);
4393   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
4394       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
4395       .addFrameIndex(FI)
4396       .addImm(4)
4397       .addMemOperand(MMOHi);
4398   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
4399   MI.eraseFromParent(); // The pseudo instruction is gone now.
4400   return BB;
4401 }
4402 
4403 static bool isSelectPseudo(MachineInstr &MI) {
4404   switch (MI.getOpcode()) {
4405   default:
4406     return false;
4407   case RISCV::Select_GPR_Using_CC_GPR:
4408   case RISCV::Select_FPR16_Using_CC_GPR:
4409   case RISCV::Select_FPR32_Using_CC_GPR:
4410   case RISCV::Select_FPR64_Using_CC_GPR:
4411     return true;
4412   }
4413 }
4414 
4415 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
4416                                            MachineBasicBlock *BB) {
4417   // To "insert" Select_* instructions, we actually have to insert the triangle
4418   // control-flow pattern.  The incoming instructions know the destination vreg
4419   // to set, the condition code register to branch on, the true/false values to
4420   // select between, and the condcode to use to select the appropriate branch.
4421   //
4422   // We produce the following control flow:
4423   //     HeadMBB
4424   //     |  \
4425   //     |  IfFalseMBB
4426   //     | /
4427   //    TailMBB
4428   //
4429   // When we find a sequence of selects we attempt to optimize their emission
4430   // by sharing the control flow. Currently we only handle cases where we have
4431   // multiple selects with the exact same condition (same LHS, RHS and CC).
4432   // The selects may be interleaved with other instructions if the other
4433   // instructions meet some requirements we deem safe:
4434   // - They are debug instructions. Otherwise,
4435   // - They do not have side-effects, do not access memory and their inputs do
4436   //   not depend on the results of the select pseudo-instructions.
4437   // The TrueV/FalseV operands of the selects cannot depend on the result of
4438   // previous selects in the sequence.
4439   // These conditions could be further relaxed. See the X86 target for a
4440   // related approach and more information.
4441   Register LHS = MI.getOperand(1).getReg();
4442   Register RHS = MI.getOperand(2).getReg();
4443   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
4444 
4445   SmallVector<MachineInstr *, 4> SelectDebugValues;
4446   SmallSet<Register, 4> SelectDests;
4447   SelectDests.insert(MI.getOperand(0).getReg());
4448 
4449   MachineInstr *LastSelectPseudo = &MI;
4450 
4451   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
4452        SequenceMBBI != E; ++SequenceMBBI) {
4453     if (SequenceMBBI->isDebugInstr())
4454       continue;
4455     else if (isSelectPseudo(*SequenceMBBI)) {
4456       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
4457           SequenceMBBI->getOperand(2).getReg() != RHS ||
4458           SequenceMBBI->getOperand(3).getImm() != CC ||
4459           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
4460           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
4461         break;
4462       LastSelectPseudo = &*SequenceMBBI;
4463       SequenceMBBI->collectDebugValues(SelectDebugValues);
4464       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
4465     } else {
4466       if (SequenceMBBI->hasUnmodeledSideEffects() ||
4467           SequenceMBBI->mayLoadOrStore())
4468         break;
4469       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
4470             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
4471           }))
4472         break;
4473     }
4474   }
4475 
4476   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
4477   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4478   DebugLoc DL = MI.getDebugLoc();
4479   MachineFunction::iterator I = ++BB->getIterator();
4480 
4481   MachineBasicBlock *HeadMBB = BB;
4482   MachineFunction *F = BB->getParent();
4483   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
4484   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
4485 
4486   F->insert(I, IfFalseMBB);
4487   F->insert(I, TailMBB);
4488 
4489   // Transfer debug instructions associated with the selects to TailMBB.
4490   for (MachineInstr *DebugInstr : SelectDebugValues) {
4491     TailMBB->push_back(DebugInstr->removeFromParent());
4492   }
4493 
4494   // Move all instructions after the sequence to TailMBB.
4495   TailMBB->splice(TailMBB->end(), HeadMBB,
4496                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
4497   // Update machine-CFG edges by transferring all successors of the current
4498   // block to the new block which will contain the Phi nodes for the selects.
4499   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
4500   // Set the successors for HeadMBB.
4501   HeadMBB->addSuccessor(IfFalseMBB);
4502   HeadMBB->addSuccessor(TailMBB);
4503 
4504   // Insert appropriate branch.
4505   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
4506 
4507   BuildMI(HeadMBB, DL, TII.get(Opcode))
4508     .addReg(LHS)
4509     .addReg(RHS)
4510     .addMBB(TailMBB);
4511 
4512   // IfFalseMBB just falls through to TailMBB.
4513   IfFalseMBB->addSuccessor(TailMBB);
4514 
4515   // Create PHIs for all of the select pseudo-instructions.
4516   auto SelectMBBI = MI.getIterator();
4517   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
4518   auto InsertionPoint = TailMBB->begin();
4519   while (SelectMBBI != SelectEnd) {
4520     auto Next = std::next(SelectMBBI);
4521     if (isSelectPseudo(*SelectMBBI)) {
4522       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
4523       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
4524               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
4525           .addReg(SelectMBBI->getOperand(4).getReg())
4526           .addMBB(HeadMBB)
4527           .addReg(SelectMBBI->getOperand(5).getReg())
4528           .addMBB(IfFalseMBB);
4529       SelectMBBI->eraseFromParent();
4530     }
4531     SelectMBBI = Next;
4532   }
4533 
4534   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
4535   return TailMBB;
4536 }
4537 
4538 static MachineBasicBlock *addVSetVL(MachineInstr &MI, MachineBasicBlock *BB,
4539                                     int VLIndex, unsigned SEWIndex,
4540                                     RISCVVLMUL VLMul, bool ForceTailAgnostic) {
4541   MachineFunction &MF = *BB->getParent();
4542   DebugLoc DL = MI.getDebugLoc();
4543   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
4544 
4545   unsigned SEW = MI.getOperand(SEWIndex).getImm();
4546   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
4547   RISCVVSEW ElementWidth = static_cast<RISCVVSEW>(Log2_32(SEW / 8));
4548 
4549   MachineRegisterInfo &MRI = MF.getRegInfo();
4550 
4551   auto BuildVSETVLI = [&]() {
4552     if (VLIndex >= 0) {
4553       Register DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
4554       Register VLReg = MI.getOperand(VLIndex).getReg();
4555 
4556       // VL might be a compile time constant, but isel would have to put it
4557       // in a register. See if VL comes from an ADDI X0, imm.
4558       if (VLReg.isVirtual()) {
4559         MachineInstr *Def = MRI.getVRegDef(VLReg);
4560         if (Def && Def->getOpcode() == RISCV::ADDI &&
4561             Def->getOperand(1).getReg() == RISCV::X0 &&
4562             Def->getOperand(2).isImm()) {
4563           uint64_t Imm = Def->getOperand(2).getImm();
4564           // VSETIVLI allows a 5-bit zero extended immediate.
4565           if (isUInt<5>(Imm))
4566             return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETIVLI))
4567                 .addReg(DestReg, RegState::Define | RegState::Dead)
4568                 .addImm(Imm);
4569         }
4570       }
4571 
4572       return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI))
4573           .addReg(DestReg, RegState::Define | RegState::Dead)
4574           .addReg(VLReg);
4575     }
4576 
4577     // With no VL operator in the pseudo, do not modify VL (rd = X0, rs1 = X0).
4578     return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI))
4579         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
4580         .addReg(RISCV::X0, RegState::Kill);
4581   };
4582 
4583   MachineInstrBuilder MIB = BuildVSETVLI();
4584 
4585   // Default to tail agnostic unless the destination is tied to a source. In
4586   // that case the user would have some control over the tail values. The tail
4587   // policy is also ignored on instructions that only update element 0 like
4588   // vmv.s.x or reductions so use agnostic there to match the common case.
4589   // FIXME: This is conservatively correct, but we might want to detect that
4590   // the input is undefined.
4591   bool TailAgnostic = true;
4592   unsigned UseOpIdx;
4593   if (!ForceTailAgnostic && MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
4594     TailAgnostic = false;
4595     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
4596     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
4597     MachineInstr *UseMI = MRI.getVRegDef(UseMO.getReg());
4598     if (UseMI && UseMI->isImplicitDef())
4599       TailAgnostic = true;
4600   }
4601 
4602   // For simplicity we reuse the vtype representation here.
4603   MIB.addImm(RISCVVType::encodeVTYPE(VLMul, ElementWidth,
4604                                      /*TailAgnostic*/ TailAgnostic,
4605                                      /*MaskAgnostic*/ false));
4606 
4607   // Remove (now) redundant operands from pseudo
4608   if (VLIndex >= 0) {
4609     MI.getOperand(VLIndex).setReg(RISCV::NoRegister);
4610     MI.getOperand(VLIndex).setIsKill(false);
4611   }
4612 
4613   return BB;
4614 }
4615 
4616 MachineBasicBlock *
4617 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
4618                                                  MachineBasicBlock *BB) const {
4619   uint64_t TSFlags = MI.getDesc().TSFlags;
4620 
4621   if (TSFlags & RISCVII::HasSEWOpMask) {
4622     unsigned NumOperands = MI.getNumExplicitOperands();
4623     int VLIndex = (TSFlags & RISCVII::HasVLOpMask) ? NumOperands - 2 : -1;
4624     unsigned SEWIndex = NumOperands - 1;
4625     bool ForceTailAgnostic = TSFlags & RISCVII::ForceTailAgnosticMask;
4626 
4627     RISCVVLMUL VLMul = static_cast<RISCVVLMUL>((TSFlags & RISCVII::VLMulMask) >>
4628                                                RISCVII::VLMulShift);
4629     return addVSetVL(MI, BB, VLIndex, SEWIndex, VLMul, ForceTailAgnostic);
4630   }
4631 
4632   switch (MI.getOpcode()) {
4633   default:
4634     llvm_unreachable("Unexpected instr type to insert");
4635   case RISCV::ReadCycleWide:
4636     assert(!Subtarget.is64Bit() &&
4637            "ReadCycleWrite is only to be used on riscv32");
4638     return emitReadCycleWidePseudo(MI, BB);
4639   case RISCV::Select_GPR_Using_CC_GPR:
4640   case RISCV::Select_FPR16_Using_CC_GPR:
4641   case RISCV::Select_FPR32_Using_CC_GPR:
4642   case RISCV::Select_FPR64_Using_CC_GPR:
4643     return emitSelectPseudo(MI, BB);
4644   case RISCV::BuildPairF64Pseudo:
4645     return emitBuildPairF64Pseudo(MI, BB);
4646   case RISCV::SplitF64Pseudo:
4647     return emitSplitF64Pseudo(MI, BB);
4648   }
4649 }
4650 
4651 // Calling Convention Implementation.
4652 // The expectations for frontend ABI lowering vary from target to target.
4653 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
4654 // details, but this is a longer term goal. For now, we simply try to keep the
4655 // role of the frontend as simple and well-defined as possible. The rules can
4656 // be summarised as:
4657 // * Never split up large scalar arguments. We handle them here.
4658 // * If a hardfloat calling convention is being used, and the struct may be
4659 // passed in a pair of registers (fp+fp, int+fp), and both registers are
4660 // available, then pass as two separate arguments. If either the GPRs or FPRs
4661 // are exhausted, then pass according to the rule below.
4662 // * If a struct could never be passed in registers or directly in a stack
4663 // slot (as it is larger than 2*XLEN and the floating point rules don't
4664 // apply), then pass it using a pointer with the byval attribute.
4665 // * If a struct is less than 2*XLEN, then coerce to either a two-element
4666 // word-sized array or a 2*XLEN scalar (depending on alignment).
4667 // * The frontend can determine whether a struct is returned by reference or
4668 // not based on its size and fields. If it will be returned by reference, the
4669 // frontend must modify the prototype so a pointer with the sret annotation is
4670 // passed as the first argument. This is not necessary for large scalar
4671 // returns.
4672 // * Struct return values and varargs should be coerced to structs containing
4673 // register-size fields in the same situations they would be for fixed
4674 // arguments.
4675 
4676 static const MCPhysReg ArgGPRs[] = {
4677   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
4678   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
4679 };
4680 static const MCPhysReg ArgFPR16s[] = {
4681   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
4682   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
4683 };
4684 static const MCPhysReg ArgFPR32s[] = {
4685   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
4686   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
4687 };
4688 static const MCPhysReg ArgFPR64s[] = {
4689   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
4690   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
4691 };
4692 // This is an interim calling convention and it may be changed in the future.
4693 static const MCPhysReg ArgVRs[] = {
4694     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
4695     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
4696     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
4697 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
4698                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
4699                                      RISCV::V20M2, RISCV::V22M2};
4700 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
4701                                      RISCV::V20M4};
4702 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
4703 
4704 // Pass a 2*XLEN argument that has been split into two XLEN values through
4705 // registers or the stack as necessary.
4706 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
4707                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
4708                                 MVT ValVT2, MVT LocVT2,
4709                                 ISD::ArgFlagsTy ArgFlags2) {
4710   unsigned XLenInBytes = XLen / 8;
4711   if (Register Reg = State.AllocateReg(ArgGPRs)) {
4712     // At least one half can be passed via register.
4713     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
4714                                      VA1.getLocVT(), CCValAssign::Full));
4715   } else {
4716     // Both halves must be passed on the stack, with proper alignment.
4717     Align StackAlign =
4718         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
4719     State.addLoc(
4720         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
4721                             State.AllocateStack(XLenInBytes, StackAlign),
4722                             VA1.getLocVT(), CCValAssign::Full));
4723     State.addLoc(CCValAssign::getMem(
4724         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
4725         LocVT2, CCValAssign::Full));
4726     return false;
4727   }
4728 
4729   if (Register Reg = State.AllocateReg(ArgGPRs)) {
4730     // The second half can also be passed via register.
4731     State.addLoc(
4732         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
4733   } else {
4734     // The second half is passed via the stack, without additional alignment.
4735     State.addLoc(CCValAssign::getMem(
4736         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
4737         LocVT2, CCValAssign::Full));
4738   }
4739 
4740   return false;
4741 }
4742 
4743 // Implements the RISC-V calling convention. Returns true upon failure.
4744 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
4745                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
4746                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
4747                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
4748                      Optional<unsigned> FirstMaskArgument) {
4749   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
4750   assert(XLen == 32 || XLen == 64);
4751   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
4752 
4753   // Any return value split in to more than two values can't be returned
4754   // directly.
4755   if (IsRet && ValNo > 1)
4756     return true;
4757 
4758   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
4759   // variadic argument, or if no F16/F32 argument registers are available.
4760   bool UseGPRForF16_F32 = true;
4761   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
4762   // variadic argument, or if no F64 argument registers are available.
4763   bool UseGPRForF64 = true;
4764 
4765   switch (ABI) {
4766   default:
4767     llvm_unreachable("Unexpected ABI");
4768   case RISCVABI::ABI_ILP32:
4769   case RISCVABI::ABI_LP64:
4770     break;
4771   case RISCVABI::ABI_ILP32F:
4772   case RISCVABI::ABI_LP64F:
4773     UseGPRForF16_F32 = !IsFixed;
4774     break;
4775   case RISCVABI::ABI_ILP32D:
4776   case RISCVABI::ABI_LP64D:
4777     UseGPRForF16_F32 = !IsFixed;
4778     UseGPRForF64 = !IsFixed;
4779     break;
4780   }
4781 
4782   // FPR16, FPR32, and FPR64 alias each other.
4783   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
4784     UseGPRForF16_F32 = true;
4785     UseGPRForF64 = true;
4786   }
4787 
4788   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
4789   // similar local variables rather than directly checking against the target
4790   // ABI.
4791 
4792   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
4793     LocVT = XLenVT;
4794     LocInfo = CCValAssign::BCvt;
4795   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
4796     LocVT = MVT::i64;
4797     LocInfo = CCValAssign::BCvt;
4798   }
4799 
4800   // If this is a variadic argument, the RISC-V calling convention requires
4801   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
4802   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
4803   // be used regardless of whether the original argument was split during
4804   // legalisation or not. The argument will not be passed by registers if the
4805   // original type is larger than 2*XLEN, so the register alignment rule does
4806   // not apply.
4807   unsigned TwoXLenInBytes = (2 * XLen) / 8;
4808   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
4809       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
4810     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
4811     // Skip 'odd' register if necessary.
4812     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
4813       State.AllocateReg(ArgGPRs);
4814   }
4815 
4816   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
4817   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
4818       State.getPendingArgFlags();
4819 
4820   assert(PendingLocs.size() == PendingArgFlags.size() &&
4821          "PendingLocs and PendingArgFlags out of sync");
4822 
4823   // Handle passing f64 on RV32D with a soft float ABI or when floating point
4824   // registers are exhausted.
4825   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
4826     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
4827            "Can't lower f64 if it is split");
4828     // Depending on available argument GPRS, f64 may be passed in a pair of
4829     // GPRs, split between a GPR and the stack, or passed completely on the
4830     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
4831     // cases.
4832     Register Reg = State.AllocateReg(ArgGPRs);
4833     LocVT = MVT::i32;
4834     if (!Reg) {
4835       unsigned StackOffset = State.AllocateStack(8, Align(8));
4836       State.addLoc(
4837           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
4838       return false;
4839     }
4840     if (!State.AllocateReg(ArgGPRs))
4841       State.AllocateStack(4, Align(4));
4842     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
4843     return false;
4844   }
4845 
4846   // Split arguments might be passed indirectly, so keep track of the pending
4847   // values.
4848   if (ArgFlags.isSplit() || !PendingLocs.empty()) {
4849     LocVT = XLenVT;
4850     LocInfo = CCValAssign::Indirect;
4851     PendingLocs.push_back(
4852         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
4853     PendingArgFlags.push_back(ArgFlags);
4854     if (!ArgFlags.isSplitEnd()) {
4855       return false;
4856     }
4857   }
4858 
4859   // If the split argument only had two elements, it should be passed directly
4860   // in registers or on the stack.
4861   if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
4862     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
4863     // Apply the normal calling convention rules to the first half of the
4864     // split argument.
4865     CCValAssign VA = PendingLocs[0];
4866     ISD::ArgFlagsTy AF = PendingArgFlags[0];
4867     PendingLocs.clear();
4868     PendingArgFlags.clear();
4869     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
4870                                ArgFlags);
4871   }
4872 
4873   // Allocate to a register if possible, or else a stack slot.
4874   Register Reg;
4875   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
4876     Reg = State.AllocateReg(ArgFPR16s);
4877   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
4878     Reg = State.AllocateReg(ArgFPR32s);
4879   else if (ValVT == MVT::f64 && !UseGPRForF64)
4880     Reg = State.AllocateReg(ArgFPR64s);
4881   else if (ValVT.isScalableVector()) {
4882     const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
4883     if (RC == &RISCV::VRRegClass) {
4884       // Assign the first mask argument to V0.
4885       // This is an interim calling convention and it may be changed in the
4886       // future.
4887       if (FirstMaskArgument.hasValue() &&
4888           ValNo == FirstMaskArgument.getValue()) {
4889         Reg = State.AllocateReg(RISCV::V0);
4890       } else {
4891         Reg = State.AllocateReg(ArgVRs);
4892       }
4893     } else if (RC == &RISCV::VRM2RegClass) {
4894       Reg = State.AllocateReg(ArgVRM2s);
4895     } else if (RC == &RISCV::VRM4RegClass) {
4896       Reg = State.AllocateReg(ArgVRM4s);
4897     } else if (RC == &RISCV::VRM8RegClass) {
4898       Reg = State.AllocateReg(ArgVRM8s);
4899     } else {
4900       llvm_unreachable("Unhandled class register for ValueType");
4901     }
4902     if (!Reg) {
4903       LocInfo = CCValAssign::Indirect;
4904       // Try using a GPR to pass the address
4905       Reg = State.AllocateReg(ArgGPRs);
4906       LocVT = XLenVT;
4907     }
4908   } else
4909     Reg = State.AllocateReg(ArgGPRs);
4910   unsigned StackOffset =
4911       Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8));
4912 
4913   // If we reach this point and PendingLocs is non-empty, we must be at the
4914   // end of a split argument that must be passed indirectly.
4915   if (!PendingLocs.empty()) {
4916     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
4917     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
4918 
4919     for (auto &It : PendingLocs) {
4920       if (Reg)
4921         It.convertToReg(Reg);
4922       else
4923         It.convertToMem(StackOffset);
4924       State.addLoc(It);
4925     }
4926     PendingLocs.clear();
4927     PendingArgFlags.clear();
4928     return false;
4929   }
4930 
4931   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
4932           (TLI.getSubtarget().hasStdExtV() && ValVT.isScalableVector())) &&
4933          "Expected an XLenVT or scalable vector types at this stage");
4934 
4935   if (Reg) {
4936     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
4937     return false;
4938   }
4939 
4940   // When a floating-point value is passed on the stack, no bit-conversion is
4941   // needed.
4942   if (ValVT.isFloatingPoint()) {
4943     LocVT = ValVT;
4944     LocInfo = CCValAssign::Full;
4945   }
4946   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
4947   return false;
4948 }
4949 
4950 template <typename ArgTy>
4951 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
4952   for (const auto &ArgIdx : enumerate(Args)) {
4953     MVT ArgVT = ArgIdx.value().VT;
4954     if (ArgVT.isScalableVector() &&
4955         ArgVT.getVectorElementType().SimpleTy == MVT::i1)
4956       return ArgIdx.index();
4957   }
4958   return None;
4959 }
4960 
4961 void RISCVTargetLowering::analyzeInputArgs(
4962     MachineFunction &MF, CCState &CCInfo,
4963     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
4964   unsigned NumArgs = Ins.size();
4965   FunctionType *FType = MF.getFunction().getFunctionType();
4966 
4967   Optional<unsigned> FirstMaskArgument;
4968   if (Subtarget.hasStdExtV())
4969     FirstMaskArgument = preAssignMask(Ins);
4970 
4971   for (unsigned i = 0; i != NumArgs; ++i) {
4972     MVT ArgVT = Ins[i].VT;
4973     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
4974 
4975     Type *ArgTy = nullptr;
4976     if (IsRet)
4977       ArgTy = FType->getReturnType();
4978     else if (Ins[i].isOrigArg())
4979       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
4980 
4981     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
4982     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
4983                  ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
4984                  FirstMaskArgument)) {
4985       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
4986                         << EVT(ArgVT).getEVTString() << '\n');
4987       llvm_unreachable(nullptr);
4988     }
4989   }
4990 }
4991 
4992 void RISCVTargetLowering::analyzeOutputArgs(
4993     MachineFunction &MF, CCState &CCInfo,
4994     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
4995     CallLoweringInfo *CLI) const {
4996   unsigned NumArgs = Outs.size();
4997 
4998   Optional<unsigned> FirstMaskArgument;
4999   if (Subtarget.hasStdExtV())
5000     FirstMaskArgument = preAssignMask(Outs);
5001 
5002   for (unsigned i = 0; i != NumArgs; i++) {
5003     MVT ArgVT = Outs[i].VT;
5004     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5005     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
5006 
5007     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
5008     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
5009                  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
5010                  FirstMaskArgument)) {
5011       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
5012                         << EVT(ArgVT).getEVTString() << "\n");
5013       llvm_unreachable(nullptr);
5014     }
5015   }
5016 }
5017 
5018 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
5019 // values.
5020 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
5021                                    const CCValAssign &VA, const SDLoc &DL) {
5022   switch (VA.getLocInfo()) {
5023   default:
5024     llvm_unreachable("Unexpected CCValAssign::LocInfo");
5025   case CCValAssign::Full:
5026     break;
5027   case CCValAssign::BCvt:
5028     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
5029       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
5030     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
5031       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
5032     else
5033       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
5034     break;
5035   }
5036   return Val;
5037 }
5038 
5039 // The caller is responsible for loading the full value if the argument is
5040 // passed with CCValAssign::Indirect.
5041 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
5042                                 const CCValAssign &VA, const SDLoc &DL,
5043                                 const RISCVTargetLowering &TLI) {
5044   MachineFunction &MF = DAG.getMachineFunction();
5045   MachineRegisterInfo &RegInfo = MF.getRegInfo();
5046   EVT LocVT = VA.getLocVT();
5047   SDValue Val;
5048   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
5049   Register VReg = RegInfo.createVirtualRegister(RC);
5050   RegInfo.addLiveIn(VA.getLocReg(), VReg);
5051   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
5052 
5053   if (VA.getLocInfo() == CCValAssign::Indirect)
5054     return Val;
5055 
5056   return convertLocVTToValVT(DAG, Val, VA, DL);
5057 }
5058 
5059 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
5060                                    const CCValAssign &VA, const SDLoc &DL) {
5061   EVT LocVT = VA.getLocVT();
5062 
5063   switch (VA.getLocInfo()) {
5064   default:
5065     llvm_unreachable("Unexpected CCValAssign::LocInfo");
5066   case CCValAssign::Full:
5067     break;
5068   case CCValAssign::BCvt:
5069     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
5070       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
5071     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
5072       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
5073     else
5074       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
5075     break;
5076   }
5077   return Val;
5078 }
5079 
5080 // The caller is responsible for loading the full value if the argument is
5081 // passed with CCValAssign::Indirect.
5082 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
5083                                 const CCValAssign &VA, const SDLoc &DL) {
5084   MachineFunction &MF = DAG.getMachineFunction();
5085   MachineFrameInfo &MFI = MF.getFrameInfo();
5086   EVT LocVT = VA.getLocVT();
5087   EVT ValVT = VA.getValVT();
5088   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
5089   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
5090                                  VA.getLocMemOffset(), /*Immutable=*/true);
5091   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
5092   SDValue Val;
5093 
5094   ISD::LoadExtType ExtType;
5095   switch (VA.getLocInfo()) {
5096   default:
5097     llvm_unreachable("Unexpected CCValAssign::LocInfo");
5098   case CCValAssign::Full:
5099   case CCValAssign::Indirect:
5100   case CCValAssign::BCvt:
5101     ExtType = ISD::NON_EXTLOAD;
5102     break;
5103   }
5104   Val = DAG.getExtLoad(
5105       ExtType, DL, LocVT, Chain, FIN,
5106       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
5107   return Val;
5108 }
5109 
5110 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
5111                                        const CCValAssign &VA, const SDLoc &DL) {
5112   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
5113          "Unexpected VA");
5114   MachineFunction &MF = DAG.getMachineFunction();
5115   MachineFrameInfo &MFI = MF.getFrameInfo();
5116   MachineRegisterInfo &RegInfo = MF.getRegInfo();
5117 
5118   if (VA.isMemLoc()) {
5119     // f64 is passed on the stack.
5120     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
5121     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
5122     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
5123                        MachinePointerInfo::getFixedStack(MF, FI));
5124   }
5125 
5126   assert(VA.isRegLoc() && "Expected register VA assignment");
5127 
5128   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
5129   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
5130   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
5131   SDValue Hi;
5132   if (VA.getLocReg() == RISCV::X17) {
5133     // Second half of f64 is passed on the stack.
5134     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
5135     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
5136     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
5137                      MachinePointerInfo::getFixedStack(MF, FI));
5138   } else {
5139     // Second half of f64 is passed in another GPR.
5140     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
5141     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
5142     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
5143   }
5144   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
5145 }
5146 
5147 // FastCC has less than 1% performance improvement for some particular
5148 // benchmark. But theoretically, it may has benenfit for some cases.
5149 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT,
5150                             CCValAssign::LocInfo LocInfo,
5151                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
5152 
5153   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
5154     // X5 and X6 might be used for save-restore libcall.
5155     static const MCPhysReg GPRList[] = {
5156         RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
5157         RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
5158         RISCV::X29, RISCV::X30, RISCV::X31};
5159     if (unsigned Reg = State.AllocateReg(GPRList)) {
5160       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
5161       return false;
5162     }
5163   }
5164 
5165   if (LocVT == MVT::f16) {
5166     static const MCPhysReg FPR16List[] = {
5167         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
5168         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
5169         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
5170         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
5171     if (unsigned Reg = State.AllocateReg(FPR16List)) {
5172       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
5173       return false;
5174     }
5175   }
5176 
5177   if (LocVT == MVT::f32) {
5178     static const MCPhysReg FPR32List[] = {
5179         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
5180         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
5181         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
5182         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
5183     if (unsigned Reg = State.AllocateReg(FPR32List)) {
5184       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
5185       return false;
5186     }
5187   }
5188 
5189   if (LocVT == MVT::f64) {
5190     static const MCPhysReg FPR64List[] = {
5191         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
5192         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
5193         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
5194         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
5195     if (unsigned Reg = State.AllocateReg(FPR64List)) {
5196       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
5197       return false;
5198     }
5199   }
5200 
5201   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
5202     unsigned Offset4 = State.AllocateStack(4, Align(4));
5203     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
5204     return false;
5205   }
5206 
5207   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
5208     unsigned Offset5 = State.AllocateStack(8, Align(8));
5209     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
5210     return false;
5211   }
5212 
5213   return true; // CC didn't match.
5214 }
5215 
5216 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
5217                          CCValAssign::LocInfo LocInfo,
5218                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
5219 
5220   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
5221     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
5222     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
5223     static const MCPhysReg GPRList[] = {
5224         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
5225         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
5226     if (unsigned Reg = State.AllocateReg(GPRList)) {
5227       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
5228       return false;
5229     }
5230   }
5231 
5232   if (LocVT == MVT::f32) {
5233     // Pass in STG registers: F1, ..., F6
5234     //                        fs0 ... fs5
5235     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
5236                                           RISCV::F18_F, RISCV::F19_F,
5237                                           RISCV::F20_F, RISCV::F21_F};
5238     if (unsigned Reg = State.AllocateReg(FPR32List)) {
5239       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
5240       return false;
5241     }
5242   }
5243 
5244   if (LocVT == MVT::f64) {
5245     // Pass in STG registers: D1, ..., D6
5246     //                        fs6 ... fs11
5247     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
5248                                           RISCV::F24_D, RISCV::F25_D,
5249                                           RISCV::F26_D, RISCV::F27_D};
5250     if (unsigned Reg = State.AllocateReg(FPR64List)) {
5251       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
5252       return false;
5253     }
5254   }
5255 
5256   report_fatal_error("No registers left in GHC calling convention");
5257   return true;
5258 }
5259 
5260 // Transform physical registers into virtual registers.
5261 SDValue RISCVTargetLowering::LowerFormalArguments(
5262     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
5263     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
5264     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5265 
5266   MachineFunction &MF = DAG.getMachineFunction();
5267 
5268   switch (CallConv) {
5269   default:
5270     report_fatal_error("Unsupported calling convention");
5271   case CallingConv::C:
5272   case CallingConv::Fast:
5273     break;
5274   case CallingConv::GHC:
5275     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
5276         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
5277       report_fatal_error(
5278         "GHC calling convention requires the F and D instruction set extensions");
5279   }
5280 
5281   const Function &Func = MF.getFunction();
5282   if (Func.hasFnAttribute("interrupt")) {
5283     if (!Func.arg_empty())
5284       report_fatal_error(
5285         "Functions with the interrupt attribute cannot have arguments!");
5286 
5287     StringRef Kind =
5288       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
5289 
5290     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
5291       report_fatal_error(
5292         "Function interrupt attribute argument not supported!");
5293   }
5294 
5295   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5296   MVT XLenVT = Subtarget.getXLenVT();
5297   unsigned XLenInBytes = Subtarget.getXLen() / 8;
5298   // Used with vargs to acumulate store chains.
5299   std::vector<SDValue> OutChains;
5300 
5301   // Assign locations to all of the incoming arguments.
5302   SmallVector<CCValAssign, 16> ArgLocs;
5303   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5304 
5305   if (CallConv == CallingConv::Fast)
5306     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC);
5307   else if (CallConv == CallingConv::GHC)
5308     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
5309   else
5310     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
5311 
5312   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
5313     CCValAssign &VA = ArgLocs[i];
5314     SDValue ArgValue;
5315     // Passing f64 on RV32D with a soft float ABI must be handled as a special
5316     // case.
5317     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
5318       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
5319     else if (VA.isRegLoc())
5320       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
5321     else
5322       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
5323 
5324     if (VA.getLocInfo() == CCValAssign::Indirect) {
5325       // If the original argument was split and passed by reference (e.g. i128
5326       // on RV32), we need to load all parts of it here (using the same
5327       // address).
5328       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
5329                                    MachinePointerInfo()));
5330       unsigned ArgIndex = Ins[i].OrigArgIndex;
5331       assert(Ins[i].PartOffset == 0);
5332       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
5333         CCValAssign &PartVA = ArgLocs[i + 1];
5334         unsigned PartOffset = Ins[i + 1].PartOffset;
5335         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
5336                                       DAG.getIntPtrConstant(PartOffset, DL));
5337         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
5338                                      MachinePointerInfo()));
5339         ++i;
5340       }
5341       continue;
5342     }
5343     InVals.push_back(ArgValue);
5344   }
5345 
5346   if (IsVarArg) {
5347     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
5348     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
5349     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
5350     MachineFrameInfo &MFI = MF.getFrameInfo();
5351     MachineRegisterInfo &RegInfo = MF.getRegInfo();
5352     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
5353 
5354     // Offset of the first variable argument from stack pointer, and size of
5355     // the vararg save area. For now, the varargs save area is either zero or
5356     // large enough to hold a0-a7.
5357     int VaArgOffset, VarArgsSaveSize;
5358 
5359     // If all registers are allocated, then all varargs must be passed on the
5360     // stack and we don't need to save any argregs.
5361     if (ArgRegs.size() == Idx) {
5362       VaArgOffset = CCInfo.getNextStackOffset();
5363       VarArgsSaveSize = 0;
5364     } else {
5365       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
5366       VaArgOffset = -VarArgsSaveSize;
5367     }
5368 
5369     // Record the frame index of the first variable argument
5370     // which is a value necessary to VASTART.
5371     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
5372     RVFI->setVarArgsFrameIndex(FI);
5373 
5374     // If saving an odd number of registers then create an extra stack slot to
5375     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
5376     // offsets to even-numbered registered remain 2*XLEN-aligned.
5377     if (Idx % 2) {
5378       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
5379       VarArgsSaveSize += XLenInBytes;
5380     }
5381 
5382     // Copy the integer registers that may have been used for passing varargs
5383     // to the vararg save area.
5384     for (unsigned I = Idx; I < ArgRegs.size();
5385          ++I, VaArgOffset += XLenInBytes) {
5386       const Register Reg = RegInfo.createVirtualRegister(RC);
5387       RegInfo.addLiveIn(ArgRegs[I], Reg);
5388       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
5389       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
5390       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
5391       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
5392                                    MachinePointerInfo::getFixedStack(MF, FI));
5393       cast<StoreSDNode>(Store.getNode())
5394           ->getMemOperand()
5395           ->setValue((Value *)nullptr);
5396       OutChains.push_back(Store);
5397     }
5398     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
5399   }
5400 
5401   // All stores are grouped in one node to allow the matching between
5402   // the size of Ins and InVals. This only happens for vararg functions.
5403   if (!OutChains.empty()) {
5404     OutChains.push_back(Chain);
5405     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
5406   }
5407 
5408   return Chain;
5409 }
5410 
5411 /// isEligibleForTailCallOptimization - Check whether the call is eligible
5412 /// for tail call optimization.
5413 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
5414 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
5415     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
5416     const SmallVector<CCValAssign, 16> &ArgLocs) const {
5417 
5418   auto &Callee = CLI.Callee;
5419   auto CalleeCC = CLI.CallConv;
5420   auto &Outs = CLI.Outs;
5421   auto &Caller = MF.getFunction();
5422   auto CallerCC = Caller.getCallingConv();
5423 
5424   // Exception-handling functions need a special set of instructions to
5425   // indicate a return to the hardware. Tail-calling another function would
5426   // probably break this.
5427   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
5428   // should be expanded as new function attributes are introduced.
5429   if (Caller.hasFnAttribute("interrupt"))
5430     return false;
5431 
5432   // Do not tail call opt if the stack is used to pass parameters.
5433   if (CCInfo.getNextStackOffset() != 0)
5434     return false;
5435 
5436   // Do not tail call opt if any parameters need to be passed indirectly.
5437   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
5438   // passed indirectly. So the address of the value will be passed in a
5439   // register, or if not available, then the address is put on the stack. In
5440   // order to pass indirectly, space on the stack often needs to be allocated
5441   // in order to store the value. In this case the CCInfo.getNextStackOffset()
5442   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
5443   // are passed CCValAssign::Indirect.
5444   for (auto &VA : ArgLocs)
5445     if (VA.getLocInfo() == CCValAssign::Indirect)
5446       return false;
5447 
5448   // Do not tail call opt if either caller or callee uses struct return
5449   // semantics.
5450   auto IsCallerStructRet = Caller.hasStructRetAttr();
5451   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
5452   if (IsCallerStructRet || IsCalleeStructRet)
5453     return false;
5454 
5455   // Externally-defined functions with weak linkage should not be
5456   // tail-called. The behaviour of branch instructions in this situation (as
5457   // used for tail calls) is implementation-defined, so we cannot rely on the
5458   // linker replacing the tail call with a return.
5459   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5460     const GlobalValue *GV = G->getGlobal();
5461     if (GV->hasExternalWeakLinkage())
5462       return false;
5463   }
5464 
5465   // The callee has to preserve all registers the caller needs to preserve.
5466   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5467   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
5468   if (CalleeCC != CallerCC) {
5469     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
5470     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
5471       return false;
5472   }
5473 
5474   // Byval parameters hand the function a pointer directly into the stack area
5475   // we want to reuse during a tail call. Working around this *is* possible
5476   // but less efficient and uglier in LowerCall.
5477   for (auto &Arg : Outs)
5478     if (Arg.Flags.isByVal())
5479       return false;
5480 
5481   return true;
5482 }
5483 
5484 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
5485 // and output parameter nodes.
5486 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
5487                                        SmallVectorImpl<SDValue> &InVals) const {
5488   SelectionDAG &DAG = CLI.DAG;
5489   SDLoc &DL = CLI.DL;
5490   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5491   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5492   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
5493   SDValue Chain = CLI.Chain;
5494   SDValue Callee = CLI.Callee;
5495   bool &IsTailCall = CLI.IsTailCall;
5496   CallingConv::ID CallConv = CLI.CallConv;
5497   bool IsVarArg = CLI.IsVarArg;
5498   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5499   MVT XLenVT = Subtarget.getXLenVT();
5500 
5501   MachineFunction &MF = DAG.getMachineFunction();
5502 
5503   // Analyze the operands of the call, assigning locations to each operand.
5504   SmallVector<CCValAssign, 16> ArgLocs;
5505   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5506 
5507   if (CallConv == CallingConv::Fast)
5508     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC);
5509   else if (CallConv == CallingConv::GHC)
5510     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
5511   else
5512     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
5513 
5514   // Check if it's really possible to do a tail call.
5515   if (IsTailCall)
5516     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
5517 
5518   if (IsTailCall)
5519     ++NumTailCalls;
5520   else if (CLI.CB && CLI.CB->isMustTailCall())
5521     report_fatal_error("failed to perform tail call elimination on a call "
5522                        "site marked musttail");
5523 
5524   // Get a count of how many bytes are to be pushed on the stack.
5525   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
5526 
5527   // Create local copies for byval args
5528   SmallVector<SDValue, 8> ByValArgs;
5529   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
5530     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5531     if (!Flags.isByVal())
5532       continue;
5533 
5534     SDValue Arg = OutVals[i];
5535     unsigned Size = Flags.getByValSize();
5536     Align Alignment = Flags.getNonZeroByValAlign();
5537 
5538     int FI =
5539         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
5540     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
5541     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
5542 
5543     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
5544                           /*IsVolatile=*/false,
5545                           /*AlwaysInline=*/false, IsTailCall,
5546                           MachinePointerInfo(), MachinePointerInfo());
5547     ByValArgs.push_back(FIPtr);
5548   }
5549 
5550   if (!IsTailCall)
5551     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
5552 
5553   // Copy argument values to their designated locations.
5554   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
5555   SmallVector<SDValue, 8> MemOpChains;
5556   SDValue StackPtr;
5557   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
5558     CCValAssign &VA = ArgLocs[i];
5559     SDValue ArgValue = OutVals[i];
5560     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5561 
5562     // Handle passing f64 on RV32D with a soft float ABI as a special case.
5563     bool IsF64OnRV32DSoftABI =
5564         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
5565     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
5566       SDValue SplitF64 = DAG.getNode(
5567           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
5568       SDValue Lo = SplitF64.getValue(0);
5569       SDValue Hi = SplitF64.getValue(1);
5570 
5571       Register RegLo = VA.getLocReg();
5572       RegsToPass.push_back(std::make_pair(RegLo, Lo));
5573 
5574       if (RegLo == RISCV::X17) {
5575         // Second half of f64 is passed on the stack.
5576         // Work out the address of the stack slot.
5577         if (!StackPtr.getNode())
5578           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
5579         // Emit the store.
5580         MemOpChains.push_back(
5581             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
5582       } else {
5583         // Second half of f64 is passed in another GPR.
5584         assert(RegLo < RISCV::X31 && "Invalid register pair");
5585         Register RegHigh = RegLo + 1;
5586         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
5587       }
5588       continue;
5589     }
5590 
5591     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
5592     // as any other MemLoc.
5593 
5594     // Promote the value if needed.
5595     // For now, only handle fully promoted and indirect arguments.
5596     if (VA.getLocInfo() == CCValAssign::Indirect) {
5597       // Store the argument in a stack slot and pass its address.
5598       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
5599       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
5600       MemOpChains.push_back(
5601           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
5602                        MachinePointerInfo::getFixedStack(MF, FI)));
5603       // If the original argument was split (e.g. i128), we need
5604       // to store all parts of it here (and pass just one address).
5605       unsigned ArgIndex = Outs[i].OrigArgIndex;
5606       assert(Outs[i].PartOffset == 0);
5607       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
5608         SDValue PartValue = OutVals[i + 1];
5609         unsigned PartOffset = Outs[i + 1].PartOffset;
5610         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
5611                                       DAG.getIntPtrConstant(PartOffset, DL));
5612         MemOpChains.push_back(
5613             DAG.getStore(Chain, DL, PartValue, Address,
5614                          MachinePointerInfo::getFixedStack(MF, FI)));
5615         ++i;
5616       }
5617       ArgValue = SpillSlot;
5618     } else {
5619       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
5620     }
5621 
5622     // Use local copy if it is a byval arg.
5623     if (Flags.isByVal())
5624       ArgValue = ByValArgs[j++];
5625 
5626     if (VA.isRegLoc()) {
5627       // Queue up the argument copies and emit them at the end.
5628       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
5629     } else {
5630       assert(VA.isMemLoc() && "Argument not register or memory");
5631       assert(!IsTailCall && "Tail call not allowed if stack is used "
5632                             "for passing parameters");
5633 
5634       // Work out the address of the stack slot.
5635       if (!StackPtr.getNode())
5636         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
5637       SDValue Address =
5638           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
5639                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
5640 
5641       // Emit the store.
5642       MemOpChains.push_back(
5643           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
5644     }
5645   }
5646 
5647   // Join the stores, which are independent of one another.
5648   if (!MemOpChains.empty())
5649     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
5650 
5651   SDValue Glue;
5652 
5653   // Build a sequence of copy-to-reg nodes, chained and glued together.
5654   for (auto &Reg : RegsToPass) {
5655     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
5656     Glue = Chain.getValue(1);
5657   }
5658 
5659   // Validate that none of the argument registers have been marked as
5660   // reserved, if so report an error. Do the same for the return address if this
5661   // is not a tailcall.
5662   validateCCReservedRegs(RegsToPass, MF);
5663   if (!IsTailCall &&
5664       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
5665     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
5666         MF.getFunction(),
5667         "Return address register required, but has been reserved."});
5668 
5669   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
5670   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
5671   // split it and then direct call can be matched by PseudoCALL.
5672   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
5673     const GlobalValue *GV = S->getGlobal();
5674 
5675     unsigned OpFlags = RISCVII::MO_CALL;
5676     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
5677       OpFlags = RISCVII::MO_PLT;
5678 
5679     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
5680   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5681     unsigned OpFlags = RISCVII::MO_CALL;
5682 
5683     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
5684                                                  nullptr))
5685       OpFlags = RISCVII::MO_PLT;
5686 
5687     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
5688   }
5689 
5690   // The first call operand is the chain and the second is the target address.
5691   SmallVector<SDValue, 8> Ops;
5692   Ops.push_back(Chain);
5693   Ops.push_back(Callee);
5694 
5695   // Add argument registers to the end of the list so that they are
5696   // known live into the call.
5697   for (auto &Reg : RegsToPass)
5698     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
5699 
5700   if (!IsTailCall) {
5701     // Add a register mask operand representing the call-preserved registers.
5702     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5703     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
5704     assert(Mask && "Missing call preserved mask for calling convention");
5705     Ops.push_back(DAG.getRegisterMask(Mask));
5706   }
5707 
5708   // Glue the call to the argument copies, if any.
5709   if (Glue.getNode())
5710     Ops.push_back(Glue);
5711 
5712   // Emit the call.
5713   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5714 
5715   if (IsTailCall) {
5716     MF.getFrameInfo().setHasTailCall();
5717     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
5718   }
5719 
5720   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
5721   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
5722   Glue = Chain.getValue(1);
5723 
5724   // Mark the end of the call, which is glued to the call itself.
5725   Chain = DAG.getCALLSEQ_END(Chain,
5726                              DAG.getConstant(NumBytes, DL, PtrVT, true),
5727                              DAG.getConstant(0, DL, PtrVT, true),
5728                              Glue, DL);
5729   Glue = Chain.getValue(1);
5730 
5731   // Assign locations to each value returned by this call.
5732   SmallVector<CCValAssign, 16> RVLocs;
5733   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
5734   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
5735 
5736   // Copy all of the result registers out of their specified physreg.
5737   for (auto &VA : RVLocs) {
5738     // Copy the value out
5739     SDValue RetValue =
5740         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
5741     // Glue the RetValue to the end of the call sequence
5742     Chain = RetValue.getValue(1);
5743     Glue = RetValue.getValue(2);
5744 
5745     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
5746       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
5747       SDValue RetValue2 =
5748           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
5749       Chain = RetValue2.getValue(1);
5750       Glue = RetValue2.getValue(2);
5751       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
5752                              RetValue2);
5753     }
5754 
5755     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
5756 
5757     InVals.push_back(RetValue);
5758   }
5759 
5760   return Chain;
5761 }
5762 
5763 bool RISCVTargetLowering::CanLowerReturn(
5764     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
5765     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
5766   SmallVector<CCValAssign, 16> RVLocs;
5767   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
5768 
5769   Optional<unsigned> FirstMaskArgument;
5770   if (Subtarget.hasStdExtV())
5771     FirstMaskArgument = preAssignMask(Outs);
5772 
5773   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
5774     MVT VT = Outs[i].VT;
5775     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5776     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
5777     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
5778                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
5779                  *this, FirstMaskArgument))
5780       return false;
5781   }
5782   return true;
5783 }
5784 
5785 SDValue
5786 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
5787                                  bool IsVarArg,
5788                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
5789                                  const SmallVectorImpl<SDValue> &OutVals,
5790                                  const SDLoc &DL, SelectionDAG &DAG) const {
5791   const MachineFunction &MF = DAG.getMachineFunction();
5792   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
5793 
5794   // Stores the assignment of the return value to a location.
5795   SmallVector<CCValAssign, 16> RVLocs;
5796 
5797   // Info about the registers and stack slot.
5798   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
5799                  *DAG.getContext());
5800 
5801   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
5802                     nullptr);
5803 
5804   if (CallConv == CallingConv::GHC && !RVLocs.empty())
5805     report_fatal_error("GHC functions return void only");
5806 
5807   SDValue Glue;
5808   SmallVector<SDValue, 4> RetOps(1, Chain);
5809 
5810   // Copy the result values into the output registers.
5811   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
5812     SDValue Val = OutVals[i];
5813     CCValAssign &VA = RVLocs[i];
5814     assert(VA.isRegLoc() && "Can only return in registers!");
5815 
5816     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
5817       // Handle returning f64 on RV32D with a soft float ABI.
5818       assert(VA.isRegLoc() && "Expected return via registers");
5819       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
5820                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
5821       SDValue Lo = SplitF64.getValue(0);
5822       SDValue Hi = SplitF64.getValue(1);
5823       Register RegLo = VA.getLocReg();
5824       assert(RegLo < RISCV::X31 && "Invalid register pair");
5825       Register RegHi = RegLo + 1;
5826 
5827       if (STI.isRegisterReservedByUser(RegLo) ||
5828           STI.isRegisterReservedByUser(RegHi))
5829         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
5830             MF.getFunction(),
5831             "Return value register required, but has been reserved."});
5832 
5833       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
5834       Glue = Chain.getValue(1);
5835       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
5836       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
5837       Glue = Chain.getValue(1);
5838       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
5839     } else {
5840       // Handle a 'normal' return.
5841       Val = convertValVTToLocVT(DAG, Val, VA, DL);
5842       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
5843 
5844       if (STI.isRegisterReservedByUser(VA.getLocReg()))
5845         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
5846             MF.getFunction(),
5847             "Return value register required, but has been reserved."});
5848 
5849       // Guarantee that all emitted copies are stuck together.
5850       Glue = Chain.getValue(1);
5851       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5852     }
5853   }
5854 
5855   RetOps[0] = Chain; // Update chain.
5856 
5857   // Add the glue node if we have it.
5858   if (Glue.getNode()) {
5859     RetOps.push_back(Glue);
5860   }
5861 
5862   // Interrupt service routines use different return instructions.
5863   const Function &Func = DAG.getMachineFunction().getFunction();
5864   if (Func.hasFnAttribute("interrupt")) {
5865     if (!Func.getReturnType()->isVoidTy())
5866       report_fatal_error(
5867           "Functions with the interrupt attribute must have void return type!");
5868 
5869     MachineFunction &MF = DAG.getMachineFunction();
5870     StringRef Kind =
5871       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
5872 
5873     unsigned RetOpc;
5874     if (Kind == "user")
5875       RetOpc = RISCVISD::URET_FLAG;
5876     else if (Kind == "supervisor")
5877       RetOpc = RISCVISD::SRET_FLAG;
5878     else
5879       RetOpc = RISCVISD::MRET_FLAG;
5880 
5881     return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
5882   }
5883 
5884   return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
5885 }
5886 
5887 void RISCVTargetLowering::validateCCReservedRegs(
5888     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
5889     MachineFunction &MF) const {
5890   const Function &F = MF.getFunction();
5891   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
5892 
5893   if (llvm::any_of(Regs, [&STI](auto Reg) {
5894         return STI.isRegisterReservedByUser(Reg.first);
5895       }))
5896     F.getContext().diagnose(DiagnosticInfoUnsupported{
5897         F, "Argument register required, but has been reserved."});
5898 }
5899 
5900 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
5901   return CI->isTailCall();
5902 }
5903 
5904 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
5905 #define NODE_NAME_CASE(NODE)                                                   \
5906   case RISCVISD::NODE:                                                         \
5907     return "RISCVISD::" #NODE;
5908   // clang-format off
5909   switch ((RISCVISD::NodeType)Opcode) {
5910   case RISCVISD::FIRST_NUMBER:
5911     break;
5912   NODE_NAME_CASE(RET_FLAG)
5913   NODE_NAME_CASE(URET_FLAG)
5914   NODE_NAME_CASE(SRET_FLAG)
5915   NODE_NAME_CASE(MRET_FLAG)
5916   NODE_NAME_CASE(CALL)
5917   NODE_NAME_CASE(SELECT_CC)
5918   NODE_NAME_CASE(BuildPairF64)
5919   NODE_NAME_CASE(SplitF64)
5920   NODE_NAME_CASE(TAIL)
5921   NODE_NAME_CASE(SLLW)
5922   NODE_NAME_CASE(SRAW)
5923   NODE_NAME_CASE(SRLW)
5924   NODE_NAME_CASE(DIVW)
5925   NODE_NAME_CASE(DIVUW)
5926   NODE_NAME_CASE(REMUW)
5927   NODE_NAME_CASE(ROLW)
5928   NODE_NAME_CASE(RORW)
5929   NODE_NAME_CASE(FSLW)
5930   NODE_NAME_CASE(FSRW)
5931   NODE_NAME_CASE(FSL)
5932   NODE_NAME_CASE(FSR)
5933   NODE_NAME_CASE(FMV_H_X)
5934   NODE_NAME_CASE(FMV_X_ANYEXTH)
5935   NODE_NAME_CASE(FMV_W_X_RV64)
5936   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
5937   NODE_NAME_CASE(READ_CYCLE_WIDE)
5938   NODE_NAME_CASE(GREVI)
5939   NODE_NAME_CASE(GREVIW)
5940   NODE_NAME_CASE(GORCI)
5941   NODE_NAME_CASE(GORCIW)
5942   NODE_NAME_CASE(SHFLI)
5943   NODE_NAME_CASE(VMV_V_X_VL)
5944   NODE_NAME_CASE(VFMV_V_F_VL)
5945   NODE_NAME_CASE(VMV_X_S)
5946   NODE_NAME_CASE(VMV_S_XF_VL)
5947   NODE_NAME_CASE(SPLAT_VECTOR_I64)
5948   NODE_NAME_CASE(READ_VLENB)
5949   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
5950   NODE_NAME_CASE(VLEFF)
5951   NODE_NAME_CASE(VLEFF_MASK)
5952   NODE_NAME_CASE(VSLIDEUP_VL)
5953   NODE_NAME_CASE(VSLIDEDOWN_VL)
5954   NODE_NAME_CASE(VID_VL)
5955   NODE_NAME_CASE(VFNCVT_ROD_VL)
5956   NODE_NAME_CASE(VECREDUCE_ADD_VL)
5957   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
5958   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
5959   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
5960   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
5961   NODE_NAME_CASE(VECREDUCE_AND_VL)
5962   NODE_NAME_CASE(VECREDUCE_OR_VL)
5963   NODE_NAME_CASE(VECREDUCE_XOR_VL)
5964   NODE_NAME_CASE(VECREDUCE_FADD_VL)
5965   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
5966   NODE_NAME_CASE(ADD_VL)
5967   NODE_NAME_CASE(AND_VL)
5968   NODE_NAME_CASE(MUL_VL)
5969   NODE_NAME_CASE(OR_VL)
5970   NODE_NAME_CASE(SDIV_VL)
5971   NODE_NAME_CASE(SHL_VL)
5972   NODE_NAME_CASE(SREM_VL)
5973   NODE_NAME_CASE(SRA_VL)
5974   NODE_NAME_CASE(SRL_VL)
5975   NODE_NAME_CASE(SUB_VL)
5976   NODE_NAME_CASE(UDIV_VL)
5977   NODE_NAME_CASE(UREM_VL)
5978   NODE_NAME_CASE(XOR_VL)
5979   NODE_NAME_CASE(FADD_VL)
5980   NODE_NAME_CASE(FSUB_VL)
5981   NODE_NAME_CASE(FMUL_VL)
5982   NODE_NAME_CASE(FDIV_VL)
5983   NODE_NAME_CASE(FNEG_VL)
5984   NODE_NAME_CASE(FABS_VL)
5985   NODE_NAME_CASE(FSQRT_VL)
5986   NODE_NAME_CASE(FMA_VL)
5987   NODE_NAME_CASE(SMIN_VL)
5988   NODE_NAME_CASE(SMAX_VL)
5989   NODE_NAME_CASE(UMIN_VL)
5990   NODE_NAME_CASE(UMAX_VL)
5991   NODE_NAME_CASE(MULHS_VL)
5992   NODE_NAME_CASE(MULHU_VL)
5993   NODE_NAME_CASE(FP_TO_SINT_VL)
5994   NODE_NAME_CASE(FP_TO_UINT_VL)
5995   NODE_NAME_CASE(SINT_TO_FP_VL)
5996   NODE_NAME_CASE(UINT_TO_FP_VL)
5997   NODE_NAME_CASE(FP_EXTEND_VL)
5998   NODE_NAME_CASE(FP_ROUND_VL)
5999   NODE_NAME_CASE(SETCC_VL)
6000   NODE_NAME_CASE(VSELECT_VL)
6001   NODE_NAME_CASE(VMAND_VL)
6002   NODE_NAME_CASE(VMOR_VL)
6003   NODE_NAME_CASE(VMXOR_VL)
6004   NODE_NAME_CASE(VMCLR_VL)
6005   NODE_NAME_CASE(VMSET_VL)
6006   NODE_NAME_CASE(VRGATHER_VX_VL)
6007   NODE_NAME_CASE(VRGATHER_VV_VL)
6008   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
6009   NODE_NAME_CASE(VSEXT_VL)
6010   NODE_NAME_CASE(VZEXT_VL)
6011   NODE_NAME_CASE(VLE_VL)
6012   NODE_NAME_CASE(VSE_VL)
6013   }
6014   // clang-format on
6015   return nullptr;
6016 #undef NODE_NAME_CASE
6017 }
6018 
6019 /// getConstraintType - Given a constraint letter, return the type of
6020 /// constraint it is for this target.
6021 RISCVTargetLowering::ConstraintType
6022 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
6023   if (Constraint.size() == 1) {
6024     switch (Constraint[0]) {
6025     default:
6026       break;
6027     case 'f':
6028       return C_RegisterClass;
6029     case 'I':
6030     case 'J':
6031     case 'K':
6032       return C_Immediate;
6033     case 'A':
6034       return C_Memory;
6035     }
6036   }
6037   return TargetLowering::getConstraintType(Constraint);
6038 }
6039 
6040 std::pair<unsigned, const TargetRegisterClass *>
6041 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
6042                                                   StringRef Constraint,
6043                                                   MVT VT) const {
6044   // First, see if this is a constraint that directly corresponds to a
6045   // RISCV register class.
6046   if (Constraint.size() == 1) {
6047     switch (Constraint[0]) {
6048     case 'r':
6049       return std::make_pair(0U, &RISCV::GPRRegClass);
6050     case 'f':
6051       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
6052         return std::make_pair(0U, &RISCV::FPR16RegClass);
6053       if (Subtarget.hasStdExtF() && VT == MVT::f32)
6054         return std::make_pair(0U, &RISCV::FPR32RegClass);
6055       if (Subtarget.hasStdExtD() && VT == MVT::f64)
6056         return std::make_pair(0U, &RISCV::FPR64RegClass);
6057       break;
6058     default:
6059       break;
6060     }
6061   }
6062 
6063   // Clang will correctly decode the usage of register name aliases into their
6064   // official names. However, other frontends like `rustc` do not. This allows
6065   // users of these frontends to use the ABI names for registers in LLVM-style
6066   // register constraints.
6067   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
6068                                .Case("{zero}", RISCV::X0)
6069                                .Case("{ra}", RISCV::X1)
6070                                .Case("{sp}", RISCV::X2)
6071                                .Case("{gp}", RISCV::X3)
6072                                .Case("{tp}", RISCV::X4)
6073                                .Case("{t0}", RISCV::X5)
6074                                .Case("{t1}", RISCV::X6)
6075                                .Case("{t2}", RISCV::X7)
6076                                .Cases("{s0}", "{fp}", RISCV::X8)
6077                                .Case("{s1}", RISCV::X9)
6078                                .Case("{a0}", RISCV::X10)
6079                                .Case("{a1}", RISCV::X11)
6080                                .Case("{a2}", RISCV::X12)
6081                                .Case("{a3}", RISCV::X13)
6082                                .Case("{a4}", RISCV::X14)
6083                                .Case("{a5}", RISCV::X15)
6084                                .Case("{a6}", RISCV::X16)
6085                                .Case("{a7}", RISCV::X17)
6086                                .Case("{s2}", RISCV::X18)
6087                                .Case("{s3}", RISCV::X19)
6088                                .Case("{s4}", RISCV::X20)
6089                                .Case("{s5}", RISCV::X21)
6090                                .Case("{s6}", RISCV::X22)
6091                                .Case("{s7}", RISCV::X23)
6092                                .Case("{s8}", RISCV::X24)
6093                                .Case("{s9}", RISCV::X25)
6094                                .Case("{s10}", RISCV::X26)
6095                                .Case("{s11}", RISCV::X27)
6096                                .Case("{t3}", RISCV::X28)
6097                                .Case("{t4}", RISCV::X29)
6098                                .Case("{t5}", RISCV::X30)
6099                                .Case("{t6}", RISCV::X31)
6100                                .Default(RISCV::NoRegister);
6101   if (XRegFromAlias != RISCV::NoRegister)
6102     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
6103 
6104   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
6105   // TableGen record rather than the AsmName to choose registers for InlineAsm
6106   // constraints, plus we want to match those names to the widest floating point
6107   // register type available, manually select floating point registers here.
6108   //
6109   // The second case is the ABI name of the register, so that frontends can also
6110   // use the ABI names in register constraint lists.
6111   if (Subtarget.hasStdExtF()) {
6112     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
6113                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
6114                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
6115                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
6116                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
6117                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
6118                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
6119                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
6120                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
6121                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
6122                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
6123                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
6124                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
6125                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
6126                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
6127                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
6128                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
6129                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
6130                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
6131                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
6132                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
6133                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
6134                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
6135                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
6136                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
6137                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
6138                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
6139                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
6140                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
6141                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
6142                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
6143                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
6144                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
6145                         .Default(RISCV::NoRegister);
6146     if (FReg != RISCV::NoRegister) {
6147       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
6148       if (Subtarget.hasStdExtD()) {
6149         unsigned RegNo = FReg - RISCV::F0_F;
6150         unsigned DReg = RISCV::F0_D + RegNo;
6151         return std::make_pair(DReg, &RISCV::FPR64RegClass);
6152       }
6153       return std::make_pair(FReg, &RISCV::FPR32RegClass);
6154     }
6155   }
6156 
6157   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6158 }
6159 
6160 unsigned
6161 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
6162   // Currently only support length 1 constraints.
6163   if (ConstraintCode.size() == 1) {
6164     switch (ConstraintCode[0]) {
6165     case 'A':
6166       return InlineAsm::Constraint_A;
6167     default:
6168       break;
6169     }
6170   }
6171 
6172   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
6173 }
6174 
6175 void RISCVTargetLowering::LowerAsmOperandForConstraint(
6176     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6177     SelectionDAG &DAG) const {
6178   // Currently only support length 1 constraints.
6179   if (Constraint.length() == 1) {
6180     switch (Constraint[0]) {
6181     case 'I':
6182       // Validate & create a 12-bit signed immediate operand.
6183       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
6184         uint64_t CVal = C->getSExtValue();
6185         if (isInt<12>(CVal))
6186           Ops.push_back(
6187               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
6188       }
6189       return;
6190     case 'J':
6191       // Validate & create an integer zero operand.
6192       if (auto *C = dyn_cast<ConstantSDNode>(Op))
6193         if (C->getZExtValue() == 0)
6194           Ops.push_back(
6195               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
6196       return;
6197     case 'K':
6198       // Validate & create a 5-bit unsigned immediate operand.
6199       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
6200         uint64_t CVal = C->getZExtValue();
6201         if (isUInt<5>(CVal))
6202           Ops.push_back(
6203               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
6204       }
6205       return;
6206     default:
6207       break;
6208     }
6209   }
6210   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6211 }
6212 
6213 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6214                                                    Instruction *Inst,
6215                                                    AtomicOrdering Ord) const {
6216   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
6217     return Builder.CreateFence(Ord);
6218   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
6219     return Builder.CreateFence(AtomicOrdering::Release);
6220   return nullptr;
6221 }
6222 
6223 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6224                                                     Instruction *Inst,
6225                                                     AtomicOrdering Ord) const {
6226   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
6227     return Builder.CreateFence(AtomicOrdering::Acquire);
6228   return nullptr;
6229 }
6230 
6231 TargetLowering::AtomicExpansionKind
6232 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
6233   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
6234   // point operations can't be used in an lr/sc sequence without breaking the
6235   // forward-progress guarantee.
6236   if (AI->isFloatingPointOperation())
6237     return AtomicExpansionKind::CmpXChg;
6238 
6239   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
6240   if (Size == 8 || Size == 16)
6241     return AtomicExpansionKind::MaskedIntrinsic;
6242   return AtomicExpansionKind::None;
6243 }
6244 
6245 static Intrinsic::ID
6246 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
6247   if (XLen == 32) {
6248     switch (BinOp) {
6249     default:
6250       llvm_unreachable("Unexpected AtomicRMW BinOp");
6251     case AtomicRMWInst::Xchg:
6252       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
6253     case AtomicRMWInst::Add:
6254       return Intrinsic::riscv_masked_atomicrmw_add_i32;
6255     case AtomicRMWInst::Sub:
6256       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
6257     case AtomicRMWInst::Nand:
6258       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
6259     case AtomicRMWInst::Max:
6260       return Intrinsic::riscv_masked_atomicrmw_max_i32;
6261     case AtomicRMWInst::Min:
6262       return Intrinsic::riscv_masked_atomicrmw_min_i32;
6263     case AtomicRMWInst::UMax:
6264       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
6265     case AtomicRMWInst::UMin:
6266       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
6267     }
6268   }
6269 
6270   if (XLen == 64) {
6271     switch (BinOp) {
6272     default:
6273       llvm_unreachable("Unexpected AtomicRMW BinOp");
6274     case AtomicRMWInst::Xchg:
6275       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
6276     case AtomicRMWInst::Add:
6277       return Intrinsic::riscv_masked_atomicrmw_add_i64;
6278     case AtomicRMWInst::Sub:
6279       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
6280     case AtomicRMWInst::Nand:
6281       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
6282     case AtomicRMWInst::Max:
6283       return Intrinsic::riscv_masked_atomicrmw_max_i64;
6284     case AtomicRMWInst::Min:
6285       return Intrinsic::riscv_masked_atomicrmw_min_i64;
6286     case AtomicRMWInst::UMax:
6287       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
6288     case AtomicRMWInst::UMin:
6289       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
6290     }
6291   }
6292 
6293   llvm_unreachable("Unexpected XLen\n");
6294 }
6295 
6296 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
6297     IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
6298     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
6299   unsigned XLen = Subtarget.getXLen();
6300   Value *Ordering =
6301       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
6302   Type *Tys[] = {AlignedAddr->getType()};
6303   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
6304       AI->getModule(),
6305       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
6306 
6307   if (XLen == 64) {
6308     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
6309     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
6310     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
6311   }
6312 
6313   Value *Result;
6314 
6315   // Must pass the shift amount needed to sign extend the loaded value prior
6316   // to performing a signed comparison for min/max. ShiftAmt is the number of
6317   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
6318   // is the number of bits to left+right shift the value in order to
6319   // sign-extend.
6320   if (AI->getOperation() == AtomicRMWInst::Min ||
6321       AI->getOperation() == AtomicRMWInst::Max) {
6322     const DataLayout &DL = AI->getModule()->getDataLayout();
6323     unsigned ValWidth =
6324         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
6325     Value *SextShamt =
6326         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
6327     Result = Builder.CreateCall(LrwOpScwLoop,
6328                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
6329   } else {
6330     Result =
6331         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
6332   }
6333 
6334   if (XLen == 64)
6335     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
6336   return Result;
6337 }
6338 
6339 TargetLowering::AtomicExpansionKind
6340 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
6341     AtomicCmpXchgInst *CI) const {
6342   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
6343   if (Size == 8 || Size == 16)
6344     return AtomicExpansionKind::MaskedIntrinsic;
6345   return AtomicExpansionKind::None;
6346 }
6347 
6348 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
6349     IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
6350     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
6351   unsigned XLen = Subtarget.getXLen();
6352   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
6353   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
6354   if (XLen == 64) {
6355     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
6356     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
6357     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
6358     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
6359   }
6360   Type *Tys[] = {AlignedAddr->getType()};
6361   Function *MaskedCmpXchg =
6362       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
6363   Value *Result = Builder.CreateCall(
6364       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
6365   if (XLen == 64)
6366     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
6367   return Result;
6368 }
6369 
6370 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
6371                                                      EVT VT) const {
6372   VT = VT.getScalarType();
6373 
6374   if (!VT.isSimple())
6375     return false;
6376 
6377   switch (VT.getSimpleVT().SimpleTy) {
6378   case MVT::f16:
6379     return Subtarget.hasStdExtZfh();
6380   case MVT::f32:
6381     return Subtarget.hasStdExtF();
6382   case MVT::f64:
6383     return Subtarget.hasStdExtD();
6384   default:
6385     break;
6386   }
6387 
6388   return false;
6389 }
6390 
6391 Register RISCVTargetLowering::getExceptionPointerRegister(
6392     const Constant *PersonalityFn) const {
6393   return RISCV::X10;
6394 }
6395 
6396 Register RISCVTargetLowering::getExceptionSelectorRegister(
6397     const Constant *PersonalityFn) const {
6398   return RISCV::X11;
6399 }
6400 
6401 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
6402   // Return false to suppress the unnecessary extensions if the LibCall
6403   // arguments or return value is f32 type for LP64 ABI.
6404   RISCVABI::ABI ABI = Subtarget.getTargetABI();
6405   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
6406     return false;
6407 
6408   return true;
6409 }
6410 
6411 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
6412   if (Subtarget.is64Bit() && Type == MVT::i32)
6413     return true;
6414 
6415   return IsSigned;
6416 }
6417 
6418 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
6419                                                  SDValue C) const {
6420   // Check integral scalar types.
6421   if (VT.isScalarInteger()) {
6422     // Omit the optimization if the sub target has the M extension and the data
6423     // size exceeds XLen.
6424     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
6425       return false;
6426     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
6427       // Break the MUL to a SLLI and an ADD/SUB.
6428       const APInt &Imm = ConstNode->getAPIntValue();
6429       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
6430           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
6431         return true;
6432       // Omit the following optimization if the sub target has the M extension
6433       // and the data size >= XLen.
6434       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
6435         return false;
6436       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
6437       // a pair of LUI/ADDI.
6438       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
6439         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
6440         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
6441             (1 - ImmS).isPowerOf2())
6442         return true;
6443       }
6444     }
6445   }
6446 
6447   return false;
6448 }
6449 
6450 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
6451   if (!Subtarget.useRVVForFixedLengthVectors())
6452     return false;
6453 
6454   if (!VT.isFixedLengthVector())
6455     return false;
6456 
6457   // Don't use RVV for vectors we cannot scalarize if required.
6458   switch (VT.getVectorElementType().SimpleTy) {
6459   // i1 is supported but has different rules.
6460   default:
6461     return false;
6462   case MVT::i1:
6463     // Masks can only use a single register.
6464     if (VT.getVectorNumElements() > Subtarget.getMinRVVVectorSizeInBits())
6465       return false;
6466     break;
6467   case MVT::i8:
6468   case MVT::i16:
6469   case MVT::i32:
6470   case MVT::i64:
6471     break;
6472   case MVT::f16:
6473     if (!Subtarget.hasStdExtZfh())
6474       return false;
6475     break;
6476   case MVT::f32:
6477     if (!Subtarget.hasStdExtF())
6478       return false;
6479     break;
6480   case MVT::f64:
6481     if (!Subtarget.hasStdExtD())
6482       return false;
6483     break;
6484   }
6485 
6486   unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT);
6487   // Don't use RVV for types that don't fit.
6488   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
6489     return false;
6490 
6491   // TODO: Perhaps an artificial restriction, but worth having whilst getting
6492   // the base fixed length RVV support in place.
6493   if (!VT.isPow2VectorType())
6494     return false;
6495 
6496   return true;
6497 }
6498 
6499 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
6500     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
6501     bool *Fast) const {
6502   if (!VT.isScalableVector())
6503     return false;
6504 
6505   EVT ElemVT = VT.getVectorElementType();
6506   if (Alignment >= ElemVT.getStoreSize()) {
6507     if (Fast)
6508       *Fast = true;
6509     return true;
6510   }
6511 
6512   return false;
6513 }
6514 
6515 #define GET_REGISTER_MATCHER
6516 #include "RISCVGenAsmMatcher.inc"
6517 
6518 Register
6519 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
6520                                        const MachineFunction &MF) const {
6521   Register Reg = MatchRegisterAltName(RegName);
6522   if (Reg == RISCV::NoRegister)
6523     Reg = MatchRegisterName(RegName);
6524   if (Reg == RISCV::NoRegister)
6525     report_fatal_error(
6526         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
6527   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
6528   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
6529     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
6530                              StringRef(RegName) + "\"."));
6531   return Reg;
6532 }
6533 
6534 namespace llvm {
6535 namespace RISCVVIntrinsicsTable {
6536 
6537 #define GET_RISCVVIntrinsicsTable_IMPL
6538 #include "RISCVGenSearchableTables.inc"
6539 
6540 } // namespace RISCVVIntrinsicsTable
6541 
6542 } // namespace llvm
6543