1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsTargetMachine.h"
19 #include "MipsTargetObjectFile.h"
20 #include "MipsSubtarget.h"
21 #include "InstPrinter/MipsInstPrinter.h"
22 #include "MCTargetDesc/MipsBaseInfo.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
39 // If I is a shifted mask, set the size (Size) and the first bit of the
40 // mask (Pos), and return true.
41 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
42 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
43 if (!isShiftedMask_64(I))
46 Size = CountPopulation_64(I);
47 Pos = CountTrailingZeros_64(I);
51 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
52 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
53 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
56 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
58 case MipsISD::JmpLink: return "MipsISD::JmpLink";
59 case MipsISD::Hi: return "MipsISD::Hi";
60 case MipsISD::Lo: return "MipsISD::Lo";
61 case MipsISD::GPRel: return "MipsISD::GPRel";
62 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
63 case MipsISD::Ret: return "MipsISD::Ret";
64 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
65 case MipsISD::FPCmp: return "MipsISD::FPCmp";
66 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
67 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
68 case MipsISD::FPRound: return "MipsISD::FPRound";
69 case MipsISD::MAdd: return "MipsISD::MAdd";
70 case MipsISD::MAddu: return "MipsISD::MAddu";
71 case MipsISD::MSub: return "MipsISD::MSub";
72 case MipsISD::MSubu: return "MipsISD::MSubu";
73 case MipsISD::DivRem: return "MipsISD::DivRem";
74 case MipsISD::DivRemU: return "MipsISD::DivRemU";
75 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
76 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
77 case MipsISD::Wrapper: return "MipsISD::Wrapper";
78 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
79 case MipsISD::Sync: return "MipsISD::Sync";
80 case MipsISD::Ext: return "MipsISD::Ext";
81 case MipsISD::Ins: return "MipsISD::Ins";
87 MipsTargetLowering(MipsTargetMachine &TM)
88 : TargetLowering(TM, new MipsTargetObjectFile()),
89 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
90 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
91 IsO32(Subtarget->isABI_O32()) {
93 // Mips does not have i1 type, so use i32 for
94 // setcc operations results (slt, sgt, ...).
95 setBooleanContents(ZeroOrOneBooleanContent);
96 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
98 // Set up the register classes
99 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
102 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
104 if (!TM.Options.UseSoftFloat) {
105 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
107 // When dealing with single precision only, use libcalls
108 if (!Subtarget->isSingleFloat()) {
110 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
112 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
116 // Load extented operations for i1 types must be promoted
117 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
118 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
119 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121 // MIPS doesn't have extending float->double load/store
122 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
123 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
125 // Used by legalize types to correctly generate the setcc result.
126 // Without this, every float setcc comes with a AND/OR with the result,
127 // we don't want this, since the fpcmp result goes to a flag register,
128 // which is used implicitly by brcond and select operations.
129 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
131 // Mips Custom Operations
132 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
133 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
134 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
135 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
136 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
137 setOperationAction(ISD::SELECT, MVT::f32, Custom);
138 setOperationAction(ISD::SELECT, MVT::f64, Custom);
139 setOperationAction(ISD::SELECT, MVT::i32, Custom);
140 setOperationAction(ISD::SETCC, MVT::f32, Custom);
141 setOperationAction(ISD::SETCC, MVT::f64, Custom);
142 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
143 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
144 setOperationAction(ISD::VASTART, MVT::Other, Custom);
145 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
146 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
147 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
148 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
151 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
152 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
153 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
154 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
155 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
156 setOperationAction(ISD::SELECT, MVT::i64, Custom);
157 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
160 setOperationAction(ISD::SDIV, MVT::i32, Expand);
161 setOperationAction(ISD::SREM, MVT::i32, Expand);
162 setOperationAction(ISD::UDIV, MVT::i32, Expand);
163 setOperationAction(ISD::UREM, MVT::i32, Expand);
164 setOperationAction(ISD::SDIV, MVT::i64, Expand);
165 setOperationAction(ISD::SREM, MVT::i64, Expand);
166 setOperationAction(ISD::UDIV, MVT::i64, Expand);
167 setOperationAction(ISD::UREM, MVT::i64, Expand);
169 // Operations not directly supported by Mips.
170 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
171 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
172 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
173 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
174 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
175 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
177 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
178 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
179 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
180 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
181 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
182 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
183 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
184 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
185 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
186 setOperationAction(ISD::ROTL, MVT::i32, Expand);
187 setOperationAction(ISD::ROTL, MVT::i64, Expand);
189 if (!Subtarget->hasMips32r2())
190 setOperationAction(ISD::ROTR, MVT::i32, Expand);
192 if (!Subtarget->hasMips64r2())
193 setOperationAction(ISD::ROTR, MVT::i64, Expand);
195 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
196 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
197 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
198 setOperationAction(ISD::FSIN, MVT::f32, Expand);
199 setOperationAction(ISD::FSIN, MVT::f64, Expand);
200 setOperationAction(ISD::FCOS, MVT::f32, Expand);
201 setOperationAction(ISD::FCOS, MVT::f64, Expand);
202 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
203 setOperationAction(ISD::FPOW, MVT::f32, Expand);
204 setOperationAction(ISD::FPOW, MVT::f64, Expand);
205 setOperationAction(ISD::FLOG, MVT::f32, Expand);
206 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
207 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
208 setOperationAction(ISD::FEXP, MVT::f32, Expand);
209 setOperationAction(ISD::FMA, MVT::f32, Expand);
210 setOperationAction(ISD::FMA, MVT::f64, Expand);
211 setOperationAction(ISD::FREM, MVT::f32, Expand);
212 setOperationAction(ISD::FREM, MVT::f64, Expand);
214 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
215 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
216 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
217 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
219 setOperationAction(ISD::VAARG, MVT::Other, Expand);
220 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
221 setOperationAction(ISD::VAEND, MVT::Other, Expand);
223 // Use the default for now
224 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
225 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
227 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
228 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
229 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
230 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
232 setInsertFencesForAtomic(true);
234 if (Subtarget->isSingleFloat())
235 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
237 if (!Subtarget->hasSEInReg()) {
238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
242 if (!Subtarget->hasBitCount()) {
243 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
244 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
247 if (!Subtarget->hasSwap()) {
248 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
249 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
252 setTargetDAGCombine(ISD::ADDE);
253 setTargetDAGCombine(ISD::SUBE);
254 setTargetDAGCombine(ISD::SDIVREM);
255 setTargetDAGCombine(ISD::UDIVREM);
256 setTargetDAGCombine(ISD::SELECT);
257 setTargetDAGCombine(ISD::AND);
258 setTargetDAGCombine(ISD::OR);
260 setMinFunctionAlignment(HasMips64 ? 3 : 2);
262 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
263 computeRegisterProperties();
265 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
266 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
269 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
270 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
278 return Subtarget->hasMips32r2Or64();
284 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
289 // Transforms a subgraph in CurDAG if the following pattern is found:
290 // (addc multLo, Lo0), (adde multHi, Hi0),
292 // multHi/Lo: product of multiplication
293 // Lo0: initial value of Lo register
294 // Hi0: initial value of Hi register
295 // Return true if pattern matching was successful.
296 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
297 // ADDENode's second operand must be a flag output of an ADDC node in order
298 // for the matching to be successful.
299 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
301 if (ADDCNode->getOpcode() != ISD::ADDC)
304 SDValue MultHi = ADDENode->getOperand(0);
305 SDValue MultLo = ADDCNode->getOperand(0);
306 SDNode* MultNode = MultHi.getNode();
307 unsigned MultOpc = MultHi.getOpcode();
309 // MultHi and MultLo must be generated by the same node,
310 if (MultLo.getNode() != MultNode)
313 // and it must be a multiplication.
314 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
317 // MultLo amd MultHi must be the first and second output of MultNode
319 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
322 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
323 // of the values of MultNode, in which case MultNode will be removed in later
325 // If there exist users other than ADDENode or ADDCNode, this function returns
326 // here, which will result in MultNode being mapped to a single MULT
327 // instruction node rather than a pair of MULT and MADD instructions being
329 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
332 SDValue Chain = CurDAG->getEntryNode();
333 DebugLoc dl = ADDENode->getDebugLoc();
335 // create MipsMAdd(u) node
336 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
338 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
339 MultNode->getOperand(0),// Factor 0
340 MultNode->getOperand(1),// Factor 1
341 ADDCNode->getOperand(1),// Lo0
342 ADDENode->getOperand(1));// Hi0
344 // create CopyFromReg nodes
345 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
347 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
349 CopyFromLo.getValue(2));
351 // replace uses of adde and addc here
352 if (!SDValue(ADDCNode, 0).use_empty())
353 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
355 if (!SDValue(ADDENode, 0).use_empty())
356 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
362 // Transforms a subgraph in CurDAG if the following pattern is found:
363 // (addc Lo0, multLo), (sube Hi0, multHi),
365 // multHi/Lo: product of multiplication
366 // Lo0: initial value of Lo register
367 // Hi0: initial value of Hi register
368 // Return true if pattern matching was successful.
369 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
370 // SUBENode's second operand must be a flag output of an SUBC node in order
371 // for the matching to be successful.
372 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
374 if (SUBCNode->getOpcode() != ISD::SUBC)
377 SDValue MultHi = SUBENode->getOperand(1);
378 SDValue MultLo = SUBCNode->getOperand(1);
379 SDNode* MultNode = MultHi.getNode();
380 unsigned MultOpc = MultHi.getOpcode();
382 // MultHi and MultLo must be generated by the same node,
383 if (MultLo.getNode() != MultNode)
386 // and it must be a multiplication.
387 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
390 // MultLo amd MultHi must be the first and second output of MultNode
392 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
395 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
396 // of the values of MultNode, in which case MultNode will be removed in later
398 // If there exist users other than SUBENode or SUBCNode, this function returns
399 // here, which will result in MultNode being mapped to a single MULT
400 // instruction node rather than a pair of MULT and MSUB instructions being
402 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
405 SDValue Chain = CurDAG->getEntryNode();
406 DebugLoc dl = SUBENode->getDebugLoc();
408 // create MipsSub(u) node
409 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
411 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
412 MultNode->getOperand(0),// Factor 0
413 MultNode->getOperand(1),// Factor 1
414 SUBCNode->getOperand(0),// Lo0
415 SUBENode->getOperand(0));// Hi0
417 // create CopyFromReg nodes
418 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
420 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
422 CopyFromLo.getValue(2));
424 // replace uses of sube and subc here
425 if (!SDValue(SUBCNode, 0).use_empty())
426 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
428 if (!SDValue(SUBENode, 0).use_empty())
429 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
434 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
435 TargetLowering::DAGCombinerInfo &DCI,
436 const MipsSubtarget* Subtarget) {
437 if (DCI.isBeforeLegalize())
440 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
442 return SDValue(N, 0);
447 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
448 TargetLowering::DAGCombinerInfo &DCI,
449 const MipsSubtarget* Subtarget) {
450 if (DCI.isBeforeLegalize())
453 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
455 return SDValue(N, 0);
460 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
461 TargetLowering::DAGCombinerInfo &DCI,
462 const MipsSubtarget* Subtarget) {
463 if (DCI.isBeforeLegalizeOps())
466 EVT Ty = N->getValueType(0);
467 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
468 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
469 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
471 DebugLoc dl = N->getDebugLoc();
473 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
474 N->getOperand(0), N->getOperand(1));
475 SDValue InChain = DAG.getEntryNode();
476 SDValue InGlue = DivRem;
479 if (N->hasAnyUseOfValue(0)) {
480 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
482 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
483 InChain = CopyFromLo.getValue(1);
484 InGlue = CopyFromLo.getValue(2);
488 if (N->hasAnyUseOfValue(1)) {
489 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
491 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
497 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
499 default: llvm_unreachable("Unknown fp condition code!");
501 case ISD::SETOEQ: return Mips::FCOND_OEQ;
502 case ISD::SETUNE: return Mips::FCOND_UNE;
504 case ISD::SETOLT: return Mips::FCOND_OLT;
506 case ISD::SETOGT: return Mips::FCOND_OGT;
508 case ISD::SETOLE: return Mips::FCOND_OLE;
510 case ISD::SETOGE: return Mips::FCOND_OGE;
511 case ISD::SETULT: return Mips::FCOND_ULT;
512 case ISD::SETULE: return Mips::FCOND_ULE;
513 case ISD::SETUGT: return Mips::FCOND_UGT;
514 case ISD::SETUGE: return Mips::FCOND_UGE;
515 case ISD::SETUO: return Mips::FCOND_UN;
516 case ISD::SETO: return Mips::FCOND_OR;
518 case ISD::SETONE: return Mips::FCOND_ONE;
519 case ISD::SETUEQ: return Mips::FCOND_UEQ;
524 // Returns true if condition code has to be inverted.
525 static bool InvertFPCondCode(Mips::CondCode CC) {
526 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
529 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
530 "Illegal Condition Code");
535 // Creates and returns an FPCmp node from a setcc node.
536 // Returns Op if setcc is not a floating point comparison.
537 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
538 // must be a SETCC node
539 if (Op.getOpcode() != ISD::SETCC)
542 SDValue LHS = Op.getOperand(0);
544 if (!LHS.getValueType().isFloatingPoint())
547 SDValue RHS = Op.getOperand(1);
548 DebugLoc dl = Op.getDebugLoc();
550 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
551 // node if necessary.
552 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
554 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
555 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
558 // Creates and returns a CMovFPT/F node.
559 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
560 SDValue False, DebugLoc DL) {
561 bool invert = InvertFPCondCode((Mips::CondCode)
562 cast<ConstantSDNode>(Cond.getOperand(2))
565 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
566 True.getValueType(), True, False, Cond);
569 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG& DAG,
570 TargetLowering::DAGCombinerInfo &DCI,
571 const MipsSubtarget* Subtarget) {
572 if (DCI.isBeforeLegalizeOps())
575 SDValue SetCC = N->getOperand(0);
577 if ((SetCC.getOpcode() != ISD::SETCC) ||
578 !SetCC.getOperand(0).getValueType().isInteger())
581 SDValue False = N->getOperand(2);
582 EVT FalseTy = False.getValueType();
584 if (!FalseTy.isInteger())
587 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
589 if (!CN || CN->getZExtValue())
592 const DebugLoc DL = N->getDebugLoc();
593 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
594 SDValue True = N->getOperand(1);
596 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
597 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
599 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
602 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
603 TargetLowering::DAGCombinerInfo &DCI,
604 const MipsSubtarget* Subtarget) {
605 // Pattern match EXT.
606 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
607 // => ext $dst, $src, size, pos
608 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
611 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
612 unsigned ShiftRightOpc = ShiftRight.getOpcode();
614 // Op's first operand must be a shift right.
615 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
618 // The second operand of the shift must be an immediate.
620 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
623 uint64_t Pos = CN->getZExtValue();
624 uint64_t SMPos, SMSize;
626 // Op's second operand must be a shifted mask.
627 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
628 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
631 // Return if the shifted mask does not start at bit 0 or the sum of its size
632 // and Pos exceeds the word's size.
633 EVT ValTy = N->getValueType(0);
634 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
637 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
638 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
639 DAG.getConstant(SMSize, MVT::i32));
642 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
643 TargetLowering::DAGCombinerInfo &DCI,
644 const MipsSubtarget* Subtarget) {
645 // Pattern match INS.
646 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
647 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
648 // => ins $dst, $src, size, pos, $src1
649 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
652 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
653 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
656 // See if Op's first operand matches (and $src1 , mask0).
657 if (And0.getOpcode() != ISD::AND)
660 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
661 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
664 // See if Op's second operand matches (and (shl $src, pos), mask1).
665 if (And1.getOpcode() != ISD::AND)
668 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
669 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
672 // The shift masks must have the same position and size.
673 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
676 SDValue Shl = And1.getOperand(0);
677 if (Shl.getOpcode() != ISD::SHL)
680 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
683 unsigned Shamt = CN->getZExtValue();
685 // Return if the shift amount and the first bit position of mask are not the
687 EVT ValTy = N->getValueType(0);
688 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
691 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
692 DAG.getConstant(SMPos0, MVT::i32),
693 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
696 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
698 SelectionDAG &DAG = DCI.DAG;
699 unsigned opc = N->getOpcode();
704 return PerformADDECombine(N, DAG, DCI, Subtarget);
706 return PerformSUBECombine(N, DAG, DCI, Subtarget);
709 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
711 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
713 return PerformANDCombine(N, DAG, DCI, Subtarget);
715 return PerformORCombine(N, DAG, DCI, Subtarget);
721 SDValue MipsTargetLowering::
722 LowerOperation(SDValue Op, SelectionDAG &DAG) const
724 switch (Op.getOpcode())
726 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
727 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
728 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
729 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
730 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
731 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
732 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
733 case ISD::SELECT: return LowerSELECT(Op, DAG);
734 case ISD::SETCC: return LowerSETCC(Op, DAG);
735 case ISD::VASTART: return LowerVASTART(Op, DAG);
736 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
737 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
738 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
739 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
744 //===----------------------------------------------------------------------===//
745 // Lower helper functions
746 //===----------------------------------------------------------------------===//
748 // AddLiveIn - This helper function adds the specified physical register to the
749 // MachineFunction as a live in value. It also creates a corresponding
750 // virtual register for it.
752 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
754 assert(RC->contains(PReg) && "Not the correct regclass!");
755 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
756 MF.getRegInfo().addLiveIn(PReg, VReg);
760 // Get fp branch code (not opcode) from condition code.
761 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
762 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
763 return Mips::BRANCH_T;
765 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
766 "Invalid CondCode.");
768 return Mips::BRANCH_F;
772 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
774 const MipsSubtarget* Subtarget,
775 const TargetInstrInfo *TII,
776 bool isFPCmp, unsigned Opc) {
777 // There is no need to expand CMov instructions if target has
778 // conditional moves.
779 if (Subtarget->hasCondMov())
782 // To "insert" a SELECT_CC instruction, we actually have to insert the
783 // diamond control-flow pattern. The incoming instruction knows the
784 // destination vreg to set, the condition code register to branch on, the
785 // true/false values to select between, and a branch opcode to use.
786 const BasicBlock *LLVM_BB = BB->getBasicBlock();
787 MachineFunction::iterator It = BB;
794 // bNE r1, r0, copy1MBB
795 // fallthrough --> copy0MBB
796 MachineBasicBlock *thisMBB = BB;
797 MachineFunction *F = BB->getParent();
798 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
799 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
800 F->insert(It, copy0MBB);
801 F->insert(It, sinkMBB);
803 // Transfer the remainder of BB and its successor edges to sinkMBB.
804 sinkMBB->splice(sinkMBB->begin(), BB,
805 llvm::next(MachineBasicBlock::iterator(MI)),
807 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
809 // Next, add the true and fallthrough blocks as its successors.
810 BB->addSuccessor(copy0MBB);
811 BB->addSuccessor(sinkMBB);
813 // Emit the right instruction according to the type of the operands compared
815 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
817 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
818 .addReg(Mips::ZERO).addMBB(sinkMBB);
822 // # fallthrough to sinkMBB
825 // Update machine-CFG edges
826 BB->addSuccessor(sinkMBB);
829 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
834 BuildMI(*BB, BB->begin(), dl,
835 TII->get(Mips::PHI), MI->getOperand(0).getReg())
836 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
837 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
839 BuildMI(*BB, BB->begin(), dl,
840 TII->get(Mips::PHI), MI->getOperand(0).getReg())
841 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
842 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
844 MI->eraseFromParent(); // The pseudo instruction is gone now.
849 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
850 MachineBasicBlock *BB) const {
851 switch (MI->getOpcode()) {
852 default: llvm_unreachable("Unexpected instr type to insert");
853 case Mips::ATOMIC_LOAD_ADD_I8:
854 case Mips::ATOMIC_LOAD_ADD_I8_P8:
855 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
856 case Mips::ATOMIC_LOAD_ADD_I16:
857 case Mips::ATOMIC_LOAD_ADD_I16_P8:
858 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
859 case Mips::ATOMIC_LOAD_ADD_I32:
860 case Mips::ATOMIC_LOAD_ADD_I32_P8:
861 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
862 case Mips::ATOMIC_LOAD_ADD_I64:
863 case Mips::ATOMIC_LOAD_ADD_I64_P8:
864 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
866 case Mips::ATOMIC_LOAD_AND_I8:
867 case Mips::ATOMIC_LOAD_AND_I8_P8:
868 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
869 case Mips::ATOMIC_LOAD_AND_I16:
870 case Mips::ATOMIC_LOAD_AND_I16_P8:
871 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
872 case Mips::ATOMIC_LOAD_AND_I32:
873 case Mips::ATOMIC_LOAD_AND_I32_P8:
874 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
875 case Mips::ATOMIC_LOAD_AND_I64:
876 case Mips::ATOMIC_LOAD_AND_I64_P8:
877 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
879 case Mips::ATOMIC_LOAD_OR_I8:
880 case Mips::ATOMIC_LOAD_OR_I8_P8:
881 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
882 case Mips::ATOMIC_LOAD_OR_I16:
883 case Mips::ATOMIC_LOAD_OR_I16_P8:
884 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
885 case Mips::ATOMIC_LOAD_OR_I32:
886 case Mips::ATOMIC_LOAD_OR_I32_P8:
887 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
888 case Mips::ATOMIC_LOAD_OR_I64:
889 case Mips::ATOMIC_LOAD_OR_I64_P8:
890 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
892 case Mips::ATOMIC_LOAD_XOR_I8:
893 case Mips::ATOMIC_LOAD_XOR_I8_P8:
894 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
895 case Mips::ATOMIC_LOAD_XOR_I16:
896 case Mips::ATOMIC_LOAD_XOR_I16_P8:
897 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
898 case Mips::ATOMIC_LOAD_XOR_I32:
899 case Mips::ATOMIC_LOAD_XOR_I32_P8:
900 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
901 case Mips::ATOMIC_LOAD_XOR_I64:
902 case Mips::ATOMIC_LOAD_XOR_I64_P8:
903 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
905 case Mips::ATOMIC_LOAD_NAND_I8:
906 case Mips::ATOMIC_LOAD_NAND_I8_P8:
907 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
908 case Mips::ATOMIC_LOAD_NAND_I16:
909 case Mips::ATOMIC_LOAD_NAND_I16_P8:
910 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
911 case Mips::ATOMIC_LOAD_NAND_I32:
912 case Mips::ATOMIC_LOAD_NAND_I32_P8:
913 return EmitAtomicBinary(MI, BB, 4, 0, true);
914 case Mips::ATOMIC_LOAD_NAND_I64:
915 case Mips::ATOMIC_LOAD_NAND_I64_P8:
916 return EmitAtomicBinary(MI, BB, 8, 0, true);
918 case Mips::ATOMIC_LOAD_SUB_I8:
919 case Mips::ATOMIC_LOAD_SUB_I8_P8:
920 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
921 case Mips::ATOMIC_LOAD_SUB_I16:
922 case Mips::ATOMIC_LOAD_SUB_I16_P8:
923 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
924 case Mips::ATOMIC_LOAD_SUB_I32:
925 case Mips::ATOMIC_LOAD_SUB_I32_P8:
926 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
927 case Mips::ATOMIC_LOAD_SUB_I64:
928 case Mips::ATOMIC_LOAD_SUB_I64_P8:
929 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
931 case Mips::ATOMIC_SWAP_I8:
932 case Mips::ATOMIC_SWAP_I8_P8:
933 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
934 case Mips::ATOMIC_SWAP_I16:
935 case Mips::ATOMIC_SWAP_I16_P8:
936 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
937 case Mips::ATOMIC_SWAP_I32:
938 case Mips::ATOMIC_SWAP_I32_P8:
939 return EmitAtomicBinary(MI, BB, 4, 0);
940 case Mips::ATOMIC_SWAP_I64:
941 case Mips::ATOMIC_SWAP_I64_P8:
942 return EmitAtomicBinary(MI, BB, 8, 0);
944 case Mips::ATOMIC_CMP_SWAP_I8:
945 case Mips::ATOMIC_CMP_SWAP_I8_P8:
946 return EmitAtomicCmpSwapPartword(MI, BB, 1);
947 case Mips::ATOMIC_CMP_SWAP_I16:
948 case Mips::ATOMIC_CMP_SWAP_I16_P8:
949 return EmitAtomicCmpSwapPartword(MI, BB, 2);
950 case Mips::ATOMIC_CMP_SWAP_I32:
951 case Mips::ATOMIC_CMP_SWAP_I32_P8:
952 return EmitAtomicCmpSwap(MI, BB, 4);
953 case Mips::ATOMIC_CMP_SWAP_I64:
954 case Mips::ATOMIC_CMP_SWAP_I64_P8:
955 return EmitAtomicCmpSwap(MI, BB, 8);
959 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
960 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
962 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
963 unsigned Size, unsigned BinOpcode,
965 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
967 MachineFunction *MF = BB->getParent();
968 MachineRegisterInfo &RegInfo = MF->getRegInfo();
969 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
970 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
971 DebugLoc dl = MI->getDebugLoc();
972 unsigned LL, SC, AND, NOR, ZERO, BEQ;
975 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
976 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
983 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
984 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
987 ZERO = Mips::ZERO_64;
991 unsigned OldVal = MI->getOperand(0).getReg();
992 unsigned Ptr = MI->getOperand(1).getReg();
993 unsigned Incr = MI->getOperand(2).getReg();
995 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
996 unsigned AndRes = RegInfo.createVirtualRegister(RC);
997 unsigned Success = RegInfo.createVirtualRegister(RC);
999 // insert new blocks after the current block
1000 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1001 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1002 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1003 MachineFunction::iterator It = BB;
1005 MF->insert(It, loopMBB);
1006 MF->insert(It, exitMBB);
1008 // Transfer the remainder of BB and its successor edges to exitMBB.
1009 exitMBB->splice(exitMBB->begin(), BB,
1010 llvm::next(MachineBasicBlock::iterator(MI)),
1012 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1016 // fallthrough --> loopMBB
1017 BB->addSuccessor(loopMBB);
1018 loopMBB->addSuccessor(loopMBB);
1019 loopMBB->addSuccessor(exitMBB);
1022 // ll oldval, 0(ptr)
1023 // <binop> storeval, oldval, incr
1024 // sc success, storeval, 0(ptr)
1025 // beq success, $0, loopMBB
1027 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1029 // and andres, oldval, incr
1030 // nor storeval, $0, andres
1031 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1032 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1033 } else if (BinOpcode) {
1034 // <binop> storeval, oldval, incr
1035 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1039 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1040 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1042 MI->eraseFromParent(); // The instruction is gone now.
1048 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1049 MachineBasicBlock *BB,
1050 unsigned Size, unsigned BinOpcode,
1052 assert((Size == 1 || Size == 2) &&
1053 "Unsupported size for EmitAtomicBinaryPartial.");
1055 MachineFunction *MF = BB->getParent();
1056 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1057 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1058 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1059 DebugLoc dl = MI->getDebugLoc();
1060 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1061 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1063 unsigned Dest = MI->getOperand(0).getReg();
1064 unsigned Ptr = MI->getOperand(1).getReg();
1065 unsigned Incr = MI->getOperand(2).getReg();
1067 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1068 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1069 unsigned Mask = RegInfo.createVirtualRegister(RC);
1070 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1071 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1072 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1073 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1074 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1075 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1076 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1077 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1078 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1079 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1080 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1081 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1082 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1083 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1084 unsigned Success = RegInfo.createVirtualRegister(RC);
1086 // insert new blocks after the current block
1087 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1088 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1089 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1090 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1091 MachineFunction::iterator It = BB;
1093 MF->insert(It, loopMBB);
1094 MF->insert(It, sinkMBB);
1095 MF->insert(It, exitMBB);
1097 // Transfer the remainder of BB and its successor edges to exitMBB.
1098 exitMBB->splice(exitMBB->begin(), BB,
1099 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1100 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1102 BB->addSuccessor(loopMBB);
1103 loopMBB->addSuccessor(loopMBB);
1104 loopMBB->addSuccessor(sinkMBB);
1105 sinkMBB->addSuccessor(exitMBB);
1108 // addiu masklsb2,$0,-4 # 0xfffffffc
1109 // and alignedaddr,ptr,masklsb2
1110 // andi ptrlsb2,ptr,3
1111 // sll shiftamt,ptrlsb2,3
1112 // ori maskupper,$0,255 # 0xff
1113 // sll mask,maskupper,shiftamt
1114 // nor mask2,$0,mask
1115 // sll incr2,incr,shiftamt
1117 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1118 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1119 .addReg(Mips::ZERO).addImm(-4);
1120 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1121 .addReg(Ptr).addReg(MaskLSB2);
1122 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1123 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1124 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1125 .addReg(Mips::ZERO).addImm(MaskImm);
1126 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1127 .addReg(ShiftAmt).addReg(MaskUpper);
1128 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1129 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1131 // atomic.load.binop
1133 // ll oldval,0(alignedaddr)
1134 // binop binopres,oldval,incr2
1135 // and newval,binopres,mask
1136 // and maskedoldval0,oldval,mask2
1137 // or storeval,maskedoldval0,newval
1138 // sc success,storeval,0(alignedaddr)
1139 // beq success,$0,loopMBB
1143 // ll oldval,0(alignedaddr)
1144 // and newval,incr2,mask
1145 // and maskedoldval0,oldval,mask2
1146 // or storeval,maskedoldval0,newval
1147 // sc success,storeval,0(alignedaddr)
1148 // beq success,$0,loopMBB
1151 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1153 // and andres, oldval, incr2
1154 // nor binopres, $0, andres
1155 // and newval, binopres, mask
1156 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1157 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1158 .addReg(Mips::ZERO).addReg(AndRes);
1159 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1160 } else if (BinOpcode) {
1161 // <binop> binopres, oldval, incr2
1162 // and newval, binopres, mask
1163 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1164 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1165 } else {// atomic.swap
1166 // and newval, incr2, mask
1167 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1170 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1171 .addReg(OldVal).addReg(Mask2);
1172 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1173 .addReg(MaskedOldVal0).addReg(NewVal);
1174 BuildMI(BB, dl, TII->get(SC), Success)
1175 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1176 BuildMI(BB, dl, TII->get(Mips::BEQ))
1177 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1180 // and maskedoldval1,oldval,mask
1181 // srl srlres,maskedoldval1,shiftamt
1182 // sll sllres,srlres,24
1183 // sra dest,sllres,24
1185 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1187 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1188 .addReg(OldVal).addReg(Mask);
1189 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1190 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1191 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1192 .addReg(SrlRes).addImm(ShiftImm);
1193 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1194 .addReg(SllRes).addImm(ShiftImm);
1196 MI->eraseFromParent(); // The instruction is gone now.
1202 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1203 MachineBasicBlock *BB,
1204 unsigned Size) const {
1205 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1207 MachineFunction *MF = BB->getParent();
1208 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1209 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1210 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1211 DebugLoc dl = MI->getDebugLoc();
1212 unsigned LL, SC, ZERO, BNE, BEQ;
1215 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1216 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1222 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1223 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1224 ZERO = Mips::ZERO_64;
1229 unsigned Dest = MI->getOperand(0).getReg();
1230 unsigned Ptr = MI->getOperand(1).getReg();
1231 unsigned OldVal = MI->getOperand(2).getReg();
1232 unsigned NewVal = MI->getOperand(3).getReg();
1234 unsigned Success = RegInfo.createVirtualRegister(RC);
1236 // insert new blocks after the current block
1237 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1238 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1239 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1240 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1241 MachineFunction::iterator It = BB;
1243 MF->insert(It, loop1MBB);
1244 MF->insert(It, loop2MBB);
1245 MF->insert(It, exitMBB);
1247 // Transfer the remainder of BB and its successor edges to exitMBB.
1248 exitMBB->splice(exitMBB->begin(), BB,
1249 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1250 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1254 // fallthrough --> loop1MBB
1255 BB->addSuccessor(loop1MBB);
1256 loop1MBB->addSuccessor(exitMBB);
1257 loop1MBB->addSuccessor(loop2MBB);
1258 loop2MBB->addSuccessor(loop1MBB);
1259 loop2MBB->addSuccessor(exitMBB);
1263 // bne dest, oldval, exitMBB
1265 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1266 BuildMI(BB, dl, TII->get(BNE))
1267 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1270 // sc success, newval, 0(ptr)
1271 // beq success, $0, loop1MBB
1273 BuildMI(BB, dl, TII->get(SC), Success)
1274 .addReg(NewVal).addReg(Ptr).addImm(0);
1275 BuildMI(BB, dl, TII->get(BEQ))
1276 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1278 MI->eraseFromParent(); // The instruction is gone now.
1284 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1285 MachineBasicBlock *BB,
1286 unsigned Size) const {
1287 assert((Size == 1 || Size == 2) &&
1288 "Unsupported size for EmitAtomicCmpSwapPartial.");
1290 MachineFunction *MF = BB->getParent();
1291 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1292 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1293 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1294 DebugLoc dl = MI->getDebugLoc();
1295 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1296 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1298 unsigned Dest = MI->getOperand(0).getReg();
1299 unsigned Ptr = MI->getOperand(1).getReg();
1300 unsigned CmpVal = MI->getOperand(2).getReg();
1301 unsigned NewVal = MI->getOperand(3).getReg();
1303 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1304 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1305 unsigned Mask = RegInfo.createVirtualRegister(RC);
1306 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1307 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1308 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1309 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1310 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1311 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1312 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1313 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1314 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1315 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1316 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1317 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1318 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1319 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1320 unsigned Success = RegInfo.createVirtualRegister(RC);
1322 // insert new blocks after the current block
1323 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1324 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1325 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1326 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1327 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1328 MachineFunction::iterator It = BB;
1330 MF->insert(It, loop1MBB);
1331 MF->insert(It, loop2MBB);
1332 MF->insert(It, sinkMBB);
1333 MF->insert(It, exitMBB);
1335 // Transfer the remainder of BB and its successor edges to exitMBB.
1336 exitMBB->splice(exitMBB->begin(), BB,
1337 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1338 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1340 BB->addSuccessor(loop1MBB);
1341 loop1MBB->addSuccessor(sinkMBB);
1342 loop1MBB->addSuccessor(loop2MBB);
1343 loop2MBB->addSuccessor(loop1MBB);
1344 loop2MBB->addSuccessor(sinkMBB);
1345 sinkMBB->addSuccessor(exitMBB);
1347 // FIXME: computation of newval2 can be moved to loop2MBB.
1349 // addiu masklsb2,$0,-4 # 0xfffffffc
1350 // and alignedaddr,ptr,masklsb2
1351 // andi ptrlsb2,ptr,3
1352 // sll shiftamt,ptrlsb2,3
1353 // ori maskupper,$0,255 # 0xff
1354 // sll mask,maskupper,shiftamt
1355 // nor mask2,$0,mask
1356 // andi maskedcmpval,cmpval,255
1357 // sll shiftedcmpval,maskedcmpval,shiftamt
1358 // andi maskednewval,newval,255
1359 // sll shiftednewval,maskednewval,shiftamt
1360 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1361 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1362 .addReg(Mips::ZERO).addImm(-4);
1363 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1364 .addReg(Ptr).addReg(MaskLSB2);
1365 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1366 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1367 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1368 .addReg(Mips::ZERO).addImm(MaskImm);
1369 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1370 .addReg(ShiftAmt).addReg(MaskUpper);
1371 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1372 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1373 .addReg(CmpVal).addImm(MaskImm);
1374 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1375 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1376 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1377 .addReg(NewVal).addImm(MaskImm);
1378 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1379 .addReg(ShiftAmt).addReg(MaskedNewVal);
1382 // ll oldval,0(alginedaddr)
1383 // and maskedoldval0,oldval,mask
1384 // bne maskedoldval0,shiftedcmpval,sinkMBB
1386 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1387 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1388 .addReg(OldVal).addReg(Mask);
1389 BuildMI(BB, dl, TII->get(Mips::BNE))
1390 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1393 // and maskedoldval1,oldval,mask2
1394 // or storeval,maskedoldval1,shiftednewval
1395 // sc success,storeval,0(alignedaddr)
1396 // beq success,$0,loop1MBB
1398 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1399 .addReg(OldVal).addReg(Mask2);
1400 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1401 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1402 BuildMI(BB, dl, TII->get(SC), Success)
1403 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1404 BuildMI(BB, dl, TII->get(Mips::BEQ))
1405 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1408 // srl srlres,maskedoldval0,shiftamt
1409 // sll sllres,srlres,24
1410 // sra dest,sllres,24
1412 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1414 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1415 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1416 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1417 .addReg(SrlRes).addImm(ShiftImm);
1418 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1419 .addReg(SllRes).addImm(ShiftImm);
1421 MI->eraseFromParent(); // The instruction is gone now.
1426 //===----------------------------------------------------------------------===//
1427 // Misc Lower Operation implementation
1428 //===----------------------------------------------------------------------===//
1429 SDValue MipsTargetLowering::
1430 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1432 MachineFunction &MF = DAG.getMachineFunction();
1433 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1434 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1436 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1437 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1438 "Cannot lower if the alignment of the allocated space is larger than \
1439 that of the stack.");
1441 SDValue Chain = Op.getOperand(0);
1442 SDValue Size = Op.getOperand(1);
1443 DebugLoc dl = Op.getDebugLoc();
1445 // Get a reference from Mips stack pointer
1446 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1448 // Subtract the dynamic size from the actual stack size to
1449 // obtain the new stack size.
1450 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1452 // The Sub result contains the new stack start address, so it
1453 // must be placed in the stack pointer register.
1454 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1456 // This node always has two return values: a new stack pointer
1457 // value and a chain
1458 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1459 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1460 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1462 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1465 SDValue MipsTargetLowering::
1466 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1468 // The first operand is the chain, the second is the condition, the third is
1469 // the block to branch to if the condition is true.
1470 SDValue Chain = Op.getOperand(0);
1471 SDValue Dest = Op.getOperand(2);
1472 DebugLoc dl = Op.getDebugLoc();
1474 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1476 // Return if flag is not set by a floating point comparison.
1477 if (CondRes.getOpcode() != MipsISD::FPCmp)
1480 SDValue CCNode = CondRes.getOperand(2);
1482 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1483 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1485 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1489 SDValue MipsTargetLowering::
1490 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1492 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1494 // Return if flag is not set by a floating point comparison.
1495 if (Cond.getOpcode() != MipsISD::FPCmp)
1498 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1502 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1503 SDValue Cond = CreateFPCmp(DAG, Op);
1505 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1506 "Floating point operand expected.");
1508 SDValue True = DAG.getConstant(1, MVT::i32);
1509 SDValue False = DAG.getConstant(0, MVT::i32);
1511 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1514 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1515 SelectionDAG &DAG) const {
1516 // FIXME there isn't actually debug info here
1517 DebugLoc dl = Op.getDebugLoc();
1518 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1520 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1521 SDVTList VTs = DAG.getVTList(MVT::i32);
1523 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1525 // %gp_rel relocation
1526 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1527 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1529 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1530 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1531 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1533 // %hi/%lo relocation
1534 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1536 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1538 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1539 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1540 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1543 EVT ValTy = Op.getValueType();
1544 bool HasGotOfst = (GV->hasInternalLinkage() ||
1545 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1546 unsigned GotFlag = IsN64 ?
1547 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1548 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1549 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1550 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1551 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1552 MachinePointerInfo(), false, false, false, 0);
1553 // On functions and global targets not internal linked only
1554 // a load from got/GP is necessary for PIC to work.
1557 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1558 IsN64 ? MipsII::MO_GOT_OFST :
1560 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1561 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1564 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1565 SelectionDAG &DAG) const {
1566 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1567 // FIXME there isn't actually debug info here
1568 DebugLoc dl = Op.getDebugLoc();
1570 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1571 // %hi/%lo relocation
1572 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1573 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1574 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1575 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1576 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1579 EVT ValTy = Op.getValueType();
1580 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1581 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1582 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1583 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1584 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1585 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1586 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1587 MachinePointerInfo(), false, false, false, 0);
1588 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1589 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1592 SDValue MipsTargetLowering::
1593 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1595 // If the relocation model is PIC, use the General Dynamic TLS Model or
1596 // Local Dynamic TLS model, otherwise use the Initial Exec or
1597 // Local Exec TLS Model.
1599 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1600 DebugLoc dl = GA->getDebugLoc();
1601 const GlobalValue *GV = GA->getGlobal();
1602 EVT PtrVT = getPointerTy();
1604 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1605 // General Dynamic TLS Model
1606 bool LocalDynamic = GV->hasInternalLinkage();
1607 unsigned Flag = LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
1608 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1609 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1610 GetGlobalReg(DAG, PtrVT), TGA);
1611 unsigned PtrSize = PtrVT.getSizeInBits();
1612 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1614 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1618 Entry.Node = Argument;
1620 Args.push_back(Entry);
1622 std::pair<SDValue, SDValue> CallResult =
1623 LowerCallTo(DAG.getEntryNode(), PtrTy,
1624 false, false, false, false, 0, CallingConv::C,
1625 /*isTailCall=*/false, /*doesNotRet=*/false,
1626 /*isReturnValueUsed=*/true,
1627 TlsGetAddr, Args, DAG, dl);
1629 SDValue Ret = CallResult.first;
1634 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1635 MipsII::MO_DTPREL_HI);
1636 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1637 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1638 MipsII::MO_DTPREL_LO);
1639 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1640 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1641 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1645 if (GV->isDeclaration()) {
1646 // Initial Exec TLS Model
1647 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1648 MipsII::MO_GOTTPREL);
1649 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1651 Offset = DAG.getLoad(PtrVT, dl,
1652 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1653 false, false, false, 0);
1655 // Local Exec TLS Model
1656 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1657 MipsII::MO_TPREL_HI);
1658 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1659 MipsII::MO_TPREL_LO);
1660 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1661 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1662 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1665 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1666 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1669 SDValue MipsTargetLowering::
1670 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1672 SDValue HiPart, JTI, JTILo;
1673 // FIXME there isn't actually debug info here
1674 DebugLoc dl = Op.getDebugLoc();
1675 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1676 EVT PtrVT = Op.getValueType();
1677 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1679 if (!IsPIC && !IsN64) {
1680 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1681 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1682 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1683 } else {// Emit Load from Global Pointer
1684 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1685 unsigned OfstFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1686 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1687 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1689 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1690 MachinePointerInfo(), false, false, false, 0);
1691 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1694 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1695 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1698 SDValue MipsTargetLowering::
1699 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1702 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1703 const Constant *C = N->getConstVal();
1704 // FIXME there isn't actually debug info here
1705 DebugLoc dl = Op.getDebugLoc();
1707 // gp_rel relocation
1708 // FIXME: we should reference the constant pool using small data sections,
1709 // but the asm printer currently doesn't support this feature without
1710 // hacking it. This feature should come soon so we can uncomment the
1712 //if (IsInSmallSection(C->getType())) {
1713 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1714 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1715 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1717 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1718 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1719 N->getOffset(), MipsII::MO_ABS_HI);
1720 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1721 N->getOffset(), MipsII::MO_ABS_LO);
1722 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1723 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1724 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1726 EVT ValTy = Op.getValueType();
1727 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1728 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1729 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1730 N->getOffset(), GOTFlag);
1731 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1732 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1733 MachinePointerInfo::getConstantPool(), false,
1735 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1736 N->getOffset(), OFSTFlag);
1737 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1738 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1744 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1745 MachineFunction &MF = DAG.getMachineFunction();
1746 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1748 DebugLoc dl = Op.getDebugLoc();
1749 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1752 // vastart just stores the address of the VarArgsFrameIndex slot into the
1753 // memory location argument.
1754 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1755 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1756 MachinePointerInfo(SV), false, false, 0);
1759 // Called if the size of integer registers is large enough to hold the whole
1760 // floating point number.
1761 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1762 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1763 EVT ValTy = Op.getValueType();
1764 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1765 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1766 DebugLoc dl = Op.getDebugLoc();
1767 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1768 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1769 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1770 DAG.getConstant(Mask - 1, IntValTy));
1771 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1772 DAG.getConstant(Mask, IntValTy));
1773 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1774 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1777 // Called if the size of integer registers is not large enough to hold the whole
1778 // floating point number (e.g. f64 & 32-bit integer register).
1780 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1782 // Use ext/ins instructions if target architecture is Mips32r2.
1783 // Eliminate redundant mfc1 and mtc1 instructions.
1784 unsigned LoIdx = 0, HiIdx = 1;
1787 std::swap(LoIdx, HiIdx);
1789 DebugLoc dl = Op.getDebugLoc();
1790 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1792 DAG.getConstant(LoIdx, MVT::i32));
1793 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1794 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1795 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1796 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1797 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1798 DAG.getConstant(0x7fffffff, MVT::i32));
1799 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1800 DAG.getConstant(0x80000000, MVT::i32));
1801 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1804 std::swap(Word0, Word1);
1806 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1810 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1811 EVT Ty = Op.getValueType();
1813 assert(Ty == MVT::f32 || Ty == MVT::f64);
1815 if (Ty == MVT::f32 || HasMips64)
1816 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1818 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1821 SDValue MipsTargetLowering::
1822 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1824 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1825 "Frame address can only be determined for current frame.");
1827 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1828 MFI->setFrameAddressIsTaken(true);
1829 EVT VT = Op.getValueType();
1830 DebugLoc dl = Op.getDebugLoc();
1831 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1832 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1836 // TODO: set SType according to the desired memory barrier behavior.
1838 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1840 DebugLoc dl = Op.getDebugLoc();
1841 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1842 DAG.getConstant(SType, MVT::i32));
1845 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1846 SelectionDAG& DAG) const {
1847 // FIXME: Need pseudo-fence for 'singlethread' fences
1848 // FIXME: Set SType for weaker fences where supported/appropriate.
1850 DebugLoc dl = Op.getDebugLoc();
1851 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1852 DAG.getConstant(SType, MVT::i32));
1855 //===----------------------------------------------------------------------===//
1856 // Calling Convention Implementation
1857 //===----------------------------------------------------------------------===//
1859 //===----------------------------------------------------------------------===//
1860 // TODO: Implement a generic logic using tblgen that can support this.
1861 // Mips O32 ABI rules:
1863 // i32 - Passed in A0, A1, A2, A3 and stack
1864 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1865 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1866 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1867 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1868 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1871 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1872 //===----------------------------------------------------------------------===//
1874 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1875 MVT LocVT, CCValAssign::LocInfo LocInfo,
1876 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1878 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1880 static const uint16_t IntRegs[] = {
1881 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1883 static const uint16_t F32Regs[] = {
1884 Mips::F12, Mips::F14
1886 static const uint16_t F64Regs[] = {
1891 if (ArgFlags.isByVal()) {
1892 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1893 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1894 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1895 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1896 r < std::min(IntRegsSize, NextReg); ++r)
1897 State.AllocateReg(IntRegs[r]);
1901 // Promote i8 and i16
1902 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1904 if (ArgFlags.isSExt())
1905 LocInfo = CCValAssign::SExt;
1906 else if (ArgFlags.isZExt())
1907 LocInfo = CCValAssign::ZExt;
1909 LocInfo = CCValAssign::AExt;
1914 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1915 // is true: function is vararg, argument is 3rd or higher, there is previous
1916 // argument which is not f32 or f64.
1917 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1918 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1919 unsigned OrigAlign = ArgFlags.getOrigAlign();
1920 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1922 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1923 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1924 // If this is the first part of an i64 arg,
1925 // the allocated register must be either A0 or A2.
1926 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1927 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1929 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1930 // Allocate int register and shadow next int register. If first
1931 // available register is Mips::A1 or Mips::A3, shadow it too.
1932 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1933 if (Reg == Mips::A1 || Reg == Mips::A3)
1934 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1935 State.AllocateReg(IntRegs, IntRegsSize);
1937 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1938 // we are guaranteed to find an available float register
1939 if (ValVT == MVT::f32) {
1940 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1941 // Shadow int register
1942 State.AllocateReg(IntRegs, IntRegsSize);
1944 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1945 // Shadow int registers
1946 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1947 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1948 State.AllocateReg(IntRegs, IntRegsSize);
1949 State.AllocateReg(IntRegs, IntRegsSize);
1952 llvm_unreachable("Cannot handle this ValVT.");
1954 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1955 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1958 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1960 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1962 return false; // CC must always match
1965 static const uint16_t Mips64IntRegs[8] =
1966 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1967 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1968 static const uint16_t Mips64DPRegs[8] =
1969 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1970 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1972 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1973 CCValAssign::LocInfo LocInfo,
1974 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1975 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1976 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1977 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1979 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1981 // If byval is 16-byte aligned, the first arg register must be even.
1982 if ((Align == 16) && (FirstIdx % 2)) {
1983 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1987 // Mark the registers allocated.
1988 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1989 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1991 // Allocate space on caller's stack.
1992 unsigned Offset = State.AllocateStack(Size, Align);
1995 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1998 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2003 #include "MipsGenCallingConv.inc"
2006 AnalyzeMips64CallOperands(CCState &CCInfo,
2007 const SmallVectorImpl<ISD::OutputArg> &Outs) {
2008 unsigned NumOps = Outs.size();
2009 for (unsigned i = 0; i != NumOps; ++i) {
2010 MVT ArgVT = Outs[i].VT;
2011 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2014 if (Outs[i].IsFixed)
2015 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2017 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2021 dbgs() << "Call operand #" << i << " has unhandled type "
2022 << EVT(ArgVT).getEVTString();
2024 llvm_unreachable(0);
2029 //===----------------------------------------------------------------------===//
2030 // Call Calling Convention Implementation
2031 //===----------------------------------------------------------------------===//
2033 static const unsigned O32IntRegsSize = 4;
2035 static const uint16_t O32IntRegs[] = {
2036 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2039 // Return next O32 integer argument register.
2040 static unsigned getNextIntArgReg(unsigned Reg) {
2041 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2042 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2045 // Write ByVal Arg to arg registers and stack.
2047 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2048 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2049 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2050 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2051 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2052 MVT PtrType, bool isLittle) {
2053 unsigned LocMemOffset = VA.getLocMemOffset();
2054 unsigned Offset = 0;
2055 uint32_t RemainingSize = Flags.getByValSize();
2056 unsigned ByValAlign = Flags.getByValAlign();
2058 // Copy the first 4 words of byval arg to registers A0 - A3.
2059 // FIXME: Use a stricter alignment if it enables better optimization in passes
2061 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2062 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2063 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2064 DAG.getConstant(Offset, MVT::i32));
2065 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2066 MachinePointerInfo(), false, false, false,
2067 std::min(ByValAlign, (unsigned )4));
2068 MemOpChains.push_back(LoadVal.getValue(1));
2069 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2070 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2073 if (RemainingSize == 0)
2076 // If there still is a register available for argument passing, write the
2077 // remaining part of the structure to it using subword loads and shifts.
2078 if (LocMemOffset < 4 * 4) {
2079 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2080 "There must be one to three bytes remaining.");
2081 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2082 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2083 DAG.getConstant(Offset, MVT::i32));
2084 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2085 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2086 LoadPtr, MachinePointerInfo(),
2087 MVT::getIntegerVT(LoadSize * 8), false,
2089 MemOpChains.push_back(LoadVal.getValue(1));
2091 // If target is big endian, shift it to the most significant half-word or
2094 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2095 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2098 RemainingSize -= LoadSize;
2100 // Read second subword if necessary.
2101 if (RemainingSize != 0) {
2102 assert(RemainingSize == 1 && "There must be one byte remaining.");
2103 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2104 DAG.getConstant(Offset, MVT::i32));
2105 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2106 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2107 LoadPtr, MachinePointerInfo(),
2108 MVT::i8, false, false, Alignment);
2109 MemOpChains.push_back(Subword.getValue(1));
2110 // Insert the loaded byte to LoadVal.
2111 // FIXME: Use INS if supported by target.
2112 unsigned ShiftAmt = isLittle ? 16 : 8;
2113 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2114 DAG.getConstant(ShiftAmt, MVT::i32));
2115 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2118 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2119 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2123 // Create a fixed object on stack at offset LocMemOffset and copy
2124 // remaining part of byval arg to it using memcpy.
2125 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2126 DAG.getConstant(Offset, MVT::i32));
2127 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2128 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2129 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2130 DAG.getConstant(RemainingSize, MVT::i32),
2131 std::min(ByValAlign, (unsigned)4),
2132 /*isVolatile=*/false, /*AlwaysInline=*/false,
2133 MachinePointerInfo(0), MachinePointerInfo(0));
2136 // Copy Mips64 byVal arg to registers and stack.
2138 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2139 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2140 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2141 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2142 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2143 EVT PtrTy, bool isLittle) {
2144 unsigned ByValSize = Flags.getByValSize();
2145 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2146 bool IsRegLoc = VA.isRegLoc();
2147 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2148 unsigned LocMemOffset = 0;
2149 unsigned MemCpySize = ByValSize;
2152 LocMemOffset = VA.getLocMemOffset();
2154 const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2156 const uint16_t *RegEnd = Mips64IntRegs + 8;
2158 // Copy double words to registers.
2159 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2160 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2161 DAG.getConstant(Offset, PtrTy));
2162 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2163 MachinePointerInfo(), false, false, false,
2165 MemOpChains.push_back(LoadVal.getValue(1));
2166 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2169 // Return if the struct has been fully copied.
2170 if (!(MemCpySize = ByValSize - Offset))
2173 // If there is an argument register available, copy the remainder of the
2174 // byval argument with sub-doubleword loads and shifts.
2175 if (Reg != RegEnd) {
2176 assert((ByValSize < Offset + 8) &&
2177 "Size of the remainder should be smaller than 8-byte.");
2179 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2180 unsigned RemSize = ByValSize - Offset;
2182 if (RemSize < LoadSize)
2185 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2186 DAG.getConstant(Offset, PtrTy));
2188 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2189 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2190 false, false, Alignment);
2191 MemOpChains.push_back(LoadVal.getValue(1));
2193 // Offset in number of bits from double word boundary.
2194 unsigned OffsetDW = (Offset % 8) * 8;
2195 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2196 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2197 DAG.getConstant(Shamt, MVT::i32));
2199 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2202 Alignment = std::min(Alignment, LoadSize);
2205 RegsToPass.push_back(std::make_pair(*Reg, Val));
2210 assert(MemCpySize && "MemCpySize must not be zero.");
2212 // Create a fixed object on stack at offset LocMemOffset and copy
2213 // remainder of byval arg to it with memcpy.
2214 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2215 DAG.getConstant(Offset, PtrTy));
2216 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2217 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2218 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2219 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2220 /*isVolatile=*/false, /*AlwaysInline=*/false,
2221 MachinePointerInfo(0), MachinePointerInfo(0));
2224 /// LowerCall - functions arguments are copied from virtual regs to
2225 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2226 /// TODO: isTailCall.
2228 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2229 CallingConv::ID CallConv, bool isVarArg,
2230 bool doesNotRet, bool &isTailCall,
2231 const SmallVectorImpl<ISD::OutputArg> &Outs,
2232 const SmallVectorImpl<SDValue> &OutVals,
2233 const SmallVectorImpl<ISD::InputArg> &Ins,
2234 DebugLoc dl, SelectionDAG &DAG,
2235 SmallVectorImpl<SDValue> &InVals) const {
2236 // MIPs target does not yet support tail call optimization.
2239 MachineFunction &MF = DAG.getMachineFunction();
2240 MachineFrameInfo *MFI = MF.getFrameInfo();
2241 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2242 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2243 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2245 // Analyze operands of the call, assigning locations to each operand.
2246 SmallVector<CCValAssign, 16> ArgLocs;
2247 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2248 getTargetMachine(), ArgLocs, *DAG.getContext());
2251 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2253 AnalyzeMips64CallOperands(CCInfo, Outs);
2255 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2257 // Get a count of how many bytes are to be pushed on the stack.
2258 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2260 // Chain is the output chain of the last Load/Store or CopyToReg node.
2261 // ByValChain is the output chain of the last Memcpy node created for copying
2262 // byval arguments to the stack.
2263 SDValue Chain, CallSeqStart, ByValChain;
2264 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2265 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2266 ByValChain = InChain;
2268 // If this is the first call, create a stack frame object that points to
2269 // a location to which .cprestore saves $gp.
2270 if (IsO32 && IsPIC && MipsFI->globalBaseRegFixed() && !MipsFI->getGPFI())
2271 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2273 // Get the frame index of the stack frame object that points to the location
2274 // of dynamically allocated area on the stack.
2275 int DynAllocFI = MipsFI->getDynAllocFI();
2277 // Update size of the maximum argument space.
2278 // For O32, a minimum of four words (16 bytes) of argument space is
2281 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2283 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2285 if (MaxCallFrameSize < NextStackOffset) {
2286 MipsFI->setMaxCallFrameSize(NextStackOffset);
2288 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2289 // allocated stack space. These offsets must be aligned to a boundary
2290 // determined by the stack alignment of the ABI.
2291 unsigned StackAlignment = TFL->getStackAlignment();
2292 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2293 StackAlignment * StackAlignment;
2295 if (MipsFI->needGPSaveRestore())
2296 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2298 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2301 // With EABI is it possible to have 16 args on registers.
2302 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2303 SmallVector<SDValue, 8> MemOpChains;
2305 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2307 // Walk the register/memloc assignments, inserting copies/loads.
2308 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2309 SDValue Arg = OutVals[i];
2310 CCValAssign &VA = ArgLocs[i];
2311 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2312 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2315 if (Flags.isByVal()) {
2316 assert(Flags.getByValSize() &&
2317 "ByVal args of size 0 should have been ignored by front-end.");
2319 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2320 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2321 Subtarget->isLittle());
2323 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2324 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2325 Subtarget->isLittle());
2329 // Promote the value if needed.
2330 switch (VA.getLocInfo()) {
2331 default: llvm_unreachable("Unknown loc info!");
2332 case CCValAssign::Full:
2333 if (VA.isRegLoc()) {
2334 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2335 (ValVT == MVT::f64 && LocVT == MVT::i64))
2336 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2337 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2338 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2339 Arg, DAG.getConstant(0, MVT::i32));
2340 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2341 Arg, DAG.getConstant(1, MVT::i32));
2342 if (!Subtarget->isLittle())
2344 unsigned LocRegLo = VA.getLocReg();
2345 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2346 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2347 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2352 case CCValAssign::SExt:
2353 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2355 case CCValAssign::ZExt:
2356 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2358 case CCValAssign::AExt:
2359 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2363 // Arguments that can be passed on register must be kept at
2364 // RegsToPass vector
2365 if (VA.isRegLoc()) {
2366 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2370 // Register can't get to this point...
2371 assert(VA.isMemLoc());
2373 // Create the frame index object for this incoming parameter
2374 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2375 VA.getLocMemOffset(), true);
2376 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2378 // emit ISD::STORE whichs stores the
2379 // parameter value to a stack Location
2380 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2381 MachinePointerInfo(), false, false, 0));
2384 // Extend range of indices of frame objects for outgoing arguments that were
2385 // created during this function call. Skip this step if no such objects were
2388 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2390 // If a memcpy has been created to copy a byval arg to a stack, replace the
2391 // chain input of CallSeqStart with ByValChain.
2392 if (InChain != ByValChain)
2393 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2394 NextStackOffsetVal);
2396 // Transform all store nodes into one single node because all store
2397 // nodes are independent of each other.
2398 if (!MemOpChains.empty())
2399 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2400 &MemOpChains[0], MemOpChains.size());
2402 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2403 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2404 // node so that legalize doesn't hack it.
2405 unsigned char OpFlag;
2406 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2407 bool GlobalOrExternal = false;
2410 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2411 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2412 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2413 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2414 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2416 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2419 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2420 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2421 getPointerTy(), 0, OpFlag);
2424 GlobalOrExternal = true;
2426 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2427 if (IsN64 || (!IsO32 && IsPIC))
2428 OpFlag = MipsII::MO_GOT_DISP;
2429 else if (!IsPIC) // !N64 && static
2430 OpFlag = MipsII::MO_NO_FLAG;
2432 OpFlag = MipsII::MO_GOT_CALL;
2433 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2435 GlobalOrExternal = true;
2440 // Create nodes that load address of callee and copy it to T9
2442 if (GlobalOrExternal) {
2443 // Load callee address
2444 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2445 GetGlobalReg(DAG, getPointerTy()), Callee);
2446 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2447 Callee, MachinePointerInfo::getGOT(),
2448 false, false, false, 0);
2450 // Use GOT+LO if callee has internal linkage.
2451 if (CalleeLo.getNode()) {
2452 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2453 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2459 // T9 should contain the address of the callee function if
2460 // -reloction-model=pic or it is an indirect call.
2461 if (IsPICCall || !GlobalOrExternal) {
2463 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2464 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2465 InFlag = Chain.getValue(1);
2466 Callee = DAG.getRegister(T9Reg, getPointerTy());
2469 // Build a sequence of copy-to-reg nodes chained together with token
2470 // chain and flag operands which copy the outgoing args into registers.
2471 // The InFlag in necessary since all emitted instructions must be
2473 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2474 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2475 RegsToPass[i].second, InFlag);
2476 InFlag = Chain.getValue(1);
2479 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2480 // = Chain, Callee, Reg#1, Reg#2, ...
2482 // Returns a chain & a flag for retval copy to use.
2483 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2484 SmallVector<SDValue, 8> Ops;
2485 Ops.push_back(Chain);
2486 Ops.push_back(Callee);
2488 // Add argument registers to the end of the list so that they are
2489 // known live into the call.
2490 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2491 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2492 RegsToPass[i].second.getValueType()));
2494 // Add a register mask operand representing the call-preserved registers.
2495 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2496 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2497 assert(Mask && "Missing call preserved mask for calling convention");
2498 Ops.push_back(DAG.getRegisterMask(Mask));
2500 if (InFlag.getNode())
2501 Ops.push_back(InFlag);
2503 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2504 InFlag = Chain.getValue(1);
2506 // Create the CALLSEQ_END node.
2507 Chain = DAG.getCALLSEQ_END(Chain,
2508 DAG.getIntPtrConstant(NextStackOffset, true),
2509 DAG.getIntPtrConstant(0, true), InFlag);
2510 InFlag = Chain.getValue(1);
2512 // Handle result values, copying them out of physregs into vregs that we
2514 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2515 Ins, dl, DAG, InVals);
2518 /// LowerCallResult - Lower the result values of a call into the
2519 /// appropriate copies out of appropriate physical registers.
2521 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2522 CallingConv::ID CallConv, bool isVarArg,
2523 const SmallVectorImpl<ISD::InputArg> &Ins,
2524 DebugLoc dl, SelectionDAG &DAG,
2525 SmallVectorImpl<SDValue> &InVals) const {
2526 // Assign locations to each value returned by this call.
2527 SmallVector<CCValAssign, 16> RVLocs;
2528 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2529 getTargetMachine(), RVLocs, *DAG.getContext());
2531 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2533 // Copy all of the result registers out of their specified physreg.
2534 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2535 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2536 RVLocs[i].getValVT(), InFlag).getValue(1);
2537 InFlag = Chain.getValue(2);
2538 InVals.push_back(Chain.getValue(0));
2544 //===----------------------------------------------------------------------===//
2545 // Formal Arguments Calling Convention Implementation
2546 //===----------------------------------------------------------------------===//
2547 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2548 std::vector<SDValue>& OutChains,
2549 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2550 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2551 const Argument *FuncArg) {
2552 unsigned LocMem = VA.getLocMemOffset();
2553 unsigned FirstWord = LocMem / 4;
2555 // copy register A0 - A3 to frame object
2556 for (unsigned i = 0; i < NumWords; ++i) {
2557 unsigned CurWord = FirstWord + i;
2558 if (CurWord >= O32IntRegsSize)
2561 unsigned SrcReg = O32IntRegs[CurWord];
2562 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2563 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2564 DAG.getConstant(i * 4, MVT::i32));
2565 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2566 StorePtr, MachinePointerInfo(FuncArg, i * 4),
2568 OutChains.push_back(Store);
2572 // Create frame object on stack and copy registers used for byval passing to it.
2574 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2575 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2576 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2577 MachineFrameInfo *MFI, bool IsRegLoc,
2578 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2579 EVT PtrTy, const Argument *FuncArg) {
2580 const uint16_t *Reg = Mips64IntRegs + 8;
2581 int FOOffset; // Frame object offset from virtual frame pointer.
2584 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2585 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2588 FOOffset = VA.getLocMemOffset();
2590 // Create frame object.
2591 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2592 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2593 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2594 InVals.push_back(FIN);
2596 // Copy arg registers.
2597 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2599 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2600 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2601 DAG.getConstant(I * 8, PtrTy));
2602 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2603 StorePtr, MachinePointerInfo(FuncArg, I * 8),
2605 OutChains.push_back(Store);
2611 /// LowerFormalArguments - transform physical registers into virtual registers
2612 /// and generate load operations for arguments places on the stack.
2614 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2615 CallingConv::ID CallConv,
2617 const SmallVectorImpl<ISD::InputArg> &Ins,
2618 DebugLoc dl, SelectionDAG &DAG,
2619 SmallVectorImpl<SDValue> &InVals)
2621 MachineFunction &MF = DAG.getMachineFunction();
2622 MachineFrameInfo *MFI = MF.getFrameInfo();
2623 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2625 MipsFI->setVarArgsFrameIndex(0);
2627 // Used with vargs to acumulate store chains.
2628 std::vector<SDValue> OutChains;
2630 // Assign locations to all of the incoming arguments.
2631 SmallVector<CCValAssign, 16> ArgLocs;
2632 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2633 getTargetMachine(), ArgLocs, *DAG.getContext());
2636 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2638 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2640 Function::const_arg_iterator FuncArg =
2641 DAG.getMachineFunction().getFunction()->arg_begin();
2642 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2644 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
2645 CCValAssign &VA = ArgLocs[i];
2646 EVT ValVT = VA.getValVT();
2647 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2648 bool IsRegLoc = VA.isRegLoc();
2650 if (Flags.isByVal()) {
2651 assert(Flags.getByValSize() &&
2652 "ByVal args of size 0 should have been ignored by front-end.");
2654 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2655 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2657 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2658 InVals.push_back(FIN);
2659 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
2662 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2663 MFI, IsRegLoc, InVals, MipsFI,
2664 getPointerTy(), &*FuncArg);
2668 // Arguments stored on registers
2670 EVT RegVT = VA.getLocVT();
2671 unsigned ArgReg = VA.getLocReg();
2672 const TargetRegisterClass *RC;
2674 if (RegVT == MVT::i32)
2675 RC = Mips::CPURegsRegisterClass;
2676 else if (RegVT == MVT::i64)
2677 RC = Mips::CPU64RegsRegisterClass;
2678 else if (RegVT == MVT::f32)
2679 RC = Mips::FGR32RegisterClass;
2680 else if (RegVT == MVT::f64)
2681 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2683 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2685 // Transform the arguments stored on
2686 // physical registers into virtual ones
2687 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2688 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2690 // If this is an 8 or 16-bit value, it has been passed promoted
2691 // to 32 bits. Insert an assert[sz]ext to capture this, then
2692 // truncate to the right size.
2693 if (VA.getLocInfo() != CCValAssign::Full) {
2694 unsigned Opcode = 0;
2695 if (VA.getLocInfo() == CCValAssign::SExt)
2696 Opcode = ISD::AssertSext;
2697 else if (VA.getLocInfo() == CCValAssign::ZExt)
2698 Opcode = ISD::AssertZext;
2700 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2701 DAG.getValueType(ValVT));
2702 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2705 // Handle floating point arguments passed in integer registers.
2706 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2707 (RegVT == MVT::i64 && ValVT == MVT::f64))
2708 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2709 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2710 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2711 getNextIntArgReg(ArgReg), RC);
2712 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2713 if (!Subtarget->isLittle())
2714 std::swap(ArgValue, ArgValue2);
2715 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2716 ArgValue, ArgValue2);
2719 InVals.push_back(ArgValue);
2720 } else { // VA.isRegLoc()
2723 assert(VA.isMemLoc());
2725 // The stack pointer offset is relative to the caller stack frame.
2726 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2727 VA.getLocMemOffset(), true);
2729 // Create load nodes to retrieve arguments from the stack
2730 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2731 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2732 MachinePointerInfo::getFixedStack(LastFI),
2733 false, false, false, 0));
2737 // The mips ABIs for returning structs by value requires that we copy
2738 // the sret argument into $v0 for the return. Save the argument into
2739 // a virtual register so that we can access it from the return points.
2740 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2741 unsigned Reg = MipsFI->getSRetReturnReg();
2743 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2744 MipsFI->setSRetReturnReg(Reg);
2746 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2747 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2751 unsigned NumOfRegs = IsO32 ? 4 : 8;
2752 const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2753 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2754 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2755 const TargetRegisterClass *RC
2756 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2757 unsigned RegSize = RC->getSize();
2758 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2760 // Offset of the first variable argument from stack pointer.
2761 int FirstVaArgOffset;
2763 if (IsO32 || (Idx == NumOfRegs)) {
2765 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2767 FirstVaArgOffset = RegSlotOffset;
2769 // Record the frame index of the first variable argument
2770 // which is a value necessary to VASTART.
2771 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2772 MipsFI->setVarArgsFrameIndex(LastFI);
2774 // Copy the integer registers that have not been used for argument passing
2775 // to the argument register save area. For O32, the save area is allocated
2776 // in the caller's stack frame, while for N32/64, it is allocated in the
2777 // callee's stack frame.
2778 for (int StackOffset = RegSlotOffset;
2779 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2780 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2781 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2782 MVT::getIntegerVT(RegSize * 8));
2783 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2784 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2785 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2786 MachinePointerInfo(), false, false, 0));
2790 MipsFI->setLastInArgFI(LastFI);
2792 // All stores are grouped in one node to allow the matching between
2793 // the size of Ins and InVals. This only happens when on varg functions
2794 if (!OutChains.empty()) {
2795 OutChains.push_back(Chain);
2796 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2797 &OutChains[0], OutChains.size());
2803 //===----------------------------------------------------------------------===//
2804 // Return Value Calling Convention Implementation
2805 //===----------------------------------------------------------------------===//
2808 MipsTargetLowering::LowerReturn(SDValue Chain,
2809 CallingConv::ID CallConv, bool isVarArg,
2810 const SmallVectorImpl<ISD::OutputArg> &Outs,
2811 const SmallVectorImpl<SDValue> &OutVals,
2812 DebugLoc dl, SelectionDAG &DAG) const {
2814 // CCValAssign - represent the assignment of
2815 // the return value to a location
2816 SmallVector<CCValAssign, 16> RVLocs;
2818 // CCState - Info about the registers and stack slot.
2819 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2820 getTargetMachine(), RVLocs, *DAG.getContext());
2822 // Analize return values.
2823 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2825 // If this is the first return lowered for this function, add
2826 // the regs to the liveout set for the function.
2827 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2828 for (unsigned i = 0; i != RVLocs.size(); ++i)
2829 if (RVLocs[i].isRegLoc())
2830 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2835 // Copy the result values into the output registers.
2836 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2837 CCValAssign &VA = RVLocs[i];
2838 assert(VA.isRegLoc() && "Can only return in registers!");
2840 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
2842 // guarantee that all emitted copies are
2843 // stuck together, avoiding something bad
2844 Flag = Chain.getValue(1);
2847 // The mips ABIs for returning structs by value requires that we copy
2848 // the sret argument into $v0 for the return. We saved the argument into
2849 // a virtual register in the entry block, so now we copy the value out
2851 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2852 MachineFunction &MF = DAG.getMachineFunction();
2853 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2854 unsigned Reg = MipsFI->getSRetReturnReg();
2857 llvm_unreachable("sret virtual register not created in the entry block");
2858 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2860 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2861 Flag = Chain.getValue(1);
2864 // Return on Mips is always a "jr $ra"
2866 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2867 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2869 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2870 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2873 //===----------------------------------------------------------------------===//
2874 // Mips Inline Assembly Support
2875 //===----------------------------------------------------------------------===//
2877 /// getConstraintType - Given a constraint letter, return the type of
2878 /// constraint it is for this target.
2879 MipsTargetLowering::ConstraintType MipsTargetLowering::
2880 getConstraintType(const std::string &Constraint) const
2882 // Mips specific constrainy
2883 // GCC config/mips/constraints.md
2885 // 'd' : An address register. Equivalent to r
2886 // unless generating MIPS16 code.
2887 // 'y' : Equivalent to r; retained for
2888 // backwards compatibility.
2889 // 'f' : Floating Point registers.
2890 if (Constraint.size() == 1) {
2891 switch (Constraint[0]) {
2896 return C_RegisterClass;
2899 return TargetLowering::getConstraintType(Constraint);
2902 /// Examine constraint type and operand type and determine a weight value.
2903 /// This object must already have been set up with the operand type
2904 /// and the current alternative constraint selected.
2905 TargetLowering::ConstraintWeight
2906 MipsTargetLowering::getSingleConstraintMatchWeight(
2907 AsmOperandInfo &info, const char *constraint) const {
2908 ConstraintWeight weight = CW_Invalid;
2909 Value *CallOperandVal = info.CallOperandVal;
2910 // If we don't have a value, we can't do a match,
2911 // but allow it at the lowest weight.
2912 if (CallOperandVal == NULL)
2914 Type *type = CallOperandVal->getType();
2915 // Look at the constraint type.
2916 switch (*constraint) {
2918 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2922 if (type->isIntegerTy())
2923 weight = CW_Register;
2926 if (type->isFloatTy())
2927 weight = CW_Register;
2933 /// Given a register class constraint, like 'r', if this corresponds directly
2934 /// to an LLVM register class, return a register of 0 and the register class
2936 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2937 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2939 if (Constraint.size() == 1) {
2940 switch (Constraint[0]) {
2941 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2942 case 'y': // Same as 'r'. Exists for compatibility.
2945 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2946 assert(VT == MVT::i64 && "Unexpected type.");
2947 return std::make_pair(0U, Mips::CPU64RegsRegisterClass);
2950 return std::make_pair(0U, Mips::FGR32RegisterClass);
2951 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2952 if (Subtarget->isFP64bit())
2953 return std::make_pair(0U, Mips::FGR64RegisterClass);
2955 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2959 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2963 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2964 // The Mips target isn't yet aware of offsets.
2968 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2969 if (VT != MVT::f32 && VT != MVT::f64)
2971 if (Imm.isNegZero())
2973 return Imm.isZero();
2976 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2978 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
2980 return TargetLowering::getJumpTableEncoding();