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::FPBrcond : return "MipsISD::FPBrcond";
45 case MipsISD::FPCmp : return "MipsISD::FPCmp";
46 case MipsISD::CMovFP_T : return "MipsISD::CMovFP_T";
47 case MipsISD::CMovFP_F : return "MipsISD::CMovFP_F";
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 case MipsISD::DivRem : return "MipsISD::DivRem";
54 case MipsISD::DivRemU : return "MipsISD::DivRemU";
55 default : return NULL;
60 MipsTargetLowering(MipsTargetMachine &TM)
61 : TargetLowering(TM, new MipsTargetObjectFile()) {
62 Subtarget = &TM.getSubtarget<MipsSubtarget>();
64 // Mips does not have i1 type, so use i32 for
65 // setcc operations results (slt, sgt, ...).
66 setBooleanContents(ZeroOrOneBooleanContent);
68 // Set up the register classes
69 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
70 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
72 // When dealing with single precision only, use libcalls
73 if (!Subtarget->isSingleFloat())
74 if (!Subtarget->isFP64bit())
75 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
77 // Load extented operations for i1 types must be promoted
78 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
79 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
80 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
82 // MIPS doesn't have extending float->double load/store
83 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
84 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
86 // Used by legalize types to correctly generate the setcc result.
87 // Without this, every float setcc comes with a AND/OR with the result,
88 // we don't want this, since the fpcmp result goes to a flag register,
89 // which is used implicitly by brcond and select operations.
90 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
92 // Mips Custom Operations
93 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
94 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
95 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
96 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
97 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
98 setOperationAction(ISD::SELECT, MVT::f32, Custom);
99 setOperationAction(ISD::SELECT, MVT::f64, Custom);
100 setOperationAction(ISD::SELECT, MVT::i32, Custom);
101 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
102 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
103 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
104 setOperationAction(ISD::VASTART, MVT::Other, Custom);
106 setOperationAction(ISD::SDIV, MVT::i32, Expand);
107 setOperationAction(ISD::SREM, MVT::i32, Expand);
108 setOperationAction(ISD::UDIV, MVT::i32, Expand);
109 setOperationAction(ISD::UREM, MVT::i32, Expand);
111 // Operations not directly supported by Mips.
112 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
113 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
114 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
115 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
116 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
118 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
119 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
120 setOperationAction(ISD::ROTL, MVT::i32, Expand);
122 if (!Subtarget->isMips32r2())
123 setOperationAction(ISD::ROTR, MVT::i32, Expand);
125 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
126 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
127 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
128 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
129 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
130 setOperationAction(ISD::FSIN, MVT::f32, Expand);
131 setOperationAction(ISD::FSIN, MVT::f64, Expand);
132 setOperationAction(ISD::FCOS, MVT::f32, Expand);
133 setOperationAction(ISD::FCOS, MVT::f64, Expand);
134 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
135 setOperationAction(ISD::FPOW, MVT::f32, Expand);
136 setOperationAction(ISD::FLOG, MVT::f32, Expand);
137 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
138 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
139 setOperationAction(ISD::FEXP, MVT::f32, Expand);
141 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
143 setOperationAction(ISD::VAARG, MVT::Other, Expand);
144 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
145 setOperationAction(ISD::VAEND, MVT::Other, Expand);
147 // Use the default for now
148 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
149 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
150 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
152 if (Subtarget->isSingleFloat())
153 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
155 if (!Subtarget->hasSEInReg()) {
156 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
157 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
160 if (!Subtarget->hasBitCount())
161 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
163 if (!Subtarget->hasSwap())
164 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
166 setTargetDAGCombine(ISD::ADDE);
167 setTargetDAGCombine(ISD::SUBE);
168 setTargetDAGCombine(ISD::SDIVREM);
169 setTargetDAGCombine(ISD::UDIVREM);
170 setTargetDAGCombine(ISD::SETCC);
172 setStackPointerRegisterToSaveRestore(Mips::SP);
173 computeRegisterProperties();
176 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
180 /// getFunctionAlignment - Return the Log2 alignment of this function.
181 unsigned MipsTargetLowering::getFunctionAlignment(const Function *) const {
186 // Transforms a subgraph in CurDAG if the following pattern is found:
187 // (addc multLo, Lo0), (adde multHi, Hi0),
189 // multHi/Lo: product of multiplication
190 // Lo0: initial value of Lo register
191 // Hi0: initial value of Hi register
192 // Return true if pattern matching was successful.
193 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
194 // ADDENode's second operand must be a flag output of an ADDC node in order
195 // for the matching to be successful.
196 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
198 if (ADDCNode->getOpcode() != ISD::ADDC)
201 SDValue MultHi = ADDENode->getOperand(0);
202 SDValue MultLo = ADDCNode->getOperand(0);
203 SDNode* MultNode = MultHi.getNode();
204 unsigned MultOpc = MultHi.getOpcode();
206 // MultHi and MultLo must be generated by the same node,
207 if (MultLo.getNode() != MultNode)
210 // and it must be a multiplication.
211 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
214 // MultLo amd MultHi must be the first and second output of MultNode
216 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
219 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
220 // of the values of MultNode, in which case MultNode will be removed in later
222 // If there exist users other than ADDENode or ADDCNode, this function returns
223 // here, which will result in MultNode being mapped to a single MULT
224 // instruction node rather than a pair of MULT and MADD instructions being
226 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
229 SDValue Chain = CurDAG->getEntryNode();
230 DebugLoc dl = ADDENode->getDebugLoc();
232 // create MipsMAdd(u) node
233 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
235 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
237 MultNode->getOperand(0),// Factor 0
238 MultNode->getOperand(1),// Factor 1
239 ADDCNode->getOperand(1),// Lo0
240 ADDENode->getOperand(1));// Hi0
242 // create CopyFromReg nodes
243 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
245 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
247 CopyFromLo.getValue(2));
249 // replace uses of adde and addc here
250 if (!SDValue(ADDCNode, 0).use_empty())
251 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
253 if (!SDValue(ADDENode, 0).use_empty())
254 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
260 // Transforms a subgraph in CurDAG if the following pattern is found:
261 // (addc Lo0, multLo), (sube Hi0, multHi),
263 // multHi/Lo: product of multiplication
264 // Lo0: initial value of Lo register
265 // Hi0: initial value of Hi register
266 // Return true if pattern matching was successful.
267 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
268 // SUBENode's second operand must be a flag output of an SUBC node in order
269 // for the matching to be successful.
270 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
272 if (SUBCNode->getOpcode() != ISD::SUBC)
275 SDValue MultHi = SUBENode->getOperand(1);
276 SDValue MultLo = SUBCNode->getOperand(1);
277 SDNode* MultNode = MultHi.getNode();
278 unsigned MultOpc = MultHi.getOpcode();
280 // MultHi and MultLo must be generated by the same node,
281 if (MultLo.getNode() != MultNode)
284 // and it must be a multiplication.
285 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
288 // MultLo amd MultHi must be the first and second output of MultNode
290 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
293 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
294 // of the values of MultNode, in which case MultNode will be removed in later
296 // If there exist users other than SUBENode or SUBCNode, this function returns
297 // here, which will result in MultNode being mapped to a single MULT
298 // instruction node rather than a pair of MULT and MSUB instructions being
300 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
303 SDValue Chain = CurDAG->getEntryNode();
304 DebugLoc dl = SUBENode->getDebugLoc();
306 // create MipsSub(u) node
307 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
309 SDValue MSub = CurDAG->getNode(MultOpc, dl,
311 MultNode->getOperand(0),// Factor 0
312 MultNode->getOperand(1),// Factor 1
313 SUBCNode->getOperand(0),// Lo0
314 SUBENode->getOperand(0));// Hi0
316 // create CopyFromReg nodes
317 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
319 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
321 CopyFromLo.getValue(2));
323 // replace uses of sube and subc here
324 if (!SDValue(SUBCNode, 0).use_empty())
325 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
327 if (!SDValue(SUBENode, 0).use_empty())
328 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
333 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
334 TargetLowering::DAGCombinerInfo &DCI,
335 const MipsSubtarget* Subtarget) {
336 if (DCI.isBeforeLegalize())
339 if (Subtarget->isMips32() && SelectMadd(N, &DAG))
340 return SDValue(N, 0);
345 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
346 TargetLowering::DAGCombinerInfo &DCI,
347 const MipsSubtarget* Subtarget) {
348 if (DCI.isBeforeLegalize())
351 if (Subtarget->isMips32() && SelectMsub(N, &DAG))
352 return SDValue(N, 0);
357 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
358 TargetLowering::DAGCombinerInfo &DCI,
359 const MipsSubtarget* Subtarget) {
360 if (DCI.isBeforeLegalizeOps())
363 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
365 DebugLoc dl = N->getDebugLoc();
367 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
368 N->getOperand(0), N->getOperand(1));
369 SDValue InChain = DAG.getEntryNode();
370 SDValue InGlue = DivRem;
373 if (N->hasAnyUseOfValue(0)) {
374 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, Mips::LO, MVT::i32,
376 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
377 InChain = CopyFromLo.getValue(1);
378 InGlue = CopyFromLo.getValue(2);
382 if (N->hasAnyUseOfValue(1)) {
383 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
384 Mips::HI, MVT::i32, InGlue);
385 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
391 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
393 default: llvm_unreachable("Unknown fp condition code!");
395 case ISD::SETOEQ: return Mips::FCOND_OEQ;
396 case ISD::SETUNE: return Mips::FCOND_UNE;
398 case ISD::SETOLT: return Mips::FCOND_OLT;
400 case ISD::SETOGT: return Mips::FCOND_OGT;
402 case ISD::SETOLE: return Mips::FCOND_OLE;
404 case ISD::SETOGE: return Mips::FCOND_OGE;
405 case ISD::SETULT: return Mips::FCOND_ULT;
406 case ISD::SETULE: return Mips::FCOND_ULE;
407 case ISD::SETUGT: return Mips::FCOND_UGT;
408 case ISD::SETUGE: return Mips::FCOND_UGE;
409 case ISD::SETUO: return Mips::FCOND_UN;
410 case ISD::SETO: return Mips::FCOND_OR;
412 case ISD::SETONE: return Mips::FCOND_ONE;
413 case ISD::SETUEQ: return Mips::FCOND_UEQ;
418 // Returns true if condition code has to be inverted.
419 static bool InvertFPCondCode(Mips::CondCode CC) {
420 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
423 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
426 assert(false && "Illegal Condition Code");
430 // Creates and returns an FPCmp node from a setcc node.
431 // Returns Op if setcc is not a floating point comparison.
432 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
433 // must be a SETCC node
434 if (Op.getOpcode() != ISD::SETCC)
437 SDValue LHS = Op.getOperand(0);
439 if (!LHS.getValueType().isFloatingPoint())
442 SDValue RHS = Op.getOperand(1);
443 DebugLoc dl = Op.getDebugLoc();
445 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of node
447 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
449 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
450 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
453 // Creates and returns a CMovFPT/F node.
454 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
455 SDValue False, DebugLoc DL) {
456 bool invert = InvertFPCondCode((Mips::CondCode)
457 cast<ConstantSDNode>(Cond.getOperand(2))
460 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
461 True.getValueType(), True, False, Cond);
464 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
465 TargetLowering::DAGCombinerInfo &DCI,
466 const MipsSubtarget* Subtarget) {
467 if (DCI.isBeforeLegalizeOps())
470 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
472 if (Cond.getOpcode() != MipsISD::FPCmp)
475 SDValue True = DAG.getConstant(1, MVT::i32);
476 SDValue False = DAG.getConstant(0, MVT::i32);
478 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
481 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
483 SelectionDAG &DAG = DCI.DAG;
484 unsigned opc = N->getOpcode();
489 return PerformADDECombine(N, DAG, DCI, Subtarget);
491 return PerformSUBECombine(N, DAG, DCI, Subtarget);
494 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
496 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
502 SDValue MipsTargetLowering::
503 LowerOperation(SDValue Op, SelectionDAG &DAG) const
505 switch (Op.getOpcode())
507 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
508 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
509 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
510 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
511 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
512 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
513 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
514 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
515 case ISD::SELECT: return LowerSELECT(Op, DAG);
516 case ISD::VASTART: return LowerVASTART(Op, DAG);
521 //===----------------------------------------------------------------------===//
522 // Lower helper functions
523 //===----------------------------------------------------------------------===//
525 // AddLiveIn - This helper function adds the specified physical register to the
526 // MachineFunction as a live in value. It also creates a corresponding
527 // virtual register for it.
529 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
531 assert(RC->contains(PReg) && "Not the correct regclass!");
532 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
533 MF.getRegInfo().addLiveIn(PReg, VReg);
537 // Get fp branch code (not opcode) from condition code.
538 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
539 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
540 return Mips::BRANCH_T;
542 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
543 return Mips::BRANCH_F;
545 return Mips::BRANCH_INVALID;
549 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
550 MachineBasicBlock *BB) const {
551 // There is no need to expand CMov instructions if target has
552 // conditional moves.
553 if (Subtarget->hasCondMov())
556 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
557 bool isFPCmp = false;
558 DebugLoc dl = MI->getDebugLoc();
561 switch (MI->getOpcode()) {
562 default: assert(false && "Unexpected instr type to insert");
587 // To "insert" a SELECT_CC instruction, we actually have to insert the
588 // diamond control-flow pattern. The incoming instruction knows the
589 // destination vreg to set, the condition code register to branch on, the
590 // true/false values to select between, and a branch opcode to use.
591 const BasicBlock *LLVM_BB = BB->getBasicBlock();
592 MachineFunction::iterator It = BB;
599 // bNE r1, r0, copy1MBB
600 // fallthrough --> copy0MBB
601 MachineBasicBlock *thisMBB = BB;
602 MachineFunction *F = BB->getParent();
603 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
604 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
605 F->insert(It, copy0MBB);
606 F->insert(It, sinkMBB);
608 // Transfer the remainder of BB and its successor edges to sinkMBB.
609 sinkMBB->splice(sinkMBB->begin(), BB,
610 llvm::next(MachineBasicBlock::iterator(MI)),
612 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
614 // Next, add the true and fallthrough blocks as its successors.
615 BB->addSuccessor(copy0MBB);
616 BB->addSuccessor(sinkMBB);
618 // Emit the right instruction according to the type of the operands compared
620 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
622 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
623 .addReg(Mips::ZERO).addMBB(sinkMBB);
628 // # fallthrough to sinkMBB
631 // Update machine-CFG edges
632 BB->addSuccessor(sinkMBB);
635 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
640 BuildMI(*BB, BB->begin(), dl,
641 TII->get(Mips::PHI), MI->getOperand(0).getReg())
642 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
643 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
645 BuildMI(*BB, BB->begin(), dl,
646 TII->get(Mips::PHI), MI->getOperand(0).getReg())
647 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
648 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
650 MI->eraseFromParent(); // The pseudo instruction is gone now.
654 //===----------------------------------------------------------------------===//
655 // Misc Lower Operation implementation
656 //===----------------------------------------------------------------------===//
658 SDValue MipsTargetLowering::
659 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const
661 if (!Subtarget->isMips1())
664 MachineFunction &MF = DAG.getMachineFunction();
665 unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
667 SDValue Chain = DAG.getEntryNode();
668 DebugLoc dl = Op.getDebugLoc();
669 SDValue Src = Op.getOperand(0);
671 // Set the condition register
672 SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
673 CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
674 CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
676 SDValue Cst = DAG.getConstant(3, MVT::i32);
677 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
678 Cst = DAG.getConstant(2, MVT::i32);
679 SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
681 SDValue InFlag(0, 0);
682 CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
684 // Emit the round instruction and bit convert to integer
685 SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
686 Src, CondReg.getValue(1));
687 SDValue BitCvt = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Trunc);
691 SDValue MipsTargetLowering::
692 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
694 SDValue Chain = Op.getOperand(0);
695 SDValue Size = Op.getOperand(1);
696 DebugLoc dl = Op.getDebugLoc();
698 // Get a reference from Mips stack pointer
699 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
701 // Subtract the dynamic size from the actual stack size to
702 // obtain the new stack size.
703 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
705 // The Sub result contains the new stack start address, so it
706 // must be placed in the stack pointer register.
707 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
709 // This node always has two return values: a new stack pointer
711 SDValue Ops[2] = { Sub, Chain };
712 return DAG.getMergeValues(Ops, 2, dl);
715 SDValue MipsTargetLowering::
716 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
718 // The first operand is the chain, the second is the condition, the third is
719 // the block to branch to if the condition is true.
720 SDValue Chain = Op.getOperand(0);
721 SDValue Dest = Op.getOperand(2);
722 DebugLoc dl = Op.getDebugLoc();
724 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
726 // Return if flag is not set by a floating point comparision.
727 if (CondRes.getOpcode() != MipsISD::FPCmp)
730 SDValue CCNode = CondRes.getOperand(2);
732 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
733 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
735 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
739 SDValue MipsTargetLowering::
740 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
742 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
744 // Return if flag is not set by a floating point comparision.
745 if (Cond.getOpcode() != MipsISD::FPCmp)
748 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
752 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
753 SelectionDAG &DAG) const {
754 // FIXME there isn't actually debug info here
755 DebugLoc dl = Op.getDebugLoc();
756 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
758 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
759 SDVTList VTs = DAG.getVTList(MVT::i32);
761 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
763 // %gp_rel relocation
764 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
765 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
767 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
768 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
769 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
771 // %hi/%lo relocation
772 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
774 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
776 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
777 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
778 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
780 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
782 SDValue ResNode = DAG.getLoad(MVT::i32, dl,
783 DAG.getEntryNode(), GA, MachinePointerInfo(),
785 // On functions and global targets not internal linked only
786 // a load from got/GP is necessary for PIC to work.
787 if (!GV->hasLocalLinkage() || isa<Function>(GV))
789 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
791 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
792 return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
795 llvm_unreachable("Dont know how to handle GlobalAddress");
799 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
800 SelectionDAG &DAG) const {
801 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
802 assert(false && "implement LowerBlockAddress for -static");
803 return SDValue(0, 0);
806 // FIXME there isn't actually debug info here
807 DebugLoc dl = Op.getDebugLoc();
808 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
809 SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
811 SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
813 SDValue Load = DAG.getLoad(MVT::i32, dl,
814 DAG.getEntryNode(), BAGOTOffset,
815 MachinePointerInfo(), false, false, 0);
816 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
817 return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
821 SDValue MipsTargetLowering::
822 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
824 llvm_unreachable("TLS not implemented for MIPS.");
825 return SDValue(); // Not reached
828 SDValue MipsTargetLowering::
829 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
833 // FIXME there isn't actually debug info here
834 DebugLoc dl = Op.getDebugLoc();
835 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
836 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
838 EVT PtrVT = Op.getValueType();
839 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
841 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
844 SDValue Ops[] = { JTI };
845 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
846 } else // Emit Load from Global Pointer
847 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
848 MachinePointerInfo(),
851 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
852 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
853 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
858 SDValue MipsTargetLowering::
859 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
862 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
863 const Constant *C = N->getConstVal();
864 // FIXME there isn't actually debug info here
865 DebugLoc dl = Op.getDebugLoc();
868 // FIXME: we should reference the constant pool using small data sections,
869 // but the asm printer currently doens't support this feature without
870 // hacking it. This feature should come soon so we can uncomment the
872 //if (IsInSmallSection(C->getType())) {
873 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
874 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
875 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
877 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
878 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
879 N->getOffset(), MipsII::MO_ABS_HI);
880 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
881 N->getOffset(), MipsII::MO_ABS_LO);
882 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
883 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
884 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
886 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
887 N->getOffset(), MipsII::MO_GOT);
888 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
889 CP, MachinePointerInfo::getConstantPool(),
891 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
892 N->getOffset(), MipsII::MO_ABS_LO);
893 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
894 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
900 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
901 MachineFunction &MF = DAG.getMachineFunction();
902 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
904 DebugLoc dl = Op.getDebugLoc();
905 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
908 // vastart just stores the address of the VarArgsFrameIndex slot into the
909 // memory location argument.
910 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
911 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
912 MachinePointerInfo(SV),
916 //===----------------------------------------------------------------------===//
917 // Calling Convention Implementation
918 //===----------------------------------------------------------------------===//
920 #include "MipsGenCallingConv.inc"
922 //===----------------------------------------------------------------------===//
923 // TODO: Implement a generic logic using tblgen that can support this.
924 // Mips O32 ABI rules:
926 // i32 - Passed in A0, A1, A2, A3 and stack
927 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
928 // an argument. Otherwise, passed in A1, A2, A3 and stack.
929 // f64 - Only passed in two aliased f32 registers if no int reg has been used
930 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
931 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
933 //===----------------------------------------------------------------------===//
935 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
936 MVT LocVT, CCValAssign::LocInfo LocInfo,
937 ISD::ArgFlagsTy ArgFlags, CCState &State) {
939 static const unsigned IntRegsSize=4, FloatRegsSize=2;
941 static const unsigned IntRegs[] = {
942 Mips::A0, Mips::A1, Mips::A2, Mips::A3
944 static const unsigned F32Regs[] = {
947 static const unsigned F64Regs[] = {
952 static bool IntRegUsed = false;
954 // This must be the first arg of the call if no regs have been allocated.
955 // Initialize IntRegUsed in that case.
956 if (IntRegs[State.getFirstUnallocated(IntRegs, IntRegsSize)] == Mips::A0 &&
957 F32Regs[State.getFirstUnallocated(F32Regs, FloatRegsSize)] == Mips::F12 &&
958 F64Regs[State.getFirstUnallocated(F64Regs, FloatRegsSize)] == Mips::D6)
961 // Promote i8 and i16
962 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
964 if (ArgFlags.isSExt())
965 LocInfo = CCValAssign::SExt;
966 else if (ArgFlags.isZExt())
967 LocInfo = CCValAssign::ZExt;
969 LocInfo = CCValAssign::AExt;
972 if (ValVT == MVT::i32) {
973 Reg = State.AllocateReg(IntRegs, IntRegsSize);
975 } else if (ValVT == MVT::f32) {
976 // An int reg has to be marked allocated regardless of whether or not
977 // IntRegUsed is true.
978 Reg = State.AllocateReg(IntRegs, IntRegsSize);
981 if (Reg) // Int reg is available
984 unsigned FReg = State.AllocateReg(F32Regs, FloatRegsSize);
985 if (FReg) // F32 reg is available
987 else if (Reg) // No F32 regs are available, but an int reg is available.
990 } else if (ValVT == MVT::f64) {
991 // Int regs have to be marked allocated regardless of whether or not
992 // IntRegUsed is true.
993 Reg = State.AllocateReg(IntRegs, IntRegsSize);
995 Reg = State.AllocateReg(IntRegs, IntRegsSize);
996 else if (Reg == Mips::A3)
998 State.AllocateReg(IntRegs, IntRegsSize);
1000 // At this point, Reg is A0, A2 or 0, and all the unavailable integer regs
1001 // are marked as allocated.
1003 if (Reg)// if int reg is available
1006 unsigned FReg = State.AllocateReg(F64Regs, FloatRegsSize);
1007 if (FReg) // F64 reg is available.
1009 else if (Reg) // No F64 regs are available, but an int reg is available.
1013 assert(false && "cannot handle this ValVT");
1016 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1017 unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
1018 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1020 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1022 return false; // CC must always match
1025 static bool CC_MipsO32_VarArgs(unsigned ValNo, MVT ValVT,
1026 MVT LocVT, CCValAssign::LocInfo LocInfo,
1027 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1029 static const unsigned IntRegsSize=4;
1031 static const unsigned IntRegs[] = {
1032 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1035 // Promote i8 and i16
1036 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1038 if (ArgFlags.isSExt())
1039 LocInfo = CCValAssign::SExt;
1040 else if (ArgFlags.isZExt())
1041 LocInfo = CCValAssign::ZExt;
1043 LocInfo = CCValAssign::AExt;
1048 if (ValVT == MVT::i32 || ValVT == MVT::f32) {
1049 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1051 } else if (ValVT == MVT::f64) {
1052 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1053 if (Reg == Mips::A1 || Reg == Mips::A3)
1054 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1055 State.AllocateReg(IntRegs, IntRegsSize);
1058 llvm_unreachable("Cannot handle this ValVT.");
1061 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1062 unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
1063 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1065 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1067 return false; // CC must always match
1070 //===----------------------------------------------------------------------===//
1071 // Call Calling Convention Implementation
1072 //===----------------------------------------------------------------------===//
1074 /// LowerCall - functions arguments are copied from virtual regs to
1075 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1076 /// TODO: isTailCall.
1078 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1079 CallingConv::ID CallConv, bool isVarArg,
1081 const SmallVectorImpl<ISD::OutputArg> &Outs,
1082 const SmallVectorImpl<SDValue> &OutVals,
1083 const SmallVectorImpl<ISD::InputArg> &Ins,
1084 DebugLoc dl, SelectionDAG &DAG,
1085 SmallVectorImpl<SDValue> &InVals) const {
1086 // MIPs target does not yet support tail call optimization.
1089 MachineFunction &MF = DAG.getMachineFunction();
1090 MachineFrameInfo *MFI = MF.getFrameInfo();
1091 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1093 // Analyze operands of the call, assigning locations to each operand.
1094 SmallVector<CCValAssign, 16> ArgLocs;
1095 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1098 // To meet O32 ABI, Mips must always allocate 16 bytes on
1099 // the stack (even if less than 4 are used as arguments)
1100 if (Subtarget->isABI_O32()) {
1101 int VTsize = MVT(MVT::i32).getSizeInBits()/8;
1102 MFI->CreateFixedObject(VTsize, (VTsize*3), true);
1103 CCInfo.AnalyzeCallOperands(Outs,
1104 isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1106 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1108 // Get a count of how many bytes are to be pushed on the stack.
1109 unsigned NumBytes = CCInfo.getNextStackOffset();
1110 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1112 // With EABI is it possible to have 16 args on registers.
1113 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1114 SmallVector<SDValue, 8> MemOpChains;
1116 // First/LastArgStackLoc contains the first/last
1117 // "at stack" argument location.
1118 int LastArgStackLoc = 0;
1119 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1121 // Walk the register/memloc assignments, inserting copies/loads.
1122 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1123 SDValue Arg = OutVals[i];
1124 CCValAssign &VA = ArgLocs[i];
1126 // Promote the value if needed.
1127 switch (VA.getLocInfo()) {
1128 default: llvm_unreachable("Unknown loc info!");
1129 case CCValAssign::Full:
1130 if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1131 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1132 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1133 if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1134 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1135 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1136 DAG.getConstant(0, getPointerTy()));
1137 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1138 DAG.getConstant(1, getPointerTy()));
1139 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1140 RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1145 case CCValAssign::SExt:
1146 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1148 case CCValAssign::ZExt:
1149 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1151 case CCValAssign::AExt:
1152 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1156 // Arguments that can be passed on register must be kept at
1157 // RegsToPass vector
1158 if (VA.isRegLoc()) {
1159 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1163 // Register can't get to this point...
1164 assert(VA.isMemLoc());
1166 // Create the frame index object for this incoming parameter
1167 // This guarantees that when allocating Local Area the firsts
1168 // 16 bytes which are alwayes reserved won't be overwritten
1169 // if O32 ABI is used. For EABI the first address is zero.
1170 LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
1171 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1172 LastArgStackLoc, true);
1174 SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
1176 // emit ISD::STORE whichs stores the
1177 // parameter value to a stack Location
1178 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1179 MachinePointerInfo(),
1183 // Transform all store nodes into one single node because all store
1184 // nodes are independent of each other.
1185 if (!MemOpChains.empty())
1186 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1187 &MemOpChains[0], MemOpChains.size());
1189 // Build a sequence of copy-to-reg nodes chained together with token
1190 // chain and flag operands which copy the outgoing args into registers.
1191 // The InFlag in necessary since all emited instructions must be
1194 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1195 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1196 RegsToPass[i].second, InFlag);
1197 InFlag = Chain.getValue(1);
1200 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1201 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1202 // node so that legalize doesn't hack it.
1203 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1204 bool LoadSymAddr = false;
1206 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1207 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1208 getPointerTy(), 0, OpFlag);
1211 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1212 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1213 getPointerTy(), OpFlag);
1217 // Create nodes that load address of callee and copy it to T9
1220 // load callee address
1221 Callee = DAG.getLoad(MVT::i32, dl, Chain, Callee,
1222 MachinePointerInfo::getGOT(),
1224 Chain = Callee.getValue(1);
1228 Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
1229 InFlag = Chain.getValue(1);
1230 Callee = DAG.getRegister(Mips::T9, MVT::i32);
1233 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1234 // = Chain, Callee, Reg#1, Reg#2, ...
1236 // Returns a chain & a flag for retval copy to use.
1237 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1238 SmallVector<SDValue, 8> Ops;
1239 Ops.push_back(Chain);
1240 Ops.push_back(Callee);
1242 // Add argument registers to the end of the list so that they are
1243 // known live into the call.
1244 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1245 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1246 RegsToPass[i].second.getValueType()));
1248 if (InFlag.getNode())
1249 Ops.push_back(InFlag);
1251 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1252 InFlag = Chain.getValue(1);
1254 // Create a stack location to hold GP when PIC is used. This stack
1255 // location is used on function prologue to save GP and also after all
1256 // emited CALL's to restore GP.
1258 // Function can have an arbitrary number of calls, so
1259 // hold the LastArgStackLoc with the biggest offset.
1261 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1262 if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
1263 LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
1264 // Create the frame index only once. SPOffset here can be anything
1265 // (this will be fixed on processFunctionBeforeFrameFinalized)
1266 if (MipsFI->getGPStackOffset() == -1) {
1267 FI = MFI->CreateFixedObject(4, 0, true);
1268 MipsFI->setGPFI(FI);
1270 MipsFI->setGPStackOffset(LastArgStackLoc);
1274 FI = MipsFI->getGPFI();
1275 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1276 SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN,
1277 MachinePointerInfo::getFixedStack(FI),
1279 Chain = GPLoad.getValue(1);
1280 Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32),
1281 GPLoad, SDValue(0,0));
1282 InFlag = Chain.getValue(1);
1285 // Create the CALLSEQ_END node.
1286 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1287 DAG.getIntPtrConstant(0, true), InFlag);
1288 InFlag = Chain.getValue(1);
1290 // Handle result values, copying them out of physregs into vregs that we
1292 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1293 Ins, dl, DAG, InVals);
1296 /// LowerCallResult - Lower the result values of a call into the
1297 /// appropriate copies out of appropriate physical registers.
1299 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1300 CallingConv::ID CallConv, bool isVarArg,
1301 const SmallVectorImpl<ISD::InputArg> &Ins,
1302 DebugLoc dl, SelectionDAG &DAG,
1303 SmallVectorImpl<SDValue> &InVals) const {
1305 // Assign locations to each value returned by this call.
1306 SmallVector<CCValAssign, 16> RVLocs;
1307 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1308 RVLocs, *DAG.getContext());
1310 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1312 // Copy all of the result registers out of their specified physreg.
1313 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1314 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1315 RVLocs[i].getValVT(), InFlag).getValue(1);
1316 InFlag = Chain.getValue(2);
1317 InVals.push_back(Chain.getValue(0));
1323 //===----------------------------------------------------------------------===//
1324 // Formal Arguments Calling Convention Implementation
1325 //===----------------------------------------------------------------------===//
1327 /// LowerFormalArguments - transform physical registers into virtual registers
1328 /// and generate load operations for arguments places on the stack.
1330 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
1331 CallingConv::ID CallConv, bool isVarArg,
1332 const SmallVectorImpl<ISD::InputArg>
1334 DebugLoc dl, SelectionDAG &DAG,
1335 SmallVectorImpl<SDValue> &InVals)
1338 MachineFunction &MF = DAG.getMachineFunction();
1339 MachineFrameInfo *MFI = MF.getFrameInfo();
1340 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1342 MipsFI->setVarArgsFrameIndex(0);
1344 // Used with vargs to acumulate store chains.
1345 std::vector<SDValue> OutChains;
1347 // Keep track of the last register used for arguments
1348 unsigned ArgRegEnd = 0;
1350 // Assign locations to all of the incoming arguments.
1351 SmallVector<CCValAssign, 16> ArgLocs;
1352 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1353 ArgLocs, *DAG.getContext());
1355 if (Subtarget->isABI_O32())
1356 CCInfo.AnalyzeFormalArguments(Ins,
1357 isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1359 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
1361 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1362 unsigned LastStackArgEndOffset = 0;
1363 EVT LastRegArgValVT;
1365 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1366 CCValAssign &VA = ArgLocs[i];
1368 // Arguments stored on registers
1369 if (VA.isRegLoc()) {
1370 EVT RegVT = VA.getLocVT();
1371 ArgRegEnd = VA.getLocReg();
1372 LastRegArgValVT = VA.getValVT();
1373 TargetRegisterClass *RC = 0;
1375 if (RegVT == MVT::i32)
1376 RC = Mips::CPURegsRegisterClass;
1377 else if (RegVT == MVT::f32)
1378 RC = Mips::FGR32RegisterClass;
1379 else if (RegVT == MVT::f64) {
1380 if (!Subtarget->isSingleFloat())
1381 RC = Mips::AFGR64RegisterClass;
1383 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
1385 // Transform the arguments stored on
1386 // physical registers into virtual ones
1387 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1388 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1390 // If this is an 8 or 16-bit value, it has been passed promoted
1391 // to 32 bits. Insert an assert[sz]ext to capture this, then
1392 // truncate to the right size.
1393 if (VA.getLocInfo() != CCValAssign::Full) {
1394 unsigned Opcode = 0;
1395 if (VA.getLocInfo() == CCValAssign::SExt)
1396 Opcode = ISD::AssertSext;
1397 else if (VA.getLocInfo() == CCValAssign::ZExt)
1398 Opcode = ISD::AssertZext;
1400 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
1401 DAG.getValueType(VA.getValVT()));
1402 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1405 // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
1406 if (Subtarget->isABI_O32()) {
1407 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
1408 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1409 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
1410 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
1411 VA.getLocReg()+1, RC);
1412 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
1413 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, ArgValue,
1415 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Pair);
1419 InVals.push_back(ArgValue);
1420 } else { // VA.isRegLoc()
1423 assert(VA.isMemLoc());
1425 // The last argument is not a register anymore
1428 // The stack pointer offset is relative to the caller stack frame.
1429 // Since the real stack size is unknown here, a negative SPOffset
1430 // is used so there's a way to adjust these offsets when the stack
1431 // size get known (on EliminateFrameIndex). A dummy SPOffset is
1432 // used instead of a direct negative address (which is recorded to
1433 // be used on emitPrologue) to avoid mis-calc of the first stack
1434 // offset on PEI::calculateFrameObjectOffsets.
1435 unsigned ArgSize = VA.getValVT().getSizeInBits()/8;
1436 LastStackArgEndOffset = FirstStackArgLoc + VA.getLocMemOffset() + ArgSize;
1437 int FI = MFI->CreateFixedObject(ArgSize, 0, true);
1438 MipsFI->recordLoadArgsFI(FI, -(4 +
1439 (FirstStackArgLoc + VA.getLocMemOffset())));
1441 // Create load nodes to retrieve arguments from the stack
1442 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1443 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1444 MachinePointerInfo::getFixedStack(FI),
1449 // The mips ABIs for returning structs by value requires that we copy
1450 // the sret argument into $v0 for the return. Save the argument into
1451 // a virtual register so that we can access it from the return points.
1452 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1453 unsigned Reg = MipsFI->getSRetReturnReg();
1455 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1456 MipsFI->setSRetReturnReg(Reg);
1458 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1459 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1462 // To meet ABI, when VARARGS are passed on registers, the registers
1463 // must have their values written to the caller stack frame. If the last
1464 // argument was placed in the stack, there's no need to save any register.
1465 if (isVarArg && Subtarget->isABI_O32()) {
1467 // Last named formal argument is passed in register.
1469 // The last register argument that must be saved is Mips::A3
1470 TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
1471 if (LastRegArgValVT == MVT::f64)
1474 if (ArgRegEnd < Mips::A3) {
1475 // Both the last named formal argument and the first variable
1476 // argument are passed in registers.
1477 for (++ArgRegEnd; ArgRegEnd <= Mips::A3; ++ArgRegEnd) {
1478 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1479 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
1481 int FI = MFI->CreateFixedObject(4, 0, true);
1482 MipsFI->recordStoreVarArgsFI(FI, -(4+(ArgRegEnd-Mips::A0)*4));
1483 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
1484 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
1485 MachinePointerInfo(),
1488 // Record the frame index of the first variable argument
1489 // which is a value necessary to VASTART.
1490 if (!MipsFI->getVarArgsFrameIndex()) {
1491 MFI->setObjectAlignment(FI, 4);
1492 MipsFI->setVarArgsFrameIndex(FI);
1496 // Last named formal argument is in register Mips::A3, and the first
1497 // variable argument is on stack. Record the frame index of the first
1498 // variable argument.
1499 int FI = MFI->CreateFixedObject(4, 0, true);
1500 MFI->setObjectAlignment(FI, 4);
1501 MipsFI->recordStoreVarArgsFI(FI, -20);
1502 MipsFI->setVarArgsFrameIndex(FI);
1505 // Last named formal argument and all the variable arguments are passed
1506 // on stack. Record the frame index of the first variable argument.
1507 int FI = MFI->CreateFixedObject(4, 0, true);
1508 MFI->setObjectAlignment(FI, 4);
1509 MipsFI->recordStoreVarArgsFI(FI, -(4+LastStackArgEndOffset));
1510 MipsFI->setVarArgsFrameIndex(FI);
1514 // All stores are grouped in one node to allow the matching between
1515 // the size of Ins and InVals. This only happens when on varg functions
1516 if (!OutChains.empty()) {
1517 OutChains.push_back(Chain);
1518 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1519 &OutChains[0], OutChains.size());
1525 //===----------------------------------------------------------------------===//
1526 // Return Value Calling Convention Implementation
1527 //===----------------------------------------------------------------------===//
1530 MipsTargetLowering::LowerReturn(SDValue Chain,
1531 CallingConv::ID CallConv, bool isVarArg,
1532 const SmallVectorImpl<ISD::OutputArg> &Outs,
1533 const SmallVectorImpl<SDValue> &OutVals,
1534 DebugLoc dl, SelectionDAG &DAG) const {
1536 // CCValAssign - represent the assignment of
1537 // the return value to a location
1538 SmallVector<CCValAssign, 16> RVLocs;
1540 // CCState - Info about the registers and stack slot.
1541 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1542 RVLocs, *DAG.getContext());
1544 // Analize return values.
1545 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1547 // If this is the first return lowered for this function, add
1548 // the regs to the liveout set for the function.
1549 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1550 for (unsigned i = 0; i != RVLocs.size(); ++i)
1551 if (RVLocs[i].isRegLoc())
1552 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1557 // Copy the result values into the output registers.
1558 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1559 CCValAssign &VA = RVLocs[i];
1560 assert(VA.isRegLoc() && "Can only return in registers!");
1562 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1565 // guarantee that all emitted copies are
1566 // stuck together, avoiding something bad
1567 Flag = Chain.getValue(1);
1570 // The mips ABIs for returning structs by value requires that we copy
1571 // the sret argument into $v0 for the return. We saved the argument into
1572 // a virtual register in the entry block, so now we copy the value out
1574 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1575 MachineFunction &MF = DAG.getMachineFunction();
1576 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1577 unsigned Reg = MipsFI->getSRetReturnReg();
1580 llvm_unreachable("sret virtual register not created in the entry block");
1581 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1583 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1584 Flag = Chain.getValue(1);
1587 // Return on Mips is always a "jr $ra"
1589 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1590 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1592 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1593 Chain, DAG.getRegister(Mips::RA, MVT::i32));
1596 //===----------------------------------------------------------------------===//
1597 // Mips Inline Assembly Support
1598 //===----------------------------------------------------------------------===//
1600 /// getConstraintType - Given a constraint letter, return the type of
1601 /// constraint it is for this target.
1602 MipsTargetLowering::ConstraintType MipsTargetLowering::
1603 getConstraintType(const std::string &Constraint) const
1605 // Mips specific constrainy
1606 // GCC config/mips/constraints.md
1608 // 'd' : An address register. Equivalent to r
1609 // unless generating MIPS16 code.
1610 // 'y' : Equivalent to r; retained for
1611 // backwards compatibility.
1612 // 'f' : Floating Point registers.
1613 if (Constraint.size() == 1) {
1614 switch (Constraint[0]) {
1619 return C_RegisterClass;
1623 return TargetLowering::getConstraintType(Constraint);
1626 /// Examine constraint type and operand type and determine a weight value.
1627 /// This object must already have been set up with the operand type
1628 /// and the current alternative constraint selected.
1629 TargetLowering::ConstraintWeight
1630 MipsTargetLowering::getSingleConstraintMatchWeight(
1631 AsmOperandInfo &info, const char *constraint) const {
1632 ConstraintWeight weight = CW_Invalid;
1633 Value *CallOperandVal = info.CallOperandVal;
1634 // If we don't have a value, we can't do a match,
1635 // but allow it at the lowest weight.
1636 if (CallOperandVal == NULL)
1638 const Type *type = CallOperandVal->getType();
1639 // Look at the constraint type.
1640 switch (*constraint) {
1642 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1646 if (type->isIntegerTy())
1647 weight = CW_Register;
1650 if (type->isFloatTy())
1651 weight = CW_Register;
1657 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1658 /// return a list of registers that can be used to satisfy the constraint.
1659 /// This should only be used for C_RegisterClass constraints.
1660 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1661 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
1663 if (Constraint.size() == 1) {
1664 switch (Constraint[0]) {
1666 return std::make_pair(0U, Mips::CPURegsRegisterClass);
1669 return std::make_pair(0U, Mips::FGR32RegisterClass);
1671 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1672 return std::make_pair(0U, Mips::AFGR64RegisterClass);
1675 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1678 /// Given a register class constraint, like 'r', if this corresponds directly
1679 /// to an LLVM register class, return a register of 0 and the register class
1681 std::vector<unsigned> MipsTargetLowering::
1682 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1685 if (Constraint.size() != 1)
1686 return std::vector<unsigned>();
1688 switch (Constraint[0]) {
1691 // GCC Mips Constraint Letters
1694 return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1695 Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1696 Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1700 if (VT == MVT::f32) {
1701 if (Subtarget->isSingleFloat())
1702 return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1703 Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1704 Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1705 Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1706 Mips::F30, Mips::F31, 0);
1708 return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1709 Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1710 Mips::F28, Mips::F30, 0);
1714 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1715 return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1716 Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1717 Mips::D14, Mips::D15, 0);
1719 return std::vector<unsigned>();
1723 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1724 // The Mips target isn't yet aware of offsets.
1728 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1729 if (VT != MVT::f32 && VT != MVT::f64)
1731 if (Imm.isNegZero())
1733 return Imm.isZero();