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 "RISCV.h"
16 #include "RISCVMachineFunctionInfo.h"
17 #include "RISCVRegisterInfo.h"
18 #include "RISCVSubtarget.h"
19 #include "RISCVTargetMachine.h"
20 #include "Utils/RISCVMatInt.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/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "riscv-lower"
41 
42 STATISTIC(NumTailCalls, "Number of tail calls");
43 
44 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
45                                          const RISCVSubtarget &STI)
46     : TargetLowering(TM), Subtarget(STI) {
47 
48   if (Subtarget.isRV32E())
49     report_fatal_error("Codegen not yet implemented for RV32E");
50 
51   RISCVABI::ABI ABI = Subtarget.getTargetABI();
52   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
53 
54   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
55       !Subtarget.hasStdExtF()) {
56     errs() << "Hard-float 'f' ABI can't be used for a target that "
57                 "doesn't support the F instruction set extension (ignoring "
58                           "target-abi)\n";
59     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
60   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
61              !Subtarget.hasStdExtD()) {
62     errs() << "Hard-float 'd' ABI can't be used for a target that "
63               "doesn't support the D instruction set extension (ignoring "
64               "target-abi)\n";
65     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
66   }
67 
68   switch (ABI) {
69   default:
70     report_fatal_error("Don't know how to lower this ABI");
71   case RISCVABI::ABI_ILP32:
72   case RISCVABI::ABI_ILP32F:
73   case RISCVABI::ABI_ILP32D:
74   case RISCVABI::ABI_LP64:
75   case RISCVABI::ABI_LP64F:
76   case RISCVABI::ABI_LP64D:
77     break;
78   }
79 
80   MVT XLenVT = Subtarget.getXLenVT();
81 
82   // Set up the register classes.
83   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
84 
85   if (Subtarget.hasStdExtZfh())
86     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
87   if (Subtarget.hasStdExtF())
88     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
89   if (Subtarget.hasStdExtD())
90     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
91 
92   if (Subtarget.hasStdExtV()) {
93     addRegisterClass(RISCVVMVTs::vbool64_t, &RISCV::VRRegClass);
94     addRegisterClass(RISCVVMVTs::vbool32_t, &RISCV::VRRegClass);
95     addRegisterClass(RISCVVMVTs::vbool16_t, &RISCV::VRRegClass);
96     addRegisterClass(RISCVVMVTs::vbool8_t, &RISCV::VRRegClass);
97     addRegisterClass(RISCVVMVTs::vbool4_t, &RISCV::VRRegClass);
98     addRegisterClass(RISCVVMVTs::vbool2_t, &RISCV::VRRegClass);
99     addRegisterClass(RISCVVMVTs::vbool1_t, &RISCV::VRRegClass);
100 
101     addRegisterClass(RISCVVMVTs::vint8mf8_t, &RISCV::VRRegClass);
102     addRegisterClass(RISCVVMVTs::vint8mf4_t, &RISCV::VRRegClass);
103     addRegisterClass(RISCVVMVTs::vint8mf2_t, &RISCV::VRRegClass);
104     addRegisterClass(RISCVVMVTs::vint8m1_t, &RISCV::VRRegClass);
105     addRegisterClass(RISCVVMVTs::vint8m2_t, &RISCV::VRM2RegClass);
106     addRegisterClass(RISCVVMVTs::vint8m4_t, &RISCV::VRM4RegClass);
107     addRegisterClass(RISCVVMVTs::vint8m8_t, &RISCV::VRM8RegClass);
108 
109     addRegisterClass(RISCVVMVTs::vint16mf4_t, &RISCV::VRRegClass);
110     addRegisterClass(RISCVVMVTs::vint16mf2_t, &RISCV::VRRegClass);
111     addRegisterClass(RISCVVMVTs::vint16m1_t, &RISCV::VRRegClass);
112     addRegisterClass(RISCVVMVTs::vint16m2_t, &RISCV::VRM2RegClass);
113     addRegisterClass(RISCVVMVTs::vint16m4_t, &RISCV::VRM4RegClass);
114     addRegisterClass(RISCVVMVTs::vint16m8_t, &RISCV::VRM8RegClass);
115 
116     addRegisterClass(RISCVVMVTs::vint32mf2_t, &RISCV::VRRegClass);
117     addRegisterClass(RISCVVMVTs::vint32m1_t, &RISCV::VRRegClass);
118     addRegisterClass(RISCVVMVTs::vint32m2_t, &RISCV::VRM2RegClass);
119     addRegisterClass(RISCVVMVTs::vint32m4_t, &RISCV::VRM4RegClass);
120     addRegisterClass(RISCVVMVTs::vint32m8_t, &RISCV::VRM8RegClass);
121 
122     addRegisterClass(RISCVVMVTs::vint64m1_t, &RISCV::VRRegClass);
123     addRegisterClass(RISCVVMVTs::vint64m2_t, &RISCV::VRM2RegClass);
124     addRegisterClass(RISCVVMVTs::vint64m4_t, &RISCV::VRM4RegClass);
125     addRegisterClass(RISCVVMVTs::vint64m8_t, &RISCV::VRM8RegClass);
126 
127     addRegisterClass(RISCVVMVTs::vfloat32mf2_t, &RISCV::VRRegClass);
128     addRegisterClass(RISCVVMVTs::vfloat32m1_t, &RISCV::VRRegClass);
129     addRegisterClass(RISCVVMVTs::vfloat32m2_t, &RISCV::VRM2RegClass);
130     addRegisterClass(RISCVVMVTs::vfloat32m4_t, &RISCV::VRM4RegClass);
131     addRegisterClass(RISCVVMVTs::vfloat32m8_t, &RISCV::VRM8RegClass);
132 
133     addRegisterClass(RISCVVMVTs::vfloat64m1_t, &RISCV::VRRegClass);
134     addRegisterClass(RISCVVMVTs::vfloat64m2_t, &RISCV::VRM2RegClass);
135     addRegisterClass(RISCVVMVTs::vfloat64m4_t, &RISCV::VRM4RegClass);
136     addRegisterClass(RISCVVMVTs::vfloat64m8_t, &RISCV::VRM8RegClass);
137   }
138 
139   // Compute derived properties from the register classes.
140   computeRegisterProperties(STI.getRegisterInfo());
141 
142   setStackPointerRegisterToSaveRestore(RISCV::X2);
143 
144   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
145     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
146 
147   // TODO: add all necessary setOperationAction calls.
148   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
149 
150   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
151   setOperationAction(ISD::BR_CC, XLenVT, Expand);
152   setOperationAction(ISD::SELECT, XLenVT, Custom);
153   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
154 
155   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
156   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
157 
158   setOperationAction(ISD::VASTART, MVT::Other, Custom);
159   setOperationAction(ISD::VAARG, MVT::Other, Expand);
160   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
161   setOperationAction(ISD::VAEND, MVT::Other, Expand);
162 
163   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
164   if (!Subtarget.hasStdExtZbb()) {
165     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
166     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
167   }
168 
169   if (Subtarget.is64Bit()) {
170     setOperationAction(ISD::ADD, MVT::i32, Custom);
171     setOperationAction(ISD::SUB, MVT::i32, Custom);
172     setOperationAction(ISD::SHL, MVT::i32, Custom);
173     setOperationAction(ISD::SRA, MVT::i32, Custom);
174     setOperationAction(ISD::SRL, MVT::i32, Custom);
175   }
176 
177   if (!Subtarget.hasStdExtM()) {
178     setOperationAction(ISD::MUL, XLenVT, Expand);
179     setOperationAction(ISD::MULHS, XLenVT, Expand);
180     setOperationAction(ISD::MULHU, XLenVT, Expand);
181     setOperationAction(ISD::SDIV, XLenVT, Expand);
182     setOperationAction(ISD::UDIV, XLenVT, Expand);
183     setOperationAction(ISD::SREM, XLenVT, Expand);
184     setOperationAction(ISD::UREM, XLenVT, Expand);
185   }
186 
187   if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) {
188     setOperationAction(ISD::MUL, MVT::i32, Custom);
189     setOperationAction(ISD::SDIV, MVT::i32, Custom);
190     setOperationAction(ISD::UDIV, MVT::i32, Custom);
191     setOperationAction(ISD::UREM, MVT::i32, Custom);
192   }
193 
194   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
195   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
196   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
197   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
198 
199   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
200   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
201   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
202 
203   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
204     if (Subtarget.is64Bit()) {
205       setOperationAction(ISD::ROTL, MVT::i32, Custom);
206       setOperationAction(ISD::ROTR, MVT::i32, Custom);
207     }
208   } else {
209     setOperationAction(ISD::ROTL, XLenVT, Expand);
210     setOperationAction(ISD::ROTR, XLenVT, Expand);
211   }
212 
213   if (Subtarget.hasStdExtZbp()) {
214     setOperationAction(ISD::BITREVERSE, XLenVT, Custom);
215     setOperationAction(ISD::BSWAP, XLenVT, Custom);
216 
217     if (Subtarget.is64Bit()) {
218       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
219       setOperationAction(ISD::BSWAP, MVT::i32, Custom);
220     }
221   } else {
222     setOperationAction(ISD::BSWAP, XLenVT, Expand);
223   }
224 
225   if (Subtarget.hasStdExtZbb()) {
226     setOperationAction(ISD::SMIN, XLenVT, Legal);
227     setOperationAction(ISD::SMAX, XLenVT, Legal);
228     setOperationAction(ISD::UMIN, XLenVT, Legal);
229     setOperationAction(ISD::UMAX, XLenVT, Legal);
230   } else {
231     setOperationAction(ISD::CTTZ, XLenVT, Expand);
232     setOperationAction(ISD::CTLZ, XLenVT, Expand);
233     setOperationAction(ISD::CTPOP, XLenVT, Expand);
234   }
235 
236   if (Subtarget.hasStdExtZbt()) {
237     setOperationAction(ISD::FSHL, XLenVT, Legal);
238     setOperationAction(ISD::FSHR, XLenVT, Legal);
239 
240     if (Subtarget.is64Bit()) {
241       setOperationAction(ISD::FSHL, MVT::i32, Custom);
242       setOperationAction(ISD::FSHR, MVT::i32, Custom);
243     }
244   }
245 
246   ISD::CondCode FPCCToExpand[] = {
247       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
248       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
249       ISD::SETGE,  ISD::SETNE};
250 
251   ISD::NodeType FPOpToExpand[] = {
252       ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP,
253       ISD::FP_TO_FP16};
254 
255   if (Subtarget.hasStdExtZfh())
256     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
257 
258   if (Subtarget.hasStdExtZfh()) {
259     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
260     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
261     for (auto CC : FPCCToExpand)
262       setCondCodeAction(CC, MVT::f16, Expand);
263     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
264     setOperationAction(ISD::SELECT, MVT::f16, Custom);
265     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
266     for (auto Op : FPOpToExpand)
267       setOperationAction(Op, MVT::f16, Expand);
268   }
269 
270   if (Subtarget.hasStdExtF()) {
271     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
272     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
273     for (auto CC : FPCCToExpand)
274       setCondCodeAction(CC, MVT::f32, Expand);
275     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
276     setOperationAction(ISD::SELECT, MVT::f32, Custom);
277     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
278     for (auto Op : FPOpToExpand)
279       setOperationAction(Op, MVT::f32, Expand);
280     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
281     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
282   }
283 
284   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
285     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
286 
287   if (Subtarget.hasStdExtD()) {
288     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
289     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
290     for (auto CC : FPCCToExpand)
291       setCondCodeAction(CC, MVT::f64, Expand);
292     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
293     setOperationAction(ISD::SELECT, MVT::f64, Custom);
294     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
295     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
296     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
297     for (auto Op : FPOpToExpand)
298       setOperationAction(Op, MVT::f64, Expand);
299     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
300     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
301   }
302 
303   if (Subtarget.is64Bit()) {
304     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
305     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
306     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
307     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
308   }
309 
310   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
311   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
312   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
313 
314   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
315 
316   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
317   // Unfortunately this can't be determined just from the ISA naming string.
318   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
319                      Subtarget.is64Bit() ? Legal : Custom);
320 
321   setOperationAction(ISD::TRAP, MVT::Other, Legal);
322   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
323   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
324 
325   if (Subtarget.hasStdExtA()) {
326     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
327     setMinCmpXchgSizeInBits(32);
328   } else {
329     setMaxAtomicSizeInBitsSupported(0);
330   }
331 
332   setBooleanContents(ZeroOrOneBooleanContent);
333 
334   if (Subtarget.hasStdExtV())
335     setBooleanVectorContents(ZeroOrOneBooleanContent);
336 
337   // Function alignments.
338   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
339   setMinFunctionAlignment(FunctionAlignment);
340   setPrefFunctionAlignment(FunctionAlignment);
341 
342   // Effectively disable jump table generation.
343   setMinimumJumpTableEntries(INT_MAX);
344 
345   // Jumps are expensive, compared to logic
346   setJumpIsExpensive();
347 
348   // We can use any register for comparisons
349   setHasMultipleConditionRegisters();
350 
351   if (Subtarget.hasStdExtZbp()) {
352     setTargetDAGCombine(ISD::OR);
353   }
354 }
355 
356 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
357                                             EVT VT) const {
358   if (!VT.isVector())
359     return getPointerTy(DL);
360   return VT.changeVectorElementTypeToInteger();
361 }
362 
363 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
364                                              const CallInst &I,
365                                              MachineFunction &MF,
366                                              unsigned Intrinsic) const {
367   switch (Intrinsic) {
368   default:
369     return false;
370   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
371   case Intrinsic::riscv_masked_atomicrmw_add_i32:
372   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
373   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
374   case Intrinsic::riscv_masked_atomicrmw_max_i32:
375   case Intrinsic::riscv_masked_atomicrmw_min_i32:
376   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
377   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
378   case Intrinsic::riscv_masked_cmpxchg_i32:
379     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
380     Info.opc = ISD::INTRINSIC_W_CHAIN;
381     Info.memVT = MVT::getVT(PtrTy->getElementType());
382     Info.ptrVal = I.getArgOperand(0);
383     Info.offset = 0;
384     Info.align = Align(4);
385     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
386                  MachineMemOperand::MOVolatile;
387     return true;
388   }
389 }
390 
391 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
392                                                 const AddrMode &AM, Type *Ty,
393                                                 unsigned AS,
394                                                 Instruction *I) const {
395   // No global is ever allowed as a base.
396   if (AM.BaseGV)
397     return false;
398 
399   // Require a 12-bit signed offset.
400   if (!isInt<12>(AM.BaseOffs))
401     return false;
402 
403   switch (AM.Scale) {
404   case 0: // "r+i" or just "i", depending on HasBaseReg.
405     break;
406   case 1:
407     if (!AM.HasBaseReg) // allow "r+i".
408       break;
409     return false; // disallow "r+r" or "r+r+i".
410   default:
411     return false;
412   }
413 
414   return true;
415 }
416 
417 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
418   return isInt<12>(Imm);
419 }
420 
421 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
422   return isInt<12>(Imm);
423 }
424 
425 // On RV32, 64-bit integers are split into their high and low parts and held
426 // in two different registers, so the trunc is free since the low register can
427 // just be used.
428 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
429   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
430     return false;
431   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
432   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
433   return (SrcBits == 64 && DestBits == 32);
434 }
435 
436 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
437   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
438       !SrcVT.isInteger() || !DstVT.isInteger())
439     return false;
440   unsigned SrcBits = SrcVT.getSizeInBits();
441   unsigned DestBits = DstVT.getSizeInBits();
442   return (SrcBits == 64 && DestBits == 32);
443 }
444 
445 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
446   // Zexts are free if they can be combined with a load.
447   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
448     EVT MemVT = LD->getMemoryVT();
449     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
450          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
451         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
452          LD->getExtensionType() == ISD::ZEXTLOAD))
453       return true;
454   }
455 
456   return TargetLowering::isZExtFree(Val, VT2);
457 }
458 
459 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
460   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
461 }
462 
463 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
464   return Subtarget.hasStdExtZbb();
465 }
466 
467 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
468   return Subtarget.hasStdExtZbb();
469 }
470 
471 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
472                                        bool ForCodeSize) const {
473   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
474     return false;
475   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
476     return false;
477   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
478     return false;
479   if (Imm.isNegZero())
480     return false;
481   return Imm.isZero();
482 }
483 
484 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
485   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
486          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
487          (VT == MVT::f64 && Subtarget.hasStdExtD());
488 }
489 
490 // Changes the condition code and swaps operands if necessary, so the SetCC
491 // operation matches one of the comparisons supported directly in the RISC-V
492 // ISA.
493 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
494   switch (CC) {
495   default:
496     break;
497   case ISD::SETGT:
498   case ISD::SETLE:
499   case ISD::SETUGT:
500   case ISD::SETULE:
501     CC = ISD::getSetCCSwappedOperands(CC);
502     std::swap(LHS, RHS);
503     break;
504   }
505 }
506 
507 // Return the RISC-V branch opcode that matches the given DAG integer
508 // condition code. The CondCode must be one of those supported by the RISC-V
509 // ISA (see normaliseSetCC).
510 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
511   switch (CC) {
512   default:
513     llvm_unreachable("Unsupported CondCode");
514   case ISD::SETEQ:
515     return RISCV::BEQ;
516   case ISD::SETNE:
517     return RISCV::BNE;
518   case ISD::SETLT:
519     return RISCV::BLT;
520   case ISD::SETGE:
521     return RISCV::BGE;
522   case ISD::SETULT:
523     return RISCV::BLTU;
524   case ISD::SETUGE:
525     return RISCV::BGEU;
526   }
527 }
528 
529 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
530                                             SelectionDAG &DAG) const {
531   switch (Op.getOpcode()) {
532   default:
533     report_fatal_error("unimplemented operand");
534   case ISD::GlobalAddress:
535     return lowerGlobalAddress(Op, DAG);
536   case ISD::BlockAddress:
537     return lowerBlockAddress(Op, DAG);
538   case ISD::ConstantPool:
539     return lowerConstantPool(Op, DAG);
540   case ISD::GlobalTLSAddress:
541     return lowerGlobalTLSAddress(Op, DAG);
542   case ISD::SELECT:
543     return lowerSELECT(Op, DAG);
544   case ISD::VASTART:
545     return lowerVASTART(Op, DAG);
546   case ISD::FRAMEADDR:
547     return lowerFRAMEADDR(Op, DAG);
548   case ISD::RETURNADDR:
549     return lowerRETURNADDR(Op, DAG);
550   case ISD::SHL_PARTS:
551     return lowerShiftLeftParts(Op, DAG);
552   case ISD::SRA_PARTS:
553     return lowerShiftRightParts(Op, DAG, true);
554   case ISD::SRL_PARTS:
555     return lowerShiftRightParts(Op, DAG, false);
556   case ISD::BITCAST: {
557     assert(((Subtarget.is64Bit() && Subtarget.hasStdExtF()) ||
558             Subtarget.hasStdExtZfh()) &&
559            "Unexpected custom legalisation");
560     SDLoc DL(Op);
561     SDValue Op0 = Op.getOperand(0);
562     if (Op.getValueType() == MVT::f16 && Subtarget.hasStdExtZfh()) {
563       if (Op0.getValueType() != MVT::i16)
564         return SDValue();
565       SDValue NewOp0 =
566           DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Op0);
567       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
568       return FPConv;
569     } else if (Op.getValueType() == MVT::f32 && Subtarget.is64Bit() &&
570                Subtarget.hasStdExtF()) {
571       if (Op0.getValueType() != MVT::i32)
572         return SDValue();
573       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
574       SDValue FPConv =
575           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
576       return FPConv;
577     }
578     return SDValue();
579   }
580   case ISD::INTRINSIC_WO_CHAIN:
581     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
582   case ISD::BSWAP:
583   case ISD::BITREVERSE: {
584     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
585     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
586     MVT VT = Op.getSimpleValueType();
587     SDLoc DL(Op);
588     // Start with the maximum immediate value which is the bitwidth - 1.
589     unsigned Imm = VT.getSizeInBits() - 1;
590     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
591     if (Op.getOpcode() == ISD::BSWAP)
592       Imm &= ~0x7U;
593     return DAG.getNode(RISCVISD::GREVI, DL, VT, Op.getOperand(0),
594                        DAG.getTargetConstant(Imm, DL, Subtarget.getXLenVT()));
595   }
596   }
597 }
598 
599 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
600                              SelectionDAG &DAG, unsigned Flags) {
601   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
602 }
603 
604 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
605                              SelectionDAG &DAG, unsigned Flags) {
606   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
607                                    Flags);
608 }
609 
610 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
611                              SelectionDAG &DAG, unsigned Flags) {
612   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
613                                    N->getOffset(), Flags);
614 }
615 
616 template <class NodeTy>
617 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
618                                      bool IsLocal) const {
619   SDLoc DL(N);
620   EVT Ty = getPointerTy(DAG.getDataLayout());
621 
622   if (isPositionIndependent()) {
623     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
624     if (IsLocal)
625       // Use PC-relative addressing to access the symbol. This generates the
626       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
627       // %pcrel_lo(auipc)).
628       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
629 
630     // Use PC-relative addressing to access the GOT for this symbol, then load
631     // the address from the GOT. This generates the pattern (PseudoLA sym),
632     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
633     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
634   }
635 
636   switch (getTargetMachine().getCodeModel()) {
637   default:
638     report_fatal_error("Unsupported code model for lowering");
639   case CodeModel::Small: {
640     // Generate a sequence for accessing addresses within the first 2 GiB of
641     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
642     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
643     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
644     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
645     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
646   }
647   case CodeModel::Medium: {
648     // Generate a sequence for accessing addresses within any 2GiB range within
649     // the address space. This generates the pattern (PseudoLLA sym), which
650     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
651     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
652     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
653   }
654   }
655 }
656 
657 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
658                                                 SelectionDAG &DAG) const {
659   SDLoc DL(Op);
660   EVT Ty = Op.getValueType();
661   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
662   int64_t Offset = N->getOffset();
663   MVT XLenVT = Subtarget.getXLenVT();
664 
665   const GlobalValue *GV = N->getGlobal();
666   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
667   SDValue Addr = getAddr(N, DAG, IsLocal);
668 
669   // In order to maximise the opportunity for common subexpression elimination,
670   // emit a separate ADD node for the global address offset instead of folding
671   // it in the global address node. Later peephole optimisations may choose to
672   // fold it back in when profitable.
673   if (Offset != 0)
674     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
675                        DAG.getConstant(Offset, DL, XLenVT));
676   return Addr;
677 }
678 
679 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
680                                                SelectionDAG &DAG) const {
681   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
682 
683   return getAddr(N, DAG);
684 }
685 
686 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
687                                                SelectionDAG &DAG) const {
688   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
689 
690   return getAddr(N, DAG);
691 }
692 
693 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
694                                               SelectionDAG &DAG,
695                                               bool UseGOT) const {
696   SDLoc DL(N);
697   EVT Ty = getPointerTy(DAG.getDataLayout());
698   const GlobalValue *GV = N->getGlobal();
699   MVT XLenVT = Subtarget.getXLenVT();
700 
701   if (UseGOT) {
702     // Use PC-relative addressing to access the GOT for this TLS symbol, then
703     // load the address from the GOT and add the thread pointer. This generates
704     // the pattern (PseudoLA_TLS_IE sym), which expands to
705     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
706     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
707     SDValue Load =
708         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
709 
710     // Add the thread pointer.
711     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
712     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
713   }
714 
715   // Generate a sequence for accessing the address relative to the thread
716   // pointer, with the appropriate adjustment for the thread pointer offset.
717   // This generates the pattern
718   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
719   SDValue AddrHi =
720       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
721   SDValue AddrAdd =
722       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
723   SDValue AddrLo =
724       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
725 
726   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
727   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
728   SDValue MNAdd = SDValue(
729       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
730       0);
731   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
732 }
733 
734 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
735                                                SelectionDAG &DAG) const {
736   SDLoc DL(N);
737   EVT Ty = getPointerTy(DAG.getDataLayout());
738   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
739   const GlobalValue *GV = N->getGlobal();
740 
741   // Use a PC-relative addressing mode to access the global dynamic GOT address.
742   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
743   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
744   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
745   SDValue Load =
746       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
747 
748   // Prepare argument list to generate call.
749   ArgListTy Args;
750   ArgListEntry Entry;
751   Entry.Node = Load;
752   Entry.Ty = CallTy;
753   Args.push_back(Entry);
754 
755   // Setup call to __tls_get_addr.
756   TargetLowering::CallLoweringInfo CLI(DAG);
757   CLI.setDebugLoc(DL)
758       .setChain(DAG.getEntryNode())
759       .setLibCallee(CallingConv::C, CallTy,
760                     DAG.getExternalSymbol("__tls_get_addr", Ty),
761                     std::move(Args));
762 
763   return LowerCallTo(CLI).first;
764 }
765 
766 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
767                                                    SelectionDAG &DAG) const {
768   SDLoc DL(Op);
769   EVT Ty = Op.getValueType();
770   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
771   int64_t Offset = N->getOffset();
772   MVT XLenVT = Subtarget.getXLenVT();
773 
774   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
775 
776   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
777       CallingConv::GHC)
778     report_fatal_error("In GHC calling convention TLS is not supported");
779 
780   SDValue Addr;
781   switch (Model) {
782   case TLSModel::LocalExec:
783     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
784     break;
785   case TLSModel::InitialExec:
786     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
787     break;
788   case TLSModel::LocalDynamic:
789   case TLSModel::GeneralDynamic:
790     Addr = getDynamicTLSAddr(N, DAG);
791     break;
792   }
793 
794   // In order to maximise the opportunity for common subexpression elimination,
795   // emit a separate ADD node for the global address offset instead of folding
796   // it in the global address node. Later peephole optimisations may choose to
797   // fold it back in when profitable.
798   if (Offset != 0)
799     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
800                        DAG.getConstant(Offset, DL, XLenVT));
801   return Addr;
802 }
803 
804 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
805   SDValue CondV = Op.getOperand(0);
806   SDValue TrueV = Op.getOperand(1);
807   SDValue FalseV = Op.getOperand(2);
808   SDLoc DL(Op);
809   MVT XLenVT = Subtarget.getXLenVT();
810 
811   // If the result type is XLenVT and CondV is the output of a SETCC node
812   // which also operated on XLenVT inputs, then merge the SETCC node into the
813   // lowered RISCVISD::SELECT_CC to take advantage of the integer
814   // compare+branch instructions. i.e.:
815   // (select (setcc lhs, rhs, cc), truev, falsev)
816   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
817   if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
818       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
819     SDValue LHS = CondV.getOperand(0);
820     SDValue RHS = CondV.getOperand(1);
821     auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
822     ISD::CondCode CCVal = CC->get();
823 
824     normaliseSetCC(LHS, RHS, CCVal);
825 
826     SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
827     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
828     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
829   }
830 
831   // Otherwise:
832   // (select condv, truev, falsev)
833   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
834   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
835   SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
836 
837   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
838 
839   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
840 }
841 
842 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
843   MachineFunction &MF = DAG.getMachineFunction();
844   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
845 
846   SDLoc DL(Op);
847   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
848                                  getPointerTy(MF.getDataLayout()));
849 
850   // vastart just stores the address of the VarArgsFrameIndex slot into the
851   // memory location argument.
852   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
853   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
854                       MachinePointerInfo(SV));
855 }
856 
857 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
858                                             SelectionDAG &DAG) const {
859   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
860   MachineFunction &MF = DAG.getMachineFunction();
861   MachineFrameInfo &MFI = MF.getFrameInfo();
862   MFI.setFrameAddressIsTaken(true);
863   Register FrameReg = RI.getFrameRegister(MF);
864   int XLenInBytes = Subtarget.getXLen() / 8;
865 
866   EVT VT = Op.getValueType();
867   SDLoc DL(Op);
868   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
869   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
870   while (Depth--) {
871     int Offset = -(XLenInBytes * 2);
872     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
873                               DAG.getIntPtrConstant(Offset, DL));
874     FrameAddr =
875         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
876   }
877   return FrameAddr;
878 }
879 
880 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
881                                              SelectionDAG &DAG) const {
882   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
883   MachineFunction &MF = DAG.getMachineFunction();
884   MachineFrameInfo &MFI = MF.getFrameInfo();
885   MFI.setReturnAddressIsTaken(true);
886   MVT XLenVT = Subtarget.getXLenVT();
887   int XLenInBytes = Subtarget.getXLen() / 8;
888 
889   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
890     return SDValue();
891 
892   EVT VT = Op.getValueType();
893   SDLoc DL(Op);
894   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
895   if (Depth) {
896     int Off = -XLenInBytes;
897     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
898     SDValue Offset = DAG.getConstant(Off, DL, VT);
899     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
900                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
901                        MachinePointerInfo());
902   }
903 
904   // Return the value of the return address register, marking it an implicit
905   // live-in.
906   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
907   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
908 }
909 
910 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
911                                                  SelectionDAG &DAG) const {
912   SDLoc DL(Op);
913   SDValue Lo = Op.getOperand(0);
914   SDValue Hi = Op.getOperand(1);
915   SDValue Shamt = Op.getOperand(2);
916   EVT VT = Lo.getValueType();
917 
918   // if Shamt-XLEN < 0: // Shamt < XLEN
919   //   Lo = Lo << Shamt
920   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
921   // else:
922   //   Lo = 0
923   //   Hi = Lo << (Shamt-XLEN)
924 
925   SDValue Zero = DAG.getConstant(0, DL, VT);
926   SDValue One = DAG.getConstant(1, DL, VT);
927   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
928   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
929   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
930   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
931 
932   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
933   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
934   SDValue ShiftRightLo =
935       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
936   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
937   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
938   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
939 
940   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
941 
942   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
943   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
944 
945   SDValue Parts[2] = {Lo, Hi};
946   return DAG.getMergeValues(Parts, DL);
947 }
948 
949 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
950                                                   bool IsSRA) const {
951   SDLoc DL(Op);
952   SDValue Lo = Op.getOperand(0);
953   SDValue Hi = Op.getOperand(1);
954   SDValue Shamt = Op.getOperand(2);
955   EVT VT = Lo.getValueType();
956 
957   // SRA expansion:
958   //   if Shamt-XLEN < 0: // Shamt < XLEN
959   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
960   //     Hi = Hi >>s Shamt
961   //   else:
962   //     Lo = Hi >>s (Shamt-XLEN);
963   //     Hi = Hi >>s (XLEN-1)
964   //
965   // SRL expansion:
966   //   if Shamt-XLEN < 0: // Shamt < XLEN
967   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
968   //     Hi = Hi >>u Shamt
969   //   else:
970   //     Lo = Hi >>u (Shamt-XLEN);
971   //     Hi = 0;
972 
973   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
974 
975   SDValue Zero = DAG.getConstant(0, DL, VT);
976   SDValue One = DAG.getConstant(1, DL, VT);
977   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
978   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
979   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
980   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
981 
982   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
983   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
984   SDValue ShiftLeftHi =
985       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
986   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
987   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
988   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
989   SDValue HiFalse =
990       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
991 
992   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
993 
994   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
995   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
996 
997   SDValue Parts[2] = {Lo, Hi};
998   return DAG.getMergeValues(Parts, DL);
999 }
1000 
1001 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1002                                                      SelectionDAG &DAG) const {
1003   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1004   SDLoc DL(Op);
1005   switch (IntNo) {
1006   default:
1007     return SDValue();    // Don't custom lower most intrinsics.
1008   case Intrinsic::thread_pointer: {
1009     EVT PtrVT = getPointerTy(DAG.getDataLayout());
1010     return DAG.getRegister(RISCV::X4, PtrVT);
1011   }
1012   }
1013 }
1014 
1015 // Returns the opcode of the target-specific SDNode that implements the 32-bit
1016 // form of the given Opcode.
1017 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
1018   switch (Opcode) {
1019   default:
1020     llvm_unreachable("Unexpected opcode");
1021   case ISD::SHL:
1022     return RISCVISD::SLLW;
1023   case ISD::SRA:
1024     return RISCVISD::SRAW;
1025   case ISD::SRL:
1026     return RISCVISD::SRLW;
1027   case ISD::SDIV:
1028     return RISCVISD::DIVW;
1029   case ISD::UDIV:
1030     return RISCVISD::DIVUW;
1031   case ISD::UREM:
1032     return RISCVISD::REMUW;
1033   case ISD::ROTL:
1034     return RISCVISD::ROLW;
1035   case ISD::ROTR:
1036     return RISCVISD::RORW;
1037   case RISCVISD::GREVI:
1038     return RISCVISD::GREVIW;
1039   case RISCVISD::GORCI:
1040     return RISCVISD::GORCIW;
1041   }
1042 }
1043 
1044 // Converts the given 32-bit operation to a target-specific SelectionDAG node.
1045 // Because i32 isn't a legal type for RV64, these operations would otherwise
1046 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
1047 // later one because the fact the operation was originally of type i32 is
1048 // lost.
1049 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) {
1050   SDLoc DL(N);
1051   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
1052   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
1053   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
1054   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
1055   // ReplaceNodeResults requires we maintain the same type for the return value.
1056   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
1057 }
1058 
1059 // Converts the given 32-bit operation to a i64 operation with signed extension
1060 // semantic to reduce the signed extension instructions.
1061 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
1062   SDLoc DL(N);
1063   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
1064   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
1065   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
1066   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
1067                                DAG.getValueType(MVT::i32));
1068   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
1069 }
1070 
1071 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
1072                                              SmallVectorImpl<SDValue> &Results,
1073                                              SelectionDAG &DAG) const {
1074   SDLoc DL(N);
1075   switch (N->getOpcode()) {
1076   default:
1077     llvm_unreachable("Don't know how to custom type legalize this operation!");
1078   case ISD::STRICT_FP_TO_SINT:
1079   case ISD::STRICT_FP_TO_UINT:
1080   case ISD::FP_TO_SINT:
1081   case ISD::FP_TO_UINT: {
1082     bool IsStrict = N->isStrictFPOpcode();
1083     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1084            "Unexpected custom legalisation");
1085     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
1086     // If the FP type needs to be softened, emit a library call using the 'si'
1087     // version. If we left it to default legalization we'd end up with 'di'. If
1088     // the FP type doesn't need to be softened just let generic type
1089     // legalization promote the result type.
1090     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
1091         TargetLowering::TypeSoftenFloat)
1092       return;
1093     RTLIB::Libcall LC;
1094     if (N->getOpcode() == ISD::FP_TO_SINT ||
1095         N->getOpcode() == ISD::STRICT_FP_TO_SINT)
1096       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
1097     else
1098       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
1099     MakeLibCallOptions CallOptions;
1100     EVT OpVT = Op0.getValueType();
1101     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
1102     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
1103     SDValue Result;
1104     std::tie(Result, Chain) =
1105         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
1106     Results.push_back(Result);
1107     if (IsStrict)
1108       Results.push_back(Chain);
1109     break;
1110   }
1111   case ISD::READCYCLECOUNTER: {
1112     assert(!Subtarget.is64Bit() &&
1113            "READCYCLECOUNTER only has custom type legalization on riscv32");
1114 
1115     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
1116     SDValue RCW =
1117         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
1118 
1119     Results.push_back(
1120         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
1121     Results.push_back(RCW.getValue(2));
1122     break;
1123   }
1124   case ISD::ADD:
1125   case ISD::SUB:
1126   case ISD::MUL:
1127     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1128            "Unexpected custom legalisation");
1129     if (N->getOperand(1).getOpcode() == ISD::Constant)
1130       return;
1131     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
1132     break;
1133   case ISD::SHL:
1134   case ISD::SRA:
1135   case ISD::SRL:
1136     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1137            "Unexpected custom legalisation");
1138     if (N->getOperand(1).getOpcode() == ISD::Constant)
1139       return;
1140     Results.push_back(customLegalizeToWOp(N, DAG));
1141     break;
1142   case ISD::ROTL:
1143   case ISD::ROTR:
1144     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1145            "Unexpected custom legalisation");
1146     Results.push_back(customLegalizeToWOp(N, DAG));
1147     break;
1148   case ISD::SDIV:
1149   case ISD::UDIV:
1150   case ISD::UREM:
1151     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1152            Subtarget.hasStdExtM() && "Unexpected custom legalisation");
1153     if (N->getOperand(0).getOpcode() == ISD::Constant ||
1154         N->getOperand(1).getOpcode() == ISD::Constant)
1155       return;
1156     Results.push_back(customLegalizeToWOp(N, DAG));
1157     break;
1158   case ISD::BITCAST: {
1159     assert(((N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1160              Subtarget.hasStdExtF()) ||
1161             (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh())) &&
1162            "Unexpected custom legalisation");
1163     SDValue Op0 = N->getOperand(0);
1164     if (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh()) {
1165       if (Op0.getValueType() != MVT::f16)
1166         return;
1167       SDValue FPConv =
1168           DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(), Op0);
1169       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
1170     } else if (N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1171                Subtarget.hasStdExtF()) {
1172       if (Op0.getValueType() != MVT::f32)
1173         return;
1174       SDValue FPConv =
1175           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
1176       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
1177     }
1178     break;
1179   }
1180   case RISCVISD::GREVI:
1181   case RISCVISD::GORCI: {
1182     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1183            "Unexpected custom legalisation");
1184     // This is similar to customLegalizeToWOp, except that we pass the second
1185     // operand (a TargetConstant) straight through: it is already of type
1186     // XLenVT.
1187     SDLoc DL(N);
1188     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
1189     SDValue NewOp0 =
1190         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
1191     SDValue NewRes =
1192         DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, N->getOperand(1));
1193     // ReplaceNodeResults requires we maintain the same type for the return
1194     // value.
1195     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
1196     break;
1197   }
1198   case ISD::BSWAP:
1199   case ISD::BITREVERSE: {
1200     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1201            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
1202     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
1203                                  N->getOperand(0));
1204     unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24;
1205     SDValue GREVIW = DAG.getNode(RISCVISD::GREVIW, DL, MVT::i64, NewOp0,
1206                                  DAG.getTargetConstant(Imm, DL,
1207                                                        Subtarget.getXLenVT()));
1208     // ReplaceNodeResults requires we maintain the same type for the return
1209     // value.
1210     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW));
1211     break;
1212   }
1213   case ISD::FSHL:
1214   case ISD::FSHR: {
1215     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1216            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
1217     SDValue NewOp0 =
1218         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
1219     SDValue NewOp1 =
1220         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
1221     SDValue NewOp2 =
1222         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
1223     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
1224     // Mask the shift amount to 5 bits.
1225     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
1226                          DAG.getConstant(0x1f, DL, MVT::i64));
1227     unsigned Opc =
1228         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
1229     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
1230     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
1231     break;
1232   }
1233   }
1234 }
1235 
1236 // A structure to hold one of the bit-manipulation patterns below. Together, a
1237 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
1238 //   (or (and (shl x, 1), 0xAAAAAAAA),
1239 //       (and (srl x, 1), 0x55555555))
1240 struct RISCVBitmanipPat {
1241   SDValue Op;
1242   unsigned ShAmt;
1243   bool IsSHL;
1244 
1245   bool formsPairWith(const RISCVBitmanipPat &Other) const {
1246     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
1247   }
1248 };
1249 
1250 // Matches any of the following bit-manipulation patterns:
1251 //   (and (shl x, 1), (0x55555555 << 1))
1252 //   (and (srl x, 1), 0x55555555)
1253 //   (shl (and x, 0x55555555), 1)
1254 //   (srl (and x, (0x55555555 << 1)), 1)
1255 // where the shift amount and mask may vary thus:
1256 //   [1]  = 0x55555555 / 0xAAAAAAAA
1257 //   [2]  = 0x33333333 / 0xCCCCCCCC
1258 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
1259 //   [8]  = 0x00FF00FF / 0xFF00FF00
1260 //   [16] = 0x0000FFFF / 0xFFFFFFFF
1261 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
1262 static Optional<RISCVBitmanipPat> matchRISCVBitmanipPat(SDValue Op) {
1263   Optional<uint64_t> Mask;
1264   // Optionally consume a mask around the shift operation.
1265   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
1266     Mask = Op.getConstantOperandVal(1);
1267     Op = Op.getOperand(0);
1268   }
1269   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
1270     return None;
1271   bool IsSHL = Op.getOpcode() == ISD::SHL;
1272 
1273   if (!isa<ConstantSDNode>(Op.getOperand(1)))
1274     return None;
1275   auto ShAmt = Op.getConstantOperandVal(1);
1276 
1277   if (!isPowerOf2_64(ShAmt))
1278     return None;
1279 
1280   // These are the unshifted masks which we use to match bit-manipulation
1281   // patterns. They may be shifted left in certain circumstances.
1282   static const uint64_t BitmanipMasks[] = {
1283       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
1284       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL,
1285   };
1286 
1287   unsigned MaskIdx = Log2_64(ShAmt);
1288   if (MaskIdx >= array_lengthof(BitmanipMasks))
1289     return None;
1290 
1291   auto Src = Op.getOperand(0);
1292 
1293   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
1294   auto ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
1295 
1296   // The expected mask is shifted left when the AND is found around SHL
1297   // patterns.
1298   //   ((x >> 1) & 0x55555555)
1299   //   ((x << 1) & 0xAAAAAAAA)
1300   bool SHLExpMask = IsSHL;
1301 
1302   if (!Mask) {
1303     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
1304     // the mask is all ones: consume that now.
1305     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
1306       Mask = Src.getConstantOperandVal(1);
1307       Src = Src.getOperand(0);
1308       // The expected mask is now in fact shifted left for SRL, so reverse the
1309       // decision.
1310       //   ((x & 0xAAAAAAAA) >> 1)
1311       //   ((x & 0x55555555) << 1)
1312       SHLExpMask = !SHLExpMask;
1313     } else {
1314       // Use a default shifted mask of all-ones if there's no AND, truncated
1315       // down to the expected width. This simplifies the logic later on.
1316       Mask = maskTrailingOnes<uint64_t>(Width);
1317       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
1318     }
1319   }
1320 
1321   if (SHLExpMask)
1322     ExpMask <<= ShAmt;
1323 
1324   if (Mask != ExpMask)
1325     return None;
1326 
1327   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
1328 }
1329 
1330 // Match the following pattern as a GREVI(W) operation
1331 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
1332 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
1333                                const RISCVSubtarget &Subtarget) {
1334   EVT VT = Op.getValueType();
1335 
1336   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
1337     auto LHS = matchRISCVBitmanipPat(Op.getOperand(0));
1338     auto RHS = matchRISCVBitmanipPat(Op.getOperand(1));
1339     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
1340       SDLoc DL(Op);
1341       return DAG.getNode(
1342           RISCVISD::GREVI, DL, VT, LHS->Op,
1343           DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT()));
1344     }
1345   }
1346   return SDValue();
1347 }
1348 
1349 // Matches any the following pattern as a GORCI(W) operation
1350 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
1351 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
1352 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
1353 // Note that with the variant of 3.,
1354 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
1355 // the inner pattern will first be matched as GREVI and then the outer
1356 // pattern will be matched to GORC via the first rule above.
1357 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
1358                                const RISCVSubtarget &Subtarget) {
1359   EVT VT = Op.getValueType();
1360 
1361   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
1362     SDLoc DL(Op);
1363     SDValue Op0 = Op.getOperand(0);
1364     SDValue Op1 = Op.getOperand(1);
1365 
1366     // Check for either commutable permutation of (or (GREVI x, shamt), x)
1367     for (const auto &OpPair :
1368          {std::make_pair(Op0, Op1), std::make_pair(Op1, Op0)}) {
1369       if (OpPair.first.getOpcode() == RISCVISD::GREVI &&
1370           OpPair.first.getOperand(0) == OpPair.second &&
1371           isPowerOf2_32(OpPair.first.getConstantOperandVal(1)))
1372         return DAG.getNode(RISCVISD::GORCI, DL, VT, OpPair.second,
1373                            OpPair.first.getOperand(1));
1374     }
1375 
1376     // OR is commutable so canonicalize its OR operand to the left
1377     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
1378       std::swap(Op0, Op1);
1379     if (Op0.getOpcode() != ISD::OR)
1380       return SDValue();
1381     SDValue OrOp0 = Op0.getOperand(0);
1382     SDValue OrOp1 = Op0.getOperand(1);
1383     auto LHS = matchRISCVBitmanipPat(OrOp0);
1384     // OR is commutable so swap the operands and try again: x might have been
1385     // on the left
1386     if (!LHS) {
1387       std::swap(OrOp0, OrOp1);
1388       LHS = matchRISCVBitmanipPat(OrOp0);
1389     }
1390     auto RHS = matchRISCVBitmanipPat(Op1);
1391     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
1392       return DAG.getNode(
1393           RISCVISD::GORCI, DL, VT, LHS->Op,
1394           DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT()));
1395     }
1396   }
1397   return SDValue();
1398 }
1399 
1400 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
1401 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
1402 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
1403 // not undo itself, but they are redundant.
1404 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
1405   unsigned ShAmt1 = N->getConstantOperandVal(1);
1406   SDValue Src = N->getOperand(0);
1407 
1408   if (Src.getOpcode() != N->getOpcode())
1409     return SDValue();
1410 
1411   unsigned ShAmt2 = Src.getConstantOperandVal(1);
1412   Src = Src.getOperand(0);
1413 
1414   unsigned CombinedShAmt;
1415   if (N->getOpcode() == RISCVISD::GORCI || N->getOpcode() == RISCVISD::GORCIW)
1416     CombinedShAmt = ShAmt1 | ShAmt2;
1417   else
1418     CombinedShAmt = ShAmt1 ^ ShAmt2;
1419 
1420   if (CombinedShAmt == 0)
1421     return Src;
1422 
1423   SDLoc DL(N);
1424   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), Src,
1425                      DAG.getTargetConstant(CombinedShAmt, DL,
1426                                            N->getOperand(1).getValueType()));
1427 }
1428 
1429 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
1430                                                DAGCombinerInfo &DCI) const {
1431   SelectionDAG &DAG = DCI.DAG;
1432 
1433   switch (N->getOpcode()) {
1434   default:
1435     break;
1436   case RISCVISD::SplitF64: {
1437     SDValue Op0 = N->getOperand(0);
1438     // If the input to SplitF64 is just BuildPairF64 then the operation is
1439     // redundant. Instead, use BuildPairF64's operands directly.
1440     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
1441       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
1442 
1443     SDLoc DL(N);
1444 
1445     // It's cheaper to materialise two 32-bit integers than to load a double
1446     // from the constant pool and transfer it to integer registers through the
1447     // stack.
1448     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
1449       APInt V = C->getValueAPF().bitcastToAPInt();
1450       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
1451       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
1452       return DCI.CombineTo(N, Lo, Hi);
1453     }
1454 
1455     // This is a target-specific version of a DAGCombine performed in
1456     // DAGCombiner::visitBITCAST. It performs the equivalent of:
1457     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
1458     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
1459     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
1460         !Op0.getNode()->hasOneUse())
1461       break;
1462     SDValue NewSplitF64 =
1463         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
1464                     Op0.getOperand(0));
1465     SDValue Lo = NewSplitF64.getValue(0);
1466     SDValue Hi = NewSplitF64.getValue(1);
1467     APInt SignBit = APInt::getSignMask(32);
1468     if (Op0.getOpcode() == ISD::FNEG) {
1469       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
1470                                   DAG.getConstant(SignBit, DL, MVT::i32));
1471       return DCI.CombineTo(N, Lo, NewHi);
1472     }
1473     assert(Op0.getOpcode() == ISD::FABS);
1474     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
1475                                 DAG.getConstant(~SignBit, DL, MVT::i32));
1476     return DCI.CombineTo(N, Lo, NewHi);
1477   }
1478   case RISCVISD::SLLW:
1479   case RISCVISD::SRAW:
1480   case RISCVISD::SRLW:
1481   case RISCVISD::ROLW:
1482   case RISCVISD::RORW: {
1483     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
1484     SDValue LHS = N->getOperand(0);
1485     SDValue RHS = N->getOperand(1);
1486     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
1487     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
1488     if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) ||
1489         SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) {
1490       if (N->getOpcode() != ISD::DELETED_NODE)
1491         DCI.AddToWorklist(N);
1492       return SDValue(N, 0);
1493     }
1494     break;
1495   }
1496   case RISCVISD::FSLW:
1497   case RISCVISD::FSRW: {
1498     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
1499     // read.
1500     SDValue Op0 = N->getOperand(0);
1501     SDValue Op1 = N->getOperand(1);
1502     SDValue ShAmt = N->getOperand(2);
1503     APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
1504     APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6);
1505     if (SimplifyDemandedBits(Op0, OpMask, DCI) ||
1506         SimplifyDemandedBits(Op1, OpMask, DCI) ||
1507         SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
1508       if (N->getOpcode() != ISD::DELETED_NODE)
1509         DCI.AddToWorklist(N);
1510       return SDValue(N, 0);
1511     }
1512     break;
1513   }
1514   case RISCVISD::GREVIW:
1515   case RISCVISD::GORCIW: {
1516     // Only the lower 32 bits of the first operand are read
1517     SDValue Op0 = N->getOperand(0);
1518     APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
1519     if (SimplifyDemandedBits(Op0, Mask, DCI)) {
1520       if (N->getOpcode() != ISD::DELETED_NODE)
1521         DCI.AddToWorklist(N);
1522       return SDValue(N, 0);
1523     }
1524 
1525     return combineGREVI_GORCI(N, DCI.DAG);
1526   }
1527   case RISCVISD::FMV_X_ANYEXTW_RV64: {
1528     SDLoc DL(N);
1529     SDValue Op0 = N->getOperand(0);
1530     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
1531     // conversion is unnecessary and can be replaced with an ANY_EXTEND
1532     // of the FMV_W_X_RV64 operand.
1533     if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
1534       assert(Op0.getOperand(0).getValueType() == MVT::i64 &&
1535              "Unexpected value type!");
1536       return Op0.getOperand(0);
1537     }
1538 
1539     // This is a target-specific version of a DAGCombine performed in
1540     // DAGCombiner::visitBITCAST. It performs the equivalent of:
1541     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
1542     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
1543     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
1544         !Op0.getNode()->hasOneUse())
1545       break;
1546     SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64,
1547                                  Op0.getOperand(0));
1548     APInt SignBit = APInt::getSignMask(32).sext(64);
1549     if (Op0.getOpcode() == ISD::FNEG)
1550       return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
1551                          DAG.getConstant(SignBit, DL, MVT::i64));
1552 
1553     assert(Op0.getOpcode() == ISD::FABS);
1554     return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
1555                        DAG.getConstant(~SignBit, DL, MVT::i64));
1556   }
1557   case RISCVISD::GREVI:
1558   case RISCVISD::GORCI:
1559     return combineGREVI_GORCI(N, DCI.DAG);
1560   case ISD::OR:
1561     if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget))
1562       return GREV;
1563     if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget))
1564       return GORC;
1565     break;
1566   }
1567 
1568   return SDValue();
1569 }
1570 
1571 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
1572     const SDNode *N, CombineLevel Level) const {
1573   // The following folds are only desirable if `(OP _, c1 << c2)` can be
1574   // materialised in fewer instructions than `(OP _, c1)`:
1575   //
1576   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
1577   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
1578   SDValue N0 = N->getOperand(0);
1579   EVT Ty = N0.getValueType();
1580   if (Ty.isScalarInteger() &&
1581       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
1582     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
1583     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
1584     if (C1 && C2) {
1585       APInt C1Int = C1->getAPIntValue();
1586       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
1587 
1588       // We can materialise `c1 << c2` into an add immediate, so it's "free",
1589       // and the combine should happen, to potentially allow further combines
1590       // later.
1591       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
1592           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
1593         return true;
1594 
1595       // We can materialise `c1` in an add immediate, so it's "free", and the
1596       // combine should be prevented.
1597       if (C1Int.getMinSignedBits() <= 64 &&
1598           isLegalAddImmediate(C1Int.getSExtValue()))
1599         return false;
1600 
1601       // Neither constant will fit into an immediate, so find materialisation
1602       // costs.
1603       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
1604                                               Subtarget.is64Bit());
1605       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
1606           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit());
1607 
1608       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
1609       // combine should be prevented.
1610       if (C1Cost < ShiftedC1Cost)
1611         return false;
1612     }
1613   }
1614   return true;
1615 }
1616 
1617 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
1618     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
1619     unsigned Depth) const {
1620   switch (Op.getOpcode()) {
1621   default:
1622     break;
1623   case RISCVISD::SLLW:
1624   case RISCVISD::SRAW:
1625   case RISCVISD::SRLW:
1626   case RISCVISD::DIVW:
1627   case RISCVISD::DIVUW:
1628   case RISCVISD::REMUW:
1629   case RISCVISD::ROLW:
1630   case RISCVISD::RORW:
1631   case RISCVISD::GREVIW:
1632   case RISCVISD::GORCIW:
1633   case RISCVISD::FSLW:
1634   case RISCVISD::FSRW:
1635     // TODO: As the result is sign-extended, this is conservatively correct. A
1636     // more precise answer could be calculated for SRAW depending on known
1637     // bits in the shift amount.
1638     return 33;
1639   }
1640 
1641   return 1;
1642 }
1643 
1644 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
1645                                                   MachineBasicBlock *BB) {
1646   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
1647 
1648   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
1649   // Should the count have wrapped while it was being read, we need to try
1650   // again.
1651   // ...
1652   // read:
1653   // rdcycleh x3 # load high word of cycle
1654   // rdcycle  x2 # load low word of cycle
1655   // rdcycleh x4 # load high word of cycle
1656   // bne x3, x4, read # check if high word reads match, otherwise try again
1657   // ...
1658 
1659   MachineFunction &MF = *BB->getParent();
1660   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1661   MachineFunction::iterator It = ++BB->getIterator();
1662 
1663   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1664   MF.insert(It, LoopMBB);
1665 
1666   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1667   MF.insert(It, DoneMBB);
1668 
1669   // Transfer the remainder of BB and its successor edges to DoneMBB.
1670   DoneMBB->splice(DoneMBB->begin(), BB,
1671                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1672   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
1673 
1674   BB->addSuccessor(LoopMBB);
1675 
1676   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1677   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1678   Register LoReg = MI.getOperand(0).getReg();
1679   Register HiReg = MI.getOperand(1).getReg();
1680   DebugLoc DL = MI.getDebugLoc();
1681 
1682   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1683   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
1684       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
1685       .addReg(RISCV::X0);
1686   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
1687       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
1688       .addReg(RISCV::X0);
1689   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
1690       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
1691       .addReg(RISCV::X0);
1692 
1693   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
1694       .addReg(HiReg)
1695       .addReg(ReadAgainReg)
1696       .addMBB(LoopMBB);
1697 
1698   LoopMBB->addSuccessor(LoopMBB);
1699   LoopMBB->addSuccessor(DoneMBB);
1700 
1701   MI.eraseFromParent();
1702 
1703   return DoneMBB;
1704 }
1705 
1706 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
1707                                              MachineBasicBlock *BB) {
1708   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
1709 
1710   MachineFunction &MF = *BB->getParent();
1711   DebugLoc DL = MI.getDebugLoc();
1712   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1713   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
1714   Register LoReg = MI.getOperand(0).getReg();
1715   Register HiReg = MI.getOperand(1).getReg();
1716   Register SrcReg = MI.getOperand(2).getReg();
1717   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
1718   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
1719 
1720   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
1721                           RI);
1722   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
1723   MachineMemOperand *MMOLo =
1724       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
1725   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
1726       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
1727   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
1728       .addFrameIndex(FI)
1729       .addImm(0)
1730       .addMemOperand(MMOLo);
1731   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
1732       .addFrameIndex(FI)
1733       .addImm(4)
1734       .addMemOperand(MMOHi);
1735   MI.eraseFromParent(); // The pseudo instruction is gone now.
1736   return BB;
1737 }
1738 
1739 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
1740                                                  MachineBasicBlock *BB) {
1741   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
1742          "Unexpected instruction");
1743 
1744   MachineFunction &MF = *BB->getParent();
1745   DebugLoc DL = MI.getDebugLoc();
1746   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1747   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
1748   Register DstReg = MI.getOperand(0).getReg();
1749   Register LoReg = MI.getOperand(1).getReg();
1750   Register HiReg = MI.getOperand(2).getReg();
1751   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
1752   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
1753 
1754   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
1755   MachineMemOperand *MMOLo =
1756       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
1757   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
1758       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
1759   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
1760       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
1761       .addFrameIndex(FI)
1762       .addImm(0)
1763       .addMemOperand(MMOLo);
1764   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
1765       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
1766       .addFrameIndex(FI)
1767       .addImm(4)
1768       .addMemOperand(MMOHi);
1769   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
1770   MI.eraseFromParent(); // The pseudo instruction is gone now.
1771   return BB;
1772 }
1773 
1774 static bool isSelectPseudo(MachineInstr &MI) {
1775   switch (MI.getOpcode()) {
1776   default:
1777     return false;
1778   case RISCV::Select_GPR_Using_CC_GPR:
1779   case RISCV::Select_FPR16_Using_CC_GPR:
1780   case RISCV::Select_FPR32_Using_CC_GPR:
1781   case RISCV::Select_FPR64_Using_CC_GPR:
1782     return true;
1783   }
1784 }
1785 
1786 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
1787                                            MachineBasicBlock *BB) {
1788   // To "insert" Select_* instructions, we actually have to insert the triangle
1789   // control-flow pattern.  The incoming instructions know the destination vreg
1790   // to set, the condition code register to branch on, the true/false values to
1791   // select between, and the condcode to use to select the appropriate branch.
1792   //
1793   // We produce the following control flow:
1794   //     HeadMBB
1795   //     |  \
1796   //     |  IfFalseMBB
1797   //     | /
1798   //    TailMBB
1799   //
1800   // When we find a sequence of selects we attempt to optimize their emission
1801   // by sharing the control flow. Currently we only handle cases where we have
1802   // multiple selects with the exact same condition (same LHS, RHS and CC).
1803   // The selects may be interleaved with other instructions if the other
1804   // instructions meet some requirements we deem safe:
1805   // - They are debug instructions. Otherwise,
1806   // - They do not have side-effects, do not access memory and their inputs do
1807   //   not depend on the results of the select pseudo-instructions.
1808   // The TrueV/FalseV operands of the selects cannot depend on the result of
1809   // previous selects in the sequence.
1810   // These conditions could be further relaxed. See the X86 target for a
1811   // related approach and more information.
1812   Register LHS = MI.getOperand(1).getReg();
1813   Register RHS = MI.getOperand(2).getReg();
1814   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
1815 
1816   SmallVector<MachineInstr *, 4> SelectDebugValues;
1817   SmallSet<Register, 4> SelectDests;
1818   SelectDests.insert(MI.getOperand(0).getReg());
1819 
1820   MachineInstr *LastSelectPseudo = &MI;
1821 
1822   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
1823        SequenceMBBI != E; ++SequenceMBBI) {
1824     if (SequenceMBBI->isDebugInstr())
1825       continue;
1826     else if (isSelectPseudo(*SequenceMBBI)) {
1827       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
1828           SequenceMBBI->getOperand(2).getReg() != RHS ||
1829           SequenceMBBI->getOperand(3).getImm() != CC ||
1830           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
1831           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
1832         break;
1833       LastSelectPseudo = &*SequenceMBBI;
1834       SequenceMBBI->collectDebugValues(SelectDebugValues);
1835       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
1836     } else {
1837       if (SequenceMBBI->hasUnmodeledSideEffects() ||
1838           SequenceMBBI->mayLoadOrStore())
1839         break;
1840       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
1841             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
1842           }))
1843         break;
1844     }
1845   }
1846 
1847   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1848   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1849   DebugLoc DL = MI.getDebugLoc();
1850   MachineFunction::iterator I = ++BB->getIterator();
1851 
1852   MachineBasicBlock *HeadMBB = BB;
1853   MachineFunction *F = BB->getParent();
1854   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
1855   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
1856 
1857   F->insert(I, IfFalseMBB);
1858   F->insert(I, TailMBB);
1859 
1860   // Transfer debug instructions associated with the selects to TailMBB.
1861   for (MachineInstr *DebugInstr : SelectDebugValues) {
1862     TailMBB->push_back(DebugInstr->removeFromParent());
1863   }
1864 
1865   // Move all instructions after the sequence to TailMBB.
1866   TailMBB->splice(TailMBB->end(), HeadMBB,
1867                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
1868   // Update machine-CFG edges by transferring all successors of the current
1869   // block to the new block which will contain the Phi nodes for the selects.
1870   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
1871   // Set the successors for HeadMBB.
1872   HeadMBB->addSuccessor(IfFalseMBB);
1873   HeadMBB->addSuccessor(TailMBB);
1874 
1875   // Insert appropriate branch.
1876   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
1877 
1878   BuildMI(HeadMBB, DL, TII.get(Opcode))
1879     .addReg(LHS)
1880     .addReg(RHS)
1881     .addMBB(TailMBB);
1882 
1883   // IfFalseMBB just falls through to TailMBB.
1884   IfFalseMBB->addSuccessor(TailMBB);
1885 
1886   // Create PHIs for all of the select pseudo-instructions.
1887   auto SelectMBBI = MI.getIterator();
1888   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
1889   auto InsertionPoint = TailMBB->begin();
1890   while (SelectMBBI != SelectEnd) {
1891     auto Next = std::next(SelectMBBI);
1892     if (isSelectPseudo(*SelectMBBI)) {
1893       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
1894       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
1895               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
1896           .addReg(SelectMBBI->getOperand(4).getReg())
1897           .addMBB(HeadMBB)
1898           .addReg(SelectMBBI->getOperand(5).getReg())
1899           .addMBB(IfFalseMBB);
1900       SelectMBBI->eraseFromParent();
1901     }
1902     SelectMBBI = Next;
1903   }
1904 
1905   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
1906   return TailMBB;
1907 }
1908 
1909 static MachineBasicBlock *addVSetVL(MachineInstr &MI, MachineBasicBlock *BB,
1910                                     int VLIndex, unsigned SEWIndex,
1911                                     unsigned VLMul) {
1912   MachineFunction &MF = *BB->getParent();
1913   DebugLoc DL = MI.getDebugLoc();
1914   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1915 
1916   unsigned SEW = MI.getOperand(SEWIndex).getImm();
1917   RISCVVLengthMultiplier::LengthMultiplier Multiplier;
1918 
1919   switch (VLMul) {
1920   default:
1921     llvm_unreachable("Unexpected LMUL for instruction");
1922   case 0:
1923   case 1:
1924   case 2:
1925   case 3:
1926   case 5:
1927   case 6:
1928   case 7:
1929     Multiplier = static_cast<RISCVVLengthMultiplier::LengthMultiplier>(VLMul);
1930     break;
1931   }
1932 
1933   RISCVVStandardElementWidth::StandardElementWidth ElementWidth;
1934   switch (SEW) {
1935   default:
1936     llvm_unreachable("Unexpected SEW for instruction");
1937   case 8:
1938     ElementWidth = RISCVVStandardElementWidth::ElementWidth8;
1939     break;
1940   case 16:
1941     ElementWidth = RISCVVStandardElementWidth::ElementWidth16;
1942     break;
1943   case 32:
1944     ElementWidth = RISCVVStandardElementWidth::ElementWidth32;
1945     break;
1946   case 64:
1947     ElementWidth = RISCVVStandardElementWidth::ElementWidth64;
1948     break;
1949   }
1950 
1951   MachineRegisterInfo &MRI = MF.getRegInfo();
1952 
1953   // VL and VTYPE are alive here.
1954   MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI));
1955 
1956   if (VLIndex >= 0) {
1957     // Set VL (rs1 != X0).
1958     unsigned DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
1959     MIB.addReg(DestReg, RegState::Define | RegState::Dead)
1960        .addReg(MI.getOperand(VLIndex).getReg());
1961   } else
1962     // With no VL operator in the pseudo, do not modify VL (rd = X0, rs1 = X0).
1963     MIB.addReg(RISCV::X0, RegState::Dead)
1964        .addReg(RISCV::X0, RegState::Kill);
1965 
1966   // For simplicity we reuse the vtype representation here.
1967   // Bits | Name       | Description
1968   // -----+------------+------------------------------------------------
1969   // 5    | vlmul[2]   | Fractional lmul?
1970   // 4:2  | vsew[2:0]  | Standard element width (SEW) setting
1971   // 1:0  | vlmul[1:0] | Vector register group multiplier (LMUL) setting
1972   MIB.addImm(((Multiplier & 0x4) << 3) | ((ElementWidth & 0x3) << 2) |
1973              (Multiplier & 0x3));
1974 
1975   // Remove (now) redundant operands from pseudo
1976   MI.getOperand(SEWIndex).setImm(-1);
1977   if (VLIndex >= 0) {
1978     MI.getOperand(VLIndex).setReg(RISCV::NoRegister);
1979     MI.getOperand(VLIndex).setIsKill(false);
1980   }
1981 
1982   return BB;
1983 }
1984 
1985 MachineBasicBlock *
1986 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1987                                                  MachineBasicBlock *BB) const {
1988 
1989   if (const RISCVVPseudosTable::PseudoInfo *RVV =
1990           RISCVVPseudosTable::getPseudoInfo(MI.getOpcode())) {
1991     int VLIndex = RVV->getVLIndex();
1992     int SEWIndex = RVV->getSEWIndex();
1993 
1994     assert(SEWIndex >= 0 && "SEWIndex must be >= 0");
1995     return addVSetVL(MI, BB, VLIndex, SEWIndex, RVV->VLMul);
1996   }
1997 
1998   switch (MI.getOpcode()) {
1999   default:
2000     llvm_unreachable("Unexpected instr type to insert");
2001   case RISCV::ReadCycleWide:
2002     assert(!Subtarget.is64Bit() &&
2003            "ReadCycleWrite is only to be used on riscv32");
2004     return emitReadCycleWidePseudo(MI, BB);
2005   case RISCV::Select_GPR_Using_CC_GPR:
2006   case RISCV::Select_FPR16_Using_CC_GPR:
2007   case RISCV::Select_FPR32_Using_CC_GPR:
2008   case RISCV::Select_FPR64_Using_CC_GPR:
2009     return emitSelectPseudo(MI, BB);
2010   case RISCV::BuildPairF64Pseudo:
2011     return emitBuildPairF64Pseudo(MI, BB);
2012   case RISCV::SplitF64Pseudo:
2013     return emitSplitF64Pseudo(MI, BB);
2014   }
2015 }
2016 
2017 // Calling Convention Implementation.
2018 // The expectations for frontend ABI lowering vary from target to target.
2019 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
2020 // details, but this is a longer term goal. For now, we simply try to keep the
2021 // role of the frontend as simple and well-defined as possible. The rules can
2022 // be summarised as:
2023 // * Never split up large scalar arguments. We handle them here.
2024 // * If a hardfloat calling convention is being used, and the struct may be
2025 // passed in a pair of registers (fp+fp, int+fp), and both registers are
2026 // available, then pass as two separate arguments. If either the GPRs or FPRs
2027 // are exhausted, then pass according to the rule below.
2028 // * If a struct could never be passed in registers or directly in a stack
2029 // slot (as it is larger than 2*XLEN and the floating point rules don't
2030 // apply), then pass it using a pointer with the byval attribute.
2031 // * If a struct is less than 2*XLEN, then coerce to either a two-element
2032 // word-sized array or a 2*XLEN scalar (depending on alignment).
2033 // * The frontend can determine whether a struct is returned by reference or
2034 // not based on its size and fields. If it will be returned by reference, the
2035 // frontend must modify the prototype so a pointer with the sret annotation is
2036 // passed as the first argument. This is not necessary for large scalar
2037 // returns.
2038 // * Struct return values and varargs should be coerced to structs containing
2039 // register-size fields in the same situations they would be for fixed
2040 // arguments.
2041 
2042 static const MCPhysReg ArgGPRs[] = {
2043   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
2044   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
2045 };
2046 static const MCPhysReg ArgFPR16s[] = {
2047   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
2048   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
2049 };
2050 static const MCPhysReg ArgFPR32s[] = {
2051   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
2052   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
2053 };
2054 static const MCPhysReg ArgFPR64s[] = {
2055   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
2056   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
2057 };
2058 
2059 // Pass a 2*XLEN argument that has been split into two XLEN values through
2060 // registers or the stack as necessary.
2061 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
2062                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
2063                                 MVT ValVT2, MVT LocVT2,
2064                                 ISD::ArgFlagsTy ArgFlags2) {
2065   unsigned XLenInBytes = XLen / 8;
2066   if (Register Reg = State.AllocateReg(ArgGPRs)) {
2067     // At least one half can be passed via register.
2068     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
2069                                      VA1.getLocVT(), CCValAssign::Full));
2070   } else {
2071     // Both halves must be passed on the stack, with proper alignment.
2072     Align StackAlign =
2073         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
2074     State.addLoc(
2075         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
2076                             State.AllocateStack(XLenInBytes, StackAlign),
2077                             VA1.getLocVT(), CCValAssign::Full));
2078     State.addLoc(CCValAssign::getMem(
2079         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
2080         LocVT2, CCValAssign::Full));
2081     return false;
2082   }
2083 
2084   if (Register Reg = State.AllocateReg(ArgGPRs)) {
2085     // The second half can also be passed via register.
2086     State.addLoc(
2087         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
2088   } else {
2089     // The second half is passed via the stack, without additional alignment.
2090     State.addLoc(CCValAssign::getMem(
2091         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
2092         LocVT2, CCValAssign::Full));
2093   }
2094 
2095   return false;
2096 }
2097 
2098 // Implements the RISC-V calling convention. Returns true upon failure.
2099 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
2100                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
2101                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
2102                      bool IsRet, Type *OrigTy) {
2103   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
2104   assert(XLen == 32 || XLen == 64);
2105   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
2106 
2107   // Any return value split in to more than two values can't be returned
2108   // directly.
2109   if (IsRet && ValNo > 1)
2110     return true;
2111 
2112   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
2113   // variadic argument, or if no F16/F32 argument registers are available.
2114   bool UseGPRForF16_F32 = true;
2115   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
2116   // variadic argument, or if no F64 argument registers are available.
2117   bool UseGPRForF64 = true;
2118 
2119   switch (ABI) {
2120   default:
2121     llvm_unreachable("Unexpected ABI");
2122   case RISCVABI::ABI_ILP32:
2123   case RISCVABI::ABI_LP64:
2124     break;
2125   case RISCVABI::ABI_ILP32F:
2126   case RISCVABI::ABI_LP64F:
2127     UseGPRForF16_F32 = !IsFixed;
2128     break;
2129   case RISCVABI::ABI_ILP32D:
2130   case RISCVABI::ABI_LP64D:
2131     UseGPRForF16_F32 = !IsFixed;
2132     UseGPRForF64 = !IsFixed;
2133     break;
2134   }
2135 
2136   // FPR16, FPR32, and FPR64 alias each other.
2137   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
2138     UseGPRForF16_F32 = true;
2139     UseGPRForF64 = true;
2140   }
2141 
2142   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
2143   // similar local variables rather than directly checking against the target
2144   // ABI.
2145 
2146   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
2147     LocVT = XLenVT;
2148     LocInfo = CCValAssign::BCvt;
2149   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
2150     LocVT = MVT::i64;
2151     LocInfo = CCValAssign::BCvt;
2152   }
2153 
2154   // If this is a variadic argument, the RISC-V calling convention requires
2155   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
2156   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
2157   // be used regardless of whether the original argument was split during
2158   // legalisation or not. The argument will not be passed by registers if the
2159   // original type is larger than 2*XLEN, so the register alignment rule does
2160   // not apply.
2161   unsigned TwoXLenInBytes = (2 * XLen) / 8;
2162   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
2163       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
2164     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
2165     // Skip 'odd' register if necessary.
2166     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
2167       State.AllocateReg(ArgGPRs);
2168   }
2169 
2170   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
2171   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
2172       State.getPendingArgFlags();
2173 
2174   assert(PendingLocs.size() == PendingArgFlags.size() &&
2175          "PendingLocs and PendingArgFlags out of sync");
2176 
2177   // Handle passing f64 on RV32D with a soft float ABI or when floating point
2178   // registers are exhausted.
2179   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
2180     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
2181            "Can't lower f64 if it is split");
2182     // Depending on available argument GPRS, f64 may be passed in a pair of
2183     // GPRs, split between a GPR and the stack, or passed completely on the
2184     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
2185     // cases.
2186     Register Reg = State.AllocateReg(ArgGPRs);
2187     LocVT = MVT::i32;
2188     if (!Reg) {
2189       unsigned StackOffset = State.AllocateStack(8, Align(8));
2190       State.addLoc(
2191           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
2192       return false;
2193     }
2194     if (!State.AllocateReg(ArgGPRs))
2195       State.AllocateStack(4, Align(4));
2196     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2197     return false;
2198   }
2199 
2200   // Split arguments might be passed indirectly, so keep track of the pending
2201   // values.
2202   if (ArgFlags.isSplit() || !PendingLocs.empty()) {
2203     LocVT = XLenVT;
2204     LocInfo = CCValAssign::Indirect;
2205     PendingLocs.push_back(
2206         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
2207     PendingArgFlags.push_back(ArgFlags);
2208     if (!ArgFlags.isSplitEnd()) {
2209       return false;
2210     }
2211   }
2212 
2213   // If the split argument only had two elements, it should be passed directly
2214   // in registers or on the stack.
2215   if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
2216     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
2217     // Apply the normal calling convention rules to the first half of the
2218     // split argument.
2219     CCValAssign VA = PendingLocs[0];
2220     ISD::ArgFlagsTy AF = PendingArgFlags[0];
2221     PendingLocs.clear();
2222     PendingArgFlags.clear();
2223     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
2224                                ArgFlags);
2225   }
2226 
2227   // Allocate to a register if possible, or else a stack slot.
2228   Register Reg;
2229   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
2230     Reg = State.AllocateReg(ArgFPR16s);
2231   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
2232     Reg = State.AllocateReg(ArgFPR32s);
2233   else if (ValVT == MVT::f64 && !UseGPRForF64)
2234     Reg = State.AllocateReg(ArgFPR64s);
2235   else
2236     Reg = State.AllocateReg(ArgGPRs);
2237   unsigned StackOffset =
2238       Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8));
2239 
2240   // If we reach this point and PendingLocs is non-empty, we must be at the
2241   // end of a split argument that must be passed indirectly.
2242   if (!PendingLocs.empty()) {
2243     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
2244     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
2245 
2246     for (auto &It : PendingLocs) {
2247       if (Reg)
2248         It.convertToReg(Reg);
2249       else
2250         It.convertToMem(StackOffset);
2251       State.addLoc(It);
2252     }
2253     PendingLocs.clear();
2254     PendingArgFlags.clear();
2255     return false;
2256   }
2257 
2258   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT) &&
2259          "Expected an XLenVT at this stage");
2260 
2261   if (Reg) {
2262     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2263     return false;
2264   }
2265 
2266   // When a floating-point value is passed on the stack, no bit-conversion is
2267   // needed.
2268   if (ValVT.isFloatingPoint()) {
2269     LocVT = ValVT;
2270     LocInfo = CCValAssign::Full;
2271   }
2272   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
2273   return false;
2274 }
2275 
2276 void RISCVTargetLowering::analyzeInputArgs(
2277     MachineFunction &MF, CCState &CCInfo,
2278     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
2279   unsigned NumArgs = Ins.size();
2280   FunctionType *FType = MF.getFunction().getFunctionType();
2281 
2282   for (unsigned i = 0; i != NumArgs; ++i) {
2283     MVT ArgVT = Ins[i].VT;
2284     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
2285 
2286     Type *ArgTy = nullptr;
2287     if (IsRet)
2288       ArgTy = FType->getReturnType();
2289     else if (Ins[i].isOrigArg())
2290       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
2291 
2292     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
2293     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
2294                  ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy)) {
2295       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
2296                         << EVT(ArgVT).getEVTString() << '\n');
2297       llvm_unreachable(nullptr);
2298     }
2299   }
2300 }
2301 
2302 void RISCVTargetLowering::analyzeOutputArgs(
2303     MachineFunction &MF, CCState &CCInfo,
2304     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
2305     CallLoweringInfo *CLI) const {
2306   unsigned NumArgs = Outs.size();
2307 
2308   for (unsigned i = 0; i != NumArgs; i++) {
2309     MVT ArgVT = Outs[i].VT;
2310     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2311     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
2312 
2313     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
2314     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
2315                  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
2316       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
2317                         << EVT(ArgVT).getEVTString() << "\n");
2318       llvm_unreachable(nullptr);
2319     }
2320   }
2321 }
2322 
2323 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
2324 // values.
2325 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
2326                                    const CCValAssign &VA, const SDLoc &DL) {
2327   switch (VA.getLocInfo()) {
2328   default:
2329     llvm_unreachable("Unexpected CCValAssign::LocInfo");
2330   case CCValAssign::Full:
2331     break;
2332   case CCValAssign::BCvt:
2333     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
2334       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
2335     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
2336       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
2337     else
2338       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2339     break;
2340   }
2341   return Val;
2342 }
2343 
2344 // The caller is responsible for loading the full value if the argument is
2345 // passed with CCValAssign::Indirect.
2346 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
2347                                 const CCValAssign &VA, const SDLoc &DL) {
2348   MachineFunction &MF = DAG.getMachineFunction();
2349   MachineRegisterInfo &RegInfo = MF.getRegInfo();
2350   EVT LocVT = VA.getLocVT();
2351   SDValue Val;
2352   const TargetRegisterClass *RC;
2353 
2354   switch (LocVT.getSimpleVT().SimpleTy) {
2355   default:
2356     llvm_unreachable("Unexpected register type");
2357   case MVT::i32:
2358   case MVT::i64:
2359     RC = &RISCV::GPRRegClass;
2360     break;
2361   case MVT::f16:
2362     RC = &RISCV::FPR16RegClass;
2363     break;
2364   case MVT::f32:
2365     RC = &RISCV::FPR32RegClass;
2366     break;
2367   case MVT::f64:
2368     RC = &RISCV::FPR64RegClass;
2369     break;
2370   }
2371 
2372   Register VReg = RegInfo.createVirtualRegister(RC);
2373   RegInfo.addLiveIn(VA.getLocReg(), VReg);
2374   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2375 
2376   if (VA.getLocInfo() == CCValAssign::Indirect)
2377     return Val;
2378 
2379   return convertLocVTToValVT(DAG, Val, VA, DL);
2380 }
2381 
2382 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
2383                                    const CCValAssign &VA, const SDLoc &DL) {
2384   EVT LocVT = VA.getLocVT();
2385 
2386   switch (VA.getLocInfo()) {
2387   default:
2388     llvm_unreachable("Unexpected CCValAssign::LocInfo");
2389   case CCValAssign::Full:
2390     break;
2391   case CCValAssign::BCvt:
2392     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
2393       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
2394     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
2395       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
2396     else
2397       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
2398     break;
2399   }
2400   return Val;
2401 }
2402 
2403 // The caller is responsible for loading the full value if the argument is
2404 // passed with CCValAssign::Indirect.
2405 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
2406                                 const CCValAssign &VA, const SDLoc &DL) {
2407   MachineFunction &MF = DAG.getMachineFunction();
2408   MachineFrameInfo &MFI = MF.getFrameInfo();
2409   EVT LocVT = VA.getLocVT();
2410   EVT ValVT = VA.getValVT();
2411   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
2412   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2413                                  VA.getLocMemOffset(), /*Immutable=*/true);
2414   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2415   SDValue Val;
2416 
2417   ISD::LoadExtType ExtType;
2418   switch (VA.getLocInfo()) {
2419   default:
2420     llvm_unreachable("Unexpected CCValAssign::LocInfo");
2421   case CCValAssign::Full:
2422   case CCValAssign::Indirect:
2423   case CCValAssign::BCvt:
2424     ExtType = ISD::NON_EXTLOAD;
2425     break;
2426   }
2427   Val = DAG.getExtLoad(
2428       ExtType, DL, LocVT, Chain, FIN,
2429       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
2430   return Val;
2431 }
2432 
2433 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
2434                                        const CCValAssign &VA, const SDLoc &DL) {
2435   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
2436          "Unexpected VA");
2437   MachineFunction &MF = DAG.getMachineFunction();
2438   MachineFrameInfo &MFI = MF.getFrameInfo();
2439   MachineRegisterInfo &RegInfo = MF.getRegInfo();
2440 
2441   if (VA.isMemLoc()) {
2442     // f64 is passed on the stack.
2443     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
2444     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
2445     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
2446                        MachinePointerInfo::getFixedStack(MF, FI));
2447   }
2448 
2449   assert(VA.isRegLoc() && "Expected register VA assignment");
2450 
2451   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
2452   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
2453   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
2454   SDValue Hi;
2455   if (VA.getLocReg() == RISCV::X17) {
2456     // Second half of f64 is passed on the stack.
2457     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
2458     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
2459     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
2460                      MachinePointerInfo::getFixedStack(MF, FI));
2461   } else {
2462     // Second half of f64 is passed in another GPR.
2463     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
2464     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
2465     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
2466   }
2467   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
2468 }
2469 
2470 // FastCC has less than 1% performance improvement for some particular
2471 // benchmark. But theoretically, it may has benenfit for some cases.
2472 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT,
2473                             CCValAssign::LocInfo LocInfo,
2474                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2475 
2476   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
2477     // X5 and X6 might be used for save-restore libcall.
2478     static const MCPhysReg GPRList[] = {
2479         RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
2480         RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
2481         RISCV::X29, RISCV::X30, RISCV::X31};
2482     if (unsigned Reg = State.AllocateReg(GPRList)) {
2483       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2484       return false;
2485     }
2486   }
2487 
2488   if (LocVT == MVT::f16) {
2489     static const MCPhysReg FPR16List[] = {
2490         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
2491         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
2492         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
2493         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
2494     if (unsigned Reg = State.AllocateReg(FPR16List)) {
2495       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2496       return false;
2497     }
2498   }
2499 
2500   if (LocVT == MVT::f32) {
2501     static const MCPhysReg FPR32List[] = {
2502         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
2503         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
2504         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
2505         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
2506     if (unsigned Reg = State.AllocateReg(FPR32List)) {
2507       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2508       return false;
2509     }
2510   }
2511 
2512   if (LocVT == MVT::f64) {
2513     static const MCPhysReg FPR64List[] = {
2514         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
2515         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
2516         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
2517         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
2518     if (unsigned Reg = State.AllocateReg(FPR64List)) {
2519       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2520       return false;
2521     }
2522   }
2523 
2524   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
2525     unsigned Offset4 = State.AllocateStack(4, Align(4));
2526     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
2527     return false;
2528   }
2529 
2530   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
2531     unsigned Offset5 = State.AllocateStack(8, Align(8));
2532     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
2533     return false;
2534   }
2535 
2536   return true; // CC didn't match.
2537 }
2538 
2539 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
2540                          CCValAssign::LocInfo LocInfo,
2541                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
2542 
2543   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
2544     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
2545     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
2546     static const MCPhysReg GPRList[] = {
2547         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
2548         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
2549     if (unsigned Reg = State.AllocateReg(GPRList)) {
2550       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2551       return false;
2552     }
2553   }
2554 
2555   if (LocVT == MVT::f32) {
2556     // Pass in STG registers: F1, ..., F6
2557     //                        fs0 ... fs5
2558     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
2559                                           RISCV::F18_F, RISCV::F19_F,
2560                                           RISCV::F20_F, RISCV::F21_F};
2561     if (unsigned Reg = State.AllocateReg(FPR32List)) {
2562       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2563       return false;
2564     }
2565   }
2566 
2567   if (LocVT == MVT::f64) {
2568     // Pass in STG registers: D1, ..., D6
2569     //                        fs6 ... fs11
2570     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
2571                                           RISCV::F24_D, RISCV::F25_D,
2572                                           RISCV::F26_D, RISCV::F27_D};
2573     if (unsigned Reg = State.AllocateReg(FPR64List)) {
2574       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2575       return false;
2576     }
2577   }
2578 
2579   report_fatal_error("No registers left in GHC calling convention");
2580   return true;
2581 }
2582 
2583 // Transform physical registers into virtual registers.
2584 SDValue RISCVTargetLowering::LowerFormalArguments(
2585     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2586     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2587     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2588 
2589   MachineFunction &MF = DAG.getMachineFunction();
2590 
2591   switch (CallConv) {
2592   default:
2593     report_fatal_error("Unsupported calling convention");
2594   case CallingConv::C:
2595   case CallingConv::Fast:
2596     break;
2597   case CallingConv::GHC:
2598     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
2599         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
2600       report_fatal_error(
2601         "GHC calling convention requires the F and D instruction set extensions");
2602   }
2603 
2604   const Function &Func = MF.getFunction();
2605   if (Func.hasFnAttribute("interrupt")) {
2606     if (!Func.arg_empty())
2607       report_fatal_error(
2608         "Functions with the interrupt attribute cannot have arguments!");
2609 
2610     StringRef Kind =
2611       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
2612 
2613     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
2614       report_fatal_error(
2615         "Function interrupt attribute argument not supported!");
2616   }
2617 
2618   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2619   MVT XLenVT = Subtarget.getXLenVT();
2620   unsigned XLenInBytes = Subtarget.getXLen() / 8;
2621   // Used with vargs to acumulate store chains.
2622   std::vector<SDValue> OutChains;
2623 
2624   // Assign locations to all of the incoming arguments.
2625   SmallVector<CCValAssign, 16> ArgLocs;
2626   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2627 
2628   if (CallConv == CallingConv::Fast)
2629     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC);
2630   else if (CallConv == CallingConv::GHC)
2631     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
2632   else
2633     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
2634 
2635   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2636     CCValAssign &VA = ArgLocs[i];
2637     SDValue ArgValue;
2638     // Passing f64 on RV32D with a soft float ABI must be handled as a special
2639     // case.
2640     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
2641       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
2642     else if (VA.isRegLoc())
2643       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
2644     else
2645       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
2646 
2647     if (VA.getLocInfo() == CCValAssign::Indirect) {
2648       // If the original argument was split and passed by reference (e.g. i128
2649       // on RV32), we need to load all parts of it here (using the same
2650       // address).
2651       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2652                                    MachinePointerInfo()));
2653       unsigned ArgIndex = Ins[i].OrigArgIndex;
2654       assert(Ins[i].PartOffset == 0);
2655       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
2656         CCValAssign &PartVA = ArgLocs[i + 1];
2657         unsigned PartOffset = Ins[i + 1].PartOffset;
2658         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2659                                       DAG.getIntPtrConstant(PartOffset, DL));
2660         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2661                                      MachinePointerInfo()));
2662         ++i;
2663       }
2664       continue;
2665     }
2666     InVals.push_back(ArgValue);
2667   }
2668 
2669   if (IsVarArg) {
2670     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
2671     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
2672     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
2673     MachineFrameInfo &MFI = MF.getFrameInfo();
2674     MachineRegisterInfo &RegInfo = MF.getRegInfo();
2675     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2676 
2677     // Offset of the first variable argument from stack pointer, and size of
2678     // the vararg save area. For now, the varargs save area is either zero or
2679     // large enough to hold a0-a7.
2680     int VaArgOffset, VarArgsSaveSize;
2681 
2682     // If all registers are allocated, then all varargs must be passed on the
2683     // stack and we don't need to save any argregs.
2684     if (ArgRegs.size() == Idx) {
2685       VaArgOffset = CCInfo.getNextStackOffset();
2686       VarArgsSaveSize = 0;
2687     } else {
2688       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
2689       VaArgOffset = -VarArgsSaveSize;
2690     }
2691 
2692     // Record the frame index of the first variable argument
2693     // which is a value necessary to VASTART.
2694     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
2695     RVFI->setVarArgsFrameIndex(FI);
2696 
2697     // If saving an odd number of registers then create an extra stack slot to
2698     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
2699     // offsets to even-numbered registered remain 2*XLEN-aligned.
2700     if (Idx % 2) {
2701       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
2702       VarArgsSaveSize += XLenInBytes;
2703     }
2704 
2705     // Copy the integer registers that may have been used for passing varargs
2706     // to the vararg save area.
2707     for (unsigned I = Idx; I < ArgRegs.size();
2708          ++I, VaArgOffset += XLenInBytes) {
2709       const Register Reg = RegInfo.createVirtualRegister(RC);
2710       RegInfo.addLiveIn(ArgRegs[I], Reg);
2711       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
2712       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
2713       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2714       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
2715                                    MachinePointerInfo::getFixedStack(MF, FI));
2716       cast<StoreSDNode>(Store.getNode())
2717           ->getMemOperand()
2718           ->setValue((Value *)nullptr);
2719       OutChains.push_back(Store);
2720     }
2721     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
2722   }
2723 
2724   // All stores are grouped in one node to allow the matching between
2725   // the size of Ins and InVals. This only happens for vararg functions.
2726   if (!OutChains.empty()) {
2727     OutChains.push_back(Chain);
2728     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2729   }
2730 
2731   return Chain;
2732 }
2733 
2734 /// isEligibleForTailCallOptimization - Check whether the call is eligible
2735 /// for tail call optimization.
2736 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
2737 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
2738     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
2739     const SmallVector<CCValAssign, 16> &ArgLocs) const {
2740 
2741   auto &Callee = CLI.Callee;
2742   auto CalleeCC = CLI.CallConv;
2743   auto &Outs = CLI.Outs;
2744   auto &Caller = MF.getFunction();
2745   auto CallerCC = Caller.getCallingConv();
2746 
2747   // Exception-handling functions need a special set of instructions to
2748   // indicate a return to the hardware. Tail-calling another function would
2749   // probably break this.
2750   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
2751   // should be expanded as new function attributes are introduced.
2752   if (Caller.hasFnAttribute("interrupt"))
2753     return false;
2754 
2755   // Do not tail call opt if the stack is used to pass parameters.
2756   if (CCInfo.getNextStackOffset() != 0)
2757     return false;
2758 
2759   // Do not tail call opt if any parameters need to be passed indirectly.
2760   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
2761   // passed indirectly. So the address of the value will be passed in a
2762   // register, or if not available, then the address is put on the stack. In
2763   // order to pass indirectly, space on the stack often needs to be allocated
2764   // in order to store the value. In this case the CCInfo.getNextStackOffset()
2765   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
2766   // are passed CCValAssign::Indirect.
2767   for (auto &VA : ArgLocs)
2768     if (VA.getLocInfo() == CCValAssign::Indirect)
2769       return false;
2770 
2771   // Do not tail call opt if either caller or callee uses struct return
2772   // semantics.
2773   auto IsCallerStructRet = Caller.hasStructRetAttr();
2774   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2775   if (IsCallerStructRet || IsCalleeStructRet)
2776     return false;
2777 
2778   // Externally-defined functions with weak linkage should not be
2779   // tail-called. The behaviour of branch instructions in this situation (as
2780   // used for tail calls) is implementation-defined, so we cannot rely on the
2781   // linker replacing the tail call with a return.
2782   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2783     const GlobalValue *GV = G->getGlobal();
2784     if (GV->hasExternalWeakLinkage())
2785       return false;
2786   }
2787 
2788   // The callee has to preserve all registers the caller needs to preserve.
2789   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
2790   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2791   if (CalleeCC != CallerCC) {
2792     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2793     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2794       return false;
2795   }
2796 
2797   // Byval parameters hand the function a pointer directly into the stack area
2798   // we want to reuse during a tail call. Working around this *is* possible
2799   // but less efficient and uglier in LowerCall.
2800   for (auto &Arg : Outs)
2801     if (Arg.Flags.isByVal())
2802       return false;
2803 
2804   return true;
2805 }
2806 
2807 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
2808 // and output parameter nodes.
2809 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
2810                                        SmallVectorImpl<SDValue> &InVals) const {
2811   SelectionDAG &DAG = CLI.DAG;
2812   SDLoc &DL = CLI.DL;
2813   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2814   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2815   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2816   SDValue Chain = CLI.Chain;
2817   SDValue Callee = CLI.Callee;
2818   bool &IsTailCall = CLI.IsTailCall;
2819   CallingConv::ID CallConv = CLI.CallConv;
2820   bool IsVarArg = CLI.IsVarArg;
2821   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2822   MVT XLenVT = Subtarget.getXLenVT();
2823 
2824   MachineFunction &MF = DAG.getMachineFunction();
2825 
2826   // Analyze the operands of the call, assigning locations to each operand.
2827   SmallVector<CCValAssign, 16> ArgLocs;
2828   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2829 
2830   if (CallConv == CallingConv::Fast)
2831     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC);
2832   else if (CallConv == CallingConv::GHC)
2833     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
2834   else
2835     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
2836 
2837   // Check if it's really possible to do a tail call.
2838   if (IsTailCall)
2839     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
2840 
2841   if (IsTailCall)
2842     ++NumTailCalls;
2843   else if (CLI.CB && CLI.CB->isMustTailCall())
2844     report_fatal_error("failed to perform tail call elimination on a call "
2845                        "site marked musttail");
2846 
2847   // Get a count of how many bytes are to be pushed on the stack.
2848   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
2849 
2850   // Create local copies for byval args
2851   SmallVector<SDValue, 8> ByValArgs;
2852   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
2853     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2854     if (!Flags.isByVal())
2855       continue;
2856 
2857     SDValue Arg = OutVals[i];
2858     unsigned Size = Flags.getByValSize();
2859     Align Alignment = Flags.getNonZeroByValAlign();
2860 
2861     int FI =
2862         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
2863     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2864     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
2865 
2866     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
2867                           /*IsVolatile=*/false,
2868                           /*AlwaysInline=*/false, IsTailCall,
2869                           MachinePointerInfo(), MachinePointerInfo());
2870     ByValArgs.push_back(FIPtr);
2871   }
2872 
2873   if (!IsTailCall)
2874     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
2875 
2876   // Copy argument values to their designated locations.
2877   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
2878   SmallVector<SDValue, 8> MemOpChains;
2879   SDValue StackPtr;
2880   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
2881     CCValAssign &VA = ArgLocs[i];
2882     SDValue ArgValue = OutVals[i];
2883     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2884 
2885     // Handle passing f64 on RV32D with a soft float ABI as a special case.
2886     bool IsF64OnRV32DSoftABI =
2887         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
2888     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
2889       SDValue SplitF64 = DAG.getNode(
2890           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
2891       SDValue Lo = SplitF64.getValue(0);
2892       SDValue Hi = SplitF64.getValue(1);
2893 
2894       Register RegLo = VA.getLocReg();
2895       RegsToPass.push_back(std::make_pair(RegLo, Lo));
2896 
2897       if (RegLo == RISCV::X17) {
2898         // Second half of f64 is passed on the stack.
2899         // Work out the address of the stack slot.
2900         if (!StackPtr.getNode())
2901           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
2902         // Emit the store.
2903         MemOpChains.push_back(
2904             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
2905       } else {
2906         // Second half of f64 is passed in another GPR.
2907         assert(RegLo < RISCV::X31 && "Invalid register pair");
2908         Register RegHigh = RegLo + 1;
2909         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
2910       }
2911       continue;
2912     }
2913 
2914     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
2915     // as any other MemLoc.
2916 
2917     // Promote the value if needed.
2918     // For now, only handle fully promoted and indirect arguments.
2919     if (VA.getLocInfo() == CCValAssign::Indirect) {
2920       // Store the argument in a stack slot and pass its address.
2921       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
2922       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2923       MemOpChains.push_back(
2924           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
2925                        MachinePointerInfo::getFixedStack(MF, FI)));
2926       // If the original argument was split (e.g. i128), we need
2927       // to store all parts of it here (and pass just one address).
2928       unsigned ArgIndex = Outs[i].OrigArgIndex;
2929       assert(Outs[i].PartOffset == 0);
2930       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
2931         SDValue PartValue = OutVals[i + 1];
2932         unsigned PartOffset = Outs[i + 1].PartOffset;
2933         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2934                                       DAG.getIntPtrConstant(PartOffset, DL));
2935         MemOpChains.push_back(
2936             DAG.getStore(Chain, DL, PartValue, Address,
2937                          MachinePointerInfo::getFixedStack(MF, FI)));
2938         ++i;
2939       }
2940       ArgValue = SpillSlot;
2941     } else {
2942       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
2943     }
2944 
2945     // Use local copy if it is a byval arg.
2946     if (Flags.isByVal())
2947       ArgValue = ByValArgs[j++];
2948 
2949     if (VA.isRegLoc()) {
2950       // Queue up the argument copies and emit them at the end.
2951       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2952     } else {
2953       assert(VA.isMemLoc() && "Argument not register or memory");
2954       assert(!IsTailCall && "Tail call not allowed if stack is used "
2955                             "for passing parameters");
2956 
2957       // Work out the address of the stack slot.
2958       if (!StackPtr.getNode())
2959         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
2960       SDValue Address =
2961           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2962                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
2963 
2964       // Emit the store.
2965       MemOpChains.push_back(
2966           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2967     }
2968   }
2969 
2970   // Join the stores, which are independent of one another.
2971   if (!MemOpChains.empty())
2972     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2973 
2974   SDValue Glue;
2975 
2976   // Build a sequence of copy-to-reg nodes, chained and glued together.
2977   for (auto &Reg : RegsToPass) {
2978     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
2979     Glue = Chain.getValue(1);
2980   }
2981 
2982   // Validate that none of the argument registers have been marked as
2983   // reserved, if so report an error. Do the same for the return address if this
2984   // is not a tailcall.
2985   validateCCReservedRegs(RegsToPass, MF);
2986   if (!IsTailCall &&
2987       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
2988     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
2989         MF.getFunction(),
2990         "Return address register required, but has been reserved."});
2991 
2992   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
2993   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
2994   // split it and then direct call can be matched by PseudoCALL.
2995   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
2996     const GlobalValue *GV = S->getGlobal();
2997 
2998     unsigned OpFlags = RISCVII::MO_CALL;
2999     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
3000       OpFlags = RISCVII::MO_PLT;
3001 
3002     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3003   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3004     unsigned OpFlags = RISCVII::MO_CALL;
3005 
3006     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
3007                                                  nullptr))
3008       OpFlags = RISCVII::MO_PLT;
3009 
3010     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
3011   }
3012 
3013   // The first call operand is the chain and the second is the target address.
3014   SmallVector<SDValue, 8> Ops;
3015   Ops.push_back(Chain);
3016   Ops.push_back(Callee);
3017 
3018   // Add argument registers to the end of the list so that they are
3019   // known live into the call.
3020   for (auto &Reg : RegsToPass)
3021     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
3022 
3023   if (!IsTailCall) {
3024     // Add a register mask operand representing the call-preserved registers.
3025     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3026     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3027     assert(Mask && "Missing call preserved mask for calling convention");
3028     Ops.push_back(DAG.getRegisterMask(Mask));
3029   }
3030 
3031   // Glue the call to the argument copies, if any.
3032   if (Glue.getNode())
3033     Ops.push_back(Glue);
3034 
3035   // Emit the call.
3036   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3037 
3038   if (IsTailCall) {
3039     MF.getFrameInfo().setHasTailCall();
3040     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
3041   }
3042 
3043   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
3044   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
3045   Glue = Chain.getValue(1);
3046 
3047   // Mark the end of the call, which is glued to the call itself.
3048   Chain = DAG.getCALLSEQ_END(Chain,
3049                              DAG.getConstant(NumBytes, DL, PtrVT, true),
3050                              DAG.getConstant(0, DL, PtrVT, true),
3051                              Glue, DL);
3052   Glue = Chain.getValue(1);
3053 
3054   // Assign locations to each value returned by this call.
3055   SmallVector<CCValAssign, 16> RVLocs;
3056   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3057   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
3058 
3059   // Copy all of the result registers out of their specified physreg.
3060   for (auto &VA : RVLocs) {
3061     // Copy the value out
3062     SDValue RetValue =
3063         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
3064     // Glue the RetValue to the end of the call sequence
3065     Chain = RetValue.getValue(1);
3066     Glue = RetValue.getValue(2);
3067 
3068     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
3069       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
3070       SDValue RetValue2 =
3071           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
3072       Chain = RetValue2.getValue(1);
3073       Glue = RetValue2.getValue(2);
3074       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
3075                              RetValue2);
3076     }
3077 
3078     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
3079 
3080     InVals.push_back(RetValue);
3081   }
3082 
3083   return Chain;
3084 }
3085 
3086 bool RISCVTargetLowering::CanLowerReturn(
3087     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
3088     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3089   SmallVector<CCValAssign, 16> RVLocs;
3090   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3091   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
3092     MVT VT = Outs[i].VT;
3093     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3094     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
3095     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
3096                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
3097       return false;
3098   }
3099   return true;
3100 }
3101 
3102 SDValue
3103 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3104                                  bool IsVarArg,
3105                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
3106                                  const SmallVectorImpl<SDValue> &OutVals,
3107                                  const SDLoc &DL, SelectionDAG &DAG) const {
3108   const MachineFunction &MF = DAG.getMachineFunction();
3109   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
3110 
3111   // Stores the assignment of the return value to a location.
3112   SmallVector<CCValAssign, 16> RVLocs;
3113 
3114   // Info about the registers and stack slot.
3115   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3116                  *DAG.getContext());
3117 
3118   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
3119                     nullptr);
3120 
3121   if (CallConv == CallingConv::GHC && !RVLocs.empty())
3122     report_fatal_error("GHC functions return void only");
3123 
3124   SDValue Glue;
3125   SmallVector<SDValue, 4> RetOps(1, Chain);
3126 
3127   // Copy the result values into the output registers.
3128   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
3129     SDValue Val = OutVals[i];
3130     CCValAssign &VA = RVLocs[i];
3131     assert(VA.isRegLoc() && "Can only return in registers!");
3132 
3133     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
3134       // Handle returning f64 on RV32D with a soft float ABI.
3135       assert(VA.isRegLoc() && "Expected return via registers");
3136       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
3137                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
3138       SDValue Lo = SplitF64.getValue(0);
3139       SDValue Hi = SplitF64.getValue(1);
3140       Register RegLo = VA.getLocReg();
3141       assert(RegLo < RISCV::X31 && "Invalid register pair");
3142       Register RegHi = RegLo + 1;
3143 
3144       if (STI.isRegisterReservedByUser(RegLo) ||
3145           STI.isRegisterReservedByUser(RegHi))
3146         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
3147             MF.getFunction(),
3148             "Return value register required, but has been reserved."});
3149 
3150       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
3151       Glue = Chain.getValue(1);
3152       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
3153       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
3154       Glue = Chain.getValue(1);
3155       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
3156     } else {
3157       // Handle a 'normal' return.
3158       Val = convertValVTToLocVT(DAG, Val, VA, DL);
3159       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
3160 
3161       if (STI.isRegisterReservedByUser(VA.getLocReg()))
3162         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
3163             MF.getFunction(),
3164             "Return value register required, but has been reserved."});
3165 
3166       // Guarantee that all emitted copies are stuck together.
3167       Glue = Chain.getValue(1);
3168       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3169     }
3170   }
3171 
3172   RetOps[0] = Chain; // Update chain.
3173 
3174   // Add the glue node if we have it.
3175   if (Glue.getNode()) {
3176     RetOps.push_back(Glue);
3177   }
3178 
3179   // Interrupt service routines use different return instructions.
3180   const Function &Func = DAG.getMachineFunction().getFunction();
3181   if (Func.hasFnAttribute("interrupt")) {
3182     if (!Func.getReturnType()->isVoidTy())
3183       report_fatal_error(
3184           "Functions with the interrupt attribute must have void return type!");
3185 
3186     MachineFunction &MF = DAG.getMachineFunction();
3187     StringRef Kind =
3188       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
3189 
3190     unsigned RetOpc;
3191     if (Kind == "user")
3192       RetOpc = RISCVISD::URET_FLAG;
3193     else if (Kind == "supervisor")
3194       RetOpc = RISCVISD::SRET_FLAG;
3195     else
3196       RetOpc = RISCVISD::MRET_FLAG;
3197 
3198     return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
3199   }
3200 
3201   return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
3202 }
3203 
3204 void RISCVTargetLowering::validateCCReservedRegs(
3205     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
3206     MachineFunction &MF) const {
3207   const Function &F = MF.getFunction();
3208   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
3209 
3210   if (std::any_of(std::begin(Regs), std::end(Regs), [&STI](auto Reg) {
3211         return STI.isRegisterReservedByUser(Reg.first);
3212       }))
3213     F.getContext().diagnose(DiagnosticInfoUnsupported{
3214         F, "Argument register required, but has been reserved."});
3215 }
3216 
3217 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3218   return CI->isTailCall();
3219 }
3220 
3221 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
3222 #define NODE_NAME_CASE(NODE)                                                   \
3223   case RISCVISD::NODE:                                                         \
3224     return "RISCVISD::" #NODE;
3225   // clang-format off
3226   switch ((RISCVISD::NodeType)Opcode) {
3227   case RISCVISD::FIRST_NUMBER:
3228     break;
3229   NODE_NAME_CASE(RET_FLAG)
3230   NODE_NAME_CASE(URET_FLAG)
3231   NODE_NAME_CASE(SRET_FLAG)
3232   NODE_NAME_CASE(MRET_FLAG)
3233   NODE_NAME_CASE(CALL)
3234   NODE_NAME_CASE(SELECT_CC)
3235   NODE_NAME_CASE(BuildPairF64)
3236   NODE_NAME_CASE(SplitF64)
3237   NODE_NAME_CASE(TAIL)
3238   NODE_NAME_CASE(SLLW)
3239   NODE_NAME_CASE(SRAW)
3240   NODE_NAME_CASE(SRLW)
3241   NODE_NAME_CASE(DIVW)
3242   NODE_NAME_CASE(DIVUW)
3243   NODE_NAME_CASE(REMUW)
3244   NODE_NAME_CASE(ROLW)
3245   NODE_NAME_CASE(RORW)
3246   NODE_NAME_CASE(FSLW)
3247   NODE_NAME_CASE(FSRW)
3248   NODE_NAME_CASE(FMV_H_X)
3249   NODE_NAME_CASE(FMV_X_ANYEXTH)
3250   NODE_NAME_CASE(FMV_W_X_RV64)
3251   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
3252   NODE_NAME_CASE(READ_CYCLE_WIDE)
3253   NODE_NAME_CASE(GREVI)
3254   NODE_NAME_CASE(GREVIW)
3255   NODE_NAME_CASE(GORCI)
3256   NODE_NAME_CASE(GORCIW)
3257   }
3258   // clang-format on
3259   return nullptr;
3260 #undef NODE_NAME_CASE
3261 }
3262 
3263 /// getConstraintType - Given a constraint letter, return the type of
3264 /// constraint it is for this target.
3265 RISCVTargetLowering::ConstraintType
3266 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
3267   if (Constraint.size() == 1) {
3268     switch (Constraint[0]) {
3269     default:
3270       break;
3271     case 'f':
3272       return C_RegisterClass;
3273     case 'I':
3274     case 'J':
3275     case 'K':
3276       return C_Immediate;
3277     case 'A':
3278       return C_Memory;
3279     }
3280   }
3281   return TargetLowering::getConstraintType(Constraint);
3282 }
3283 
3284 std::pair<unsigned, const TargetRegisterClass *>
3285 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3286                                                   StringRef Constraint,
3287                                                   MVT VT) const {
3288   // First, see if this is a constraint that directly corresponds to a
3289   // RISCV register class.
3290   if (Constraint.size() == 1) {
3291     switch (Constraint[0]) {
3292     case 'r':
3293       return std::make_pair(0U, &RISCV::GPRRegClass);
3294     case 'f':
3295       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
3296         return std::make_pair(0U, &RISCV::FPR16RegClass);
3297       if (Subtarget.hasStdExtF() && VT == MVT::f32)
3298         return std::make_pair(0U, &RISCV::FPR32RegClass);
3299       if (Subtarget.hasStdExtD() && VT == MVT::f64)
3300         return std::make_pair(0U, &RISCV::FPR64RegClass);
3301       break;
3302     default:
3303       break;
3304     }
3305   }
3306 
3307   // Clang will correctly decode the usage of register name aliases into their
3308   // official names. However, other frontends like `rustc` do not. This allows
3309   // users of these frontends to use the ABI names for registers in LLVM-style
3310   // register constraints.
3311   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
3312                                .Case("{zero}", RISCV::X0)
3313                                .Case("{ra}", RISCV::X1)
3314                                .Case("{sp}", RISCV::X2)
3315                                .Case("{gp}", RISCV::X3)
3316                                .Case("{tp}", RISCV::X4)
3317                                .Case("{t0}", RISCV::X5)
3318                                .Case("{t1}", RISCV::X6)
3319                                .Case("{t2}", RISCV::X7)
3320                                .Cases("{s0}", "{fp}", RISCV::X8)
3321                                .Case("{s1}", RISCV::X9)
3322                                .Case("{a0}", RISCV::X10)
3323                                .Case("{a1}", RISCV::X11)
3324                                .Case("{a2}", RISCV::X12)
3325                                .Case("{a3}", RISCV::X13)
3326                                .Case("{a4}", RISCV::X14)
3327                                .Case("{a5}", RISCV::X15)
3328                                .Case("{a6}", RISCV::X16)
3329                                .Case("{a7}", RISCV::X17)
3330                                .Case("{s2}", RISCV::X18)
3331                                .Case("{s3}", RISCV::X19)
3332                                .Case("{s4}", RISCV::X20)
3333                                .Case("{s5}", RISCV::X21)
3334                                .Case("{s6}", RISCV::X22)
3335                                .Case("{s7}", RISCV::X23)
3336                                .Case("{s8}", RISCV::X24)
3337                                .Case("{s9}", RISCV::X25)
3338                                .Case("{s10}", RISCV::X26)
3339                                .Case("{s11}", RISCV::X27)
3340                                .Case("{t3}", RISCV::X28)
3341                                .Case("{t4}", RISCV::X29)
3342                                .Case("{t5}", RISCV::X30)
3343                                .Case("{t6}", RISCV::X31)
3344                                .Default(RISCV::NoRegister);
3345   if (XRegFromAlias != RISCV::NoRegister)
3346     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
3347 
3348   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
3349   // TableGen record rather than the AsmName to choose registers for InlineAsm
3350   // constraints, plus we want to match those names to the widest floating point
3351   // register type available, manually select floating point registers here.
3352   //
3353   // The second case is the ABI name of the register, so that frontends can also
3354   // use the ABI names in register constraint lists.
3355   if (Subtarget.hasStdExtF()) {
3356     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
3357                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
3358                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
3359                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
3360                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
3361                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
3362                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
3363                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
3364                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
3365                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
3366                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
3367                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
3368                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
3369                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
3370                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
3371                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
3372                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
3373                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
3374                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
3375                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
3376                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
3377                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
3378                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
3379                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
3380                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
3381                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
3382                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
3383                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
3384                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
3385                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
3386                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
3387                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
3388                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
3389                         .Default(RISCV::NoRegister);
3390     if (FReg != RISCV::NoRegister) {
3391       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
3392       if (Subtarget.hasStdExtD()) {
3393         unsigned RegNo = FReg - RISCV::F0_F;
3394         unsigned DReg = RISCV::F0_D + RegNo;
3395         return std::make_pair(DReg, &RISCV::FPR64RegClass);
3396       }
3397       return std::make_pair(FReg, &RISCV::FPR32RegClass);
3398     }
3399   }
3400 
3401   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3402 }
3403 
3404 unsigned
3405 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3406   // Currently only support length 1 constraints.
3407   if (ConstraintCode.size() == 1) {
3408     switch (ConstraintCode[0]) {
3409     case 'A':
3410       return InlineAsm::Constraint_A;
3411     default:
3412       break;
3413     }
3414   }
3415 
3416   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
3417 }
3418 
3419 void RISCVTargetLowering::LowerAsmOperandForConstraint(
3420     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3421     SelectionDAG &DAG) const {
3422   // Currently only support length 1 constraints.
3423   if (Constraint.length() == 1) {
3424     switch (Constraint[0]) {
3425     case 'I':
3426       // Validate & create a 12-bit signed immediate operand.
3427       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3428         uint64_t CVal = C->getSExtValue();
3429         if (isInt<12>(CVal))
3430           Ops.push_back(
3431               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
3432       }
3433       return;
3434     case 'J':
3435       // Validate & create an integer zero operand.
3436       if (auto *C = dyn_cast<ConstantSDNode>(Op))
3437         if (C->getZExtValue() == 0)
3438           Ops.push_back(
3439               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
3440       return;
3441     case 'K':
3442       // Validate & create a 5-bit unsigned immediate operand.
3443       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3444         uint64_t CVal = C->getZExtValue();
3445         if (isUInt<5>(CVal))
3446           Ops.push_back(
3447               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
3448       }
3449       return;
3450     default:
3451       break;
3452     }
3453   }
3454   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3455 }
3456 
3457 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
3458                                                    Instruction *Inst,
3459                                                    AtomicOrdering Ord) const {
3460   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
3461     return Builder.CreateFence(Ord);
3462   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
3463     return Builder.CreateFence(AtomicOrdering::Release);
3464   return nullptr;
3465 }
3466 
3467 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
3468                                                     Instruction *Inst,
3469                                                     AtomicOrdering Ord) const {
3470   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
3471     return Builder.CreateFence(AtomicOrdering::Acquire);
3472   return nullptr;
3473 }
3474 
3475 TargetLowering::AtomicExpansionKind
3476 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
3477   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
3478   // point operations can't be used in an lr/sc sequence without breaking the
3479   // forward-progress guarantee.
3480   if (AI->isFloatingPointOperation())
3481     return AtomicExpansionKind::CmpXChg;
3482 
3483   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
3484   if (Size == 8 || Size == 16)
3485     return AtomicExpansionKind::MaskedIntrinsic;
3486   return AtomicExpansionKind::None;
3487 }
3488 
3489 static Intrinsic::ID
3490 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
3491   if (XLen == 32) {
3492     switch (BinOp) {
3493     default:
3494       llvm_unreachable("Unexpected AtomicRMW BinOp");
3495     case AtomicRMWInst::Xchg:
3496       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
3497     case AtomicRMWInst::Add:
3498       return Intrinsic::riscv_masked_atomicrmw_add_i32;
3499     case AtomicRMWInst::Sub:
3500       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
3501     case AtomicRMWInst::Nand:
3502       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
3503     case AtomicRMWInst::Max:
3504       return Intrinsic::riscv_masked_atomicrmw_max_i32;
3505     case AtomicRMWInst::Min:
3506       return Intrinsic::riscv_masked_atomicrmw_min_i32;
3507     case AtomicRMWInst::UMax:
3508       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
3509     case AtomicRMWInst::UMin:
3510       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
3511     }
3512   }
3513 
3514   if (XLen == 64) {
3515     switch (BinOp) {
3516     default:
3517       llvm_unreachable("Unexpected AtomicRMW BinOp");
3518     case AtomicRMWInst::Xchg:
3519       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
3520     case AtomicRMWInst::Add:
3521       return Intrinsic::riscv_masked_atomicrmw_add_i64;
3522     case AtomicRMWInst::Sub:
3523       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
3524     case AtomicRMWInst::Nand:
3525       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
3526     case AtomicRMWInst::Max:
3527       return Intrinsic::riscv_masked_atomicrmw_max_i64;
3528     case AtomicRMWInst::Min:
3529       return Intrinsic::riscv_masked_atomicrmw_min_i64;
3530     case AtomicRMWInst::UMax:
3531       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
3532     case AtomicRMWInst::UMin:
3533       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
3534     }
3535   }
3536 
3537   llvm_unreachable("Unexpected XLen\n");
3538 }
3539 
3540 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
3541     IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
3542     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
3543   unsigned XLen = Subtarget.getXLen();
3544   Value *Ordering =
3545       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
3546   Type *Tys[] = {AlignedAddr->getType()};
3547   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
3548       AI->getModule(),
3549       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
3550 
3551   if (XLen == 64) {
3552     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
3553     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
3554     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
3555   }
3556 
3557   Value *Result;
3558 
3559   // Must pass the shift amount needed to sign extend the loaded value prior
3560   // to performing a signed comparison for min/max. ShiftAmt is the number of
3561   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
3562   // is the number of bits to left+right shift the value in order to
3563   // sign-extend.
3564   if (AI->getOperation() == AtomicRMWInst::Min ||
3565       AI->getOperation() == AtomicRMWInst::Max) {
3566     const DataLayout &DL = AI->getModule()->getDataLayout();
3567     unsigned ValWidth =
3568         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
3569     Value *SextShamt =
3570         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
3571     Result = Builder.CreateCall(LrwOpScwLoop,
3572                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
3573   } else {
3574     Result =
3575         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
3576   }
3577 
3578   if (XLen == 64)
3579     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
3580   return Result;
3581 }
3582 
3583 TargetLowering::AtomicExpansionKind
3584 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
3585     AtomicCmpXchgInst *CI) const {
3586   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
3587   if (Size == 8 || Size == 16)
3588     return AtomicExpansionKind::MaskedIntrinsic;
3589   return AtomicExpansionKind::None;
3590 }
3591 
3592 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
3593     IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
3594     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
3595   unsigned XLen = Subtarget.getXLen();
3596   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
3597   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
3598   if (XLen == 64) {
3599     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
3600     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
3601     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
3602     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
3603   }
3604   Type *Tys[] = {AlignedAddr->getType()};
3605   Function *MaskedCmpXchg =
3606       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
3607   Value *Result = Builder.CreateCall(
3608       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
3609   if (XLen == 64)
3610     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
3611   return Result;
3612 }
3613 
3614 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
3615                                                      EVT VT) const {
3616   VT = VT.getScalarType();
3617 
3618   if (!VT.isSimple())
3619     return false;
3620 
3621   switch (VT.getSimpleVT().SimpleTy) {
3622   case MVT::f16:
3623     return Subtarget.hasStdExtZfh();
3624   case MVT::f32:
3625     return Subtarget.hasStdExtF();
3626   case MVT::f64:
3627     return Subtarget.hasStdExtD();
3628   default:
3629     break;
3630   }
3631 
3632   return false;
3633 }
3634 
3635 Register RISCVTargetLowering::getExceptionPointerRegister(
3636     const Constant *PersonalityFn) const {
3637   return RISCV::X10;
3638 }
3639 
3640 Register RISCVTargetLowering::getExceptionSelectorRegister(
3641     const Constant *PersonalityFn) const {
3642   return RISCV::X11;
3643 }
3644 
3645 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
3646   // Return false to suppress the unnecessary extensions if the LibCall
3647   // arguments or return value is f32 type for LP64 ABI.
3648   RISCVABI::ABI ABI = Subtarget.getTargetABI();
3649   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
3650     return false;
3651 
3652   return true;
3653 }
3654 
3655 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
3656                                                  SDValue C) const {
3657   // Check integral scalar types.
3658   if (VT.isScalarInteger()) {
3659     // Do not perform the transformation on riscv32 with the M extension.
3660     if (!Subtarget.is64Bit() && Subtarget.hasStdExtM())
3661       return false;
3662     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
3663       if (ConstNode->getAPIntValue().getBitWidth() > 8 * sizeof(int64_t))
3664         return false;
3665       int64_t Imm = ConstNode->getSExtValue();
3666       if (isPowerOf2_64(Imm + 1) || isPowerOf2_64(Imm - 1) ||
3667           isPowerOf2_64(1 - Imm) || isPowerOf2_64(-1 - Imm))
3668         return true;
3669     }
3670   }
3671 
3672   return false;
3673 }
3674 
3675 #define GET_REGISTER_MATCHER
3676 #include "RISCVGenAsmMatcher.inc"
3677 
3678 Register
3679 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
3680                                        const MachineFunction &MF) const {
3681   Register Reg = MatchRegisterAltName(RegName);
3682   if (Reg == RISCV::NoRegister)
3683     Reg = MatchRegisterName(RegName);
3684   if (Reg == RISCV::NoRegister)
3685     report_fatal_error(
3686         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
3687   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
3688   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
3689     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
3690                              StringRef(RegName) + "\"."));
3691   return Reg;
3692 }
3693