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