blob: d3d0d0370b9fbbd1472cf7a14812db9498be0730 [file] [log] [blame]
Alex Bradbury89718422017-10-19 21:37:38 +00001//===-- 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"
Alex Bradburyc85be0d2018-01-10 19:41:03 +000017#include "RISCVMachineFunctionInfo.h"
Alex Bradbury89718422017-10-19 21:37:38 +000018#include "RISCVRegisterInfo.h"
19#include "RISCVSubtarget.h"
20#include "RISCVTargetMachine.h"
21#include "llvm/CodeGen/CallingConvLower.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/SelectionDAGISel.h"
27#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Craig Topper2fa14362018-03-29 17:21:10 +000028#include "llvm/CodeGen/ValueTypes.h"
Alex Bradbury89718422017-10-19 21:37:38 +000029#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/DiagnosticPrinter.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34
35using namespace llvm;
36
37#define DEBUG_TYPE "riscv-lower"
38
39RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
40 const RISCVSubtarget &STI)
41 : TargetLowering(TM), Subtarget(STI) {
42
43 MVT XLenVT = Subtarget.getXLenVT();
44
45 // Set up the register classes.
46 addRegisterClass(XLenVT, &RISCV::GPRRegClass);
47
Alex Bradbury76c29ee2018-03-20 12:45:35 +000048 if (Subtarget.hasStdExtF())
49 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
Alex Bradbury0b4175f2018-04-12 05:34:25 +000050 if (Subtarget.hasStdExtD())
51 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
Alex Bradbury76c29ee2018-03-20 12:45:35 +000052
Alex Bradbury89718422017-10-19 21:37:38 +000053 // Compute derived properties from the register classes.
54 computeRegisterProperties(STI.getRegisterInfo());
55
56 setStackPointerRegisterToSaveRestore(RISCV::X2);
57
Alex Bradburycfa62912017-11-08 12:20:01 +000058 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
59 setLoadExtAction(N, XLenVT, MVT::i1, Promote);
60
Alex Bradbury89718422017-10-19 21:37:38 +000061 // TODO: add all necessary setOperationAction calls.
Alex Bradburybfb00d42017-12-11 12:38:17 +000062 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
63
Alex Bradburyffc435e2017-11-21 08:11:03 +000064 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
Alex Bradbury74913e12017-11-08 13:31:40 +000065 setOperationAction(ISD::BR_CC, XLenVT, Expand);
Alex Bradbury65385162017-11-21 07:51:32 +000066 setOperationAction(ISD::SELECT, XLenVT, Custom);
67 setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
68
Alex Bradburybfb00d42017-12-11 12:38:17 +000069 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
70 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
71
Alex Bradburyc85be0d2018-01-10 19:41:03 +000072 setOperationAction(ISD::VASTART, MVT::Other, Custom);
73 setOperationAction(ISD::VAARG, MVT::Other, Expand);
74 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
75 setOperationAction(ISD::VAEND, MVT::Other, Expand);
76
Alex Bradburyffc435e2017-11-21 08:11:03 +000077 for (auto VT : {MVT::i1, MVT::i8, MVT::i16})
78 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
79
80 setOperationAction(ISD::ADDC, XLenVT, Expand);
81 setOperationAction(ISD::ADDE, XLenVT, Expand);
82 setOperationAction(ISD::SUBC, XLenVT, Expand);
83 setOperationAction(ISD::SUBE, XLenVT, Expand);
84
Alex Bradbury92138382018-01-18 12:36:38 +000085 if (!Subtarget.hasStdExtM()) {
86 setOperationAction(ISD::MUL, XLenVT, Expand);
87 setOperationAction(ISD::MULHS, XLenVT, Expand);
88 setOperationAction(ISD::MULHU, XLenVT, Expand);
89 setOperationAction(ISD::SDIV, XLenVT, Expand);
90 setOperationAction(ISD::UDIV, XLenVT, Expand);
91 setOperationAction(ISD::SREM, XLenVT, Expand);
92 setOperationAction(ISD::UREM, XLenVT, Expand);
93 }
Alex Bradburyffc435e2017-11-21 08:11:03 +000094
Alex Bradbury92138382018-01-18 12:36:38 +000095 setOperationAction(ISD::SDIVREM, XLenVT, Expand);
96 setOperationAction(ISD::UDIVREM, XLenVT, Expand);
Alex Bradburyffc435e2017-11-21 08:11:03 +000097 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
98 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
Alex Bradburyffc435e2017-11-21 08:11:03 +000099
100 setOperationAction(ISD::SHL_PARTS, XLenVT, Expand);
101 setOperationAction(ISD::SRL_PARTS, XLenVT, Expand);
102 setOperationAction(ISD::SRA_PARTS, XLenVT, Expand);
103
104 setOperationAction(ISD::ROTL, XLenVT, Expand);
105 setOperationAction(ISD::ROTR, XLenVT, Expand);
106 setOperationAction(ISD::BSWAP, XLenVT, Expand);
107 setOperationAction(ISD::CTTZ, XLenVT, Expand);
108 setOperationAction(ISD::CTLZ, XLenVT, Expand);
109 setOperationAction(ISD::CTPOP, XLenVT, Expand);
110
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000111 ISD::CondCode FPCCToExtend[] = {
112 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETO, ISD::SETUEQ,
113 ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE,
114 ISD::SETGT, ISD::SETGE, ISD::SETNE};
115
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000116 if (Subtarget.hasStdExtF()) {
117 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
118 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000119 for (auto CC : FPCCToExtend)
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000120 setCondCodeAction(CC, MVT::f32, Expand);
121 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
122 setOperationAction(ISD::SELECT, MVT::f32, Custom);
123 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000124 }
125
Alex Bradbury5d0dfa52018-04-12 05:42:42 +0000126 if (Subtarget.hasStdExtD()) {
127 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
128 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000129 for (auto CC : FPCCToExtend)
130 setCondCodeAction(CC, MVT::f64, Expand);
131 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
132 setOperationAction(ISD::SELECT, MVT::f64, Custom);
133 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000134 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
Alex Bradbury60baa2e2018-04-12 05:47:15 +0000135 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
Alex Bradbury5d0dfa52018-04-12 05:42:42 +0000136 }
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000137
Alex Bradburyffc435e2017-11-21 08:11:03 +0000138 setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
139 setOperationAction(ISD::BlockAddress, XLenVT, Custom);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000140 setOperationAction(ISD::ConstantPool, XLenVT, Custom);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000141
Alex Bradbury89718422017-10-19 21:37:38 +0000142 setBooleanContents(ZeroOrOneBooleanContent);
143
144 // Function alignments (log2).
Shiva Chenb48b0272018-04-12 11:30:59 +0000145 unsigned FunctionAlignment = Subtarget.hasStdExtC() ? 1 : 2;
146 setMinFunctionAlignment(FunctionAlignment);
147 setPrefFunctionAlignment(FunctionAlignment);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000148
149 // Effectively disable jump table generation.
150 setMinimumJumpTableEntries(INT_MAX);
Alex Bradbury89718422017-10-19 21:37:38 +0000151}
152
Shiva Chenbbf4c5c2018-02-02 02:43:18 +0000153EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
154 EVT VT) const {
155 if (!VT.isVector())
156 return getPointerTy(DL);
157 return VT.changeVectorElementTypeToInteger();
158}
159
Alex Bradbury09926292018-04-26 12:13:48 +0000160bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
161 const AddrMode &AM, Type *Ty,
162 unsigned AS,
163 Instruction *I) const {
164 // No global is ever allowed as a base.
165 if (AM.BaseGV)
166 return false;
167
168 // Require a 12-bit signed offset.
169 if (!isInt<12>(AM.BaseOffs))
170 return false;
171
172 switch (AM.Scale) {
173 case 0: // "r+i" or just "i", depending on HasBaseReg.
174 break;
175 case 1:
176 if (!AM.HasBaseReg) // allow "r+i".
177 break;
178 return false; // disallow "r+r" or "r+r+i".
179 default:
180 return false;
181 }
182
183 return true;
184}
185
Alex Bradburydcbff632018-04-26 13:15:17 +0000186bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
187 return isInt<12>(Imm);
188}
189
Alex Bradbury5c41ece2018-04-26 13:00:37 +0000190bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
191 return isInt<12>(Imm);
192}
193
Alex Bradbury130b8b32018-04-26 13:37:00 +0000194// On RV32, 64-bit integers are split into their high and low parts and held
195// in two different registers, so the trunc is free since the low register can
196// just be used.
197bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
198 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
199 return false;
200 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
201 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
202 return (SrcBits == 64 && DestBits == 32);
203}
204
205bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
206 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
207 !SrcVT.isInteger() || !DstVT.isInteger())
208 return false;
209 unsigned SrcBits = SrcVT.getSizeInBits();
210 unsigned DestBits = DstVT.getSizeInBits();
211 return (SrcBits == 64 && DestBits == 32);
212}
213
Alex Bradbury15e894b2018-04-26 14:04:18 +0000214bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
215 // Zexts are free if they can be combined with a load.
216 if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
217 EVT MemVT = LD->getMemoryVT();
218 if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
219 (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
220 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
221 LD->getExtensionType() == ISD::ZEXTLOAD))
222 return true;
223 }
224
225 return TargetLowering::isZExtFree(Val, VT2);
226}
227
Alex Bradbury65385162017-11-21 07:51:32 +0000228// Changes the condition code and swaps operands if necessary, so the SetCC
229// operation matches one of the comparisons supported directly in the RISC-V
230// ISA.
231static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
232 switch (CC) {
233 default:
234 break;
235 case ISD::SETGT:
236 case ISD::SETLE:
237 case ISD::SETUGT:
238 case ISD::SETULE:
239 CC = ISD::getSetCCSwappedOperands(CC);
240 std::swap(LHS, RHS);
241 break;
242 }
243}
244
245// Return the RISC-V branch opcode that matches the given DAG integer
246// condition code. The CondCode must be one of those supported by the RISC-V
247// ISA (see normaliseSetCC).
248static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
249 switch (CC) {
250 default:
251 llvm_unreachable("Unsupported CondCode");
252 case ISD::SETEQ:
253 return RISCV::BEQ;
254 case ISD::SETNE:
255 return RISCV::BNE;
256 case ISD::SETLT:
257 return RISCV::BLT;
258 case ISD::SETGE:
259 return RISCV::BGE;
260 case ISD::SETULT:
261 return RISCV::BLTU;
262 case ISD::SETUGE:
263 return RISCV::BGEU;
264 }
265}
266
Alex Bradbury89718422017-10-19 21:37:38 +0000267SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
268 SelectionDAG &DAG) const {
269 switch (Op.getOpcode()) {
270 default:
271 report_fatal_error("unimplemented operand");
Alex Bradburyec8aa912017-11-08 13:24:21 +0000272 case ISD::GlobalAddress:
273 return lowerGlobalAddress(Op, DAG);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000274 case ISD::BlockAddress:
275 return lowerBlockAddress(Op, DAG);
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000276 case ISD::ConstantPool:
277 return lowerConstantPool(Op, DAG);
Alex Bradbury65385162017-11-21 07:51:32 +0000278 case ISD::SELECT:
279 return lowerSELECT(Op, DAG);
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000280 case ISD::VASTART:
281 return lowerVASTART(Op, DAG);
Alex Bradbury70f137b2018-01-10 20:12:00 +0000282 case ISD::FRAMEADDR:
283 return LowerFRAMEADDR(Op, DAG);
284 case ISD::RETURNADDR:
285 return LowerRETURNADDR(Op, DAG);
Alex Bradburyec8aa912017-11-08 13:24:21 +0000286 }
287}
288
289SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
290 SelectionDAG &DAG) const {
291 SDLoc DL(Op);
292 EVT Ty = Op.getValueType();
293 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
294 const GlobalValue *GV = N->getGlobal();
295 int64_t Offset = N->getOffset();
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000296 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburyec8aa912017-11-08 13:24:21 +0000297
Alex Bradburyffc435e2017-11-21 08:11:03 +0000298 if (isPositionIndependent() || Subtarget.is64Bit())
Alex Bradburyec8aa912017-11-08 13:24:21 +0000299 report_fatal_error("Unable to lowerGlobalAddress");
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000300 // In order to maximise the opportunity for common subexpression elimination,
301 // emit a separate ADD node for the global address offset instead of folding
302 // it in the global address node. Later peephole optimisations may choose to
303 // fold it back in when profitable.
304 SDValue GAHi = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_HI);
305 SDValue GALo = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_LO);
Alex Bradburyffc435e2017-11-21 08:11:03 +0000306 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
307 SDValue MNLo =
308 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
Sameer AbuAsal1dc0a8f2018-05-17 18:14:53 +0000309 if (Offset != 0)
310 return DAG.getNode(ISD::ADD, DL, Ty, MNLo,
311 DAG.getConstant(Offset, DL, XLenVT));
Alex Bradburyffc435e2017-11-21 08:11:03 +0000312 return MNLo;
313}
314
315SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
316 SelectionDAG &DAG) const {
317 SDLoc DL(Op);
318 EVT Ty = Op.getValueType();
319 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
320 const BlockAddress *BA = N->getBlockAddress();
321 int64_t Offset = N->getOffset();
322
323 if (isPositionIndependent() || Subtarget.is64Bit())
324 report_fatal_error("Unable to lowerBlockAddress");
325
326 SDValue BAHi = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_HI);
327 SDValue BALo = DAG.getTargetBlockAddress(BA, Ty, Offset, RISCVII::MO_LO);
328 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, BAHi), 0);
329 SDValue MNLo =
330 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, BALo), 0);
331 return MNLo;
332}
333
Alex Bradbury80c8eb72018-03-20 13:26:12 +0000334SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
335 SelectionDAG &DAG) const {
336 SDLoc DL(Op);
337 EVT Ty = Op.getValueType();
338 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
339 const Constant *CPA = N->getConstVal();
340 int64_t Offset = N->getOffset();
341 unsigned Alignment = N->getAlignment();
342
343 if (!isPositionIndependent()) {
344 SDValue CPAHi =
345 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_HI);
346 SDValue CPALo =
347 DAG.getTargetConstantPool(CPA, Ty, Alignment, Offset, RISCVII::MO_LO);
348 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, CPAHi), 0);
349 SDValue MNLo =
350 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, CPALo), 0);
351 return MNLo;
352 } else {
353 report_fatal_error("Unable to lowerConstantPool");
354 }
355}
356
Alex Bradburyffc435e2017-11-21 08:11:03 +0000357SDValue RISCVTargetLowering::lowerExternalSymbol(SDValue Op,
358 SelectionDAG &DAG) const {
359 SDLoc DL(Op);
360 EVT Ty = Op.getValueType();
361 ExternalSymbolSDNode *N = cast<ExternalSymbolSDNode>(Op);
362 const char *Sym = N->getSymbol();
363
364 // TODO: should also handle gp-relative loads.
365
366 if (isPositionIndependent() || Subtarget.is64Bit())
367 report_fatal_error("Unable to lowerExternalSymbol");
368
369 SDValue GAHi = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_HI);
370 SDValue GALo = DAG.getTargetExternalSymbol(Sym, Ty, RISCVII::MO_LO);
371 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, GAHi), 0);
372 SDValue MNLo =
373 SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, GALo), 0);
374 return MNLo;
Alex Bradbury89718422017-10-19 21:37:38 +0000375}
376
Alex Bradbury65385162017-11-21 07:51:32 +0000377SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
378 SDValue CondV = Op.getOperand(0);
379 SDValue TrueV = Op.getOperand(1);
380 SDValue FalseV = Op.getOperand(2);
381 SDLoc DL(Op);
382 MVT XLenVT = Subtarget.getXLenVT();
383
384 // If the result type is XLenVT and CondV is the output of a SETCC node
385 // which also operated on XLenVT inputs, then merge the SETCC node into the
386 // lowered RISCVISD::SELECT_CC to take advantage of the integer
387 // compare+branch instructions. i.e.:
388 // (select (setcc lhs, rhs, cc), truev, falsev)
389 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
390 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
391 CondV.getOperand(0).getSimpleValueType() == XLenVT) {
392 SDValue LHS = CondV.getOperand(0);
393 SDValue RHS = CondV.getOperand(1);
394 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
395 ISD::CondCode CCVal = CC->get();
396
397 normaliseSetCC(LHS, RHS, CCVal);
398
399 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
400 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
401 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
402 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
403 }
404
405 // Otherwise:
406 // (select condv, truev, falsev)
407 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
408 SDValue Zero = DAG.getConstant(0, DL, XLenVT);
409 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
410
411 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
412 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
413
414 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
415}
416
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000417SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
418 MachineFunction &MF = DAG.getMachineFunction();
419 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
420
421 SDLoc DL(Op);
422 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
423 getPointerTy(MF.getDataLayout()));
424
425 // vastart just stores the address of the VarArgsFrameIndex slot into the
426 // memory location argument.
427 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
428 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
429 MachinePointerInfo(SV));
430}
431
Alex Bradbury70f137b2018-01-10 20:12:00 +0000432SDValue RISCVTargetLowering::LowerFRAMEADDR(SDValue Op,
433 SelectionDAG &DAG) const {
434 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
435 MachineFunction &MF = DAG.getMachineFunction();
436 MachineFrameInfo &MFI = MF.getFrameInfo();
437 MFI.setFrameAddressIsTaken(true);
438 unsigned FrameReg = RI.getFrameRegister(MF);
439 int XLenInBytes = Subtarget.getXLen() / 8;
440
441 EVT VT = Op.getValueType();
442 SDLoc DL(Op);
443 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
444 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
445 while (Depth--) {
446 int Offset = -(XLenInBytes * 2);
447 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
448 DAG.getIntPtrConstant(Offset, DL));
449 FrameAddr =
450 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
451 }
452 return FrameAddr;
453}
454
455SDValue RISCVTargetLowering::LowerRETURNADDR(SDValue Op,
456 SelectionDAG &DAG) const {
457 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
458 MachineFunction &MF = DAG.getMachineFunction();
459 MachineFrameInfo &MFI = MF.getFrameInfo();
460 MFI.setReturnAddressIsTaken(true);
461 MVT XLenVT = Subtarget.getXLenVT();
462 int XLenInBytes = Subtarget.getXLen() / 8;
463
464 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
465 return SDValue();
466
467 EVT VT = Op.getValueType();
468 SDLoc DL(Op);
469 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
470 if (Depth) {
471 int Off = -XLenInBytes;
472 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
473 SDValue Offset = DAG.getConstant(Off, DL, VT);
474 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
475 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
476 MachinePointerInfo());
477 }
478
479 // Return the value of the return address register, marking it an implicit
480 // live-in.
481 unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
482 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
483}
484
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000485static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
486 MachineBasicBlock *BB) {
487 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
488
489 MachineFunction &MF = *BB->getParent();
490 DebugLoc DL = MI.getDebugLoc();
491 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
492 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
493 unsigned LoReg = MI.getOperand(0).getReg();
494 unsigned HiReg = MI.getOperand(1).getReg();
495 unsigned SrcReg = MI.getOperand(2).getReg();
496 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
497 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
498
499 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
500 RI);
501 MachineMemOperand *MMO =
502 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
503 MachineMemOperand::MOLoad, 8, 8);
504 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
505 .addFrameIndex(FI)
506 .addImm(0)
507 .addMemOperand(MMO);
508 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
509 .addFrameIndex(FI)
510 .addImm(4)
511 .addMemOperand(MMO);
512 MI.eraseFromParent(); // The pseudo instruction is gone now.
513 return BB;
514}
515
516static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
517 MachineBasicBlock *BB) {
518 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
519 "Unexpected instruction");
520
521 MachineFunction &MF = *BB->getParent();
522 DebugLoc DL = MI.getDebugLoc();
523 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
524 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
525 unsigned DstReg = MI.getOperand(0).getReg();
526 unsigned LoReg = MI.getOperand(1).getReg();
527 unsigned HiReg = MI.getOperand(2).getReg();
528 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
529 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
530
531 MachineMemOperand *MMO =
532 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
533 MachineMemOperand::MOStore, 8, 8);
534 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
535 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
536 .addFrameIndex(FI)
537 .addImm(0)
538 .addMemOperand(MMO);
539 BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
540 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
541 .addFrameIndex(FI)
542 .addImm(4)
543 .addMemOperand(MMO);
544 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
545 MI.eraseFromParent(); // The pseudo instruction is gone now.
546 return BB;
547}
548
Alex Bradbury65385162017-11-21 07:51:32 +0000549MachineBasicBlock *
550RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
551 MachineBasicBlock *BB) const {
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000552 switch (MI.getOpcode()) {
553 default:
554 llvm_unreachable("Unexpected instr type to insert");
555 case RISCV::Select_GPR_Using_CC_GPR:
556 case RISCV::Select_FPR32_Using_CC_GPR:
Alex Bradbury21d28fe2018-04-12 05:50:06 +0000557 case RISCV::Select_FPR64_Using_CC_GPR:
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000558 break;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000559 case RISCV::BuildPairF64Pseudo:
560 return emitBuildPairF64Pseudo(MI, BB);
561 case RISCV::SplitF64Pseudo:
562 return emitSplitF64Pseudo(MI, BB);
Alex Bradbury65d6ea52018-03-21 15:11:02 +0000563 }
Alex Bradbury65385162017-11-21 07:51:32 +0000564
565 // To "insert" a SELECT instruction, we actually have to insert the triangle
566 // control-flow pattern. The incoming instruction knows the destination vreg
567 // to set, the condition code register to branch on, the true/false values to
568 // select between, and the condcode to use to select the appropriate branch.
569 //
570 // We produce the following control flow:
571 // HeadMBB
572 // | \
573 // | IfFalseMBB
574 // | /
575 // TailMBB
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000576 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
Alex Bradbury65385162017-11-21 07:51:32 +0000577 const BasicBlock *LLVM_BB = BB->getBasicBlock();
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000578 DebugLoc DL = MI.getDebugLoc();
Alex Bradbury65385162017-11-21 07:51:32 +0000579 MachineFunction::iterator I = ++BB->getIterator();
580
581 MachineBasicBlock *HeadMBB = BB;
582 MachineFunction *F = BB->getParent();
583 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
584 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
585
586 F->insert(I, IfFalseMBB);
587 F->insert(I, TailMBB);
588 // Move all remaining instructions to TailMBB.
589 TailMBB->splice(TailMBB->begin(), HeadMBB,
590 std::next(MachineBasicBlock::iterator(MI)), HeadMBB->end());
591 // Update machine-CFG edges by transferring all successors of the current
592 // block to the new block which will contain the Phi node for the select.
593 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
594 // Set the successors for HeadMBB.
595 HeadMBB->addSuccessor(IfFalseMBB);
596 HeadMBB->addSuccessor(TailMBB);
597
598 // Insert appropriate branch.
599 unsigned LHS = MI.getOperand(1).getReg();
600 unsigned RHS = MI.getOperand(2).getReg();
601 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
602 unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
603
604 BuildMI(HeadMBB, DL, TII.get(Opcode))
605 .addReg(LHS)
606 .addReg(RHS)
607 .addMBB(TailMBB);
608
609 // IfFalseMBB just falls through to TailMBB.
610 IfFalseMBB->addSuccessor(TailMBB);
611
612 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
613 BuildMI(*TailMBB, TailMBB->begin(), DL, TII.get(RISCV::PHI),
614 MI.getOperand(0).getReg())
615 .addReg(MI.getOperand(4).getReg())
616 .addMBB(HeadMBB)
617 .addReg(MI.getOperand(5).getReg())
618 .addMBB(IfFalseMBB);
619
620 MI.eraseFromParent(); // The pseudo instruction is gone now.
621 return TailMBB;
622}
623
Alex Bradbury89718422017-10-19 21:37:38 +0000624// Calling Convention Implementation.
Alex Bradburydc31c612017-12-11 12:49:02 +0000625// The expectations for frontend ABI lowering vary from target to target.
626// Ideally, an LLVM frontend would be able to avoid worrying about many ABI
627// details, but this is a longer term goal. For now, we simply try to keep the
628// role of the frontend as simple and well-defined as possible. The rules can
629// be summarised as:
630// * Never split up large scalar arguments. We handle them here.
631// * If a hardfloat calling convention is being used, and the struct may be
632// passed in a pair of registers (fp+fp, int+fp), and both registers are
633// available, then pass as two separate arguments. If either the GPRs or FPRs
634// are exhausted, then pass according to the rule below.
635// * If a struct could never be passed in registers or directly in a stack
636// slot (as it is larger than 2*XLEN and the floating point rules don't
637// apply), then pass it using a pointer with the byval attribute.
638// * If a struct is less than 2*XLEN, then coerce to either a two-element
639// word-sized array or a 2*XLEN scalar (depending on alignment).
640// * The frontend can determine whether a struct is returned by reference or
641// not based on its size and fields. If it will be returned by reference, the
642// frontend must modify the prototype so a pointer with the sret annotation is
643// passed as the first argument. This is not necessary for large scalar
644// returns.
645// * Struct return values and varargs should be coerced to structs containing
646// register-size fields in the same situations they would be for fixed
647// arguments.
648
649static const MCPhysReg ArgGPRs[] = {
650 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
651 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
652};
653
654// Pass a 2*XLEN argument that has been split into two XLEN values through
655// registers or the stack as necessary.
656static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
657 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
658 MVT ValVT2, MVT LocVT2,
659 ISD::ArgFlagsTy ArgFlags2) {
660 unsigned XLenInBytes = XLen / 8;
661 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
662 // At least one half can be passed via register.
663 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
664 VA1.getLocVT(), CCValAssign::Full));
665 } else {
666 // Both halves must be passed on the stack, with proper alignment.
667 unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
668 State.addLoc(
669 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
670 State.AllocateStack(XLenInBytes, StackAlign),
671 VA1.getLocVT(), CCValAssign::Full));
672 State.addLoc(CCValAssign::getMem(
673 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
674 CCValAssign::Full));
675 return false;
676 }
677
678 if (unsigned Reg = State.AllocateReg(ArgGPRs)) {
679 // The second half can also be passed via register.
680 State.addLoc(
681 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
682 } else {
683 // The second half is passed via the stack, without additional alignment.
684 State.addLoc(CCValAssign::getMem(
685 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
686 CCValAssign::Full));
687 }
688
689 return false;
690}
691
692// Implements the RISC-V calling convention. Returns true upon failure.
693static bool CC_RISCV(const DataLayout &DL, unsigned ValNo, MVT ValVT, MVT LocVT,
694 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000695 CCState &State, bool IsFixed, bool IsRet, Type *OrigTy) {
Alex Bradburydc31c612017-12-11 12:49:02 +0000696 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
697 assert(XLen == 32 || XLen == 64);
698 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000699 if (ValVT == MVT::f32) {
700 LocVT = MVT::i32;
701 LocInfo = CCValAssign::BCvt;
702 }
Alex Bradburydc31c612017-12-11 12:49:02 +0000703
704 // Any return value split in to more than two values can't be returned
705 // directly.
706 if (IsRet && ValNo > 1)
707 return true;
708
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000709 // If this is a variadic argument, the RISC-V calling convention requires
710 // that it is assigned an 'even' or 'aligned' register if it has 8-byte
711 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
712 // be used regardless of whether the original argument was split during
713 // legalisation or not. The argument will not be passed by registers if the
714 // original type is larger than 2*XLEN, so the register alignment rule does
715 // not apply.
716 unsigned TwoXLenInBytes = (2 * XLen) / 8;
717 if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
718 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
719 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
720 // Skip 'odd' register if necessary.
721 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
722 State.AllocateReg(ArgGPRs);
723 }
724
Alex Bradburydc31c612017-12-11 12:49:02 +0000725 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
726 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
727 State.getPendingArgFlags();
728
729 assert(PendingLocs.size() == PendingArgFlags.size() &&
730 "PendingLocs and PendingArgFlags out of sync");
731
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000732 // Handle passing f64 on RV32D with a soft float ABI.
733 if (XLen == 32 && ValVT == MVT::f64) {
Mandeep Singh Grang88a8b262018-04-16 18:56:10 +0000734 assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000735 "Can't lower f64 if it is split");
736 // Depending on available argument GPRS, f64 may be passed in a pair of
737 // GPRs, split between a GPR and the stack, or passed completely on the
738 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
739 // cases.
740 unsigned Reg = State.AllocateReg(ArgGPRs);
741 LocVT = MVT::i32;
742 if (!Reg) {
743 unsigned StackOffset = State.AllocateStack(8, 8);
744 State.addLoc(
745 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
746 return false;
747 }
748 if (!State.AllocateReg(ArgGPRs))
749 State.AllocateStack(4, 4);
750 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
751 return false;
752 }
753
Alex Bradburydc31c612017-12-11 12:49:02 +0000754 // Split arguments might be passed indirectly, so keep track of the pending
755 // values.
756 if (ArgFlags.isSplit() || !PendingLocs.empty()) {
757 LocVT = XLenVT;
758 LocInfo = CCValAssign::Indirect;
759 PendingLocs.push_back(
760 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
761 PendingArgFlags.push_back(ArgFlags);
762 if (!ArgFlags.isSplitEnd()) {
763 return false;
764 }
765 }
766
767 // If the split argument only had two elements, it should be passed directly
768 // in registers or on the stack.
769 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
770 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
771 // Apply the normal calling convention rules to the first half of the
772 // split argument.
773 CCValAssign VA = PendingLocs[0];
774 ISD::ArgFlagsTy AF = PendingArgFlags[0];
775 PendingLocs.clear();
776 PendingArgFlags.clear();
777 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
778 ArgFlags);
779 }
780
781 // Allocate to a register if possible, or else a stack slot.
782 unsigned Reg = State.AllocateReg(ArgGPRs);
783 unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
784
785 // If we reach this point and PendingLocs is non-empty, we must be at the
786 // end of a split argument that must be passed indirectly.
787 if (!PendingLocs.empty()) {
788 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
789 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
790
791 for (auto &It : PendingLocs) {
792 if (Reg)
793 It.convertToReg(Reg);
794 else
795 It.convertToMem(StackOffset);
796 State.addLoc(It);
797 }
798 PendingLocs.clear();
799 PendingArgFlags.clear();
800 return false;
801 }
802
803 assert(LocVT == XLenVT && "Expected an XLenVT at this stage");
804
805 if (Reg) {
806 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
807 } else {
808 State.addLoc(
809 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
810 }
811 return false;
812}
813
814void RISCVTargetLowering::analyzeInputArgs(
815 MachineFunction &MF, CCState &CCInfo,
816 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
817 unsigned NumArgs = Ins.size();
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000818 FunctionType *FType = MF.getFunction().getFunctionType();
Alex Bradburydc31c612017-12-11 12:49:02 +0000819
820 for (unsigned i = 0; i != NumArgs; ++i) {
821 MVT ArgVT = Ins[i].VT;
822 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
823
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000824 Type *ArgTy = nullptr;
825 if (IsRet)
826 ArgTy = FType->getReturnType();
827 else if (Ins[i].isOrigArg())
828 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
829
Alex Bradburydc31c612017-12-11 12:49:02 +0000830 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000831 ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000832 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
833 << EVT(ArgVT).getEVTString() << '\n');
Alex Bradburydc31c612017-12-11 12:49:02 +0000834 llvm_unreachable(nullptr);
835 }
836 }
837}
838
839void RISCVTargetLowering::analyzeOutputArgs(
840 MachineFunction &MF, CCState &CCInfo,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000841 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
842 CallLoweringInfo *CLI) const {
Alex Bradburydc31c612017-12-11 12:49:02 +0000843 unsigned NumArgs = Outs.size();
844
845 for (unsigned i = 0; i != NumArgs; i++) {
846 MVT ArgVT = Outs[i].VT;
847 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000848 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
Alex Bradburydc31c612017-12-11 12:49:02 +0000849
850 if (CC_RISCV(MF.getDataLayout(), i, ArgVT, ArgVT, CCValAssign::Full,
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000851 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000852 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
853 << EVT(ArgVT).getEVTString() << "\n");
Alex Bradburydc31c612017-12-11 12:49:02 +0000854 llvm_unreachable(nullptr);
855 }
856 }
857}
858
859// The caller is responsible for loading the full value if the argument is
860// passed with CCValAssign::Indirect.
861static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
862 const CCValAssign &VA, const SDLoc &DL) {
863 MachineFunction &MF = DAG.getMachineFunction();
864 MachineRegisterInfo &RegInfo = MF.getRegInfo();
865 EVT LocVT = VA.getLocVT();
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000866 EVT ValVT = VA.getValVT();
Alex Bradburydc31c612017-12-11 12:49:02 +0000867 SDValue Val;
868
869 unsigned VReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
870 RegInfo.addLiveIn(VA.getLocReg(), VReg);
871 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
872
873 switch (VA.getLocInfo()) {
874 default:
875 llvm_unreachable("Unexpected CCValAssign::LocInfo");
876 case CCValAssign::Full:
877 case CCValAssign::Indirect:
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000878 break;
879 case CCValAssign::BCvt:
880 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
881 break;
Alex Bradburydc31c612017-12-11 12:49:02 +0000882 }
Alex Bradbury76c29ee2018-03-20 12:45:35 +0000883 return Val;
Alex Bradburydc31c612017-12-11 12:49:02 +0000884}
885
886// The caller is responsible for loading the full value if the argument is
887// passed with CCValAssign::Indirect.
888static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
889 const CCValAssign &VA, const SDLoc &DL) {
890 MachineFunction &MF = DAG.getMachineFunction();
891 MachineFrameInfo &MFI = MF.getFrameInfo();
892 EVT LocVT = VA.getLocVT();
893 EVT ValVT = VA.getValVT();
894 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
895 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
896 VA.getLocMemOffset(), /*Immutable=*/true);
897 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
898 SDValue Val;
899
900 ISD::LoadExtType ExtType;
901 switch (VA.getLocInfo()) {
902 default:
903 llvm_unreachable("Unexpected CCValAssign::LocInfo");
904 case CCValAssign::Full:
905 case CCValAssign::Indirect:
906 ExtType = ISD::NON_EXTLOAD;
907 break;
908 }
909 Val = DAG.getExtLoad(
910 ExtType, DL, LocVT, Chain, FIN,
911 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
912 return Val;
913}
Alex Bradbury89718422017-10-19 21:37:38 +0000914
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000915static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
916 const CCValAssign &VA, const SDLoc &DL) {
917 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
918 "Unexpected VA");
919 MachineFunction &MF = DAG.getMachineFunction();
920 MachineFrameInfo &MFI = MF.getFrameInfo();
921 MachineRegisterInfo &RegInfo = MF.getRegInfo();
922
923 if (VA.isMemLoc()) {
924 // f64 is passed on the stack.
925 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
926 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
927 return DAG.getLoad(MVT::f64, DL, Chain, FIN,
928 MachinePointerInfo::getFixedStack(MF, FI));
929 }
930
931 assert(VA.isRegLoc() && "Expected register VA assignment");
932
933 unsigned LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
934 RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
935 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
936 SDValue Hi;
937 if (VA.getLocReg() == RISCV::X17) {
938 // Second half of f64 is passed on the stack.
939 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
940 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
941 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
942 MachinePointerInfo::getFixedStack(MF, FI));
943 } else {
944 // Second half of f64 is passed in another GPR.
945 unsigned HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
946 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
947 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
948 }
949 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
950}
951
Alex Bradbury89718422017-10-19 21:37:38 +0000952// Transform physical registers into virtual registers.
953SDValue RISCVTargetLowering::LowerFormalArguments(
954 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
955 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
956 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
957
958 switch (CallConv) {
959 default:
960 report_fatal_error("Unsupported calling convention");
961 case CallingConv::C:
Alex Bradburya3376752017-11-08 13:41:21 +0000962 case CallingConv::Fast:
Alex Bradbury89718422017-10-19 21:37:38 +0000963 break;
964 }
965
966 MachineFunction &MF = DAG.getMachineFunction();
Alex Bradburydc31c612017-12-11 12:49:02 +0000967 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000968 MVT XLenVT = Subtarget.getXLenVT();
969 unsigned XLenInBytes = Subtarget.getXLen() / 8;
970 // Used with vargs to acumulate store chains.
971 std::vector<SDValue> OutChains;
Alex Bradbury89718422017-10-19 21:37:38 +0000972
973 // Assign locations to all of the incoming arguments.
974 SmallVector<CCValAssign, 16> ArgLocs;
975 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +0000976 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
Alex Bradbury89718422017-10-19 21:37:38 +0000977
Alex Bradburydc31c612017-12-11 12:49:02 +0000978 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
979 CCValAssign &VA = ArgLocs[i];
Alex Bradburyc85be0d2018-01-10 19:41:03 +0000980 assert(VA.getLocVT() == XLenVT && "Unhandled argument type");
Alex Bradburydc31c612017-12-11 12:49:02 +0000981 SDValue ArgValue;
Alex Bradbury0b4175f2018-04-12 05:34:25 +0000982 // Passing f64 on RV32D with a soft float ABI must be handled as a special
983 // case.
984 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
985 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
986 else if (VA.isRegLoc())
Alex Bradburydc31c612017-12-11 12:49:02 +0000987 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
988 else
989 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
Alex Bradbury89718422017-10-19 21:37:38 +0000990
Alex Bradburydc31c612017-12-11 12:49:02 +0000991 if (VA.getLocInfo() == CCValAssign::Indirect) {
992 // If the original argument was split and passed by reference (e.g. i128
993 // on RV32), we need to load all parts of it here (using the same
994 // address).
995 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
996 MachinePointerInfo()));
997 unsigned ArgIndex = Ins[i].OrigArgIndex;
998 assert(Ins[i].PartOffset == 0);
999 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
1000 CCValAssign &PartVA = ArgLocs[i + 1];
1001 unsigned PartOffset = Ins[i + 1].PartOffset;
1002 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1003 DAG.getIntPtrConstant(PartOffset, DL));
1004 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1005 MachinePointerInfo()));
1006 ++i;
1007 }
1008 continue;
Alex Bradbury89718422017-10-19 21:37:38 +00001009 }
Alex Bradburydc31c612017-12-11 12:49:02 +00001010 InVals.push_back(ArgValue);
Alex Bradbury89718422017-10-19 21:37:38 +00001011 }
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001012
1013 if (IsVarArg) {
1014 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
1015 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
1016 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1017 MachineFrameInfo &MFI = MF.getFrameInfo();
1018 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1019 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1020
1021 // Offset of the first variable argument from stack pointer, and size of
1022 // the vararg save area. For now, the varargs save area is either zero or
1023 // large enough to hold a0-a7.
1024 int VaArgOffset, VarArgsSaveSize;
1025
1026 // If all registers are allocated, then all varargs must be passed on the
1027 // stack and we don't need to save any argregs.
1028 if (ArgRegs.size() == Idx) {
1029 VaArgOffset = CCInfo.getNextStackOffset();
1030 VarArgsSaveSize = 0;
1031 } else {
1032 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1033 VaArgOffset = -VarArgsSaveSize;
1034 }
1035
1036 // Record the frame index of the first variable argument
1037 // which is a value necessary to VASTART.
1038 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1039 RVFI->setVarArgsFrameIndex(FI);
1040
1041 // If saving an odd number of registers then create an extra stack slot to
1042 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1043 // offsets to even-numbered registered remain 2*XLEN-aligned.
1044 if (Idx % 2) {
1045 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes,
1046 true);
1047 VarArgsSaveSize += XLenInBytes;
1048 }
1049
1050 // Copy the integer registers that may have been used for passing varargs
1051 // to the vararg save area.
1052 for (unsigned I = Idx; I < ArgRegs.size();
1053 ++I, VaArgOffset += XLenInBytes) {
1054 const unsigned Reg = RegInfo.createVirtualRegister(RC);
1055 RegInfo.addLiveIn(ArgRegs[I], Reg);
1056 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1057 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1058 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1059 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
1060 MachinePointerInfo::getFixedStack(MF, FI));
1061 cast<StoreSDNode>(Store.getNode())
1062 ->getMemOperand()
1063 ->setValue((Value *)nullptr);
1064 OutChains.push_back(Store);
1065 }
1066 RVFI->setVarArgsSaveSize(VarArgsSaveSize);
1067 }
1068
1069 // All stores are grouped in one node to allow the matching between
1070 // the size of Ins and InVals. This only happens for vararg functions.
1071 if (!OutChains.empty()) {
1072 OutChains.push_back(Chain);
1073 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1074 }
1075
Alex Bradbury89718422017-10-19 21:37:38 +00001076 return Chain;
1077}
1078
Alex Bradburya3376752017-11-08 13:41:21 +00001079// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
1080// and output parameter nodes.
1081SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
1082 SmallVectorImpl<SDValue> &InVals) const {
1083 SelectionDAG &DAG = CLI.DAG;
1084 SDLoc &DL = CLI.DL;
1085 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1086 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1087 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1088 SDValue Chain = CLI.Chain;
1089 SDValue Callee = CLI.Callee;
1090 CLI.IsTailCall = false;
1091 CallingConv::ID CallConv = CLI.CallConv;
1092 bool IsVarArg = CLI.IsVarArg;
1093 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Alex Bradburydc31c612017-12-11 12:49:02 +00001094 MVT XLenVT = Subtarget.getXLenVT();
Alex Bradburya3376752017-11-08 13:41:21 +00001095
Alex Bradburya3376752017-11-08 13:41:21 +00001096 MachineFunction &MF = DAG.getMachineFunction();
1097
1098 // Analyze the operands of the call, assigning locations to each operand.
1099 SmallVector<CCValAssign, 16> ArgLocs;
1100 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001101 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
Alex Bradburya3376752017-11-08 13:41:21 +00001102
1103 // Get a count of how many bytes are to be pushed on the stack.
1104 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1105
Alex Bradburydc31c612017-12-11 12:49:02 +00001106 // Create local copies for byval args
1107 SmallVector<SDValue, 8> ByValArgs;
1108 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1109 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1110 if (!Flags.isByVal())
Alex Bradburya3376752017-11-08 13:41:21 +00001111 continue;
Alex Bradburydc31c612017-12-11 12:49:02 +00001112
1113 SDValue Arg = OutVals[i];
1114 unsigned Size = Flags.getByValSize();
1115 unsigned Align = Flags.getByValAlign();
1116
1117 int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
1118 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1119 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
1120
1121 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
1122 /*IsVolatile=*/false,
1123 /*AlwaysInline=*/false,
1124 /*isTailCall=*/false, MachinePointerInfo(),
1125 MachinePointerInfo());
1126 ByValArgs.push_back(FIPtr);
Alex Bradburya3376752017-11-08 13:41:21 +00001127 }
1128
1129 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
1130
1131 // Copy argument values to their designated locations.
1132 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
Alex Bradburydc31c612017-12-11 12:49:02 +00001133 SmallVector<SDValue, 8> MemOpChains;
Alex Bradburya3376752017-11-08 13:41:21 +00001134 SDValue StackPtr;
Alex Bradburydc31c612017-12-11 12:49:02 +00001135 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
1136 CCValAssign &VA = ArgLocs[i];
1137 SDValue ArgValue = OutVals[i];
1138 ISD::ArgFlagsTy Flags = Outs[i].Flags;
Alex Bradburya3376752017-11-08 13:41:21 +00001139
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001140 // Handle passing f64 on RV32D with a soft float ABI as a special case.
1141 bool IsF64OnRV32DSoftABI =
1142 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
1143 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
1144 SDValue SplitF64 = DAG.getNode(
1145 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
1146 SDValue Lo = SplitF64.getValue(0);
1147 SDValue Hi = SplitF64.getValue(1);
1148
1149 unsigned RegLo = VA.getLocReg();
1150 RegsToPass.push_back(std::make_pair(RegLo, Lo));
1151
1152 if (RegLo == RISCV::X17) {
1153 // Second half of f64 is passed on the stack.
1154 // Work out the address of the stack slot.
1155 if (!StackPtr.getNode())
1156 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1157 // Emit the store.
1158 MemOpChains.push_back(
1159 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
1160 } else {
1161 // Second half of f64 is passed in another GPR.
1162 unsigned RegHigh = RegLo + 1;
1163 RegsToPass.push_back(std::make_pair(RegHigh, Hi));
1164 }
1165 continue;
1166 }
1167
1168 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
1169 // as any other MemLoc.
1170
Alex Bradburya3376752017-11-08 13:41:21 +00001171 // Promote the value if needed.
Alex Bradburydc31c612017-12-11 12:49:02 +00001172 // For now, only handle fully promoted and indirect arguments.
Alex Bradburya3376752017-11-08 13:41:21 +00001173 switch (VA.getLocInfo()) {
1174 case CCValAssign::Full:
1175 break;
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001176 case CCValAssign::BCvt:
1177 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), ArgValue);
1178 break;
Alex Bradburydc31c612017-12-11 12:49:02 +00001179 case CCValAssign::Indirect: {
1180 // Store the argument in a stack slot and pass its address.
1181 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
1182 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1183 MemOpChains.push_back(
1184 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1185 MachinePointerInfo::getFixedStack(MF, FI)));
1186 // If the original argument was split (e.g. i128), we need
1187 // to store all parts of it here (and pass just one address).
1188 unsigned ArgIndex = Outs[i].OrigArgIndex;
1189 assert(Outs[i].PartOffset == 0);
1190 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
1191 SDValue PartValue = OutVals[i + 1];
1192 unsigned PartOffset = Outs[i + 1].PartOffset;
1193 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1194 DAG.getIntPtrConstant(PartOffset, DL));
1195 MemOpChains.push_back(
1196 DAG.getStore(Chain, DL, PartValue, Address,
1197 MachinePointerInfo::getFixedStack(MF, FI)));
1198 ++i;
1199 }
1200 ArgValue = SpillSlot;
1201 break;
1202 }
Alex Bradburya3376752017-11-08 13:41:21 +00001203 default:
1204 llvm_unreachable("Unknown loc info!");
1205 }
1206
Alex Bradburydc31c612017-12-11 12:49:02 +00001207 // Use local copy if it is a byval arg.
1208 if (Flags.isByVal())
1209 ArgValue = ByValArgs[j++];
1210
Alex Bradburya3376752017-11-08 13:41:21 +00001211 if (VA.isRegLoc()) {
1212 // Queue up the argument copies and emit them at the end.
1213 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1214 } else {
1215 assert(VA.isMemLoc() && "Argument not register or memory");
Alex Bradburydc31c612017-12-11 12:49:02 +00001216
1217 // Work out the address of the stack slot.
1218 if (!StackPtr.getNode())
1219 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
1220 SDValue Address =
1221 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1222 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
1223
1224 // Emit the store.
1225 MemOpChains.push_back(
1226 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
Alex Bradburya3376752017-11-08 13:41:21 +00001227 }
1228 }
1229
Alex Bradburydc31c612017-12-11 12:49:02 +00001230 // Join the stores, which are independent of one another.
1231 if (!MemOpChains.empty())
1232 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1233
Alex Bradburya3376752017-11-08 13:41:21 +00001234 SDValue Glue;
1235
1236 // Build a sequence of copy-to-reg nodes, chained and glued together.
1237 for (auto &Reg : RegsToPass) {
1238 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
1239 Glue = Chain.getValue(1);
1240 }
1241
Shiva Chend58bd8d2018-04-25 14:19:12 +00001242 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
1243 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
1244 // split it and then direct call can be matched by PseudoCALL.
1245 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
1246 Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, 0);
1247 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1248 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, 0);
Alex Bradburya3376752017-11-08 13:41:21 +00001249 }
1250
1251 // The first call operand is the chain and the second is the target address.
1252 SmallVector<SDValue, 8> Ops;
1253 Ops.push_back(Chain);
1254 Ops.push_back(Callee);
1255
1256 // Add argument registers to the end of the list so that they are
1257 // known live into the call.
1258 for (auto &Reg : RegsToPass)
1259 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1260
1261 // Add a register mask operand representing the call-preserved registers.
1262 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1263 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1264 assert(Mask && "Missing call preserved mask for calling convention");
1265 Ops.push_back(DAG.getRegisterMask(Mask));
1266
1267 // Glue the call to the argument copies, if any.
1268 if (Glue.getNode())
1269 Ops.push_back(Glue);
1270
1271 // Emit the call.
1272 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1273 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
1274 Glue = Chain.getValue(1);
1275
1276 // Mark the end of the call, which is glued to the call itself.
1277 Chain = DAG.getCALLSEQ_END(Chain,
1278 DAG.getConstant(NumBytes, DL, PtrVT, true),
1279 DAG.getConstant(0, DL, PtrVT, true),
1280 Glue, DL);
1281 Glue = Chain.getValue(1);
1282
1283 // Assign locations to each value returned by this call.
1284 SmallVector<CCValAssign, 16> RVLocs;
1285 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
Alex Bradburydc31c612017-12-11 12:49:02 +00001286 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
Alex Bradburya3376752017-11-08 13:41:21 +00001287
1288 // Copy all of the result registers out of their specified physreg.
1289 for (auto &VA : RVLocs) {
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001290 // Copy the value out
1291 SDValue RetValue =
1292 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
1293 // Glue the RetValue to the end of the call sequence
Alex Bradburya3376752017-11-08 13:41:21 +00001294 Chain = RetValue.getValue(1);
1295 Glue = RetValue.getValue(2);
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001296 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1297 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
1298 SDValue RetValue2 =
1299 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
1300 Chain = RetValue2.getValue(1);
1301 Glue = RetValue2.getValue(2);
1302 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
1303 RetValue2);
1304 }
Alex Bradburya3376752017-11-08 13:41:21 +00001305
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001306 switch (VA.getLocInfo()) {
1307 default:
1308 llvm_unreachable("Unknown loc info!");
1309 case CCValAssign::Full:
1310 break;
1311 case CCValAssign::BCvt:
1312 RetValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), RetValue);
1313 break;
1314 }
1315
Alex Bradburydc31c612017-12-11 12:49:02 +00001316 InVals.push_back(RetValue);
Alex Bradburya3376752017-11-08 13:41:21 +00001317 }
1318
1319 return Chain;
1320}
1321
Alex Bradburydc31c612017-12-11 12:49:02 +00001322bool RISCVTargetLowering::CanLowerReturn(
1323 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
1324 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
1325 SmallVector<CCValAssign, 16> RVLocs;
1326 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1327 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1328 MVT VT = Outs[i].VT;
1329 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1330 if (CC_RISCV(MF.getDataLayout(), i, VT, VT, CCValAssign::Full, ArgFlags,
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001331 CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
Alex Bradburydc31c612017-12-11 12:49:02 +00001332 return false;
1333 }
1334 return true;
1335}
1336
Alex Bradbury76c29ee2018-03-20 12:45:35 +00001337static SDValue packIntoRegLoc(SelectionDAG &DAG, SDValue Val,
1338 const CCValAssign &VA, const SDLoc &DL) {
1339 EVT LocVT = VA.getLocVT();
1340
1341 switch (VA.getLocInfo()) {
1342 default:
1343 llvm_unreachable("Unexpected CCValAssign::LocInfo");
1344 case CCValAssign::Full:
1345 break;
1346 case CCValAssign::BCvt:
1347 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1348 break;
1349 }
1350 return Val;
1351}
1352
Alex Bradbury89718422017-10-19 21:37:38 +00001353SDValue
1354RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1355 bool IsVarArg,
1356 const SmallVectorImpl<ISD::OutputArg> &Outs,
1357 const SmallVectorImpl<SDValue> &OutVals,
1358 const SDLoc &DL, SelectionDAG &DAG) const {
Alex Bradbury89718422017-10-19 21:37:38 +00001359 // Stores the assignment of the return value to a location.
1360 SmallVector<CCValAssign, 16> RVLocs;
1361
1362 // Info about the registers and stack slot.
1363 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1364 *DAG.getContext());
1365
Alex Bradburyc85be0d2018-01-10 19:41:03 +00001366 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
1367 nullptr);
Alex Bradbury89718422017-10-19 21:37:38 +00001368
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001369 SDValue Glue;
Alex Bradbury89718422017-10-19 21:37:38 +00001370 SmallVector<SDValue, 4> RetOps(1, Chain);
1371
1372 // Copy the result values into the output registers.
1373 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
Alex Bradburydc31c612017-12-11 12:49:02 +00001374 SDValue Val = OutVals[i];
Alex Bradbury89718422017-10-19 21:37:38 +00001375 CCValAssign &VA = RVLocs[i];
1376 assert(VA.isRegLoc() && "Can only return in registers!");
1377
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001378 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
1379 // Handle returning f64 on RV32D with a soft float ABI.
1380 assert(VA.isRegLoc() && "Expected return via registers");
1381 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
1382 DAG.getVTList(MVT::i32, MVT::i32), Val);
1383 SDValue Lo = SplitF64.getValue(0);
1384 SDValue Hi = SplitF64.getValue(1);
1385 unsigned RegLo = VA.getLocReg();
1386 unsigned RegHi = RegLo + 1;
1387 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
1388 Glue = Chain.getValue(1);
1389 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
1390 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
1391 Glue = Chain.getValue(1);
1392 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
1393 } else {
1394 // Handle a 'normal' return.
1395 Val = packIntoRegLoc(DAG, Val, VA, DL);
1396 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001397
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001398 // Guarantee that all emitted copies are stuck together.
1399 Glue = Chain.getValue(1);
1400 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1401 }
Alex Bradbury89718422017-10-19 21:37:38 +00001402 }
1403
1404 RetOps[0] = Chain; // Update chain.
1405
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001406 // Add the glue node if we have it.
1407 if (Glue.getNode()) {
1408 RetOps.push_back(Glue);
Alex Bradbury89718422017-10-19 21:37:38 +00001409 }
1410
1411 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
1412}
1413
1414const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
1415 switch ((RISCVISD::NodeType)Opcode) {
1416 case RISCVISD::FIRST_NUMBER:
1417 break;
1418 case RISCVISD::RET_FLAG:
1419 return "RISCVISD::RET_FLAG";
Alex Bradburya3376752017-11-08 13:41:21 +00001420 case RISCVISD::CALL:
1421 return "RISCVISD::CALL";
Alex Bradbury65385162017-11-21 07:51:32 +00001422 case RISCVISD::SELECT_CC:
1423 return "RISCVISD::SELECT_CC";
Alex Bradbury0b4175f2018-04-12 05:34:25 +00001424 case RISCVISD::BuildPairF64:
1425 return "RISCVISD::BuildPairF64";
1426 case RISCVISD::SplitF64:
1427 return "RISCVISD::SplitF64";
Alex Bradbury89718422017-10-19 21:37:38 +00001428 }
1429 return nullptr;
1430}
Alex Bradbury9330e642018-01-10 20:05:09 +00001431
1432std::pair<unsigned, const TargetRegisterClass *>
1433RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1434 StringRef Constraint,
1435 MVT VT) const {
1436 // First, see if this is a constraint that directly corresponds to a
1437 // RISCV register class.
1438 if (Constraint.size() == 1) {
1439 switch (Constraint[0]) {
1440 case 'r':
1441 return std::make_pair(0U, &RISCV::GPRRegClass);
1442 default:
1443 break;
1444 }
1445 }
1446
1447 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1448}