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 "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
37 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
39 case MipsISD::JmpLink : return "MipsISD::JmpLink";
40 case MipsISD::Hi : return "MipsISD::Hi";
41 case MipsISD::Lo : return "MipsISD::Lo";
42 case MipsISD::GPRel : return "MipsISD::GPRel";
43 case MipsISD::Ret : return "MipsISD::Ret";
44 case MipsISD::SelectCC : return "MipsISD::SelectCC";
45 case MipsISD::FPSelectCC : return "MipsISD::FPSelectCC";
46 case MipsISD::FPBrcond : return "MipsISD::FPBrcond";
47 case MipsISD::FPCmp : return "MipsISD::FPCmp";
48 case MipsISD::FPRound : return "MipsISD::FPRound";
49 case MipsISD::MAdd : return "MipsISD::MAdd";
50 case MipsISD::MAddu : return "MipsISD::MAddu";
51 case MipsISD::MSub : return "MipsISD::MSub";
52 case MipsISD::MSubu : return "MipsISD::MSubu";
53 default : return NULL;
58 MipsTargetLowering(MipsTargetMachine &TM)
59 : TargetLowering(TM, new MipsTargetObjectFile()) {
60 Subtarget = &TM.getSubtarget<MipsSubtarget>();
62 // Mips does not have i1 type, so use i32 for
63 // setcc operations results (slt, sgt, ...).
64 setBooleanContents(ZeroOrOneBooleanContent);
66 // Set up the register classes
67 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
68 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
70 // When dealing with single precision only, use libcalls
71 if (!Subtarget->isSingleFloat())
72 if (!Subtarget->isFP64bit())
73 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
75 // Load extented operations for i1 types must be promoted
76 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
77 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
78 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
80 // MIPS doesn't have extending float->double load/store
81 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
82 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
84 // Used by legalize types to correctly generate the setcc result.
85 // Without this, every float setcc comes with a AND/OR with the result,
86 // we don't want this, since the fpcmp result goes to a flag register,
87 // which is used implicitly by brcond and select operations.
88 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
90 // Mips Custom Operations
91 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
92 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
93 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
94 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
95 setOperationAction(ISD::SELECT, MVT::f32, Custom);
96 setOperationAction(ISD::SELECT, MVT::f64, Custom);
97 setOperationAction(ISD::SELECT, MVT::i32, Custom);
98 setOperationAction(ISD::SETCC, MVT::f32, Custom);
99 setOperationAction(ISD::SETCC, MVT::f64, Custom);
100 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
101 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
102 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
103 setOperationAction(ISD::VASTART, MVT::Other, Custom);
106 // We custom lower AND/OR to handle the case where the DAG contain 'ands/ors'
107 // with operands comming from setcc fp comparions. This is necessary since
108 // the result from these setcc are in a flag registers (FCR31).
109 setOperationAction(ISD::AND, MVT::i32, Custom);
110 setOperationAction(ISD::OR, MVT::i32, Custom);
112 // Operations not directly supported by Mips.
113 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
114 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
115 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
116 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
117 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
119 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
120 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
121 setOperationAction(ISD::ROTL, MVT::i32, Expand);
123 if (!Subtarget->isMips32r2())
124 setOperationAction(ISD::ROTR, MVT::i32, Expand);
126 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
127 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
128 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
129 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
130 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
131 setOperationAction(ISD::FSIN, MVT::f32, Expand);
132 setOperationAction(ISD::FCOS, MVT::f32, Expand);
133 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
134 setOperationAction(ISD::FPOW, MVT::f32, Expand);
135 setOperationAction(ISD::FLOG, MVT::f32, Expand);
136 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
137 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
138 setOperationAction(ISD::FEXP, MVT::f32, Expand);
140 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
142 // Use the default for now
143 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
144 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
145 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
147 if (Subtarget->isSingleFloat())
148 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
150 if (!Subtarget->hasSEInReg()) {
151 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
152 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
155 if (!Subtarget->hasBitCount())
156 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
158 if (!Subtarget->hasSwap())
159 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
161 setTargetDAGCombine(ISD::ADDE);
162 setTargetDAGCombine(ISD::SUBE);
164 setStackPointerRegisterToSaveRestore(Mips::SP);
165 computeRegisterProperties();
168 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
172 /// getFunctionAlignment - Return the Log2 alignment of this function.
173 unsigned MipsTargetLowering::getFunctionAlignment(const Function *) const {
178 // Transforms a subgraph in CurDAG if the following pattern is found:
179 // (addc multLo, Lo0), (adde multHi, Hi0),
181 // multHi/Lo: product of multiplication
182 // Lo0: initial value of Lo register
183 // Hi0: initial value of Hi register
184 // Return true if mattern matching was successful.
185 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
186 // ADDENode's second operand must be a flag output of an ADDC node in order
187 // for the matching to be successful.
188 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
190 if (ADDCNode->getOpcode() != ISD::ADDC)
193 SDValue MultHi = ADDENode->getOperand(0);
194 SDValue MultLo = ADDCNode->getOperand(0);
195 SDNode* MultNode = MultHi.getNode();
196 unsigned MultOpc = MultHi.getOpcode();
198 // MultHi and MultLo must be generated by the same node,
199 if (MultLo.getNode() != MultNode)
202 // and it must be a multiplication.
203 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
206 // MultLo amd MultHi must be the first and second output of MultNode
208 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
211 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
212 // of the values of MultNode, in which case MultNode will be removed in later
214 // If there exist users other than ADDENode or ADDCNode, this function returns
215 // here, which will result in MultNode being mapped to a single MULT
216 // instruction node rather than a pair of MULT and MADD instructions being
218 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
221 SDValue Chain = CurDAG->getEntryNode();
222 DebugLoc dl = ADDENode->getDebugLoc();
224 // create MipsMAdd(u) node
225 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
227 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
229 MultNode->getOperand(0),// Factor 0
230 MultNode->getOperand(1),// Factor 1
231 ADDCNode->getOperand(1),// Lo0
232 ADDENode->getOperand(1));// Hi0
234 // create CopyFromReg nodes
235 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
237 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
239 CopyFromLo.getValue(2));
241 // replace uses of adde and addc here
242 if (!SDValue(ADDCNode, 0).use_empty())
243 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
245 if (!SDValue(ADDENode, 0).use_empty())
246 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
252 // Transforms a subgraph in CurDAG if the following pattern is found:
253 // (addc Lo0, multLo), (sube Hi0, multHi),
255 // multHi/Lo: product of multiplication
256 // Lo0: initial value of Lo register
257 // Hi0: initial value of Hi register
258 // Return true if mattern matching was successful.
259 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
260 // SUBENode's second operand must be a flag output of an SUBC node in order
261 // for the matching to be successful.
262 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
264 if (SUBCNode->getOpcode() != ISD::SUBC)
267 SDValue MultHi = SUBENode->getOperand(1);
268 SDValue MultLo = SUBCNode->getOperand(1);
269 SDNode* MultNode = MultHi.getNode();
270 unsigned MultOpc = MultHi.getOpcode();
272 // MultHi and MultLo must be generated by the same node,
273 if (MultLo.getNode() != MultNode)
276 // and it must be a multiplication.
277 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
280 // MultLo amd MultHi must be the first and second output of MultNode
282 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
285 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
286 // of the values of MultNode, in which case MultNode will be removed in later
288 // If there exist users other than SUBENode or SUBCNode, this function returns
289 // here, which will result in MultNode being mapped to a single MULT
290 // instruction node rather than a pair of MULT and MSUB instructions being
292 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
295 SDValue Chain = CurDAG->getEntryNode();
296 DebugLoc dl = SUBENode->getDebugLoc();
298 // create MipsSub(u) node
299 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
301 SDValue MSub = CurDAG->getNode(MultOpc, dl,
303 MultNode->getOperand(0),// Factor 0
304 MultNode->getOperand(1),// Factor 1
305 SUBCNode->getOperand(0),// Lo0
306 SUBENode->getOperand(0));// Hi0
308 // create CopyFromReg nodes
309 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
311 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
313 CopyFromLo.getValue(2));
315 // replace uses of sube and subc here
316 if (!SDValue(SUBCNode, 0).use_empty())
317 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
319 if (!SDValue(SUBENode, 0).use_empty())
320 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
325 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
326 TargetLowering::DAGCombinerInfo &DCI,
327 const MipsSubtarget* Subtarget) {
328 if (DCI.isBeforeLegalize())
331 if (Subtarget->isMips32() && SelectMadd(N, &DAG))
332 return SDValue(N, 0);
337 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
338 TargetLowering::DAGCombinerInfo &DCI,
339 const MipsSubtarget* Subtarget) {
340 if (DCI.isBeforeLegalize())
343 if (Subtarget->isMips32() && SelectMsub(N, &DAG))
344 return SDValue(N, 0);
349 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
351 SelectionDAG &DAG = DCI.DAG;
352 unsigned opc = N->getOpcode();
357 return PerformADDECombine(N, DAG, DCI, Subtarget);
359 return PerformSUBECombine(N, DAG, DCI, Subtarget);
365 SDValue MipsTargetLowering::
366 LowerOperation(SDValue Op, SelectionDAG &DAG) const
368 switch (Op.getOpcode())
370 case ISD::AND: return LowerANDOR(Op, DAG);
371 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
372 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
373 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
374 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
375 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
376 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
377 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
378 case ISD::OR: return LowerANDOR(Op, DAG);
379 case ISD::SELECT: return LowerSELECT(Op, DAG);
380 case ISD::SETCC: return LowerSETCC(Op, DAG);
381 case ISD::VASTART: return LowerVASTART(Op, DAG);
386 //===----------------------------------------------------------------------===//
387 // Lower helper functions
388 //===----------------------------------------------------------------------===//
390 // AddLiveIn - This helper function adds the specified physical register to the
391 // MachineFunction as a live in value. It also creates a corresponding
392 // virtual register for it.
394 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
396 assert(RC->contains(PReg) && "Not the correct regclass!");
397 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
398 MF.getRegInfo().addLiveIn(PReg, VReg);
402 // Get fp branch code (not opcode) from condition code.
403 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
404 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
405 return Mips::BRANCH_T;
407 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
408 return Mips::BRANCH_F;
410 return Mips::BRANCH_INVALID;
413 static unsigned FPBranchCodeToOpc(Mips::FPBranchCode BC) {
416 llvm_unreachable("Unknown branch code");
417 case Mips::BRANCH_T : return Mips::BC1T;
418 case Mips::BRANCH_F : return Mips::BC1F;
419 case Mips::BRANCH_TL : return Mips::BC1TL;
420 case Mips::BRANCH_FL : return Mips::BC1FL;
424 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
426 default: llvm_unreachable("Unknown fp condition code!");
428 case ISD::SETOEQ: return Mips::FCOND_EQ;
429 case ISD::SETUNE: return Mips::FCOND_OGL;
431 case ISD::SETOLT: return Mips::FCOND_OLT;
433 case ISD::SETOGT: return Mips::FCOND_OGT;
435 case ISD::SETOLE: return Mips::FCOND_OLE;
437 case ISD::SETOGE: return Mips::FCOND_OGE;
438 case ISD::SETULT: return Mips::FCOND_ULT;
439 case ISD::SETULE: return Mips::FCOND_ULE;
440 case ISD::SETUGT: return Mips::FCOND_UGT;
441 case ISD::SETUGE: return Mips::FCOND_UGE;
442 case ISD::SETUO: return Mips::FCOND_UN;
443 case ISD::SETO: return Mips::FCOND_OR;
445 case ISD::SETONE: return Mips::FCOND_NEQ;
446 case ISD::SETUEQ: return Mips::FCOND_UEQ;
451 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
452 MachineBasicBlock *BB) const {
453 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
454 bool isFPCmp = false;
455 DebugLoc dl = MI->getDebugLoc();
457 switch (MI->getOpcode()) {
458 default: assert(false && "Unexpected instr type to insert");
459 case Mips::Select_FCC:
460 case Mips::Select_FCC_S32:
461 case Mips::Select_FCC_D32:
462 isFPCmp = true; // FALL THROUGH
463 case Mips::Select_CC:
464 case Mips::Select_CC_S32:
465 case Mips::Select_CC_D32: {
466 // To "insert" a SELECT_CC instruction, we actually have to insert the
467 // diamond control-flow pattern. The incoming instruction knows the
468 // destination vreg to set, the condition code register to branch on, the
469 // true/false values to select between, and a branch opcode to use.
470 const BasicBlock *LLVM_BB = BB->getBasicBlock();
471 MachineFunction::iterator It = BB;
478 // bNE r1, r0, copy1MBB
479 // fallthrough --> copy0MBB
480 MachineBasicBlock *thisMBB = BB;
481 MachineFunction *F = BB->getParent();
482 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
483 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
484 F->insert(It, copy0MBB);
485 F->insert(It, sinkMBB);
487 // Transfer the remainder of BB and its successor edges to sinkMBB.
488 sinkMBB->splice(sinkMBB->begin(), BB,
489 llvm::next(MachineBasicBlock::iterator(MI)),
491 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
493 // Next, add the true and fallthrough blocks as its successors.
494 BB->addSuccessor(copy0MBB);
495 BB->addSuccessor(sinkMBB);
497 // Emit the right instruction according to the type of the operands compared
499 // Find the condiction code present in the setcc operation.
500 Mips::CondCode CC = (Mips::CondCode)MI->getOperand(4).getImm();
501 // Get the branch opcode from the branch code.
502 unsigned Opc = FPBranchCodeToOpc(GetFPBranchCodeFromCond(CC));
503 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
505 BuildMI(BB, dl, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
506 .addReg(Mips::ZERO).addMBB(sinkMBB);
510 // # fallthrough to sinkMBB
513 // Update machine-CFG edges
514 BB->addSuccessor(sinkMBB);
517 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
520 BuildMI(*BB, BB->begin(), dl,
521 TII->get(Mips::PHI), MI->getOperand(0).getReg())
522 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
523 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
525 MI->eraseFromParent(); // The pseudo instruction is gone now.
531 //===----------------------------------------------------------------------===//
532 // Misc Lower Operation implementation
533 //===----------------------------------------------------------------------===//
535 SDValue MipsTargetLowering::
536 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const
538 if (!Subtarget->isMips1())
541 MachineFunction &MF = DAG.getMachineFunction();
542 unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
544 SDValue Chain = DAG.getEntryNode();
545 DebugLoc dl = Op.getDebugLoc();
546 SDValue Src = Op.getOperand(0);
548 // Set the condition register
549 SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
550 CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
551 CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
553 SDValue Cst = DAG.getConstant(3, MVT::i32);
554 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
555 Cst = DAG.getConstant(2, MVT::i32);
556 SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
558 SDValue InFlag(0, 0);
559 CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
561 // Emit the round instruction and bit convert to integer
562 SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
563 Src, CondReg.getValue(1));
564 SDValue BitCvt = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Trunc);
568 SDValue MipsTargetLowering::
569 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
571 SDValue Chain = Op.getOperand(0);
572 SDValue Size = Op.getOperand(1);
573 DebugLoc dl = Op.getDebugLoc();
575 // Get a reference from Mips stack pointer
576 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
578 // Subtract the dynamic size from the actual stack size to
579 // obtain the new stack size.
580 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
582 // The Sub result contains the new stack start address, so it
583 // must be placed in the stack pointer register.
584 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
586 // This node always has two return values: a new stack pointer
588 SDValue Ops[2] = { Sub, Chain };
589 return DAG.getMergeValues(Ops, 2, dl);
592 SDValue MipsTargetLowering::
593 LowerANDOR(SDValue Op, SelectionDAG &DAG) const
595 SDValue LHS = Op.getOperand(0);
596 SDValue RHS = Op.getOperand(1);
597 DebugLoc dl = Op.getDebugLoc();
599 if (LHS.getOpcode() != MipsISD::FPCmp || RHS.getOpcode() != MipsISD::FPCmp)
602 SDValue True = DAG.getConstant(1, MVT::i32);
603 SDValue False = DAG.getConstant(0, MVT::i32);
605 SDValue LSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
606 LHS, True, False, LHS.getOperand(2));
607 SDValue RSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
608 RHS, True, False, RHS.getOperand(2));
610 return DAG.getNode(Op.getOpcode(), dl, MVT::i32, LSEL, RSEL);
613 SDValue MipsTargetLowering::
614 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
616 // The first operand is the chain, the second is the condition, the third is
617 // the block to branch to if the condition is true.
618 SDValue Chain = Op.getOperand(0);
619 SDValue Dest = Op.getOperand(2);
620 DebugLoc dl = Op.getDebugLoc();
622 if (Op.getOperand(1).getOpcode() != MipsISD::FPCmp)
625 SDValue CondRes = Op.getOperand(1);
626 SDValue CCNode = CondRes.getOperand(2);
628 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
629 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
631 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
635 SDValue MipsTargetLowering::
636 LowerSETCC(SDValue Op, SelectionDAG &DAG) const
638 // The operands to this are the left and right operands to compare (ops #0,
639 // and #1) and the condition code to compare them with (op #2) as a
641 SDValue LHS = Op.getOperand(0);
642 SDValue RHS = Op.getOperand(1);
643 DebugLoc dl = Op.getDebugLoc();
645 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
647 return DAG.getNode(MipsISD::FPCmp, dl, Op.getValueType(), LHS, RHS,
648 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
651 SDValue MipsTargetLowering::
652 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
654 SDValue Cond = Op.getOperand(0);
655 SDValue True = Op.getOperand(1);
656 SDValue False = Op.getOperand(2);
657 DebugLoc dl = Op.getDebugLoc();
659 // if the incomming condition comes from a integer compare, the select
660 // operation must be SelectCC or a conditional move if the subtarget
662 if (Cond.getOpcode() != MipsISD::FPCmp) {
663 if (Subtarget->hasCondMov() && !True.getValueType().isFloatingPoint())
665 return DAG.getNode(MipsISD::SelectCC, dl, True.getValueType(),
669 // if the incomming condition comes from fpcmp, the select
670 // operation must use FPSelectCC.
671 SDValue CCNode = Cond.getOperand(2);
672 return DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
673 Cond, True, False, CCNode);
676 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
677 SelectionDAG &DAG) const {
678 // FIXME there isn't actually debug info here
679 DebugLoc dl = Op.getDebugLoc();
680 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
682 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
683 SDVTList VTs = DAG.getVTList(MVT::i32);
685 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
687 // %gp_rel relocation
688 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
689 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
691 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
692 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
693 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
695 // %hi/%lo relocation
696 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
697 MipsII::MO_ABS_HILO);
698 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GA, 1);
699 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
700 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
703 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
705 SDValue ResNode = DAG.getLoad(MVT::i32, dl,
706 DAG.getEntryNode(), GA, MachinePointerInfo(),
708 // On functions and global targets not internal linked only
709 // a load from got/GP is necessary for PIC to work.
710 if (!GV->hasLocalLinkage() || isa<Function>(GV))
712 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
713 return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
716 llvm_unreachable("Dont know how to handle GlobalAddress");
720 SDValue MipsTargetLowering::
721 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
723 llvm_unreachable("TLS not implemented for MIPS.");
724 return SDValue(); // Not reached
727 SDValue MipsTargetLowering::
728 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
732 // FIXME there isn't actually debug info here
733 DebugLoc dl = Op.getDebugLoc();
734 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
735 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HILO;
737 EVT PtrVT = Op.getValueType();
738 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
740 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
743 SDValue Ops[] = { JTI };
744 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
745 } else // Emit Load from Global Pointer
746 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
747 MachinePointerInfo(),
750 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTI);
751 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
756 SDValue MipsTargetLowering::
757 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
760 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
761 const Constant *C = N->getConstVal();
762 // FIXME there isn't actually debug info here
763 DebugLoc dl = Op.getDebugLoc();
766 // FIXME: we should reference the constant pool using small data sections,
767 // but the asm printer currently doens't support this feature without
768 // hacking it. This feature should come soon so we can uncomment the
770 //if (IsInSmallSection(C->getType())) {
771 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
772 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
773 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
775 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
776 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
777 N->getOffset(), MipsII::MO_ABS_HILO);
778 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CP);
779 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
780 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
782 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
783 N->getOffset(), MipsII::MO_GOT);
784 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
785 CP, MachinePointerInfo::getConstantPool(),
787 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
788 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
794 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
795 MachineFunction &MF = DAG.getMachineFunction();
796 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
798 DebugLoc dl = Op.getDebugLoc();
799 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
802 // vastart just stores the address of the VarArgsFrameIndex slot into the
803 // memory location argument.
804 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
805 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
806 MachinePointerInfo(SV),
810 //===----------------------------------------------------------------------===//
811 // Calling Convention Implementation
812 //===----------------------------------------------------------------------===//
814 #include "MipsGenCallingConv.inc"
816 //===----------------------------------------------------------------------===//
817 // TODO: Implement a generic logic using tblgen that can support this.
818 // Mips O32 ABI rules:
820 // i32 - Passed in A0, A1, A2, A3 and stack
821 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
822 // an argument. Otherwise, passed in A1, A2, A3 and stack.
823 // f64 - Only passed in two aliased f32 registers if no int reg has been used
824 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
825 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
827 //===----------------------------------------------------------------------===//
829 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
830 MVT LocVT, CCValAssign::LocInfo LocInfo,
831 ISD::ArgFlagsTy ArgFlags, CCState &State) {
833 static const unsigned IntRegsSize=4, FloatRegsSize=2;
835 static const unsigned IntRegs[] = {
836 Mips::A0, Mips::A1, Mips::A2, Mips::A3
838 static const unsigned F32Regs[] = {
841 static const unsigned F64Regs[] = {
846 unsigned UnallocIntReg = State.getFirstUnallocated(IntRegs, IntRegsSize);
847 bool IntRegUsed = (IntRegs[UnallocIntReg] != (unsigned (Mips::A0)));
849 // Promote i8 and i16
850 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
852 if (ArgFlags.isSExt())
853 LocInfo = CCValAssign::SExt;
854 else if (ArgFlags.isZExt())
855 LocInfo = CCValAssign::ZExt;
857 LocInfo = CCValAssign::AExt;
860 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && IntRegUsed)) {
861 Reg = State.AllocateReg(IntRegs, IntRegsSize);
866 if (ValVT.isFloatingPoint() && !IntRegUsed) {
867 if (ValVT == MVT::f32)
868 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
870 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
873 if (ValVT == MVT::f64 && IntRegUsed) {
874 if (UnallocIntReg != IntRegsSize) {
875 // If we hit register A3 as the first not allocated, we must
876 // mark it as allocated (shadow) and use the stack instead.
877 if (IntRegs[UnallocIntReg] != (unsigned (Mips::A3)))
879 for (;UnallocIntReg < IntRegsSize; ++UnallocIntReg)
880 State.AllocateReg(UnallocIntReg);
886 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
887 unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
888 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
890 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
892 return false; // CC must always match
895 static bool CC_MipsO32_VarArgs(unsigned ValNo, MVT ValVT,
896 MVT LocVT, CCValAssign::LocInfo LocInfo,
897 ISD::ArgFlagsTy ArgFlags, CCState &State) {
899 static const unsigned IntRegsSize=4;
901 static const unsigned IntRegs[] = {
902 Mips::A0, Mips::A1, Mips::A2, Mips::A3
905 // Promote i8 and i16
906 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
908 if (ArgFlags.isSExt())
909 LocInfo = CCValAssign::SExt;
910 else if (ArgFlags.isZExt())
911 LocInfo = CCValAssign::ZExt;
913 LocInfo = CCValAssign::AExt;
916 if (ValVT == MVT::i32 || ValVT == MVT::f32) {
917 if (unsigned Reg = State.AllocateReg(IntRegs, IntRegsSize)) {
918 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
921 unsigned Off = State.AllocateStack(4, 4);
922 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Off, LocVT, LocInfo));
926 unsigned UnallocIntReg = State.getFirstUnallocated(IntRegs, IntRegsSize);
927 if (ValVT == MVT::f64) {
928 if (IntRegs[UnallocIntReg] == (unsigned (Mips::A1))) {
929 // A1 can't be used anymore, because 64 bit arguments
930 // must be aligned when copied back to the caller stack
931 State.AllocateReg(IntRegs, IntRegsSize);
935 if (IntRegs[UnallocIntReg] == (unsigned (Mips::A0)) ||
936 IntRegs[UnallocIntReg] == (unsigned (Mips::A2))) {
937 unsigned Reg = State.AllocateReg(IntRegs, IntRegsSize);
938 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
939 // Shadow the next register so it can be used
940 // later to get the other 32bit part.
941 State.AllocateReg(IntRegs, IntRegsSize);
945 // Register is shadowed to preserve alignment, and the
946 // argument goes to a stack location.
947 if (UnallocIntReg != IntRegsSize)
948 State.AllocateReg(IntRegs, IntRegsSize);
950 unsigned Off = State.AllocateStack(8, 8);
951 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Off, LocVT, LocInfo));
955 return true; // CC didn't match
958 //===----------------------------------------------------------------------===//
959 // Call Calling Convention Implementation
960 //===----------------------------------------------------------------------===//
962 /// LowerCall - functions arguments are copied from virtual regs to
963 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
964 /// TODO: isTailCall.
966 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
967 CallingConv::ID CallConv, bool isVarArg,
969 const SmallVectorImpl<ISD::OutputArg> &Outs,
970 const SmallVectorImpl<SDValue> &OutVals,
971 const SmallVectorImpl<ISD::InputArg> &Ins,
972 DebugLoc dl, SelectionDAG &DAG,
973 SmallVectorImpl<SDValue> &InVals) const {
974 // MIPs target does not yet support tail call optimization.
977 MachineFunction &MF = DAG.getMachineFunction();
978 MachineFrameInfo *MFI = MF.getFrameInfo();
979 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
981 // Analyze operands of the call, assigning locations to each operand.
982 SmallVector<CCValAssign, 16> ArgLocs;
983 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
986 // To meet O32 ABI, Mips must always allocate 16 bytes on
987 // the stack (even if less than 4 are used as arguments)
988 if (Subtarget->isABI_O32()) {
989 int VTsize = MVT(MVT::i32).getSizeInBits()/8;
990 MFI->CreateFixedObject(VTsize, (VTsize*3), true);
991 CCInfo.AnalyzeCallOperands(Outs,
992 isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
994 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
996 // Get a count of how many bytes are to be pushed on the stack.
997 unsigned NumBytes = CCInfo.getNextStackOffset();
998 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1000 // With EABI is it possible to have 16 args on registers.
1001 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1002 SmallVector<SDValue, 8> MemOpChains;
1004 // First/LastArgStackLoc contains the first/last
1005 // "at stack" argument location.
1006 int LastArgStackLoc = 0;
1007 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1009 // Walk the register/memloc assignments, inserting copies/loads.
1010 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1011 SDValue Arg = OutVals[i];
1012 CCValAssign &VA = ArgLocs[i];
1014 // Promote the value if needed.
1015 switch (VA.getLocInfo()) {
1016 default: llvm_unreachable("Unknown loc info!");
1017 case CCValAssign::Full:
1018 if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1019 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1020 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1021 if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1022 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1023 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1024 DAG.getConstant(0, getPointerTy()));
1025 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1026 DAG.getConstant(1, getPointerTy()));
1027 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1028 RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1033 case CCValAssign::SExt:
1034 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1036 case CCValAssign::ZExt:
1037 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1039 case CCValAssign::AExt:
1040 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1044 // Arguments that can be passed on register must be kept at
1045 // RegsToPass vector
1046 if (VA.isRegLoc()) {
1047 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1051 // Register can't get to this point...
1052 assert(VA.isMemLoc());
1054 // Create the frame index object for this incoming parameter
1055 // This guarantees that when allocating Local Area the firsts
1056 // 16 bytes which are alwayes reserved won't be overwritten
1057 // if O32 ABI is used. For EABI the first address is zero.
1058 LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
1059 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1060 LastArgStackLoc, true);
1062 SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
1064 // emit ISD::STORE whichs stores the
1065 // parameter value to a stack Location
1066 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1067 MachinePointerInfo(),
1071 // Transform all store nodes into one single node because all store
1072 // nodes are independent of each other.
1073 if (!MemOpChains.empty())
1074 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1075 &MemOpChains[0], MemOpChains.size());
1077 // Build a sequence of copy-to-reg nodes chained together with token
1078 // chain and flag operands which copy the outgoing args into registers.
1079 // The InFlag in necessary since all emited instructions must be
1082 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1083 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1084 RegsToPass[i].second, InFlag);
1085 InFlag = Chain.getValue(1);
1088 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1089 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1090 // node so that legalize doesn't hack it.
1091 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1092 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1093 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1094 getPointerTy(), 0, OpFlag);
1095 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1096 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1097 getPointerTy(), OpFlag);
1099 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1100 // = Chain, Callee, Reg#1, Reg#2, ...
1102 // Returns a chain & a flag for retval copy to use.
1103 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1104 SmallVector<SDValue, 8> Ops;
1105 Ops.push_back(Chain);
1106 Ops.push_back(Callee);
1108 // Add argument registers to the end of the list so that they are
1109 // known live into the call.
1110 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1111 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1112 RegsToPass[i].second.getValueType()));
1114 if (InFlag.getNode())
1115 Ops.push_back(InFlag);
1117 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1118 InFlag = Chain.getValue(1);
1120 // Create a stack location to hold GP when PIC is used. This stack
1121 // location is used on function prologue to save GP and also after all
1122 // emited CALL's to restore GP.
1124 // Function can have an arbitrary number of calls, so
1125 // hold the LastArgStackLoc with the biggest offset.
1127 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1128 if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
1129 LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
1130 // Create the frame index only once. SPOffset here can be anything
1131 // (this will be fixed on processFunctionBeforeFrameFinalized)
1132 if (MipsFI->getGPStackOffset() == -1) {
1133 FI = MFI->CreateFixedObject(4, 0, true);
1134 MipsFI->setGPFI(FI);
1136 MipsFI->setGPStackOffset(LastArgStackLoc);
1140 FI = MipsFI->getGPFI();
1141 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1142 SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN,
1143 MachinePointerInfo::getFixedStack(FI),
1145 Chain = GPLoad.getValue(1);
1146 Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32),
1147 GPLoad, SDValue(0,0));
1148 InFlag = Chain.getValue(1);
1151 // Create the CALLSEQ_END node.
1152 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1153 DAG.getIntPtrConstant(0, true), InFlag);
1154 InFlag = Chain.getValue(1);
1156 // Handle result values, copying them out of physregs into vregs that we
1158 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1159 Ins, dl, DAG, InVals);
1162 /// LowerCallResult - Lower the result values of a call into the
1163 /// appropriate copies out of appropriate physical registers.
1165 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1166 CallingConv::ID CallConv, bool isVarArg,
1167 const SmallVectorImpl<ISD::InputArg> &Ins,
1168 DebugLoc dl, SelectionDAG &DAG,
1169 SmallVectorImpl<SDValue> &InVals) const {
1171 // Assign locations to each value returned by this call.
1172 SmallVector<CCValAssign, 16> RVLocs;
1173 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1174 RVLocs, *DAG.getContext());
1176 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1178 // Copy all of the result registers out of their specified physreg.
1179 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1180 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1181 RVLocs[i].getValVT(), InFlag).getValue(1);
1182 InFlag = Chain.getValue(2);
1183 InVals.push_back(Chain.getValue(0));
1189 //===----------------------------------------------------------------------===//
1190 // Formal Arguments Calling Convention Implementation
1191 //===----------------------------------------------------------------------===//
1193 /// LowerFormalArguments - transform physical registers into virtual registers
1194 /// and generate load operations for arguments places on the stack.
1196 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
1197 CallingConv::ID CallConv, bool isVarArg,
1198 const SmallVectorImpl<ISD::InputArg>
1200 DebugLoc dl, SelectionDAG &DAG,
1201 SmallVectorImpl<SDValue> &InVals)
1204 MachineFunction &MF = DAG.getMachineFunction();
1205 MachineFrameInfo *MFI = MF.getFrameInfo();
1206 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1208 unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
1209 MipsFI->setVarArgsFrameIndex(0);
1211 // Used with vargs to acumulate store chains.
1212 std::vector<SDValue> OutChains;
1214 // Keep track of the last register used for arguments
1215 unsigned ArgRegEnd = 0;
1217 // Assign locations to all of the incoming arguments.
1218 SmallVector<CCValAssign, 16> ArgLocs;
1219 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1220 ArgLocs, *DAG.getContext());
1222 if (Subtarget->isABI_O32())
1223 CCInfo.AnalyzeFormalArguments(Ins,
1224 isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1226 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
1230 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1232 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1233 CCValAssign &VA = ArgLocs[i];
1235 // Arguments stored on registers
1236 if (VA.isRegLoc()) {
1237 EVT RegVT = VA.getLocVT();
1238 ArgRegEnd = VA.getLocReg();
1239 TargetRegisterClass *RC = 0;
1241 if (RegVT == MVT::i32)
1242 RC = Mips::CPURegsRegisterClass;
1243 else if (RegVT == MVT::f32)
1244 RC = Mips::FGR32RegisterClass;
1245 else if (RegVT == MVT::f64) {
1246 if (!Subtarget->isSingleFloat())
1247 RC = Mips::AFGR64RegisterClass;
1249 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
1251 // Transform the arguments stored on
1252 // physical registers into virtual ones
1253 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1254 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1256 // If this is an 8 or 16-bit value, it has been passed promoted
1257 // to 32 bits. Insert an assert[sz]ext to capture this, then
1258 // truncate to the right size.
1259 if (VA.getLocInfo() != CCValAssign::Full) {
1260 unsigned Opcode = 0;
1261 if (VA.getLocInfo() == CCValAssign::SExt)
1262 Opcode = ISD::AssertSext;
1263 else if (VA.getLocInfo() == CCValAssign::ZExt)
1264 Opcode = ISD::AssertZext;
1266 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
1267 DAG.getValueType(VA.getValVT()));
1268 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1271 // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
1272 if (Subtarget->isABI_O32()) {
1273 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
1274 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1275 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
1276 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
1277 VA.getLocReg()+1, RC);
1278 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
1279 SDValue Hi = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1280 SDValue Lo = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue2);
1281 ArgValue = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::f64, Lo, Hi);
1285 InVals.push_back(ArgValue);
1286 } else { // VA.isRegLoc()
1289 assert(VA.isMemLoc());
1291 // The last argument is not a register anymore
1294 // The stack pointer offset is relative to the caller stack frame.
1295 // Since the real stack size is unknown here, a negative SPOffset
1296 // is used so there's a way to adjust these offsets when the stack
1297 // size get known (on EliminateFrameIndex). A dummy SPOffset is
1298 // used instead of a direct negative address (which is recorded to
1299 // be used on emitPrologue) to avoid mis-calc of the first stack
1300 // offset on PEI::calculateFrameObjectOffsets.
1301 // Arguments are always 32-bit.
1302 unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1303 int FI = MFI->CreateFixedObject(ArgSize, 0, true);
1304 MipsFI->recordLoadArgsFI(FI, -(ArgSize+
1305 (FirstStackArgLoc + VA.getLocMemOffset())));
1307 // Create load nodes to retrieve arguments from the stack
1308 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1309 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1310 MachinePointerInfo::getFixedStack(FI),
1315 // The mips ABIs for returning structs by value requires that we copy
1316 // the sret argument into $v0 for the return. Save the argument into
1317 // a virtual register so that we can access it from the return points.
1318 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1319 unsigned Reg = MipsFI->getSRetReturnReg();
1321 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1322 MipsFI->setSRetReturnReg(Reg);
1324 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1325 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1328 // To meet ABI, when VARARGS are passed on registers, the registers
1329 // must have their values written to the caller stack frame. If the last
1330 // argument was placed in the stack, there's no need to save any register.
1331 if ((isVarArg) && (Subtarget->isABI_O32() && ArgRegEnd)) {
1332 if (StackPtr.getNode() == 0)
1333 StackPtr = DAG.getRegister(StackReg, getPointerTy());
1335 // The last register argument that must be saved is Mips::A3
1336 TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
1337 unsigned StackLoc = ArgLocs.size()-1;
1339 for (++ArgRegEnd; ArgRegEnd <= Mips::A3; ++ArgRegEnd, ++StackLoc) {
1340 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1341 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
1343 int FI = MFI->CreateFixedObject(4, 0, true);
1344 MipsFI->recordStoreVarArgsFI(FI, -(4+(StackLoc*4)));
1345 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
1346 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
1347 MachinePointerInfo(),
1350 // Record the frame index of the first variable argument
1351 // which is a value necessary to VASTART.
1352 if (!MipsFI->getVarArgsFrameIndex())
1353 MipsFI->setVarArgsFrameIndex(FI);
1357 // All stores are grouped in one node to allow the matching between
1358 // the size of Ins and InVals. This only happens when on varg functions
1359 if (!OutChains.empty()) {
1360 OutChains.push_back(Chain);
1361 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1362 &OutChains[0], OutChains.size());
1368 //===----------------------------------------------------------------------===//
1369 // Return Value Calling Convention Implementation
1370 //===----------------------------------------------------------------------===//
1373 MipsTargetLowering::LowerReturn(SDValue Chain,
1374 CallingConv::ID CallConv, bool isVarArg,
1375 const SmallVectorImpl<ISD::OutputArg> &Outs,
1376 const SmallVectorImpl<SDValue> &OutVals,
1377 DebugLoc dl, SelectionDAG &DAG) const {
1379 // CCValAssign - represent the assignment of
1380 // the return value to a location
1381 SmallVector<CCValAssign, 16> RVLocs;
1383 // CCState - Info about the registers and stack slot.
1384 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1385 RVLocs, *DAG.getContext());
1387 // Analize return values.
1388 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1390 // If this is the first return lowered for this function, add
1391 // the regs to the liveout set for the function.
1392 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1393 for (unsigned i = 0; i != RVLocs.size(); ++i)
1394 if (RVLocs[i].isRegLoc())
1395 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1400 // Copy the result values into the output registers.
1401 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1402 CCValAssign &VA = RVLocs[i];
1403 assert(VA.isRegLoc() && "Can only return in registers!");
1405 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1408 // guarantee that all emitted copies are
1409 // stuck together, avoiding something bad
1410 Flag = Chain.getValue(1);
1413 // The mips ABIs for returning structs by value requires that we copy
1414 // the sret argument into $v0 for the return. We saved the argument into
1415 // a virtual register in the entry block, so now we copy the value out
1417 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1418 MachineFunction &MF = DAG.getMachineFunction();
1419 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1420 unsigned Reg = MipsFI->getSRetReturnReg();
1423 llvm_unreachable("sret virtual register not created in the entry block");
1424 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1426 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1427 Flag = Chain.getValue(1);
1430 // Return on Mips is always a "jr $ra"
1432 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1433 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1435 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1436 Chain, DAG.getRegister(Mips::RA, MVT::i32));
1439 //===----------------------------------------------------------------------===//
1440 // Mips Inline Assembly Support
1441 //===----------------------------------------------------------------------===//
1443 /// getConstraintType - Given a constraint letter, return the type of
1444 /// constraint it is for this target.
1445 MipsTargetLowering::ConstraintType MipsTargetLowering::
1446 getConstraintType(const std::string &Constraint) const
1448 // Mips specific constrainy
1449 // GCC config/mips/constraints.md
1451 // 'd' : An address register. Equivalent to r
1452 // unless generating MIPS16 code.
1453 // 'y' : Equivalent to r; retained for
1454 // backwards compatibility.
1455 // 'f' : Floating Point registers.
1456 if (Constraint.size() == 1) {
1457 switch (Constraint[0]) {
1462 return C_RegisterClass;
1466 return TargetLowering::getConstraintType(Constraint);
1469 /// Examine constraint type and operand type and determine a weight value.
1470 /// This object must already have been set up with the operand type
1471 /// and the current alternative constraint selected.
1472 TargetLowering::ConstraintWeight
1473 MipsTargetLowering::getSingleConstraintMatchWeight(
1474 AsmOperandInfo &info, const char *constraint) const {
1475 ConstraintWeight weight = CW_Invalid;
1476 Value *CallOperandVal = info.CallOperandVal;
1477 // If we don't have a value, we can't do a match,
1478 // but allow it at the lowest weight.
1479 if (CallOperandVal == NULL)
1481 const Type *type = CallOperandVal->getType();
1482 // Look at the constraint type.
1483 switch (*constraint) {
1485 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1489 if (type->isIntegerTy())
1490 weight = CW_Register;
1493 if (type->isFloatTy())
1494 weight = CW_Register;
1500 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1501 /// return a list of registers that can be used to satisfy the constraint.
1502 /// This should only be used for C_RegisterClass constraints.
1503 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1504 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
1506 if (Constraint.size() == 1) {
1507 switch (Constraint[0]) {
1509 return std::make_pair(0U, Mips::CPURegsRegisterClass);
1512 return std::make_pair(0U, Mips::FGR32RegisterClass);
1514 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1515 return std::make_pair(0U, Mips::AFGR64RegisterClass);
1518 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1521 /// Given a register class constraint, like 'r', if this corresponds directly
1522 /// to an LLVM register class, return a register of 0 and the register class
1524 std::vector<unsigned> MipsTargetLowering::
1525 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1528 if (Constraint.size() != 1)
1529 return std::vector<unsigned>();
1531 switch (Constraint[0]) {
1534 // GCC Mips Constraint Letters
1537 return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1538 Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1539 Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1543 if (VT == MVT::f32) {
1544 if (Subtarget->isSingleFloat())
1545 return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1546 Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1547 Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1548 Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1549 Mips::F30, Mips::F31, 0);
1551 return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1552 Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1553 Mips::F28, Mips::F30, 0);
1557 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1558 return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1559 Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1560 Mips::D14, Mips::D15, 0);
1562 return std::vector<unsigned>();
1566 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1567 // The Mips target isn't yet aware of offsets.
1571 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1572 if (VT != MVT::f32 && VT != MVT::f64)
1574 return Imm.isZero();