1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that RISCV uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "RISCVISelLowering.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/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   MVT XLenVT = Subtarget.getXLenVT();
47 
48   // Set up the register classes.
49   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
50 
51   if (Subtarget.hasStdExtF())
52     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
53   if (Subtarget.hasStdExtD())
54     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
55 
56   // Compute derived properties from the register classes.
57   computeRegisterProperties(STI.getRegisterInfo());
58 
59   setStackPointerRegisterToSaveRestore(RISCV::X2);
60 
61   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
62     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
63 
64   // TODO: add all necessary setOperationAction calls.
65   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
66 
67   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
68   setOperationAction(ISD::BR_CC, XLenVT, Expand);
69   setOperationAction(ISD::SELECT, XLenVT, Custom);
70   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
71 
72   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
73   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
74 
75   setOperationAction(ISD::VASTART, MVT::Other, Custom);
76   setOperationAction(ISD::VAARG, MVT::Other, Expand);
77   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
78   setOperationAction(ISD::VAEND, MVT::Other, Expand);
79 
80   for (auto VT : {MVT::i1, MVT::i8, MVT::i16})
81     setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
82 
83   if (!Subtarget.hasStdExtM()) {
84     setOperationAction(ISD::MUL, XLenVT, Expand);
85     setOperationAction(ISD::MULHS, XLenVT, Expand);
86     setOperationAction(ISD::MULHU, XLenVT, Expand);
87     setOperationAction(ISD::SDIV, XLenVT, Expand);
88     setOperationAction(ISD::UDIV, XLenVT, Expand);
89     setOperationAction(ISD::SREM, XLenVT, Expand);
90     setOperationAction(ISD::UREM, XLenVT, Expand);
91   }
92 
93   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
94   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
95   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
96   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
97 
98   setOperationAction(ISD::SHL_PARTS, XLenVT, Expand);
99   setOperationAction(ISD::SRL_PARTS, XLenVT, Expand);
100   setOperationAction(ISD::SRA_PARTS, XLenVT, Expand);
101 
102   setOperationAction(ISD::ROTL, XLenVT, Expand);
103   setOperationAction(ISD::ROTR, XLenVT, Expand);
104   setOperationAction(ISD::BSWAP, XLenVT, Expand);
105   setOperationAction(ISD::CTTZ, XLenVT, Expand);
106   setOperationAction(ISD::CTLZ, XLenVT, Expand);
107   setOperationAction(ISD::CTPOP, XLenVT, Expand);
108 
109   ISD::CondCode FPCCToExtend[] = {
110       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETO,   ISD::SETUEQ,
111       ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE,
112       ISD::SETGT,  ISD::SETGE,  ISD::SETNE};
113 
114   if (Subtarget.hasStdExtF()) {
115     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
116     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
117     for (auto CC : FPCCToExtend)
118       setCondCodeAction(CC, MVT::f32, Expand);
119     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
120     setOperationAction(ISD::SELECT, MVT::f32, Custom);
121     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
122   }
123 
124   if (Subtarget.hasStdExtD()) {
125     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
126     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
127     for (auto CC : FPCCToExtend)
128       setCondCodeAction(CC, MVT::f64, Expand);
129     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
130     setOperationAction(ISD::SELECT, MVT::f64, Custom);
131     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
132     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
133     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
134   }
135 
136   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
137   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
138   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
139 
140   setBooleanContents(ZeroOrOneBooleanContent);
141 
142   // Function alignments (log2).
143   unsigned FunctionAlignment = Subtarget.hasStdExtC() ? 1 : 2;
144   setMinFunctionAlignment(FunctionAlignment);
145   setPrefFunctionAlignment(FunctionAlignment);
146 
147   // Effectively disable jump table generation.
148   setMinimumJumpTableEntries(INT_MAX);
149 }
150 
151 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
152                                             EVT VT) const {
153   if (!VT.isVector())
154     return getPointerTy(DL);
155   return VT.changeVectorElementTypeToInteger();
156 }
157 
158 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
159                                                 const AddrMode &AM, Type *Ty,
160                                                 unsigned AS,
161                                                 Instruction *I) const {
162   // No global is ever allowed as a base.
163   if (AM.BaseGV)
164     return false;
165 
166   // Require a 12-bit signed offset.
167   if (!isInt<12>(AM.BaseOffs))
168     return false;
169 
170   switch (AM.Scale) {
171   case 0: // "r+i" or just "i", depending on HasBaseReg.
172     break;
173   case 1:
174     if (!AM.HasBaseReg) // allow "r+i".
175       break;
176     return false; // disallow "r+r" or "r+r+i".
177   default:
178     return false;
179   }
180 
181   return true;
182 }
183 
184 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
185   return isInt<12>(Imm);
186 }
187 
188 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
189   return isInt<12>(Imm);
190 }
191 
192 // On RV32, 64-bit integers are split into their high and low parts and held
193 // in two different registers, so the trunc is free since the low register can
194 // just be used.
195 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
196   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
197     return false;
198   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
199   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
200   return (SrcBits == 64 && DestBits == 32);
201 }
202 
203 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
204   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
205       !SrcVT.isInteger() || !DstVT.isInteger())
206     return false;
207   unsigned SrcBits = SrcVT.getSizeInBits();
208   unsigned DestBits = DstVT.getSizeInBits();
209   return (SrcBits == 64 && DestBits == 32);
210 }
211 
212 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
213   // Zexts are free if they can be combined with a load.
214   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
215     EVT MemVT = LD->getMemoryVT();
216     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
217          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
218         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
219          LD->getExtensionType() == ISD::ZEXTLOAD))
220       return true;
221   }
222 
223   return TargetLowering::isZExtFree(Val, VT2);
224 }
225 
226 // Changes the condition code and swaps operands if necessary, so the SetCC
227 // operation matches one of the comparisons supported directly in the RISC-V
228 // ISA.
229 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
230   switch (CC) {
231   default:
232     break;
233   case ISD::SETGT:
234   case ISD::SETLE:
235   case ISD::SETUGT:
236   case ISD::SETULE:
237     CC = ISD::getSetCCSwappedOperands(CC);
238     std::swap(LHS, RHS);
239     break;
240   }
241 }
242 
243 // Return the RISC-V branch opcode that matches the given DAG integer
244 // condition code. The CondCode must be one of those supported by the RISC-V
245 // ISA (see normaliseSetCC).
246 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
247   switch (CC) {
248   default:
249     llvm_unreachable("Unsupported CondCode");
250   case ISD::SETEQ:
251     return RISCV::BEQ;
252   case ISD::SETNE:
253     return RISCV::BNE;
254   case ISD::SETLT:
255     return RISCV::BLT;
256   case ISD::SETGE:
257     return RISCV::BGE;
258   case ISD::SETULT:
259     return RISCV::BLTU;
260   case ISD::SETUGE:
261     return RISCV::BGEU;
262   }
263 }
264 
265 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
266                                             SelectionDAG &DAG) const {
267   switch (Op.getOpcode()) {
268   default:
269     report_fatal_error("unimplemented operand");
270   case ISD::GlobalAddress:
271     return lowerGlobalAddress(Op, DAG);
272   case ISD::BlockAddress:
273     return lowerBlockAddress(Op, DAG);
274   case ISD::ConstantPool:
275     return lowerConstantPool(Op, DAG);
276   case ISD::SELECT:
277     return lowerSELECT(Op, DAG);
278   case ISD::VASTART:
279     return lowerVASTART(Op, DAG);
280   case ISD::FRAMEADDR:
281     return LowerFRAMEADDR(Op, DAG);
282   case ISD::RETURNADDR:
283     return LowerRETURNADDR(Op, DAG);
284   }
285 }
286 
287 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
288                                                 SelectionDAG &DAG) const {
289   SDLoc DL(Op);
290   EVT Ty = Op.getValueType();
291   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
292   const GlobalValue *GV = N->getGlobal();
293   int64_t Offset = N->getOffset();
294   MVT XLenVT = Subtarget.getXLenVT();
295 
296   if (isPositionIndependent() || Subtarget.is64Bit())
297     report_fatal_error("Unable to lowerGlobalAddress");
298   // In order to maximise the opportunity for common subexpression elimination,
299   // emit a separate ADD node for the global address offset instead of folding
300   // it in the global address node. Later peephole optimisations may choose to
301   // fold it back in when profitable.
302   SDValue GAHi = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_HI);
303   SDValue GALo = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_LO);
304   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
305   SDValue MNLo =
306     SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
307   if (Offset != 0)
308     return DAG.getNode(ISD::ADD, DL, Ty, MNLo,
309                        DAG.getConstant(Offset, DL, XLenVT));
310   return MNLo;
311 }
312 
313 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
314                                                SelectionDAG &DAG) const {
315   SDLoc DL(Op);
316   EVT Ty = Op.getValueType();
317   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
318   const BlockAddress *BA = N->getBlockAddress();
319   int64_t Offset = N->getOffset();
320 
321   if (isPositionIndependent() || Subtarget.is64Bit())
322     report_fatal_error("Unable to lowerBlockAddress");
323 
324   SDValue BAHi = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_HI);
325   SDValue BALo = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_LO);
326   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, BAHi), 0);
327   SDValue MNLo =
328     SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, BALo), 0);
329   return MNLo;
330 }
331 
332 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
333                                                SelectionDAG &DAG) const {
334   SDLoc DL(Op);
335   EVT Ty = Op.getValueType();
336   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
337   const Constant *CPA = N->getConstVal();
338   int64_t Offset = N->getOffset();
339   unsigned Alignment = N->getAlignment();
340 
341   if (!isPositionIndependent()) {
342     SDValue CPAHi =
343         DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_HI);
344     SDValue CPALo =
345         DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_LO);
346     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, CPAHi), 0);
347     SDValue MNLo =
348         SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, CPALo), 0);
349     return MNLo;
350   } else {
351     report_fatal_error("Unable to lowerConstantPool");
352   }
353 }
354 
355 SDValue RISCVTargetLowering::lowerExternalSymbol(SDValue Op,
356                                                  SelectionDAG &DAG) const {
357   SDLoc DL(Op);
358   EVT Ty = Op.getValueType();
359   ExternalSymbolSDNode *N = cast<ExternalSymbolSDNode>(Op);
360   const char *Sym = N->getSymbol();
361 
362   // TODO: should also handle gp-relative loads.
363 
364   if (isPositionIndependent() || Subtarget.is64Bit())
365     report_fatal_error("Unable to lowerExternalSymbol");
366 
367   SDValue GAHi = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_HI);
368   SDValue GALo = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_LO);
369   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
370   SDValue MNLo =
371     SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
372   return MNLo;
373 }
374 
375 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
376   SDValue CondV = Op.getOperand(0);
377   SDValue TrueV = Op.getOperand(1);
378   SDValue FalseV = Op.getOperand(2);
379   SDLoc DL(Op);
380   MVT XLenVT = Subtarget.getXLenVT();
381 
382   // If the result type is XLenVT and CondV is the output of a SETCC node
383   // which also operated on XLenVT inputs, then merge the SETCC node into the
384   // lowered RISCVISD::SELECT_CC to take advantage of the integer
385   // compare+branch instructions. i.e.:
386   // (select (setcc lhs, rhs, cc), truev, falsev)
387   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
388   if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
389       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
390     SDValue LHS = CondV.getOperand(0);
391     SDValue RHS = CondV.getOperand(1);
392     auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
393     ISD::CondCode CCVal = CC->get();
394 
395     normaliseSetCC(LHS, RHS, CCVal);
396 
397     SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
398     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
399     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
400     return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
401   }
402 
403   // Otherwise:
404   // (select condv, truev, falsev)
405   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
406   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
407   SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
408 
409   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
410   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
411 
412   return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
413 }
414 
415 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
416   MachineFunction &MF = DAG.getMachineFunction();
417   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
418 
419   SDLoc DL(Op);
420   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
421                                  getPointerTy(MF.getDataLayout()));
422 
423   // vastart just stores the address of the VarArgsFrameIndex slot into the
424   // memory location argument.
425   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
426   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
427                       MachinePointerInfo(SV));
428 }
429 
430 SDValue RISCVTargetLowering::LowerFRAMEADDR(SDValue Op,
431                                             SelectionDAG &DAG) const {
432   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
433   MachineFunction &MF = DAG.getMachineFunction();
434   MachineFrameInfo &MFI = MF.getFrameInfo();
435   MFI.setFrameAddressIsTaken(true);
436   unsigned FrameReg = RI.getFrameRegister(MF);
437   int XLenInBytes = Subtarget.getXLen() / 8;
438 
439   EVT VT = Op.getValueType();
440   SDLoc DL(Op);
441   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
442   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
443   while (Depth--) {
444     int Offset = -(XLenInBytes * 2);
445     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
446                               DAG.getIntPtrConstant(Offset, DL));
447     FrameAddr =
448         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
449   }
450   return FrameAddr;
451 }
452 
453 SDValue RISCVTargetLowering::LowerRETURNADDR(SDValue Op,
454                                              SelectionDAG &DAG) const {
455   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
456   MachineFunction &MF = DAG.getMachineFunction();
457   MachineFrameInfo &MFI = MF.getFrameInfo();
458   MFI.setReturnAddressIsTaken(true);
459   MVT XLenVT = Subtarget.getXLenVT();
460   int XLenInBytes = Subtarget.getXLen() / 8;
461 
462   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
463     return SDValue();
464 
465   EVT VT = Op.getValueType();
466   SDLoc DL(Op);
467   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
468   if (Depth) {
469     int Off = -XLenInBytes;
470     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
471     SDValue Offset = DAG.getConstant(Off, DL, VT);
472     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
473                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
474                        MachinePointerInfo());
475   }
476 
477   // Return the value of the return address register, marking it an implicit
478   // live-in.
479   unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
480   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
481 }
482 
483 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
484                                              MachineBasicBlock *BB) {
485   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
486 
487   MachineFunction &MF = *BB->getParent();
488   DebugLoc DL = MI.getDebugLoc();
489   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
490   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
491   unsigned LoReg = MI.getOperand(0).getReg();
492   unsigned HiReg = MI.getOperand(1).getReg();
493   unsigned SrcReg = MI.getOperand(2).getReg();
494   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
495   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
496 
497   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
498                           RI);
499   MachineMemOperand *MMO =
500       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
501                               MachineMemOperand::MOLoad, 8, 8);
502   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
503       .addFrameIndex(FI)
504       .addImm(0)
505       .addMemOperand(MMO);
506   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
507       .addFrameIndex(FI)
508       .addImm(4)
509       .addMemOperand(MMO);
510   MI.eraseFromParent(); // The pseudo instruction is gone now.
511   return BB;
512 }
513 
514 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
515                                                  MachineBasicBlock *BB) {
516   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
517          "Unexpected instruction");
518 
519   MachineFunction &MF = *BB->getParent();
520   DebugLoc DL = MI.getDebugLoc();
521   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
522   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
523   unsigned DstReg = MI.getOperand(0).getReg();
524   unsigned LoReg = MI.getOperand(1).getReg();
525   unsigned HiReg = MI.getOperand(2).getReg();
526   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
527   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
528 
529   MachineMemOperand *MMO =
530       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
531                               MachineMemOperand::MOStore, 8, 8);
532   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
533       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
534       .addFrameIndex(FI)
535       .addImm(0)
536       .addMemOperand(MMO);
537   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
538       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
539       .addFrameIndex(FI)
540       .addImm(4)
541       .addMemOperand(MMO);
542   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
543   MI.eraseFromParent(); // The pseudo instruction is gone now.
544   return BB;
545 }
546 
547 MachineBasicBlock *
548 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
549                                                  MachineBasicBlock *BB) const {
550   switch (MI.getOpcode()) {
551   default:
552     llvm_unreachable("Unexpected instr type to insert");
553   case RISCV::Select_GPR_Using_CC_GPR:
554   case RISCV::Select_FPR32_Using_CC_GPR:
555   case RISCV::Select_FPR64_Using_CC_GPR:
556     break;
557   case RISCV::BuildPairF64Pseudo:
558     return emitBuildPairF64Pseudo(MI, BB);
559   case RISCV::SplitF64Pseudo:
560     return emitSplitF64Pseudo(MI, BB);
561   }
562 
563   // To "insert" a SELECT instruction, we actually have to insert the triangle
564   // control-flow pattern.  The incoming instruction knows the destination vreg
565   // to set, the condition code register to branch on, the true/false values to
566   // select between, and the condcode to use to select the appropriate branch.
567   //
568   // We produce the following control flow:
569   //     HeadMBB
570   //     |  \
571   //     |  IfFalseMBB
572   //     | /
573   //    TailMBB
574   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
575   const BasicBlock *LLVM_BB = BB->getBasicBlock();
576   DebugLoc DL = MI.getDebugLoc();
577   MachineFunction::iterator I = ++BB->getIterator();
578 
579   MachineBasicBlock *HeadMBB = BB;
580   MachineFunction *F = BB->getParent();
581   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
582   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
583 
584   F->insert(I, IfFalseMBB);
585   F->insert(I, TailMBB);
586   // Move all remaining instructions to TailMBB.
587   TailMBB->splice(TailMBB->begin(), HeadMBB,
588                   std::next(MachineBasicBlock::iterator(MI)), HeadMBB->end());
589   // Update machine-CFG edges by transferring all successors of the current
590   // block to the new block which will contain the Phi node for the select.
591   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
592   // Set the successors for HeadMBB.
593   HeadMBB->addSuccessor(IfFalseMBB);
594   HeadMBB->addSuccessor(TailMBB);
595 
596   // Insert appropriate branch.
597   unsigned LHS = MI.getOperand(1).getReg();
598   unsigned RHS = MI.getOperand(2).getReg();
599   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
600   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
601 
602   BuildMI(HeadMBB, DL, TII.get(Opcode))
603     .addReg(LHS)
604     .addReg(RHS)
605     .addMBB(TailMBB);
606 
607   // IfFalseMBB just falls through to TailMBB.
608   IfFalseMBB->addSuccessor(TailMBB);
609 
610   // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
611   BuildMI(*TailMBB, TailMBB->begin(), DL, TII.get(RISCV::PHI),
612           MI.getOperand(0).getReg())
613       .addReg(MI.getOperand(4).getReg())
614       .addMBB(HeadMBB)
615       .addReg(MI.getOperand(5).getReg())
616       .addMBB(IfFalseMBB);
617 
618   MI.eraseFromParent(); // The pseudo instruction is gone now.
619   return TailMBB;
620 }
621 
622 // Calling Convention Implementation.
623 // The expectations for frontend ABI lowering vary from target to target.
624 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
625 // details, but this is a longer term goal. For now, we simply try to keep the
626 // role of the frontend as simple and well-defined as possible. The rules can
627 // be summarised as:
628 // * Never split up large scalar arguments. We handle them here.
629 // * If a hardfloat calling convention is being used, and the struct may be
630 // passed in a pair of registers (fp+fp, int+fp), and both registers are
631 // available, then pass as two separate arguments. If either the GPRs or FPRs
632 // are exhausted, then pass according to the rule below.
633 // * If a struct could never be passed in registers or directly in a stack
634 // slot (as it is larger than 2*XLEN and the floating point rules don't
635 // apply), then pass it using a pointer with the byval attribute.
636 // * If a struct is less than 2*XLEN, then coerce to either a two-element
637 // word-sized array or a 2*XLEN scalar (depending on alignment).
638 // * The frontend can determine whether a struct is returned by reference or
639 // not based on its size and fields. If it will be returned by reference, the
640 // frontend must modify the prototype so a pointer with the sret annotation is
641 // passed as the first argument. This is not necessary for large scalar
642 // returns.
643 // * Struct return values and varargs should be coerced to structs containing
644 // register-size fields in the same situations they would be for fixed
645 // arguments.
646 
647 static const MCPhysReg ArgGPRs[] = {
648   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
649   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
650 };
651 
652 // Pass a 2*XLEN argument that has been split into two XLEN values through
653 // registers or the stack as necessary.
654 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
655                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
656                                 MVT ValVT2, MVT LocVT2,
657                                 ISD::ArgFlagsTy ArgFlags2) {
658   unsigned XLenInBytes = XLen / 8;
659   if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
660     // At least one half can be passed via register.
661     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
662                                      VA1.getLocVT(), CCValAssign::Full));
663   } else {
664     // Both halves must be passed on the stack, with proper alignment.
665     unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
666     State.addLoc(
667         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
668                             State.AllocateStack(XLenInBytes, StackAlign),
669                             VA1.getLocVT(), CCValAssign::Full));
670     State.addLoc(CCValAssign::getMem(
671         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
672         CCValAssign::Full));
673     return false;
674   }
675 
676   if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
677     // The second half can also be passed via register.
678     State.addLoc(
679         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
680   } else {
681     // The second half is passed via the stack, without additional alignment.
682     State.addLoc(CCValAssign::getMem(
683         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
684         CCValAssign::Full));
685   }
686 
687   return false;
688 }
689 
690 // Implements the RISC-V calling convention. Returns true upon failure.
691 static bool CC_RISCV(const DataLayout &DL, unsigned ValNo, MVT ValVT, MVT LocVT,
692                      CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
693                      CCState &State, bool IsFixed, bool IsRet, Type *OrigTy) {
694   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
695   assert(XLen == 32 || XLen == 64);
696   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
697   if (ValVT == MVT::f32) {
698     LocVT = MVT::i32;
699     LocInfo = CCValAssign::BCvt;
700   }
701 
702   // Any return value split in to more than two values can't be returned
703   // directly.
704   if (IsRet && ValNo > 1)
705     return true;
706 
707   // If this is a variadic argument, the RISC-V calling convention requires
708   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
709   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
710   // be used regardless of whether the original argument was split during
711   // legalisation or not. The argument will not be passed by registers if the
712   // original type is larger than 2*XLEN, so the register alignment rule does
713   // not apply.
714   unsigned TwoXLenInBytes = (2 * XLen) / 8;
715   if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
716       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
717     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
718     // Skip 'odd' register if necessary.
719     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
720       State.AllocateReg(ArgGPRs);
721   }
722 
723   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
724   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
725       State.getPendingArgFlags();
726 
727   assert(PendingLocs.size() == PendingArgFlags.size() &&
728          "PendingLocs and PendingArgFlags out of sync");
729 
730   // Handle passing f64 on RV32D with a soft float ABI.
731   if (XLen == 32 && ValVT == MVT::f64) {
732     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
733            "Can't lower f64 if it is split");
734     // Depending on available argument GPRS, f64 may be passed in a pair of
735     // GPRs, split between a GPR and the stack, or passed completely on the
736     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
737     // cases.
738     unsigned Reg = State.AllocateReg(ArgGPRs);
739     LocVT = MVT::i32;
740     if (!Reg) {
741       unsigned StackOffset = State.AllocateStack(8, 8);
742       State.addLoc(
743           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
744       return false;
745     }
746     if (!State.AllocateReg(ArgGPRs))
747       State.AllocateStack(4, 4);
748     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
749     return false;
750   }
751 
752   // Split arguments might be passed indirectly, so keep track of the pending
753   // values.
754   if (ArgFlags.isSplit() || !PendingLocs.empty()) {
755     LocVT = XLenVT;
756     LocInfo = CCValAssign::Indirect;
757     PendingLocs.push_back(
758         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
759     PendingArgFlags.push_back(ArgFlags);
760     if (!ArgFlags.isSplitEnd()) {
761       return false;
762     }
763   }
764 
765   // If the split argument only had two elements, it should be passed directly
766   // in registers or on the stack.
767   if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
768     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
769     // Apply the normal calling convention rules to the first half of the
770     // split argument.
771     CCValAssign VA = PendingLocs[0];
772     ISD::ArgFlagsTy AF = PendingArgFlags[0];
773     PendingLocs.clear();
774     PendingArgFlags.clear();
775     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
776                                ArgFlags);
777   }
778 
779   // Allocate to a register if possible, or else a stack slot.
780   unsigned Reg = State.AllocateReg(ArgGPRs);
781   unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
782 
783   // If we reach this point and PendingLocs is non-empty, we must be at the
784   // end of a split argument that must be passed indirectly.
785   if (!PendingLocs.empty()) {
786     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
787     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
788 
789     for (auto &It : PendingLocs) {
790       if (Reg)
791         It.convertToReg(Reg);
792       else
793         It.convertToMem(StackOffset);
794       State.addLoc(It);
795     }
796     PendingLocs.clear();
797     PendingArgFlags.clear();
798     return false;
799   }
800 
801   assert(LocVT == XLenVT && "Expected an XLenVT at this stage");
802 
803   if (Reg) {
804     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
805   } else {
806     State.addLoc(
807         CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
808   }
809   return false;
810 }
811 
812 void RISCVTargetLowering::analyzeInputArgs(
813     MachineFunction &MF, CCState &CCInfo,
814     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
815   unsigned NumArgs = Ins.size();
816   FunctionType *FType = MF.getFunction().getFunctionType();
817 
818   for (unsigned i = 0; i != NumArgs; ++i) {
819     MVT ArgVT = Ins[i].VT;
820     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
821 
822     Type *ArgTy = nullptr;
823     if (IsRet)
824       ArgTy = FType->getReturnType();
825     else if (Ins[i].isOrigArg())
826       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
827 
828     if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
829                  ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
830       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
831                         << EVT(ArgVT).getEVTString() << '\n');
832       llvm_unreachable(nullptr);
833     }
834   }
835 }
836 
837 void RISCVTargetLowering::analyzeOutputArgs(
838     MachineFunction &MF, CCState &CCInfo,
839     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
840     CallLoweringInfo *CLI) const {
841   unsigned NumArgs = Outs.size();
842 
843   for (unsigned i = 0; i != NumArgs; i++) {
844     MVT ArgVT = Outs[i].VT;
845     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
846     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
847 
848     if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
849                  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
850       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
851                         << EVT(ArgVT).getEVTString() << "\n");
852       llvm_unreachable(nullptr);
853     }
854   }
855 }
856 
857 // The caller is responsible for loading the full value if the argument is
858 // passed with CCValAssign::Indirect.
859 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
860                                 const CCValAssign &VA, const SDLoc &DL) {
861   MachineFunction &MF = DAG.getMachineFunction();
862   MachineRegisterInfo &RegInfo = MF.getRegInfo();
863   EVT LocVT = VA.getLocVT();
864   EVT ValVT = VA.getValVT();
865   SDValue Val;
866 
867   unsigned VReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
868   RegInfo.addLiveIn(VA.getLocReg(), VReg);
869   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
870 
871   switch (VA.getLocInfo()) {
872   default:
873     llvm_unreachable("Unexpected CCValAssign::LocInfo");
874   case CCValAssign::Full:
875   case CCValAssign::Indirect:
876     break;
877   case CCValAssign::BCvt:
878     Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
879     break;
880   }
881   return Val;
882 }
883 
884 // The caller is responsible for loading the full value if the argument is
885 // passed with CCValAssign::Indirect.
886 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
887                                 const CCValAssign &VA, const SDLoc &DL) {
888   MachineFunction &MF = DAG.getMachineFunction();
889   MachineFrameInfo &MFI = MF.getFrameInfo();
890   EVT LocVT = VA.getLocVT();
891   EVT ValVT = VA.getValVT();
892   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
893   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
894                                  VA.getLocMemOffset(), /*Immutable=*/true);
895   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
896   SDValue Val;
897 
898   ISD::LoadExtType ExtType;
899   switch (VA.getLocInfo()) {
900   default:
901     llvm_unreachable("Unexpected CCValAssign::LocInfo");
902   case CCValAssign::Full:
903   case CCValAssign::Indirect:
904     ExtType = ISD::NON_EXTLOAD;
905     break;
906   }
907   Val = DAG.getExtLoad(
908       ExtType, DL, LocVT, Chain, FIN,
909       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
910   return Val;
911 }
912 
913 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
914                                        const CCValAssign &VA, const SDLoc &DL) {
915   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
916          "Unexpected VA");
917   MachineFunction &MF = DAG.getMachineFunction();
918   MachineFrameInfo &MFI = MF.getFrameInfo();
919   MachineRegisterInfo &RegInfo = MF.getRegInfo();
920 
921   if (VA.isMemLoc()) {
922     // f64 is passed on the stack.
923     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
924     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
925     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
926                        MachinePointerInfo::getFixedStack(MF, FI));
927   }
928 
929   assert(VA.isRegLoc() && "Expected register VA assignment");
930 
931   unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
932   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
933   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
934   SDValue Hi;
935   if (VA.getLocReg() == RISCV::X17) {
936     // Second half of f64 is passed on the stack.
937     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
938     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
939     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
940                      MachinePointerInfo::getFixedStack(MF, FI));
941   } else {
942     // Second half of f64 is passed in another GPR.
943     unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
944     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
945     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
946   }
947   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
948 }
949 
950 // Transform physical registers into virtual registers.
951 SDValue RISCVTargetLowering::LowerFormalArguments(
952     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
953     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
954     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
955 
956   switch (CallConv) {
957   default:
958     report_fatal_error("Unsupported calling convention");
959   case CallingConv::C:
960   case CallingConv::Fast:
961     break;
962   }
963 
964   MachineFunction &MF = DAG.getMachineFunction();
965   EVT PtrVT = getPointerTy(DAG.getDataLayout());
966   MVT XLenVT = Subtarget.getXLenVT();
967   unsigned XLenInBytes = Subtarget.getXLen() / 8;
968   // Used with vargs to acumulate store chains.
969   std::vector<SDValue> OutChains;
970 
971   // Assign locations to all of the incoming arguments.
972   SmallVector<CCValAssign, 16> ArgLocs;
973   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
974   analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
975 
976   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
977     CCValAssign &VA = ArgLocs[i];
978     assert(VA.getLocVT() == XLenVT && "Unhandled argument type");
979     SDValue ArgValue;
980     // Passing f64 on RV32D with a soft float ABI must be handled as a special
981     // case.
982     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
983       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
984     else if (VA.isRegLoc())
985       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
986     else
987       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
988 
989     if (VA.getLocInfo() == CCValAssign::Indirect) {
990       // If the original argument was split and passed by reference (e.g. i128
991       // on RV32), we need to load all parts of it here (using the same
992       // address).
993       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
994                                    MachinePointerInfo()));
995       unsigned ArgIndex = Ins[i].OrigArgIndex;
996       assert(Ins[i].PartOffset == 0);
997       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
998         CCValAssign &PartVA = ArgLocs[i + 1];
999         unsigned PartOffset = Ins[i + 1].PartOffset;
1000         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1001                                       DAG.getIntPtrConstant(PartOffset, DL));
1002         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1003                                      MachinePointerInfo()));
1004         ++i;
1005       }
1006       continue;
1007     }
1008     InVals.push_back(ArgValue);
1009   }
1010 
1011   if (IsVarArg) {
1012     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
1013     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
1014     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1015     MachineFrameInfo &MFI = MF.getFrameInfo();
1016     MachineRegisterInfo &RegInfo = MF.getRegInfo();
1017     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1018 
1019     // Offset of the first variable argument from stack pointer, and size of
1020     // the vararg save area. For now, the varargs save area is either zero or
1021     // large enough to hold a0-a7.
1022     int VaArgOffset, VarArgsSaveSize;
1023 
1024     // If all registers are allocated, then all varargs must be passed on the
1025     // stack and we don't need to save any argregs.
1026     if (ArgRegs.size() == Idx) {
1027       VaArgOffset = CCInfo.getNextStackOffset();
1028       VarArgsSaveSize = 0;
1029     } else {
1030       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1031       VaArgOffset = -VarArgsSaveSize;
1032     }
1033 
1034     // Record the frame index of the first variable argument
1035     // which is a value necessary to VASTART.
1036     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1037     RVFI->setVarArgsFrameIndex(FI);
1038 
1039     // If saving an odd number of registers then create an extra stack slot to
1040     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1041     // offsets to even-numbered registered remain 2*XLEN-aligned.
1042     if (Idx % 2) {
1043       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1044                                  true);
1045       VarArgsSaveSize += XLenInBytes;
1046     }
1047 
1048     // Copy the integer registers that may have been used for passing varargs
1049     // to the vararg save area.
1050     for (unsigned I = Idx; I < ArgRegs.size();
1051          ++I, VaArgOffset += XLenInBytes) {
1052       const unsigned Reg = RegInfo.createVirtualRegister(RC);
1053       RegInfo.addLiveIn(ArgRegs[I], Reg);
1054       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1055       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1056       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1057       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1058                                    MachinePointerInfo::getFixedStack(MF, FI));
1059       cast<StoreSDNode>(Store.getNode())
1060           ->getMemOperand()
1061           ->setValue((Value *)nullptr);
1062       OutChains.push_back(Store);
1063     }
1064     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1065   }
1066 
1067   // All stores are grouped in one node to allow the matching between
1068   // the size of Ins and InVals. This only happens for vararg functions.
1069   if (!OutChains.empty()) {
1070     OutChains.push_back(Chain);
1071     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1072   }
1073 
1074   return Chain;
1075 }
1076 
1077 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1078 /// for tail call optimization.
1079 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
1080 bool RISCVTargetLowering::IsEligibleForTailCallOptimization(
1081   CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
1082   const SmallVector<CCValAssign, 16> &ArgLocs) const {
1083 
1084   auto &Callee = CLI.Callee;
1085   auto CalleeCC = CLI.CallConv;
1086   auto IsVarArg = CLI.IsVarArg;
1087   auto &Outs = CLI.Outs;
1088   auto &Caller = MF.getFunction();
1089   auto CallerCC = Caller.getCallingConv();
1090 
1091   // Do not tail call opt functions with "disable-tail-calls" attribute.
1092   if (Caller.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
1093     return false;
1094 
1095   // Exception-handling functions need a special set of instructions to
1096   // indicate a return to the hardware. Tail-calling another function would
1097   // probably break this.
1098   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
1099   // should be expanded as new function attributes are introduced.
1100   if (Caller.hasFnAttribute("interrupt"))
1101     return false;
1102 
1103   // Do not tail call opt functions with varargs.
1104   if (IsVarArg)
1105     return false;
1106 
1107   // Do not tail call opt if the stack is used to pass parameters.
1108   if (CCInfo.getNextStackOffset() != 0)
1109     return false;
1110 
1111   // Do not tail call opt if any parameters need to be passed indirectly.
1112   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
1113   // passed indirectly. So the address of the value will be passed in a
1114   // register, or if not available, then the address is put on the stack. In
1115   // order to pass indirectly, space on the stack often needs to be allocated
1116   // in order to store the value. In this case the CCInfo.getNextStackOffset()
1117   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
1118   // are passed CCValAssign::Indirect.
1119   for (auto &VA : ArgLocs)
1120     if (VA.getLocInfo() == CCValAssign::Indirect)
1121       return false;
1122 
1123   // Do not tail call opt if either caller or callee uses struct return
1124   // semantics.
1125   auto IsCallerStructRet = Caller.hasStructRetAttr();
1126   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
1127   if (IsCallerStructRet || IsCalleeStructRet)
1128     return false;
1129 
1130   // Externally-defined functions with weak linkage should not be
1131   // tail-called. The behaviour of branch instructions in this situation (as
1132   // used for tail calls) is implementation-defined, so we cannot rely on the
1133   // linker replacing the tail call with a return.
1134   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1135     const GlobalValue *GV = G->getGlobal();
1136     if (GV->hasExternalWeakLinkage())
1137       return false;
1138   }
1139 
1140   // The callee has to preserve all registers the caller needs to preserve.
1141   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
1142   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1143   if (CalleeCC != CallerCC) {
1144     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
1145     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
1146       return false;
1147   }
1148 
1149   // Byval parameters hand the function a pointer directly into the stack area
1150   // we want to reuse during a tail call. Working around this *is* possible
1151   // but less efficient and uglier in LowerCall.
1152   for (auto &Arg : Outs)
1153     if (Arg.Flags.isByVal())
1154       return false;
1155 
1156   return true;
1157 }
1158 
1159 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1160 // and output parameter nodes.
1161 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1162                                        SmallVectorImpl<SDValue> &InVals) const {
1163   SelectionDAG &DAG = CLI.DAG;
1164   SDLoc &DL = CLI.DL;
1165   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1166   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1167   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1168   SDValue Chain = CLI.Chain;
1169   SDValue Callee = CLI.Callee;
1170   bool &IsTailCall = CLI.IsTailCall;
1171   CallingConv::ID CallConv = CLI.CallConv;
1172   bool IsVarArg = CLI.IsVarArg;
1173   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1174   MVT XLenVT = Subtarget.getXLenVT();
1175 
1176   MachineFunction &MF = DAG.getMachineFunction();
1177 
1178   // Analyze the operands of the call, assigning locations to each operand.
1179   SmallVector<CCValAssign, 16> ArgLocs;
1180   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1181   analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
1182 
1183   // Check if it's really possible to do a tail call.
1184   if (IsTailCall)
1185     IsTailCall = IsEligibleForTailCallOptimization(ArgCCInfo, CLI, MF,
1186                                                    ArgLocs);
1187 
1188   if (IsTailCall)
1189     ++NumTailCalls;
1190   else if (CLI.CS && CLI.CS.isMustTailCall())
1191     report_fatal_error("failed to perform tail call elimination on a call "
1192                        "site marked musttail");
1193 
1194   // Get a count of how many bytes are to be pushed on the stack.
1195   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1196 
1197   // Create local copies for byval args
1198   SmallVector<SDValue, 8> ByValArgs;
1199   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1200     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1201     if (!Flags.isByVal())
1202       continue;
1203 
1204     SDValue Arg = OutVals[i];
1205     unsigned Size = Flags.getByValSize();
1206     unsigned Align = Flags.getByValAlign();
1207 
1208     int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1209     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1210     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1211 
1212     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1213                           /*IsVolatile=*/false,
1214                           /*AlwaysInline=*/false,
1215                           IsTailCall, MachinePointerInfo(),
1216                           MachinePointerInfo());
1217     ByValArgs.push_back(FIPtr);
1218   }
1219 
1220   if (!IsTailCall)
1221     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
1222 
1223   // Copy argument values to their designated locations.
1224   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1225   SmallVector<SDValue, 8> MemOpChains;
1226   SDValue StackPtr;
1227   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1228     CCValAssign &VA = ArgLocs[i];
1229     SDValue ArgValue = OutVals[i];
1230     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1231 
1232     // Handle passing f64 on RV32D with a soft float ABI as a special case.
1233     bool IsF64OnRV32DSoftABI =
1234         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1235     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1236       SDValue SplitF64 = DAG.getNode(
1237           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1238       SDValue Lo = SplitF64.getValue(0);
1239       SDValue Hi = SplitF64.getValue(1);
1240 
1241       unsigned RegLo = VA.getLocReg();
1242       RegsToPass.push_back(std::make_pair(RegLo, Lo));
1243 
1244       if (RegLo == RISCV::X17) {
1245         // Second half of f64 is passed on the stack.
1246         // Work out the address of the stack slot.
1247         if (!StackPtr.getNode())
1248           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1249         // Emit the store.
1250         MemOpChains.push_back(
1251             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1252       } else {
1253         // Second half of f64 is passed in another GPR.
1254         unsigned RegHigh = RegLo + 1;
1255         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1256       }
1257       continue;
1258     }
1259 
1260     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1261     // as any other MemLoc.
1262 
1263     // Promote the value if needed.
1264     // For now, only handle fully promoted and indirect arguments.
1265     switch (VA.getLocInfo()) {
1266     case CCValAssign::Full:
1267       break;
1268     case CCValAssign::BCvt:
1269       ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), ArgValue);
1270       break;
1271     case CCValAssign::Indirect: {
1272       // Store the argument in a stack slot and pass its address.
1273       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1274       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1275       MemOpChains.push_back(
1276           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1277                        MachinePointerInfo::getFixedStack(MF, FI)));
1278       // If the original argument was split (e.g. i128), we need
1279       // to store all parts of it here (and pass just one address).
1280       unsigned ArgIndex = Outs[i].OrigArgIndex;
1281       assert(Outs[i].PartOffset == 0);
1282       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1283         SDValue PartValue = OutVals[i + 1];
1284         unsigned PartOffset = Outs[i + 1].PartOffset;
1285         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1286                                       DAG.getIntPtrConstant(PartOffset, DL));
1287         MemOpChains.push_back(
1288             DAG.getStore(Chain, DL, PartValue, Address,
1289                          MachinePointerInfo::getFixedStack(MF, FI)));
1290         ++i;
1291       }
1292       ArgValue = SpillSlot;
1293       break;
1294     }
1295     default:
1296       llvm_unreachable("Unknown loc info!");
1297     }
1298 
1299     // Use local copy if it is a byval arg.
1300     if (Flags.isByVal())
1301       ArgValue = ByValArgs[j++];
1302 
1303     if (VA.isRegLoc()) {
1304       // Queue up the argument copies and emit them at the end.
1305       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1306     } else {
1307       assert(VA.isMemLoc() && "Argument not register or memory");
1308       assert(!IsTailCall && "Tail call not allowed if stack is used "
1309                             "for passing parameters");
1310 
1311       // Work out the address of the stack slot.
1312       if (!StackPtr.getNode())
1313         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1314       SDValue Address =
1315           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1316                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1317 
1318       // Emit the store.
1319       MemOpChains.push_back(
1320           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1321     }
1322   }
1323 
1324   // Join the stores, which are independent of one another.
1325   if (!MemOpChains.empty())
1326     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1327 
1328   SDValue Glue;
1329 
1330   // Build a sequence of copy-to-reg nodes, chained and glued together.
1331   for (auto &Reg : RegsToPass) {
1332     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1333     Glue = Chain.getValue(1);
1334   }
1335 
1336   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1337   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1338   // split it and then direct call can be matched by PseudoCALL.
1339   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1340     Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, 0);
1341   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1342     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, 0);
1343   }
1344 
1345   // The first call operand is the chain and the second is the target address.
1346   SmallVector<SDValue, 8> Ops;
1347   Ops.push_back(Chain);
1348   Ops.push_back(Callee);
1349 
1350   // Add argument registers to the end of the list so that they are
1351   // known live into the call.
1352   for (auto &Reg : RegsToPass)
1353     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1354 
1355   if (!IsTailCall) {
1356     // Add a register mask operand representing the call-preserved registers.
1357     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1358     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1359     assert(Mask && "Missing call preserved mask for calling convention");
1360     Ops.push_back(DAG.getRegisterMask(Mask));
1361   }
1362 
1363   // Glue the call to the argument copies, if any.
1364   if (Glue.getNode())
1365     Ops.push_back(Glue);
1366 
1367   // Emit the call.
1368   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1369 
1370   if (IsTailCall) {
1371     MF.getFrameInfo().setHasTailCall();
1372     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
1373   }
1374 
1375   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1376   Glue = Chain.getValue(1);
1377 
1378   // Mark the end of the call, which is glued to the call itself.
1379   Chain = DAG.getCALLSEQ_END(Chain,
1380                              DAG.getConstant(NumBytes, DL, PtrVT, true),
1381                              DAG.getConstant(0, DL, PtrVT, true),
1382                              Glue, DL);
1383   Glue = Chain.getValue(1);
1384 
1385   // Assign locations to each value returned by this call.
1386   SmallVector<CCValAssign, 16> RVLocs;
1387   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
1388   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
1389 
1390   // Copy all of the result registers out of their specified physreg.
1391   for (auto &VA : RVLocs) {
1392     // Copy the value out
1393     SDValue RetValue =
1394         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1395     // Glue the RetValue to the end of the call sequence
1396     Chain = RetValue.getValue(1);
1397     Glue = RetValue.getValue(2);
1398     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1399       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1400       SDValue RetValue2 =
1401           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1402       Chain = RetValue2.getValue(1);
1403       Glue = RetValue2.getValue(2);
1404       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1405                              RetValue2);
1406     }
1407 
1408     switch (VA.getLocInfo()) {
1409     default:
1410       llvm_unreachable("Unknown loc info!");
1411     case CCValAssign::Full:
1412       break;
1413     case CCValAssign::BCvt:
1414       RetValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), RetValue);
1415       break;
1416     }
1417 
1418     InVals.push_back(RetValue);
1419   }
1420 
1421   return Chain;
1422 }
1423 
1424 bool RISCVTargetLowering::CanLowerReturn(
1425     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1426     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1427   SmallVector<CCValAssign, 16> RVLocs;
1428   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1429   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1430     MVT VT = Outs[i].VT;
1431     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1432     if (CC_RISCV(MF.getDataLayout(), i, VT, VT, CCValAssign::Full, ArgFlags,
1433                  CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
1434       return false;
1435   }
1436   return true;
1437 }
1438 
1439 static SDValue packIntoRegLoc(SelectionDAG &DAG, SDValue Val,
1440                               const CCValAssign &VA, const SDLoc &DL) {
1441   EVT LocVT = VA.getLocVT();
1442 
1443   switch (VA.getLocInfo()) {
1444   default:
1445     llvm_unreachable("Unexpected CCValAssign::LocInfo");
1446   case CCValAssign::Full:
1447     break;
1448   case CCValAssign::BCvt:
1449     Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1450     break;
1451   }
1452   return Val;
1453 }
1454 
1455 SDValue
1456 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1457                                  bool IsVarArg,
1458                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1459                                  const SmallVectorImpl<SDValue> &OutVals,
1460                                  const SDLoc &DL, SelectionDAG &DAG) const {
1461   // Stores the assignment of the return value to a location.
1462   SmallVector<CCValAssign, 16> RVLocs;
1463 
1464   // Info about the registers and stack slot.
1465   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1466                  *DAG.getContext());
1467 
1468   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1469                     nullptr);
1470 
1471   SDValue Glue;
1472   SmallVector<SDValue, 4> RetOps(1, Chain);
1473 
1474   // Copy the result values into the output registers.
1475   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
1476     SDValue Val = OutVals[i];
1477     CCValAssign &VA = RVLocs[i];
1478     assert(VA.isRegLoc() && "Can only return in registers!");
1479 
1480     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1481       // Handle returning f64 on RV32D with a soft float ABI.
1482       assert(VA.isRegLoc() && "Expected return via registers");
1483       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1484                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
1485       SDValue Lo = SplitF64.getValue(0);
1486       SDValue Hi = SplitF64.getValue(1);
1487       unsigned RegLo = VA.getLocReg();
1488       unsigned RegHi = RegLo + 1;
1489       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1490       Glue = Chain.getValue(1);
1491       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1492       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1493       Glue = Chain.getValue(1);
1494       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1495     } else {
1496       // Handle a 'normal' return.
1497       Val = packIntoRegLoc(DAG, Val, VA, DL);
1498       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
1499 
1500       // Guarantee that all emitted copies are stuck together.
1501       Glue = Chain.getValue(1);
1502       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1503     }
1504   }
1505 
1506   RetOps[0] = Chain; // Update chain.
1507 
1508   // Add the glue node if we have it.
1509   if (Glue.getNode()) {
1510     RetOps.push_back(Glue);
1511   }
1512 
1513   return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1514 }
1515 
1516 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1517   switch ((RISCVISD::NodeType)Opcode) {
1518   case RISCVISD::FIRST_NUMBER:
1519     break;
1520   case RISCVISD::RET_FLAG:
1521     return "RISCVISD::RET_FLAG";
1522   case RISCVISD::CALL:
1523     return "RISCVISD::CALL";
1524   case RISCVISD::SELECT_CC:
1525     return "RISCVISD::SELECT_CC";
1526   case RISCVISD::BuildPairF64:
1527     return "RISCVISD::BuildPairF64";
1528   case RISCVISD::SplitF64:
1529     return "RISCVISD::SplitF64";
1530   case RISCVISD::TAIL:
1531     return "RISCVISD::TAIL";
1532   }
1533   return nullptr;
1534 }
1535 
1536 std::pair<unsigned, const TargetRegisterClass *>
1537 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1538                                                   StringRef Constraint,
1539                                                   MVT VT) const {
1540   // First, see if this is a constraint that directly corresponds to a
1541   // RISCV register class.
1542   if (Constraint.size() == 1) {
1543     switch (Constraint[0]) {
1544     case 'r':
1545       return std::make_pair(0U, &RISCV::GPRRegClass);
1546     default:
1547       break;
1548     }
1549   }
1550 
1551   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1552 }
1553