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