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