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 "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAGISel.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/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "riscv-lower"
39 
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 
42 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
43                                          const RISCVSubtarget &STI)
44     : TargetLowering(TM), Subtarget(STI) {
45 
46   if (Subtarget.isRV32E())
47     report_fatal_error("Codegen not yet implemented for RV32E");
48 
49   RISCVABI::ABI ABI = Subtarget.getTargetABI();
50   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
51 
52   switch (ABI) {
53   default:
54     report_fatal_error("Don't know how to lower this ABI");
55   case RISCVABI::ABI_ILP32:
56   case RISCVABI::ABI_ILP32F:
57   case RISCVABI::ABI_ILP32D:
58   case RISCVABI::ABI_LP64:
59   case RISCVABI::ABI_LP64F:
60   case RISCVABI::ABI_LP64D:
61     break;
62   }
63 
64   MVT XLenVT = Subtarget.getXLenVT();
65 
66   // Set up the register classes.
67   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
68 
69   if (Subtarget.hasStdExtF())
70     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
71   if (Subtarget.hasStdExtD())
72     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
73 
74   // Compute derived properties from the register classes.
75   computeRegisterProperties(STI.getRegisterInfo());
76 
77   setStackPointerRegisterToSaveRestore(RISCV::X2);
78 
79   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
80     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
81 
82   // TODO: add all necessary setOperationAction calls.
83   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
84 
85   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
86   setOperationAction(ISD::BR_CC, XLenVT, Expand);
87   setOperationAction(ISD::SELECT, XLenVT, Custom);
88   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
89 
90   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
91   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
92 
93   setOperationAction(ISD::VASTART, MVT::Other, Custom);
94   setOperationAction(ISD::VAARG, MVT::Other, Expand);
95   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
96   setOperationAction(ISD::VAEND, MVT::Other, Expand);
97 
98   for (auto VT : {MVT::i1, MVT::i8, MVT::i16})
99     setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
100 
101   if (Subtarget.is64Bit()) {
102     setOperationAction(ISD::SHL, MVT::i32, Custom);
103     setOperationAction(ISD::SRA, MVT::i32, Custom);
104     setOperationAction(ISD::SRL, MVT::i32, Custom);
105   }
106 
107   if (!Subtarget.hasStdExtM()) {
108     setOperationAction(ISD::MUL, XLenVT, Expand);
109     setOperationAction(ISD::MULHS, XLenVT, Expand);
110     setOperationAction(ISD::MULHU, XLenVT, Expand);
111     setOperationAction(ISD::SDIV, XLenVT, Expand);
112     setOperationAction(ISD::UDIV, XLenVT, Expand);
113     setOperationAction(ISD::SREM, XLenVT, Expand);
114     setOperationAction(ISD::UREM, XLenVT, Expand);
115   }
116 
117   if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) {
118     setOperationAction(ISD::SDIV, MVT::i32, Custom);
119     setOperationAction(ISD::UDIV, MVT::i32, Custom);
120     setOperationAction(ISD::UREM, MVT::i32, Custom);
121   }
122 
123   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
124   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
125   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
126   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
127 
128   setOperationAction(ISD::SHL_PARTS, XLenVT, Expand);
129   setOperationAction(ISD::SRL_PARTS, XLenVT, Expand);
130   setOperationAction(ISD::SRA_PARTS, XLenVT, Expand);
131 
132   setOperationAction(ISD::ROTL, XLenVT, Expand);
133   setOperationAction(ISD::ROTR, XLenVT, Expand);
134   setOperationAction(ISD::BSWAP, XLenVT, Expand);
135   setOperationAction(ISD::CTTZ, XLenVT, Expand);
136   setOperationAction(ISD::CTLZ, XLenVT, Expand);
137   setOperationAction(ISD::CTPOP, XLenVT, Expand);
138 
139   ISD::CondCode FPCCToExtend[] = {
140       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
141       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
142       ISD::SETGE,  ISD::SETNE};
143 
144   ISD::NodeType FPOpToExtend[] = {
145       ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM};
146 
147   if (Subtarget.hasStdExtF()) {
148     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
149     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
150     for (auto CC : FPCCToExtend)
151       setCondCodeAction(CC, MVT::f32, Expand);
152     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
153     setOperationAction(ISD::SELECT, MVT::f32, Custom);
154     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
155     for (auto Op : FPOpToExtend)
156       setOperationAction(Op, MVT::f32, Expand);
157   }
158 
159   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
160     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
161 
162   if (Subtarget.hasStdExtD()) {
163     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
164     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
165     for (auto CC : FPCCToExtend)
166       setCondCodeAction(CC, MVT::f64, Expand);
167     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
168     setOperationAction(ISD::SELECT, MVT::f64, Custom);
169     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
170     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
171     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
172     for (auto Op : FPOpToExtend)
173       setOperationAction(Op, MVT::f64, Expand);
174   }
175 
176   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
177   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
178   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
179 
180   if (Subtarget.hasStdExtA()) {
181     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
182     setMinCmpXchgSizeInBits(32);
183   } else {
184     setMaxAtomicSizeInBitsSupported(0);
185   }
186 
187   setBooleanContents(ZeroOrOneBooleanContent);
188 
189   // Function alignments (log2).
190   unsigned FunctionAlignment = Subtarget.hasStdExtC() ? 1 : 2;
191   setMinFunctionAlignment(FunctionAlignment);
192   setPrefFunctionAlignment(FunctionAlignment);
193 
194   // Effectively disable jump table generation.
195   setMinimumJumpTableEntries(INT_MAX);
196 }
197 
198 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
199                                             EVT VT) const {
200   if (!VT.isVector())
201     return getPointerTy(DL);
202   return VT.changeVectorElementTypeToInteger();
203 }
204 
205 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
206                                              const CallInst &I,
207                                              MachineFunction &MF,
208                                              unsigned Intrinsic) const {
209   switch (Intrinsic) {
210   default:
211     return false;
212   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
213   case Intrinsic::riscv_masked_atomicrmw_add_i32:
214   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
215   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
216   case Intrinsic::riscv_masked_atomicrmw_max_i32:
217   case Intrinsic::riscv_masked_atomicrmw_min_i32:
218   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
219   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
220   case Intrinsic::riscv_masked_cmpxchg_i32:
221     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
222     Info.opc = ISD::INTRINSIC_W_CHAIN;
223     Info.memVT = MVT::getVT(PtrTy->getElementType());
224     Info.ptrVal = I.getArgOperand(0);
225     Info.offset = 0;
226     Info.align = 4;
227     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
228                  MachineMemOperand::MOVolatile;
229     return true;
230   }
231 }
232 
233 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
234                                                 const AddrMode &AM, Type *Ty,
235                                                 unsigned AS,
236                                                 Instruction *I) const {
237   // No global is ever allowed as a base.
238   if (AM.BaseGV)
239     return false;
240 
241   // Require a 12-bit signed offset.
242   if (!isInt<12>(AM.BaseOffs))
243     return false;
244 
245   switch (AM.Scale) {
246   case 0: // "r+i" or just "i", depending on HasBaseReg.
247     break;
248   case 1:
249     if (!AM.HasBaseReg) // allow "r+i".
250       break;
251     return false; // disallow "r+r" or "r+r+i".
252   default:
253     return false;
254   }
255 
256   return true;
257 }
258 
259 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
260   return isInt<12>(Imm);
261 }
262 
263 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
264   return isInt<12>(Imm);
265 }
266 
267 // On RV32, 64-bit integers are split into their high and low parts and held
268 // in two different registers, so the trunc is free since the low register can
269 // just be used.
270 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
271   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
272     return false;
273   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
274   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
275   return (SrcBits == 64 && DestBits == 32);
276 }
277 
278 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
279   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
280       !SrcVT.isInteger() || !DstVT.isInteger())
281     return false;
282   unsigned SrcBits = SrcVT.getSizeInBits();
283   unsigned DestBits = DstVT.getSizeInBits();
284   return (SrcBits == 64 && DestBits == 32);
285 }
286 
287 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
288   // Zexts are free if they can be combined with a load.
289   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
290     EVT MemVT = LD->getMemoryVT();
291     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
292          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
293         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
294          LD->getExtensionType() == ISD::ZEXTLOAD))
295       return true;
296   }
297 
298   return TargetLowering::isZExtFree(Val, VT2);
299 }
300 
301 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
302   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
303 }
304 
305 // Changes the condition code and swaps operands if necessary, so the SetCC
306 // operation matches one of the comparisons supported directly in the RISC-V
307 // ISA.
308 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
309   switch (CC) {
310   default:
311     break;
312   case ISD::SETGT:
313   case ISD::SETLE:
314   case ISD::SETUGT:
315   case ISD::SETULE:
316     CC = ISD::getSetCCSwappedOperands(CC);
317     std::swap(LHS, RHS);
318     break;
319   }
320 }
321 
322 // Return the RISC-V branch opcode that matches the given DAG integer
323 // condition code. The CondCode must be one of those supported by the RISC-V
324 // ISA (see normaliseSetCC).
325 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
326   switch (CC) {
327   default:
328     llvm_unreachable("Unsupported CondCode");
329   case ISD::SETEQ:
330     return RISCV::BEQ;
331   case ISD::SETNE:
332     return RISCV::BNE;
333   case ISD::SETLT:
334     return RISCV::BLT;
335   case ISD::SETGE:
336     return RISCV::BGE;
337   case ISD::SETULT:
338     return RISCV::BLTU;
339   case ISD::SETUGE:
340     return RISCV::BGEU;
341   }
342 }
343 
344 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
345                                             SelectionDAG &DAG) const {
346   switch (Op.getOpcode()) {
347   default:
348     report_fatal_error("unimplemented operand");
349   case ISD::GlobalAddress:
350     return lowerGlobalAddress(Op, DAG);
351   case ISD::BlockAddress:
352     return lowerBlockAddress(Op, DAG);
353   case ISD::ConstantPool:
354     return lowerConstantPool(Op, DAG);
355   case ISD::SELECT:
356     return lowerSELECT(Op, DAG);
357   case ISD::VASTART:
358     return lowerVASTART(Op, DAG);
359   case ISD::FRAMEADDR:
360     return lowerFRAMEADDR(Op, DAG);
361   case ISD::RETURNADDR:
362     return lowerRETURNADDR(Op, DAG);
363   case ISD::BITCAST: {
364     assert(Subtarget.is64Bit() && Subtarget.hasStdExtF() &&
365            "Unexpected custom legalisation");
366     SDLoc DL(Op);
367     SDValue Op0 = Op.getOperand(0);
368     if (Op.getValueType() != MVT::f32 || Op0.getValueType() != MVT::i32)
369       return SDValue();
370     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
371     SDValue FPConv = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
372     return FPConv;
373   }
374   }
375 }
376 
377 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
378                              SelectionDAG &DAG, unsigned Flags) {
379   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
380 }
381 
382 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
383                              SelectionDAG &DAG, unsigned Flags) {
384   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
385                                    Flags);
386 }
387 
388 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
389                              SelectionDAG &DAG, unsigned Flags) {
390   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
391                                    N->getOffset(), Flags);
392 }
393 
394 template <class NodeTy>
395 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const {
396   SDLoc DL(N);
397   EVT Ty = getPointerTy(DAG.getDataLayout());
398 
399   switch (getTargetMachine().getCodeModel()) {
400   default:
401     report_fatal_error("Unsupported code model for lowering");
402   case CodeModel::Small: {
403     // Generate a sequence for accessing addresses within the first 2 GiB of
404     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
405     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
406     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
407     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
408     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
409   }
410   case CodeModel::Medium: {
411     // Generate a sequence for accessing addresses within any 2GiB range within
412     // the address space. This generates the pattern (PseudoLLA sym), which
413     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
414     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
415     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
416   }
417   }
418 }
419 
420 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
421                                                 SelectionDAG &DAG) const {
422   SDLoc DL(Op);
423   EVT Ty = Op.getValueType();
424   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
425   int64_t Offset = N->getOffset();
426   MVT XLenVT = Subtarget.getXLenVT();
427 
428   if (isPositionIndependent())
429     report_fatal_error("Unable to lowerGlobalAddress");
430 
431   SDValue Addr = getAddr(N, DAG);
432 
433   // In order to maximise the opportunity for common subexpression elimination,
434   // emit a separate ADD node for the global address offset instead of folding
435   // it in the global address node. Later peephole optimisations may choose to
436   // fold it back in when profitable.
437   if (Offset != 0)
438     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
439                        DAG.getConstant(Offset, DL, XLenVT));
440   return Addr;
441 }
442 
443 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
444                                                SelectionDAG &DAG) const {
445   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
446 
447   if (isPositionIndependent())
448     report_fatal_error("Unable to lowerBlockAddress");
449 
450   return getAddr(N, DAG);
451 }
452 
453 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
454                                                SelectionDAG &DAG) const {
455   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
456 
457   if (isPositionIndependent())
458     report_fatal_error("Unable to lowerConstantPool");
459 
460   return getAddr(N, DAG);
461 }
462 
463 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
464   SDValue CondV = Op.getOperand(0);
465   SDValue TrueV = Op.getOperand(1);
466   SDValue FalseV = Op.getOperand(2);
467   SDLoc DL(Op);
468   MVT XLenVT = Subtarget.getXLenVT();
469 
470   // If the result type is XLenVT and CondV is the output of a SETCC node
471   // which also operated on XLenVT inputs, then merge the SETCC node into the
472   // lowered RISCVISD::SELECT_CC to take advantage of the integer
473   // compare+branch instructions. i.e.:
474   // (select (setcc lhs, rhs, cc), truev, falsev)
475   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
476   if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
477       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
478     SDValue LHS = CondV.getOperand(0);
479     SDValue RHS = CondV.getOperand(1);
480     auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
481     ISD::CondCode CCVal = CC->get();
482 
483     normaliseSetCC(LHS, RHS, CCVal);
484 
485     SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
486     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
487     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
488     return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
489   }
490 
491   // Otherwise:
492   // (select condv, truev, falsev)
493   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
494   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
495   SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
496 
497   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
498   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
499 
500   return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
501 }
502 
503 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
504   MachineFunction &MF = DAG.getMachineFunction();
505   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
506 
507   SDLoc DL(Op);
508   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
509                                  getPointerTy(MF.getDataLayout()));
510 
511   // vastart just stores the address of the VarArgsFrameIndex slot into the
512   // memory location argument.
513   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
514   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
515                       MachinePointerInfo(SV));
516 }
517 
518 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
519                                             SelectionDAG &DAG) const {
520   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
521   MachineFunction &MF = DAG.getMachineFunction();
522   MachineFrameInfo &MFI = MF.getFrameInfo();
523   MFI.setFrameAddressIsTaken(true);
524   unsigned FrameReg = RI.getFrameRegister(MF);
525   int XLenInBytes = Subtarget.getXLen() / 8;
526 
527   EVT VT = Op.getValueType();
528   SDLoc DL(Op);
529   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
530   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
531   while (Depth--) {
532     int Offset = -(XLenInBytes * 2);
533     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
534                               DAG.getIntPtrConstant(Offset, DL));
535     FrameAddr =
536         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
537   }
538   return FrameAddr;
539 }
540 
541 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
542                                              SelectionDAG &DAG) const {
543   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
544   MachineFunction &MF = DAG.getMachineFunction();
545   MachineFrameInfo &MFI = MF.getFrameInfo();
546   MFI.setReturnAddressIsTaken(true);
547   MVT XLenVT = Subtarget.getXLenVT();
548   int XLenInBytes = Subtarget.getXLen() / 8;
549 
550   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
551     return SDValue();
552 
553   EVT VT = Op.getValueType();
554   SDLoc DL(Op);
555   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
556   if (Depth) {
557     int Off = -XLenInBytes;
558     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
559     SDValue Offset = DAG.getConstant(Off, DL, VT);
560     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
561                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
562                        MachinePointerInfo());
563   }
564 
565   // Return the value of the return address register, marking it an implicit
566   // live-in.
567   unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
568   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
569 }
570 
571 // Returns the opcode of the target-specific SDNode that implements the 32-bit
572 // form of the given Opcode.
573 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
574   switch (Opcode) {
575   default:
576     llvm_unreachable("Unexpected opcode");
577   case ISD::SHL:
578     return RISCVISD::SLLW;
579   case ISD::SRA:
580     return RISCVISD::SRAW;
581   case ISD::SRL:
582     return RISCVISD::SRLW;
583   case ISD::SDIV:
584     return RISCVISD::DIVW;
585   case ISD::UDIV:
586     return RISCVISD::DIVUW;
587   case ISD::UREM:
588     return RISCVISD::REMUW;
589   }
590 }
591 
592 // Converts the given 32-bit operation to a target-specific SelectionDAG node.
593 // Because i32 isn't a legal type for RV64, these operations would otherwise
594 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
595 // later one because the fact the operation was originally of type i32 is
596 // lost.
597 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) {
598   SDLoc DL(N);
599   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
600   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
601   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
602   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
603   // ReplaceNodeResults requires we maintain the same type for the return value.
604   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
605 }
606 
607 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
608                                              SmallVectorImpl<SDValue> &Results,
609                                              SelectionDAG &DAG) const {
610   SDLoc DL(N);
611   switch (N->getOpcode()) {
612   default:
613     llvm_unreachable("Don't know how to custom type legalize this operation!");
614   case ISD::SHL:
615   case ISD::SRA:
616   case ISD::SRL:
617     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
618            "Unexpected custom legalisation");
619     if (N->getOperand(1).getOpcode() == ISD::Constant)
620       return;
621     Results.push_back(customLegalizeToWOp(N, DAG));
622     break;
623   case ISD::SDIV:
624   case ISD::UDIV:
625   case ISD::UREM:
626     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
627            Subtarget.hasStdExtM() && "Unexpected custom legalisation");
628     if (N->getOperand(0).getOpcode() == ISD::Constant ||
629         N->getOperand(1).getOpcode() == ISD::Constant)
630       return;
631     Results.push_back(customLegalizeToWOp(N, DAG));
632     break;
633   case ISD::BITCAST: {
634     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
635            Subtarget.hasStdExtF() && "Unexpected custom legalisation");
636     SDLoc DL(N);
637     SDValue Op0 = N->getOperand(0);
638     if (Op0.getValueType() != MVT::f32)
639       return;
640     SDValue FPConv =
641         DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
642     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
643     break;
644   }
645   }
646 }
647 
648 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
649                                                DAGCombinerInfo &DCI) const {
650   SelectionDAG &DAG = DCI.DAG;
651 
652   switch (N->getOpcode()) {
653   default:
654     break;
655   case RISCVISD::SplitF64: {
656     SDValue Op0 = N->getOperand(0);
657     // If the input to SplitF64 is just BuildPairF64 then the operation is
658     // redundant. Instead, use BuildPairF64's operands directly.
659     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
660       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
661 
662     SDLoc DL(N);
663 
664     // It's cheaper to materialise two 32-bit integers than to load a double
665     // from the constant pool and transfer it to integer registers through the
666     // stack.
667     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
668       APInt V = C->getValueAPF().bitcastToAPInt();
669       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
670       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
671       return DCI.CombineTo(N, Lo, Hi);
672     }
673 
674     // This is a target-specific version of a DAGCombine performed in
675     // DAGCombiner::visitBITCAST. It performs the equivalent of:
676     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
677     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
678     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
679         !Op0.getNode()->hasOneUse())
680       break;
681     SDValue NewSplitF64 =
682         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
683                     Op0.getOperand(0));
684     SDValue Lo = NewSplitF64.getValue(0);
685     SDValue Hi = NewSplitF64.getValue(1);
686     APInt SignBit = APInt::getSignMask(32);
687     if (Op0.getOpcode() == ISD::FNEG) {
688       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
689                                   DAG.getConstant(SignBit, DL, MVT::i32));
690       return DCI.CombineTo(N, Lo, NewHi);
691     }
692     assert(Op0.getOpcode() == ISD::FABS);
693     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
694                                 DAG.getConstant(~SignBit, DL, MVT::i32));
695     return DCI.CombineTo(N, Lo, NewHi);
696   }
697   case RISCVISD::SLLW:
698   case RISCVISD::SRAW:
699   case RISCVISD::SRLW: {
700     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
701     SDValue LHS = N->getOperand(0);
702     SDValue RHS = N->getOperand(1);
703     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
704     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
705     if ((SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI)) ||
706         (SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)))
707       return SDValue();
708     break;
709   }
710   case RISCVISD::FMV_X_ANYEXTW_RV64: {
711     SDLoc DL(N);
712     SDValue Op0 = N->getOperand(0);
713     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
714     // conversion is unnecessary and can be replaced with an ANY_EXTEND
715     // of the FMV_W_X_RV64 operand.
716     if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
717       SDValue AExtOp =
718           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0.getOperand(0));
719       return DCI.CombineTo(N, AExtOp);
720     }
721 
722     // This is a target-specific version of a DAGCombine performed in
723     // DAGCombiner::visitBITCAST. It performs the equivalent of:
724     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
725     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
726     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
727         !Op0.getNode()->hasOneUse())
728       break;
729     SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64,
730                                  Op0.getOperand(0));
731     APInt SignBit = APInt::getSignMask(32).sext(64);
732     if (Op0.getOpcode() == ISD::FNEG) {
733       return DCI.CombineTo(N,
734                            DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
735                                        DAG.getConstant(SignBit, DL, MVT::i64)));
736     }
737     assert(Op0.getOpcode() == ISD::FABS);
738     return DCI.CombineTo(N,
739                          DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
740                                      DAG.getConstant(~SignBit, DL, MVT::i64)));
741   }
742   }
743 
744   return SDValue();
745 }
746 
747 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
748     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
749     unsigned Depth) const {
750   switch (Op.getOpcode()) {
751   default:
752     break;
753   case RISCVISD::SLLW:
754   case RISCVISD::SRAW:
755   case RISCVISD::SRLW:
756   case RISCVISD::DIVW:
757   case RISCVISD::DIVUW:
758   case RISCVISD::REMUW:
759     // TODO: As the result is sign-extended, this is conservatively correct. A
760     // more precise answer could be calculated for SRAW depending on known
761     // bits in the shift amount.
762     return 33;
763   }
764 
765   return 1;
766 }
767 
768 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
769                                              MachineBasicBlock *BB) {
770   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
771 
772   MachineFunction &MF = *BB->getParent();
773   DebugLoc DL = MI.getDebugLoc();
774   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
775   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
776   unsigned LoReg = MI.getOperand(0).getReg();
777   unsigned HiReg = MI.getOperand(1).getReg();
778   unsigned SrcReg = MI.getOperand(2).getReg();
779   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
780   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
781 
782   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
783                           RI);
784   MachineMemOperand *MMO =
785       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
786                               MachineMemOperand::MOLoad, 8, 8);
787   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
788       .addFrameIndex(FI)
789       .addImm(0)
790       .addMemOperand(MMO);
791   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
792       .addFrameIndex(FI)
793       .addImm(4)
794       .addMemOperand(MMO);
795   MI.eraseFromParent(); // The pseudo instruction is gone now.
796   return BB;
797 }
798 
799 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
800                                                  MachineBasicBlock *BB) {
801   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
802          "Unexpected instruction");
803 
804   MachineFunction &MF = *BB->getParent();
805   DebugLoc DL = MI.getDebugLoc();
806   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
807   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
808   unsigned DstReg = MI.getOperand(0).getReg();
809   unsigned LoReg = MI.getOperand(1).getReg();
810   unsigned HiReg = MI.getOperand(2).getReg();
811   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
812   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
813 
814   MachineMemOperand *MMO =
815       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
816                               MachineMemOperand::MOStore, 8, 8);
817   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
818       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
819       .addFrameIndex(FI)
820       .addImm(0)
821       .addMemOperand(MMO);
822   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
823       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
824       .addFrameIndex(FI)
825       .addImm(4)
826       .addMemOperand(MMO);
827   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
828   MI.eraseFromParent(); // The pseudo instruction is gone now.
829   return BB;
830 }
831 
832 static bool isSelectPseudo(MachineInstr &MI) {
833   switch (MI.getOpcode()) {
834   default:
835     return false;
836   case RISCV::Select_GPR_Using_CC_GPR:
837   case RISCV::Select_FPR32_Using_CC_GPR:
838   case RISCV::Select_FPR64_Using_CC_GPR:
839     return true;
840   }
841 }
842 
843 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
844                                            MachineBasicBlock *BB) {
845   // To "insert" Select_* instructions, we actually have to insert the triangle
846   // control-flow pattern.  The incoming instructions know the destination vreg
847   // to set, the condition code register to branch on, the true/false values to
848   // select between, and the condcode to use to select the appropriate branch.
849   //
850   // We produce the following control flow:
851   //     HeadMBB
852   //     |  \
853   //     |  IfFalseMBB
854   //     | /
855   //    TailMBB
856   //
857   // When we find a sequence of selects we attempt to optimize their emission
858   // by sharing the control flow. Currently we only handle cases where we have
859   // multiple selects with the exact same condition (same LHS, RHS and CC).
860   // The selects may be interleaved with other instructions if the other
861   // instructions meet some requirements we deem safe:
862   // - They are debug instructions. Otherwise,
863   // - They do not have side-effects, do not access memory and their inputs do
864   //   not depend on the results of the select pseudo-instructions.
865   // The TrueV/FalseV operands of the selects cannot depend on the result of
866   // previous selects in the sequence.
867   // These conditions could be further relaxed. See the X86 target for a
868   // related approach and more information.
869   unsigned LHS = MI.getOperand(1).getReg();
870   unsigned RHS = MI.getOperand(2).getReg();
871   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
872 
873   SmallVector<MachineInstr *, 4> SelectDebugValues;
874   SmallSet<unsigned, 4> SelectDests;
875   SelectDests.insert(MI.getOperand(0).getReg());
876 
877   MachineInstr *LastSelectPseudo = &MI;
878 
879   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
880        SequenceMBBI != E; ++SequenceMBBI) {
881     if (SequenceMBBI->isDebugInstr())
882       continue;
883     else if (isSelectPseudo(*SequenceMBBI)) {
884       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
885           SequenceMBBI->getOperand(2).getReg() != RHS ||
886           SequenceMBBI->getOperand(3).getImm() != CC ||
887           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
888           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
889         break;
890       LastSelectPseudo = &*SequenceMBBI;
891       SequenceMBBI->collectDebugValues(SelectDebugValues);
892       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
893     } else {
894       if (SequenceMBBI->hasUnmodeledSideEffects() ||
895           SequenceMBBI->mayLoadOrStore())
896         break;
897       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
898             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
899           }))
900         break;
901     }
902   }
903 
904   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
905   const BasicBlock *LLVM_BB = BB->getBasicBlock();
906   DebugLoc DL = MI.getDebugLoc();
907   MachineFunction::iterator I = ++BB->getIterator();
908 
909   MachineBasicBlock *HeadMBB = BB;
910   MachineFunction *F = BB->getParent();
911   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
912   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
913 
914   F->insert(I, IfFalseMBB);
915   F->insert(I, TailMBB);
916 
917   // Transfer debug instructions associated with the selects to TailMBB.
918   for (MachineInstr *DebugInstr : SelectDebugValues) {
919     TailMBB->push_back(DebugInstr->removeFromParent());
920   }
921 
922   // Move all instructions after the sequence to TailMBB.
923   TailMBB->splice(TailMBB->end(), HeadMBB,
924                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
925   // Update machine-CFG edges by transferring all successors of the current
926   // block to the new block which will contain the Phi nodes for the selects.
927   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
928   // Set the successors for HeadMBB.
929   HeadMBB->addSuccessor(IfFalseMBB);
930   HeadMBB->addSuccessor(TailMBB);
931 
932   // Insert appropriate branch.
933   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
934 
935   BuildMI(HeadMBB, DL, TII.get(Opcode))
936     .addReg(LHS)
937     .addReg(RHS)
938     .addMBB(TailMBB);
939 
940   // IfFalseMBB just falls through to TailMBB.
941   IfFalseMBB->addSuccessor(TailMBB);
942 
943   // Create PHIs for all of the select pseudo-instructions.
944   auto SelectMBBI = MI.getIterator();
945   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
946   auto InsertionPoint = TailMBB->begin();
947   while (SelectMBBI != SelectEnd) {
948     auto Next = std::next(SelectMBBI);
949     if (isSelectPseudo(*SelectMBBI)) {
950       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
951       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
952               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
953           .addReg(SelectMBBI->getOperand(4).getReg())
954           .addMBB(HeadMBB)
955           .addReg(SelectMBBI->getOperand(5).getReg())
956           .addMBB(IfFalseMBB);
957       SelectMBBI->eraseFromParent();
958     }
959     SelectMBBI = Next;
960   }
961 
962   return TailMBB;
963 }
964 
965 MachineBasicBlock *
966 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
967                                                  MachineBasicBlock *BB) const {
968   switch (MI.getOpcode()) {
969   default:
970     llvm_unreachable("Unexpected instr type to insert");
971   case RISCV::Select_GPR_Using_CC_GPR:
972   case RISCV::Select_FPR32_Using_CC_GPR:
973   case RISCV::Select_FPR64_Using_CC_GPR:
974     return emitSelectPseudo(MI, BB);
975   case RISCV::BuildPairF64Pseudo:
976     return emitBuildPairF64Pseudo(MI, BB);
977   case RISCV::SplitF64Pseudo:
978     return emitSplitF64Pseudo(MI, BB);
979   }
980 }
981 
982 // Calling Convention Implementation.
983 // The expectations for frontend ABI lowering vary from target to target.
984 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
985 // details, but this is a longer term goal. For now, we simply try to keep the
986 // role of the frontend as simple and well-defined as possible. The rules can
987 // be summarised as:
988 // * Never split up large scalar arguments. We handle them here.
989 // * If a hardfloat calling convention is being used, and the struct may be
990 // passed in a pair of registers (fp+fp, int+fp), and both registers are
991 // available, then pass as two separate arguments. If either the GPRs or FPRs
992 // are exhausted, then pass according to the rule below.
993 // * If a struct could never be passed in registers or directly in a stack
994 // slot (as it is larger than 2*XLEN and the floating point rules don't
995 // apply), then pass it using a pointer with the byval attribute.
996 // * If a struct is less than 2*XLEN, then coerce to either a two-element
997 // word-sized array or a 2*XLEN scalar (depending on alignment).
998 // * The frontend can determine whether a struct is returned by reference or
999 // not based on its size and fields. If it will be returned by reference, the
1000 // frontend must modify the prototype so a pointer with the sret annotation is
1001 // passed as the first argument. This is not necessary for large scalar
1002 // returns.
1003 // * Struct return values and varargs should be coerced to structs containing
1004 // register-size fields in the same situations they would be for fixed
1005 // arguments.
1006 
1007 static const MCPhysReg ArgGPRs[] = {
1008   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
1009   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
1010 };
1011 static const MCPhysReg ArgFPR32s[] = {
1012   RISCV::F10_32, RISCV::F11_32, RISCV::F12_32, RISCV::F13_32,
1013   RISCV::F14_32, RISCV::F15_32, RISCV::F16_32, RISCV::F17_32
1014 };
1015 static const MCPhysReg ArgFPR64s[] = {
1016   RISCV::F10_64, RISCV::F11_64, RISCV::F12_64, RISCV::F13_64,
1017   RISCV::F14_64, RISCV::F15_64, RISCV::F16_64, RISCV::F17_64
1018 };
1019 
1020 // Pass a 2*XLEN argument that has been split into two XLEN values through
1021 // registers or the stack as necessary.
1022 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
1023                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
1024                                 MVT ValVT2, MVT LocVT2,
1025                                 ISD::ArgFlagsTy ArgFlags2) {
1026   unsigned XLenInBytes = XLen / 8;
1027   if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
1028     // At least one half can be passed via register.
1029     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
1030                                      VA1.getLocVT(), CCValAssign::Full));
1031   } else {
1032     // Both halves must be passed on the stack, with proper alignment.
1033     unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
1034     State.addLoc(
1035         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
1036                             State.AllocateStack(XLenInBytes, StackAlign),
1037                             VA1.getLocVT(), CCValAssign::Full));
1038     State.addLoc(CCValAssign::getMem(
1039         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
1040         CCValAssign::Full));
1041     return false;
1042   }
1043 
1044   if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
1045     // The second half can also be passed via register.
1046     State.addLoc(
1047         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
1048   } else {
1049     // The second half is passed via the stack, without additional alignment.
1050     State.addLoc(CCValAssign::getMem(
1051         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
1052         CCValAssign::Full));
1053   }
1054 
1055   return false;
1056 }
1057 
1058 // Implements the RISC-V calling convention. Returns true upon failure.
1059 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
1060                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
1061                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
1062                      bool IsRet, Type *OrigTy) {
1063   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
1064   assert(XLen == 32 || XLen == 64);
1065   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
1066 
1067   // Any return value split in to more than two values can't be returned
1068   // directly.
1069   if (IsRet && ValNo > 1)
1070     return true;
1071 
1072   // UseGPRForF32 if targeting one of the soft-float ABIs, if passing a
1073   // variadic argument, or if no F32 argument registers are available.
1074   bool UseGPRForF32 = true;
1075   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
1076   // variadic argument, or if no F64 argument registers are available.
1077   bool UseGPRForF64 = true;
1078 
1079   switch (ABI) {
1080   default:
1081     llvm_unreachable("Unexpected ABI");
1082   case RISCVABI::ABI_ILP32:
1083   case RISCVABI::ABI_LP64:
1084     break;
1085   case RISCVABI::ABI_ILP32F:
1086   case RISCVABI::ABI_LP64F:
1087     UseGPRForF32 = !IsFixed;
1088     break;
1089   case RISCVABI::ABI_ILP32D:
1090   case RISCVABI::ABI_LP64D:
1091     UseGPRForF32 = !IsFixed;
1092     UseGPRForF64 = !IsFixed;
1093     break;
1094   }
1095 
1096   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s))
1097     UseGPRForF32 = true;
1098   if (State.getFirstUnallocated(ArgFPR64s) == array_lengthof(ArgFPR64s))
1099     UseGPRForF64 = true;
1100 
1101   // From this point on, rely on UseGPRForF32, UseGPRForF64 and similar local
1102   // variables rather than directly checking against the target ABI.
1103 
1104   if (UseGPRForF32 && ValVT == MVT::f32) {
1105     LocVT = XLenVT;
1106     LocInfo = CCValAssign::BCvt;
1107   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
1108     LocVT = MVT::i64;
1109     LocInfo = CCValAssign::BCvt;
1110   }
1111 
1112   // If this is a variadic argument, the RISC-V calling convention requires
1113   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
1114   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
1115   // be used regardless of whether the original argument was split during
1116   // legalisation or not. The argument will not be passed by registers if the
1117   // original type is larger than 2*XLEN, so the register alignment rule does
1118   // not apply.
1119   unsigned TwoXLenInBytes = (2 * XLen) / 8;
1120   if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
1121       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
1122     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
1123     // Skip 'odd' register if necessary.
1124     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
1125       State.AllocateReg(ArgGPRs);
1126   }
1127 
1128   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
1129   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
1130       State.getPendingArgFlags();
1131 
1132   assert(PendingLocs.size() == PendingArgFlags.size() &&
1133          "PendingLocs and PendingArgFlags out of sync");
1134 
1135   // Handle passing f64 on RV32D with a soft float ABI or when floating point
1136   // registers are exhausted.
1137   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
1138     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
1139            "Can't lower f64 if it is split");
1140     // Depending on available argument GPRS, f64 may be passed in a pair of
1141     // GPRs, split between a GPR and the stack, or passed completely on the
1142     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
1143     // cases.
1144     unsigned Reg = State.AllocateReg(ArgGPRs);
1145     LocVT = MVT::i32;
1146     if (!Reg) {
1147       unsigned StackOffset = State.AllocateStack(8, 8);
1148       State.addLoc(
1149           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
1150       return false;
1151     }
1152     if (!State.AllocateReg(ArgGPRs))
1153       State.AllocateStack(4, 4);
1154     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1155     return false;
1156   }
1157 
1158   // Split arguments might be passed indirectly, so keep track of the pending
1159   // values.
1160   if (ArgFlags.isSplit() || !PendingLocs.empty()) {
1161     LocVT = XLenVT;
1162     LocInfo = CCValAssign::Indirect;
1163     PendingLocs.push_back(
1164         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
1165     PendingArgFlags.push_back(ArgFlags);
1166     if (!ArgFlags.isSplitEnd()) {
1167       return false;
1168     }
1169   }
1170 
1171   // If the split argument only had two elements, it should be passed directly
1172   // in registers or on the stack.
1173   if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
1174     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
1175     // Apply the normal calling convention rules to the first half of the
1176     // split argument.
1177     CCValAssign VA = PendingLocs[0];
1178     ISD::ArgFlagsTy AF = PendingArgFlags[0];
1179     PendingLocs.clear();
1180     PendingArgFlags.clear();
1181     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
1182                                ArgFlags);
1183   }
1184 
1185   // Allocate to a register if possible, or else a stack slot.
1186   unsigned Reg;
1187   if (ValVT == MVT::f32 && !UseGPRForF32)
1188     Reg = State.AllocateReg(ArgFPR32s, ArgFPR64s);
1189   else if (ValVT == MVT::f64 && !UseGPRForF64)
1190     Reg = State.AllocateReg(ArgFPR64s, ArgFPR32s);
1191   else
1192     Reg = State.AllocateReg(ArgGPRs);
1193   unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
1194 
1195   // If we reach this point and PendingLocs is non-empty, we must be at the
1196   // end of a split argument that must be passed indirectly.
1197   if (!PendingLocs.empty()) {
1198     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
1199     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
1200 
1201     for (auto &It : PendingLocs) {
1202       if (Reg)
1203         It.convertToReg(Reg);
1204       else
1205         It.convertToMem(StackOffset);
1206       State.addLoc(It);
1207     }
1208     PendingLocs.clear();
1209     PendingArgFlags.clear();
1210     return false;
1211   }
1212 
1213   assert((!UseGPRForF32 || !UseGPRForF64 || LocVT == XLenVT) &&
1214          "Expected an XLenVT at this stage");
1215 
1216   if (Reg) {
1217     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1218     return false;
1219   }
1220 
1221   // When an f32 or f64 is passed on the stack, no bit-conversion is needed.
1222   if (ValVT == MVT::f32 || ValVT == MVT::f64) {
1223     LocVT = ValVT;
1224     LocInfo = CCValAssign::Full;
1225   }
1226   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
1227   return false;
1228 }
1229 
1230 void RISCVTargetLowering::analyzeInputArgs(
1231     MachineFunction &MF, CCState &CCInfo,
1232     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
1233   unsigned NumArgs = Ins.size();
1234   FunctionType *FType = MF.getFunction().getFunctionType();
1235 
1236   for (unsigned i = 0; i != NumArgs; ++i) {
1237     MVT ArgVT = Ins[i].VT;
1238     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
1239 
1240     Type *ArgTy = nullptr;
1241     if (IsRet)
1242       ArgTy = FType->getReturnType();
1243     else if (Ins[i].isOrigArg())
1244       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
1245 
1246     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
1247     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
1248                  ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
1249       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
1250                         << EVT(ArgVT).getEVTString() << '\n');
1251       llvm_unreachable(nullptr);
1252     }
1253   }
1254 }
1255 
1256 void RISCVTargetLowering::analyzeOutputArgs(
1257     MachineFunction &MF, CCState &CCInfo,
1258     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
1259     CallLoweringInfo *CLI) const {
1260   unsigned NumArgs = Outs.size();
1261 
1262   for (unsigned i = 0; i != NumArgs; i++) {
1263     MVT ArgVT = Outs[i].VT;
1264     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1265     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
1266 
1267     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
1268     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
1269                  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
1270       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
1271                         << EVT(ArgVT).getEVTString() << "\n");
1272       llvm_unreachable(nullptr);
1273     }
1274   }
1275 }
1276 
1277 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
1278 // values.
1279 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
1280                                    const CCValAssign &VA, const SDLoc &DL) {
1281   switch (VA.getLocInfo()) {
1282   default:
1283     llvm_unreachable("Unexpected CCValAssign::LocInfo");
1284   case CCValAssign::Full:
1285     break;
1286   case CCValAssign::BCvt:
1287     if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) {
1288       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
1289       break;
1290     }
1291     Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1292     break;
1293   }
1294   return Val;
1295 }
1296 
1297 // The caller is responsible for loading the full value if the argument is
1298 // passed with CCValAssign::Indirect.
1299 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
1300                                 const CCValAssign &VA, const SDLoc &DL) {
1301   MachineFunction &MF = DAG.getMachineFunction();
1302   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1303   EVT LocVT = VA.getLocVT();
1304   SDValue Val;
1305   const TargetRegisterClass *RC;
1306 
1307   switch (LocVT.getSimpleVT().SimpleTy) {
1308   default:
1309     llvm_unreachable("Unexpected register type");
1310   case MVT::i32:
1311   case MVT::i64:
1312     RC = &RISCV::GPRRegClass;
1313     break;
1314   case MVT::f32:
1315     RC = &RISCV::FPR32RegClass;
1316     break;
1317   case MVT::f64:
1318     RC = &RISCV::FPR64RegClass;
1319     break;
1320   }
1321 
1322   unsigned VReg = RegInfo.createVirtualRegister(RC);
1323   RegInfo.addLiveIn(VA.getLocReg(), VReg);
1324   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1325 
1326   if (VA.getLocInfo() == CCValAssign::Indirect)
1327     return Val;
1328 
1329   return convertLocVTToValVT(DAG, Val, VA, DL);
1330 }
1331 
1332 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
1333                                    const CCValAssign &VA, const SDLoc &DL) {
1334   EVT LocVT = VA.getLocVT();
1335 
1336   switch (VA.getLocInfo()) {
1337   default:
1338     llvm_unreachable("Unexpected CCValAssign::LocInfo");
1339   case CCValAssign::Full:
1340     break;
1341   case CCValAssign::BCvt:
1342     if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) {
1343       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
1344       break;
1345     }
1346     Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1347     break;
1348   }
1349   return Val;
1350 }
1351 
1352 // The caller is responsible for loading the full value if the argument is
1353 // passed with CCValAssign::Indirect.
1354 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
1355                                 const CCValAssign &VA, const SDLoc &DL) {
1356   MachineFunction &MF = DAG.getMachineFunction();
1357   MachineFrameInfo &MFI = MF.getFrameInfo();
1358   EVT LocVT = VA.getLocVT();
1359   EVT ValVT = VA.getValVT();
1360   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
1361   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
1362                                  VA.getLocMemOffset(), /*Immutable=*/true);
1363   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1364   SDValue Val;
1365 
1366   ISD::LoadExtType ExtType;
1367   switch (VA.getLocInfo()) {
1368   default:
1369     llvm_unreachable("Unexpected CCValAssign::LocInfo");
1370   case CCValAssign::Full:
1371   case CCValAssign::Indirect:
1372   case CCValAssign::BCvt:
1373     ExtType = ISD::NON_EXTLOAD;
1374     break;
1375   }
1376   Val = DAG.getExtLoad(
1377       ExtType, DL, LocVT, Chain, FIN,
1378       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
1379   return Val;
1380 }
1381 
1382 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
1383                                        const CCValAssign &VA, const SDLoc &DL) {
1384   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
1385          "Unexpected VA");
1386   MachineFunction &MF = DAG.getMachineFunction();
1387   MachineFrameInfo &MFI = MF.getFrameInfo();
1388   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1389 
1390   if (VA.isMemLoc()) {
1391     // f64 is passed on the stack.
1392     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
1393     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1394     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
1395                        MachinePointerInfo::getFixedStack(MF, FI));
1396   }
1397 
1398   assert(VA.isRegLoc() && "Expected register VA assignment");
1399 
1400   unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1401   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
1402   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
1403   SDValue Hi;
1404   if (VA.getLocReg() == RISCV::X17) {
1405     // Second half of f64 is passed on the stack.
1406     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
1407     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1408     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
1409                      MachinePointerInfo::getFixedStack(MF, FI));
1410   } else {
1411     // Second half of f64 is passed in another GPR.
1412     unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1413     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
1414     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
1415   }
1416   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
1417 }
1418 
1419 // Transform physical registers into virtual registers.
1420 SDValue RISCVTargetLowering::LowerFormalArguments(
1421     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1422     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1423     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1424 
1425   switch (CallConv) {
1426   default:
1427     report_fatal_error("Unsupported calling convention");
1428   case CallingConv::C:
1429   case CallingConv::Fast:
1430     break;
1431   }
1432 
1433   MachineFunction &MF = DAG.getMachineFunction();
1434 
1435   const Function &Func = MF.getFunction();
1436   if (Func.hasFnAttribute("interrupt")) {
1437     if (!Func.arg_empty())
1438       report_fatal_error(
1439         "Functions with the interrupt attribute cannot have arguments!");
1440 
1441     StringRef Kind =
1442       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
1443 
1444     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
1445       report_fatal_error(
1446         "Function interrupt attribute argument not supported!");
1447   }
1448 
1449   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1450   MVT XLenVT = Subtarget.getXLenVT();
1451   unsigned XLenInBytes = Subtarget.getXLen() / 8;
1452   // Used with vargs to acumulate store chains.
1453   std::vector<SDValue> OutChains;
1454 
1455   // Assign locations to all of the incoming arguments.
1456   SmallVector<CCValAssign, 16> ArgLocs;
1457   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1458   analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
1459 
1460   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1461     CCValAssign &VA = ArgLocs[i];
1462     SDValue ArgValue;
1463     // Passing f64 on RV32D with a soft float ABI must be handled as a special
1464     // case.
1465     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
1466       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
1467     else if (VA.isRegLoc())
1468       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
1469     else
1470       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
1471 
1472     if (VA.getLocInfo() == CCValAssign::Indirect) {
1473       // If the original argument was split and passed by reference (e.g. i128
1474       // on RV32), we need to load all parts of it here (using the same
1475       // address).
1476       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1477                                    MachinePointerInfo()));
1478       unsigned ArgIndex = Ins[i].OrigArgIndex;
1479       assert(Ins[i].PartOffset == 0);
1480       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
1481         CCValAssign &PartVA = ArgLocs[i + 1];
1482         unsigned PartOffset = Ins[i + 1].PartOffset;
1483         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1484                                       DAG.getIntPtrConstant(PartOffset, DL));
1485         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1486                                      MachinePointerInfo()));
1487         ++i;
1488       }
1489       continue;
1490     }
1491     InVals.push_back(ArgValue);
1492   }
1493 
1494   if (IsVarArg) {
1495     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
1496     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
1497     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1498     MachineFrameInfo &MFI = MF.getFrameInfo();
1499     MachineRegisterInfo &RegInfo = MF.getRegInfo();
1500     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1501 
1502     // Offset of the first variable argument from stack pointer, and size of
1503     // the vararg save area. For now, the varargs save area is either zero or
1504     // large enough to hold a0-a7.
1505     int VaArgOffset, VarArgsSaveSize;
1506 
1507     // If all registers are allocated, then all varargs must be passed on the
1508     // stack and we don't need to save any argregs.
1509     if (ArgRegs.size() == Idx) {
1510       VaArgOffset = CCInfo.getNextStackOffset();
1511       VarArgsSaveSize = 0;
1512     } else {
1513       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1514       VaArgOffset = -VarArgsSaveSize;
1515     }
1516 
1517     // Record the frame index of the first variable argument
1518     // which is a value necessary to VASTART.
1519     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1520     RVFI->setVarArgsFrameIndex(FI);
1521 
1522     // If saving an odd number of registers then create an extra stack slot to
1523     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1524     // offsets to even-numbered registered remain 2*XLEN-aligned.
1525     if (Idx % 2) {
1526       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1527                                  true);
1528       VarArgsSaveSize += XLenInBytes;
1529     }
1530 
1531     // Copy the integer registers that may have been used for passing varargs
1532     // to the vararg save area.
1533     for (unsigned I = Idx; I < ArgRegs.size();
1534          ++I, VaArgOffset += XLenInBytes) {
1535       const unsigned Reg = RegInfo.createVirtualRegister(RC);
1536       RegInfo.addLiveIn(ArgRegs[I], Reg);
1537       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1538       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1539       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1540       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1541                                    MachinePointerInfo::getFixedStack(MF, FI));
1542       cast<StoreSDNode>(Store.getNode())
1543           ->getMemOperand()
1544           ->setValue((Value *)nullptr);
1545       OutChains.push_back(Store);
1546     }
1547     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1548   }
1549 
1550   // All stores are grouped in one node to allow the matching between
1551   // the size of Ins and InVals. This only happens for vararg functions.
1552   if (!OutChains.empty()) {
1553     OutChains.push_back(Chain);
1554     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1555   }
1556 
1557   return Chain;
1558 }
1559 
1560 /// isEligibleForTailCallOptimization - Check whether the call is eligible
1561 /// for tail call optimization.
1562 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
1563 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
1564     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
1565     const SmallVector<CCValAssign, 16> &ArgLocs) const {
1566 
1567   auto &Callee = CLI.Callee;
1568   auto CalleeCC = CLI.CallConv;
1569   auto IsVarArg = CLI.IsVarArg;
1570   auto &Outs = CLI.Outs;
1571   auto &Caller = MF.getFunction();
1572   auto CallerCC = Caller.getCallingConv();
1573 
1574   // Do not tail call opt functions with "disable-tail-calls" attribute.
1575   if (Caller.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
1576     return false;
1577 
1578   // Exception-handling functions need a special set of instructions to
1579   // indicate a return to the hardware. Tail-calling another function would
1580   // probably break this.
1581   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
1582   // should be expanded as new function attributes are introduced.
1583   if (Caller.hasFnAttribute("interrupt"))
1584     return false;
1585 
1586   // Do not tail call opt functions with varargs.
1587   if (IsVarArg)
1588     return false;
1589 
1590   // Do not tail call opt if the stack is used to pass parameters.
1591   if (CCInfo.getNextStackOffset() != 0)
1592     return false;
1593 
1594   // Do not tail call opt if any parameters need to be passed indirectly.
1595   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
1596   // passed indirectly. So the address of the value will be passed in a
1597   // register, or if not available, then the address is put on the stack. In
1598   // order to pass indirectly, space on the stack often needs to be allocated
1599   // in order to store the value. In this case the CCInfo.getNextStackOffset()
1600   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
1601   // are passed CCValAssign::Indirect.
1602   for (auto &VA : ArgLocs)
1603     if (VA.getLocInfo() == CCValAssign::Indirect)
1604       return false;
1605 
1606   // Do not tail call opt if either caller or callee uses struct return
1607   // semantics.
1608   auto IsCallerStructRet = Caller.hasStructRetAttr();
1609   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
1610   if (IsCallerStructRet || IsCalleeStructRet)
1611     return false;
1612 
1613   // Externally-defined functions with weak linkage should not be
1614   // tail-called. The behaviour of branch instructions in this situation (as
1615   // used for tail calls) is implementation-defined, so we cannot rely on the
1616   // linker replacing the tail call with a return.
1617   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1618     const GlobalValue *GV = G->getGlobal();
1619     if (GV->hasExternalWeakLinkage())
1620       return false;
1621   }
1622 
1623   // The callee has to preserve all registers the caller needs to preserve.
1624   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
1625   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1626   if (CalleeCC != CallerCC) {
1627     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
1628     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
1629       return false;
1630   }
1631 
1632   // Byval parameters hand the function a pointer directly into the stack area
1633   // we want to reuse during a tail call. Working around this *is* possible
1634   // but less efficient and uglier in LowerCall.
1635   for (auto &Arg : Outs)
1636     if (Arg.Flags.isByVal())
1637       return false;
1638 
1639   return true;
1640 }
1641 
1642 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1643 // and output parameter nodes.
1644 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1645                                        SmallVectorImpl<SDValue> &InVals) const {
1646   SelectionDAG &DAG = CLI.DAG;
1647   SDLoc &DL = CLI.DL;
1648   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1649   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1650   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1651   SDValue Chain = CLI.Chain;
1652   SDValue Callee = CLI.Callee;
1653   bool &IsTailCall = CLI.IsTailCall;
1654   CallingConv::ID CallConv = CLI.CallConv;
1655   bool IsVarArg = CLI.IsVarArg;
1656   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1657   MVT XLenVT = Subtarget.getXLenVT();
1658 
1659   MachineFunction &MF = DAG.getMachineFunction();
1660 
1661   // Analyze the operands of the call, assigning locations to each operand.
1662   SmallVector<CCValAssign, 16> ArgLocs;
1663   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1664   analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
1665 
1666   // Check if it's really possible to do a tail call.
1667   if (IsTailCall)
1668     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
1669 
1670   if (IsTailCall)
1671     ++NumTailCalls;
1672   else if (CLI.CS && CLI.CS.isMustTailCall())
1673     report_fatal_error("failed to perform tail call elimination on a call "
1674                        "site marked musttail");
1675 
1676   // Get a count of how many bytes are to be pushed on the stack.
1677   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1678 
1679   // Create local copies for byval args
1680   SmallVector<SDValue, 8> ByValArgs;
1681   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1682     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1683     if (!Flags.isByVal())
1684       continue;
1685 
1686     SDValue Arg = OutVals[i];
1687     unsigned Size = Flags.getByValSize();
1688     unsigned Align = Flags.getByValAlign();
1689 
1690     int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1691     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1692     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1693 
1694     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1695                           /*IsVolatile=*/false,
1696                           /*AlwaysInline=*/false,
1697                           IsTailCall, MachinePointerInfo(),
1698                           MachinePointerInfo());
1699     ByValArgs.push_back(FIPtr);
1700   }
1701 
1702   if (!IsTailCall)
1703     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
1704 
1705   // Copy argument values to their designated locations.
1706   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1707   SmallVector<SDValue, 8> MemOpChains;
1708   SDValue StackPtr;
1709   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1710     CCValAssign &VA = ArgLocs[i];
1711     SDValue ArgValue = OutVals[i];
1712     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1713 
1714     // Handle passing f64 on RV32D with a soft float ABI as a special case.
1715     bool IsF64OnRV32DSoftABI =
1716         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1717     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1718       SDValue SplitF64 = DAG.getNode(
1719           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1720       SDValue Lo = SplitF64.getValue(0);
1721       SDValue Hi = SplitF64.getValue(1);
1722 
1723       unsigned RegLo = VA.getLocReg();
1724       RegsToPass.push_back(std::make_pair(RegLo, Lo));
1725 
1726       if (RegLo == RISCV::X17) {
1727         // Second half of f64 is passed on the stack.
1728         // Work out the address of the stack slot.
1729         if (!StackPtr.getNode())
1730           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1731         // Emit the store.
1732         MemOpChains.push_back(
1733             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1734       } else {
1735         // Second half of f64 is passed in another GPR.
1736         unsigned RegHigh = RegLo + 1;
1737         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1738       }
1739       continue;
1740     }
1741 
1742     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1743     // as any other MemLoc.
1744 
1745     // Promote the value if needed.
1746     // For now, only handle fully promoted and indirect arguments.
1747     if (VA.getLocInfo() == CCValAssign::Indirect) {
1748       // Store the argument in a stack slot and pass its address.
1749       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1750       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1751       MemOpChains.push_back(
1752           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1753                        MachinePointerInfo::getFixedStack(MF, FI)));
1754       // If the original argument was split (e.g. i128), we need
1755       // to store all parts of it here (and pass just one address).
1756       unsigned ArgIndex = Outs[i].OrigArgIndex;
1757       assert(Outs[i].PartOffset == 0);
1758       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1759         SDValue PartValue = OutVals[i + 1];
1760         unsigned PartOffset = Outs[i + 1].PartOffset;
1761         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1762                                       DAG.getIntPtrConstant(PartOffset, DL));
1763         MemOpChains.push_back(
1764             DAG.getStore(Chain, DL, PartValue, Address,
1765                          MachinePointerInfo::getFixedStack(MF, FI)));
1766         ++i;
1767       }
1768       ArgValue = SpillSlot;
1769     } else {
1770       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
1771     }
1772 
1773     // Use local copy if it is a byval arg.
1774     if (Flags.isByVal())
1775       ArgValue = ByValArgs[j++];
1776 
1777     if (VA.isRegLoc()) {
1778       // Queue up the argument copies and emit them at the end.
1779       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1780     } else {
1781       assert(VA.isMemLoc() && "Argument not register or memory");
1782       assert(!IsTailCall && "Tail call not allowed if stack is used "
1783                             "for passing parameters");
1784 
1785       // Work out the address of the stack slot.
1786       if (!StackPtr.getNode())
1787         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1788       SDValue Address =
1789           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1790                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1791 
1792       // Emit the store.
1793       MemOpChains.push_back(
1794           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1795     }
1796   }
1797 
1798   // Join the stores, which are independent of one another.
1799   if (!MemOpChains.empty())
1800     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1801 
1802   SDValue Glue;
1803 
1804   // Build a sequence of copy-to-reg nodes, chained and glued together.
1805   for (auto &Reg : RegsToPass) {
1806     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1807     Glue = Chain.getValue(1);
1808   }
1809 
1810   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1811   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1812   // split it and then direct call can be matched by PseudoCALL.
1813   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1814     Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0,
1815                                         RISCVII::MO_CALL);
1816   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1817     Callee =
1818         DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, RISCVII::MO_CALL);
1819   }
1820 
1821   // The first call operand is the chain and the second is the target address.
1822   SmallVector<SDValue, 8> Ops;
1823   Ops.push_back(Chain);
1824   Ops.push_back(Callee);
1825 
1826   // Add argument registers to the end of the list so that they are
1827   // known live into the call.
1828   for (auto &Reg : RegsToPass)
1829     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1830 
1831   if (!IsTailCall) {
1832     // Add a register mask operand representing the call-preserved registers.
1833     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1834     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1835     assert(Mask && "Missing call preserved mask for calling convention");
1836     Ops.push_back(DAG.getRegisterMask(Mask));
1837   }
1838 
1839   // Glue the call to the argument copies, if any.
1840   if (Glue.getNode())
1841     Ops.push_back(Glue);
1842 
1843   // Emit the call.
1844   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1845 
1846   if (IsTailCall) {
1847     MF.getFrameInfo().setHasTailCall();
1848     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
1849   }
1850 
1851   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1852   Glue = Chain.getValue(1);
1853 
1854   // Mark the end of the call, which is glued to the call itself.
1855   Chain = DAG.getCALLSEQ_END(Chain,
1856                              DAG.getConstant(NumBytes, DL, PtrVT, true),
1857                              DAG.getConstant(0, DL, PtrVT, true),
1858                              Glue, DL);
1859   Glue = Chain.getValue(1);
1860 
1861   // Assign locations to each value returned by this call.
1862   SmallVector<CCValAssign, 16> RVLocs;
1863   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
1864   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
1865 
1866   // Copy all of the result registers out of their specified physreg.
1867   for (auto &VA : RVLocs) {
1868     // Copy the value out
1869     SDValue RetValue =
1870         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1871     // Glue the RetValue to the end of the call sequence
1872     Chain = RetValue.getValue(1);
1873     Glue = RetValue.getValue(2);
1874 
1875     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1876       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1877       SDValue RetValue2 =
1878           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1879       Chain = RetValue2.getValue(1);
1880       Glue = RetValue2.getValue(2);
1881       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1882                              RetValue2);
1883     }
1884 
1885     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
1886 
1887     InVals.push_back(RetValue);
1888   }
1889 
1890   return Chain;
1891 }
1892 
1893 bool RISCVTargetLowering::CanLowerReturn(
1894     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1895     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1896   SmallVector<CCValAssign, 16> RVLocs;
1897   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1898   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1899     MVT VT = Outs[i].VT;
1900     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1901     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
1902     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
1903                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
1904       return false;
1905   }
1906   return true;
1907 }
1908 
1909 SDValue
1910 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1911                                  bool IsVarArg,
1912                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1913                                  const SmallVectorImpl<SDValue> &OutVals,
1914                                  const SDLoc &DL, SelectionDAG &DAG) const {
1915   // Stores the assignment of the return value to a location.
1916   SmallVector<CCValAssign, 16> RVLocs;
1917 
1918   // Info about the registers and stack slot.
1919   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1920                  *DAG.getContext());
1921 
1922   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1923                     nullptr);
1924 
1925   SDValue Glue;
1926   SmallVector<SDValue, 4> RetOps(1, Chain);
1927 
1928   // Copy the result values into the output registers.
1929   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
1930     SDValue Val = OutVals[i];
1931     CCValAssign &VA = RVLocs[i];
1932     assert(VA.isRegLoc() && "Can only return in registers!");
1933 
1934     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1935       // Handle returning f64 on RV32D with a soft float ABI.
1936       assert(VA.isRegLoc() && "Expected return via registers");
1937       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1938                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
1939       SDValue Lo = SplitF64.getValue(0);
1940       SDValue Hi = SplitF64.getValue(1);
1941       unsigned RegLo = VA.getLocReg();
1942       unsigned RegHi = RegLo + 1;
1943       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1944       Glue = Chain.getValue(1);
1945       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1946       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1947       Glue = Chain.getValue(1);
1948       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1949     } else {
1950       // Handle a 'normal' return.
1951       Val = convertValVTToLocVT(DAG, Val, VA, DL);
1952       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
1953 
1954       // Guarantee that all emitted copies are stuck together.
1955       Glue = Chain.getValue(1);
1956       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1957     }
1958   }
1959 
1960   RetOps[0] = Chain; // Update chain.
1961 
1962   // Add the glue node if we have it.
1963   if (Glue.getNode()) {
1964     RetOps.push_back(Glue);
1965   }
1966 
1967   // Interrupt service routines use different return instructions.
1968   const Function &Func = DAG.getMachineFunction().getFunction();
1969   if (Func.hasFnAttribute("interrupt")) {
1970     if (!Func.getReturnType()->isVoidTy())
1971       report_fatal_error(
1972           "Functions with the interrupt attribute must have void return type!");
1973 
1974     MachineFunction &MF = DAG.getMachineFunction();
1975     StringRef Kind =
1976       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
1977 
1978     unsigned RetOpc;
1979     if (Kind == "user")
1980       RetOpc = RISCVISD::URET_FLAG;
1981     else if (Kind == "supervisor")
1982       RetOpc = RISCVISD::SRET_FLAG;
1983     else
1984       RetOpc = RISCVISD::MRET_FLAG;
1985 
1986     return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
1987   }
1988 
1989   return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1990 }
1991 
1992 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1993   switch ((RISCVISD::NodeType)Opcode) {
1994   case RISCVISD::FIRST_NUMBER:
1995     break;
1996   case RISCVISD::RET_FLAG:
1997     return "RISCVISD::RET_FLAG";
1998   case RISCVISD::URET_FLAG:
1999     return "RISCVISD::URET_FLAG";
2000   case RISCVISD::SRET_FLAG:
2001     return "RISCVISD::SRET_FLAG";
2002   case RISCVISD::MRET_FLAG:
2003     return "RISCVISD::MRET_FLAG";
2004   case RISCVISD::CALL:
2005     return "RISCVISD::CALL";
2006   case RISCVISD::SELECT_CC:
2007     return "RISCVISD::SELECT_CC";
2008   case RISCVISD::BuildPairF64:
2009     return "RISCVISD::BuildPairF64";
2010   case RISCVISD::SplitF64:
2011     return "RISCVISD::SplitF64";
2012   case RISCVISD::TAIL:
2013     return "RISCVISD::TAIL";
2014   case RISCVISD::SLLW:
2015     return "RISCVISD::SLLW";
2016   case RISCVISD::SRAW:
2017     return "RISCVISD::SRAW";
2018   case RISCVISD::SRLW:
2019     return "RISCVISD::SRLW";
2020   case RISCVISD::DIVW:
2021     return "RISCVISD::DIVW";
2022   case RISCVISD::DIVUW:
2023     return "RISCVISD::DIVUW";
2024   case RISCVISD::REMUW:
2025     return "RISCVISD::REMUW";
2026   case RISCVISD::FMV_W_X_RV64:
2027     return "RISCVISD::FMV_W_X_RV64";
2028   case RISCVISD::FMV_X_ANYEXTW_RV64:
2029     return "RISCVISD::FMV_X_ANYEXTW_RV64";
2030   }
2031   return nullptr;
2032 }
2033 
2034 std::pair<unsigned, const TargetRegisterClass *>
2035 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2036                                                   StringRef Constraint,
2037                                                   MVT VT) const {
2038   // First, see if this is a constraint that directly corresponds to a
2039   // RISCV register class.
2040   if (Constraint.size() == 1) {
2041     switch (Constraint[0]) {
2042     case 'r':
2043       return std::make_pair(0U, &RISCV::GPRRegClass);
2044     default:
2045       break;
2046     }
2047   }
2048 
2049   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2050 }
2051 
2052 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
2053                                                    Instruction *Inst,
2054                                                    AtomicOrdering Ord) const {
2055   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
2056     return Builder.CreateFence(Ord);
2057   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
2058     return Builder.CreateFence(AtomicOrdering::Release);
2059   return nullptr;
2060 }
2061 
2062 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
2063                                                     Instruction *Inst,
2064                                                     AtomicOrdering Ord) const {
2065   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
2066     return Builder.CreateFence(AtomicOrdering::Acquire);
2067   return nullptr;
2068 }
2069 
2070 TargetLowering::AtomicExpansionKind
2071 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
2072   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
2073   // point operations can't be used in an lr/sc sequence without breaking the
2074   // forward-progress guarantee.
2075   if (AI->isFloatingPointOperation())
2076     return AtomicExpansionKind::CmpXChg;
2077 
2078   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
2079   if (Size == 8 || Size == 16)
2080     return AtomicExpansionKind::MaskedIntrinsic;
2081   return AtomicExpansionKind::None;
2082 }
2083 
2084 static Intrinsic::ID
2085 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
2086   if (XLen == 32) {
2087     switch (BinOp) {
2088     default:
2089       llvm_unreachable("Unexpected AtomicRMW BinOp");
2090     case AtomicRMWInst::Xchg:
2091       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
2092     case AtomicRMWInst::Add:
2093       return Intrinsic::riscv_masked_atomicrmw_add_i32;
2094     case AtomicRMWInst::Sub:
2095       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
2096     case AtomicRMWInst::Nand:
2097       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
2098     case AtomicRMWInst::Max:
2099       return Intrinsic::riscv_masked_atomicrmw_max_i32;
2100     case AtomicRMWInst::Min:
2101       return Intrinsic::riscv_masked_atomicrmw_min_i32;
2102     case AtomicRMWInst::UMax:
2103       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
2104     case AtomicRMWInst::UMin:
2105       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
2106     }
2107   }
2108 
2109   if (XLen == 64) {
2110     switch (BinOp) {
2111     default:
2112       llvm_unreachable("Unexpected AtomicRMW BinOp");
2113     case AtomicRMWInst::Xchg:
2114       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
2115     case AtomicRMWInst::Add:
2116       return Intrinsic::riscv_masked_atomicrmw_add_i64;
2117     case AtomicRMWInst::Sub:
2118       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
2119     case AtomicRMWInst::Nand:
2120       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
2121     case AtomicRMWInst::Max:
2122       return Intrinsic::riscv_masked_atomicrmw_max_i64;
2123     case AtomicRMWInst::Min:
2124       return Intrinsic::riscv_masked_atomicrmw_min_i64;
2125     case AtomicRMWInst::UMax:
2126       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
2127     case AtomicRMWInst::UMin:
2128       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
2129     }
2130   }
2131 
2132   llvm_unreachable("Unexpected XLen\n");
2133 }
2134 
2135 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
2136     IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
2137     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
2138   unsigned XLen = Subtarget.getXLen();
2139   Value *Ordering =
2140       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
2141   Type *Tys[] = {AlignedAddr->getType()};
2142   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
2143       AI->getModule(),
2144       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
2145 
2146   if (XLen == 64) {
2147     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
2148     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
2149     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
2150   }
2151 
2152   Value *Result;
2153 
2154   // Must pass the shift amount needed to sign extend the loaded value prior
2155   // to performing a signed comparison for min/max. ShiftAmt is the number of
2156   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
2157   // is the number of bits to left+right shift the value in order to
2158   // sign-extend.
2159   if (AI->getOperation() == AtomicRMWInst::Min ||
2160       AI->getOperation() == AtomicRMWInst::Max) {
2161     const DataLayout &DL = AI->getModule()->getDataLayout();
2162     unsigned ValWidth =
2163         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
2164     Value *SextShamt =
2165         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
2166     Result = Builder.CreateCall(LrwOpScwLoop,
2167                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
2168   } else {
2169     Result =
2170         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
2171   }
2172 
2173   if (XLen == 64)
2174     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
2175   return Result;
2176 }
2177 
2178 TargetLowering::AtomicExpansionKind
2179 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
2180     AtomicCmpXchgInst *CI) const {
2181   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
2182   if (Size == 8 || Size == 16)
2183     return AtomicExpansionKind::MaskedIntrinsic;
2184   return AtomicExpansionKind::None;
2185 }
2186 
2187 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
2188     IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
2189     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
2190   unsigned XLen = Subtarget.getXLen();
2191   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
2192   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
2193   if (XLen == 64) {
2194     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
2195     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
2196     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
2197     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
2198   }
2199   Type *Tys[] = {AlignedAddr->getType()};
2200   Function *MaskedCmpXchg =
2201       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
2202   Value *Result = Builder.CreateCall(
2203       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
2204   if (XLen == 64)
2205     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
2206   return Result;
2207 }
2208