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"
17 #include "MipsISelLowering.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsTargetMachine.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"
39 const char *MipsTargetLowering::
40 getTargetNodeName(unsigned Opcode) const
44 case MipsISD::JmpLink : return "MipsISD::JmpLink";
45 case MipsISD::Hi : return "MipsISD::Hi";
46 case MipsISD::Lo : return "MipsISD::Lo";
47 case MipsISD::GPRel : return "MipsISD::GPRel";
48 case MipsISD::Ret : return "MipsISD::Ret";
49 case MipsISD::SelectCC : return "MipsISD::SelectCC";
50 case MipsISD::FPBrcond : return "MipsISD::FPBrcond";
51 case MipsISD::FPCmp : return "MipsISD::FPCmp";
52 default : return NULL;
57 MipsTargetLowering(MipsTargetMachine &TM): TargetLowering(TM)
59 Subtarget = &TM.getSubtarget<MipsSubtarget>();
61 // Mips does not have i1 type, so use i32 for
62 // setcc operations results (slt, sgt, ...).
63 setSetCCResultContents(ZeroOrOneSetCCResult);
65 // JumpTable targets must use GOT when using PIC_
66 setUsesGlobalOffsetTable(true);
68 // Set up the register classes
69 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
71 // When dealing with single precision only, use libcalls
72 if (!Subtarget->isSingleFloat()) {
73 addRegisterClass(MVT::f32, Mips::AFGR32RegisterClass);
74 if (!Subtarget->isFP64bit())
75 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
77 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
79 // Load extented operations for i1 types must be promoted
80 setLoadXAction(ISD::EXTLOAD, MVT::i1, Promote);
81 setLoadXAction(ISD::ZEXTLOAD, MVT::i1, Promote);
82 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
84 // Mips Custom Operations
85 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
86 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
87 setOperationAction(ISD::RET, MVT::Other, Custom);
88 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
89 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
90 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
91 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
92 setOperationAction(ISD::SETCC, MVT::f32, Custom);
93 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
95 // Operations not directly supported by Mips.
96 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
97 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
98 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
99 setOperationAction(ISD::SELECT, MVT::i32, Expand);
100 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
101 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
102 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
104 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
105 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
106 setOperationAction(ISD::ROTL, MVT::i32, Expand);
107 setOperationAction(ISD::ROTR, MVT::i32, Expand);
108 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
109 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
110 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
111 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
113 // We don't have line number support yet.
114 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
115 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
116 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
117 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
119 // Use the default for now
120 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
121 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
122 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
124 if (Subtarget->isSingleFloat())
125 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
127 if (!Subtarget->hasSEInReg()) {
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
132 setStackPointerRegisterToSaveRestore(Mips::SP);
133 computeRegisterProperties();
137 MVT MipsTargetLowering::getSetCCResultType(const SDValue &) const {
142 SDValue MipsTargetLowering::
143 LowerOperation(SDValue Op, SelectionDAG &DAG)
145 switch (Op.getOpcode())
147 case ISD::CALL: return LowerCALL(Op, DAG);
148 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
149 case ISD::RET: return LowerRET(Op, DAG);
150 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
151 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
152 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
153 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
154 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
155 case ISD::SETCC: return LowerSETCC(Op, DAG);
156 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
162 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
163 MachineBasicBlock *BB)
165 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
166 switch (MI->getOpcode()) {
167 default: assert(false && "Unexpected instr type to insert");
168 case Mips::Select_CC: {
169 // To "insert" a SELECT_CC instruction, we actually have to insert the
170 // diamond control-flow pattern. The incoming instruction knows the
171 // destination vreg to set, the condition code register to branch on, the
172 // true/false values to select between, and a branch opcode to use.
173 const BasicBlock *LLVM_BB = BB->getBasicBlock();
174 MachineFunction::iterator It = BB;
181 // bNE r1, r0, copy1MBB
182 // fallthrough --> copy0MBB
183 MachineBasicBlock *thisMBB = BB;
184 MachineFunction *F = BB->getParent();
185 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
186 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
187 BuildMI(BB, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
188 .addReg(Mips::ZERO).addMBB(sinkMBB);
189 F->insert(It, copy0MBB);
190 F->insert(It, sinkMBB);
191 // Update machine-CFG edges by first adding all successors of the current
192 // block to the new block which will contain the Phi node for the select.
193 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
194 e = BB->succ_end(); i != e; ++i)
195 sinkMBB->addSuccessor(*i);
196 // Next, remove all successors of the current block, and add the true
197 // and fallthrough blocks as its successors.
198 while(!BB->succ_empty())
199 BB->removeSuccessor(BB->succ_begin());
200 BB->addSuccessor(copy0MBB);
201 BB->addSuccessor(sinkMBB);
205 // # fallthrough to sinkMBB
208 // Update machine-CFG edges
209 BB->addSuccessor(sinkMBB);
212 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
215 BuildMI(BB, TII->get(Mips::PHI), MI->getOperand(0).getReg())
216 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
217 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB);
219 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
225 //===----------------------------------------------------------------------===//
226 // Lower helper functions
227 //===----------------------------------------------------------------------===//
229 // AddLiveIn - This helper function adds the specified physical register to the
230 // MachineFunction as a live in value. It also creates a corresponding
231 // virtual register for it.
233 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
235 assert(RC->contains(PReg) && "Not the correct regclass!");
236 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
237 MF.getRegInfo().addLiveIn(PReg, VReg);
241 // A address must be loaded from a small section if its size is less than the
242 // small section size threshold. Data in this section must be addressed using
244 bool MipsTargetLowering::IsInSmallSection(unsigned Size) {
245 return (Size > 0 && (Size <= Subtarget->getSSectionThreshold()));
248 // Discover if this global address can be placed into small data/bss section.
249 bool MipsTargetLowering::IsGlobalInSmallSection(GlobalValue *GV)
251 const TargetData *TD = getTargetData();
252 const GlobalVariable *GVA = dyn_cast<GlobalVariable>(GV);
257 const Type *Ty = GV->getType()->getElementType();
258 unsigned Size = TD->getABITypeSize(Ty);
260 // if this is a internal constant string, there is a special
261 // section for it, but not in small data/bss.
262 if (GVA->hasInitializer() && GV->hasInternalLinkage()) {
263 Constant *C = GVA->getInitializer();
264 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
265 if (CVA && CVA->isCString())
269 return IsInSmallSection(Size);
272 // Get fp branch code (not opcode) from condition code.
273 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
274 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
275 return Mips::BRANCH_T;
277 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
278 return Mips::BRANCH_F;
280 return Mips::BRANCH_INVALID;
284 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
286 default: assert(0 && "Unknown fp condition code!");
288 case ISD::SETOEQ: return Mips::FCOND_EQ;
289 case ISD::SETUNE: return Mips::FCOND_OGL;
291 case ISD::SETOLT: return Mips::FCOND_OLT;
293 case ISD::SETOGT: return Mips::FCOND_OGT;
295 case ISD::SETOLE: return Mips::FCOND_OLE;
297 case ISD::SETOGE: return Mips::FCOND_OGE;
298 case ISD::SETULT: return Mips::FCOND_ULT;
299 case ISD::SETULE: return Mips::FCOND_ULE;
300 case ISD::SETUGT: return Mips::FCOND_UGT;
301 case ISD::SETUGE: return Mips::FCOND_UGE;
302 case ISD::SETUO: return Mips::FCOND_UN;
303 case ISD::SETO: return Mips::FCOND_OR;
305 case ISD::SETONE: return Mips::FCOND_NEQ;
306 case ISD::SETUEQ: return Mips::FCOND_UEQ;
310 //===----------------------------------------------------------------------===//
311 // Misc Lower Operation implementation
312 //===----------------------------------------------------------------------===//
313 SDValue MipsTargetLowering::
314 LowerBRCOND(SDValue Op, SelectionDAG &DAG)
316 // The first operand is the chain, the second is the condition, the third is
317 // the block to branch to if the condition is true.
318 SDValue Chain = Op.getOperand(0);
319 SDValue Dest = Op.getOperand(2);
322 if (Op.getOperand(1).getOpcode() == ISD::AND)
323 CondRes = Op.getOperand(1).getOperand(0);
324 else if (Op.getOperand(1).getOpcode() == MipsISD::FPCmp)
325 CondRes = Op.getOperand(1);
327 assert(0 && "Incoming condition flag unknown");
329 SDValue CCNode = CondRes.getOperand(2);
330 Mips::CondCode CC = (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getValue();
331 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
333 return DAG.getNode(MipsISD::FPBrcond, Op.getValueType(), Chain, BrCode,
337 SDValue MipsTargetLowering::
338 LowerSETCC(SDValue Op, SelectionDAG &DAG)
340 // The operands to this are the left and right operands to compare (ops #0,
341 // and #1) and the condition code to compare them with (op #2) as a
343 SDValue LHS = Op.getOperand(0);
344 SDValue RHS = Op.getOperand(1);
346 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
348 return DAG.getNode(MipsISD::FPCmp, Op.getValueType(), LHS, RHS,
349 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
352 SDValue MipsTargetLowering::
353 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
355 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
356 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
358 if (!Subtarget->hasABICall()) {
359 if (isa<Function>(GV)) return GA;
360 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
361 SDValue Ops[] = { GA };
363 if (IsGlobalInSmallSection(GV)) { // %gp_rel relocation
364 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, VTs, 1, Ops, 1);
365 SDValue GOT = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, MVT::i32);
366 return DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
368 // %hi/%lo relocation
369 SDValue HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
370 SDValue Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
371 return DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
373 } else { // Abicall relocations, TODO: make this cleaner.
374 SDValue ResNode = DAG.getLoad(MVT::i32, DAG.getEntryNode(), GA, NULL, 0);
375 // On functions and global targets not internal linked only
376 // a load from got/GP is necessary for PIC to work.
377 if (!GV->hasInternalLinkage() || isa<Function>(GV))
379 SDValue Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
380 return DAG.getNode(ISD::ADD, MVT::i32, ResNode, Lo);
383 assert(0 && "Dont know how to handle GlobalAddress");
387 SDValue MipsTargetLowering::
388 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
390 assert(0 && "TLS not implemented for MIPS.");
391 return SDValue(); // Not reached
394 SDValue MipsTargetLowering::
395 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
397 SDValue LHS = Op.getOperand(0);
398 SDValue RHS = Op.getOperand(1);
399 SDValue True = Op.getOperand(2);
400 SDValue False = Op.getOperand(3);
401 SDValue CC = Op.getOperand(4);
403 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
404 SDValue Ops[] = { LHS, RHS, CC };
405 SDValue SetCCRes = DAG.getNode(ISD::SETCC, VTs, 1, Ops, 3);
407 return DAG.getNode(MipsISD::SelectCC, True.getValueType(),
408 SetCCRes, True, False);
411 SDValue MipsTargetLowering::
412 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
417 MVT PtrVT = Op.getValueType();
418 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
419 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
421 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
422 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
423 SDValue Ops[] = { JTI };
424 HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
425 } else // Emit Load from Global Pointer
426 HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), JTI, NULL, 0);
428 SDValue Lo = DAG.getNode(MipsISD::Lo, MVT::i32, JTI);
429 ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
434 SDValue MipsTargetLowering::
435 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
438 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
439 Constant *C = N->getConstVal();
440 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
443 // FIXME: we should reference the constant pool using small data sections,
444 // but the asm printer currently doens't support this feature without
445 // hacking it. This feature should come soon so we can uncomment the
447 //if (!Subtarget->hasABICall() &&
448 // IsInSmallSection(getTargetData()->getABITypeSize(C->getType()))) {
449 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
450 // SDValue GOT = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, MVT::i32);
451 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
452 //} else { // %hi/%lo relocation
453 SDValue HiPart = DAG.getNode(MipsISD::Hi, MVT::i32, CP);
454 SDValue Lo = DAG.getNode(MipsISD::Lo, MVT::i32, CP);
455 ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
461 //===----------------------------------------------------------------------===//
462 // Calling Convention Implementation
464 // The lower operations present on calling convention works on this order:
465 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
466 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
467 // LowerRET (virt regs --> phys regs)
468 // LowerCALL (phys regs --> virt regs)
470 //===----------------------------------------------------------------------===//
472 #include "MipsGenCallingConv.inc"
474 //===----------------------------------------------------------------------===//
475 // CALL Calling Convention Implementation
476 //===----------------------------------------------------------------------===//
478 /// Mips custom CALL implementation
479 SDValue MipsTargetLowering::
480 LowerCALL(SDValue Op, SelectionDAG &DAG)
482 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
484 // By now, only CallingConv::C implemented
485 switch (CallingConv) {
487 assert(0 && "Unsupported calling convention");
488 case CallingConv::Fast:
490 return LowerCCCCallTo(Op, DAG, CallingConv);
494 /// LowerCCCCallTo - functions arguments are copied from virtual
495 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
496 /// CALLSEQ_END are emitted.
497 /// TODO: isVarArg, isTailCall.
498 SDValue MipsTargetLowering::
499 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
501 MachineFunction &MF = DAG.getMachineFunction();
503 SDValue Chain = Op.getOperand(0);
504 SDValue Callee = Op.getOperand(4);
505 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
507 MachineFrameInfo *MFI = MF.getFrameInfo();
509 // Analyze operands of the call, assigning locations to each operand.
510 SmallVector<CCValAssign, 16> ArgLocs;
511 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
513 // To meet O32 ABI, Mips must always allocate 16 bytes on
514 // the stack (even if less than 4 are used as arguments)
515 if (Subtarget->isABI_O32()) {
516 int VTsize = MVT(MVT::i32).getSizeInBits()/8;
517 MFI->CreateFixedObject(VTsize, (VTsize*3));
520 CCInfo.AnalyzeCallOperands(Op.Val, CC_Mips);
522 // Get a count of how many bytes are to be pushed on the stack.
523 unsigned NumBytes = CCInfo.getNextStackOffset();
524 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
527 // With EABI is it possible to have 16 args on registers.
528 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
529 SmallVector<SDValue, 8> MemOpChains;
531 // First/LastArgStackLoc contains the first/last
532 // "at stack" argument location.
533 int LastArgStackLoc = 0;
534 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
536 // Walk the register/memloc assignments, inserting copies/loads.
537 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
538 CCValAssign &VA = ArgLocs[i];
540 // Arguments start after the 5 first operands of ISD::CALL
541 SDValue Arg = Op.getOperand(5+2*VA.getValNo());
543 // Promote the value if needed.
544 switch (VA.getLocInfo()) {
545 default: assert(0 && "Unknown loc info!");
546 case CCValAssign::Full: break;
547 case CCValAssign::SExt:
548 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
550 case CCValAssign::ZExt:
551 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
553 case CCValAssign::AExt:
554 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
558 // Arguments that can be passed on register must be kept at
561 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
565 // Register cant get to this point...
566 assert(VA.isMemLoc());
568 // Create the frame index object for this incoming parameter
569 // This guarantees that when allocating Local Area the firsts
570 // 16 bytes which are alwayes reserved won't be overwritten
571 // if O32 ABI is used. For EABI the first address is zero.
572 LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
573 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
576 SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
578 // emit ISD::STORE whichs stores the
579 // parameter value to a stack Location
580 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
583 // Transform all store nodes into one single node because all store
584 // nodes are independent of each other.
585 if (!MemOpChains.empty())
586 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
587 &MemOpChains[0], MemOpChains.size());
589 // Build a sequence of copy-to-reg nodes chained together with token
590 // chain and flag operands which copy the outgoing args into registers.
591 // The InFlag in necessary since all emited instructions must be
594 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
595 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first,
596 RegsToPass[i].second, InFlag);
597 InFlag = Chain.getValue(1);
600 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
601 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
602 // node so that legalize doesn't hack it.
603 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
604 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
605 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
606 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
609 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
610 // = Chain, Callee, Reg#1, Reg#2, ...
612 // Returns a chain & a flag for retval copy to use.
613 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
614 SmallVector<SDValue, 8> Ops;
615 Ops.push_back(Chain);
616 Ops.push_back(Callee);
618 // Add argument registers to the end of the list so that they are
619 // known live into the call.
620 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
621 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
622 RegsToPass[i].second.getValueType()));
625 Ops.push_back(InFlag);
627 Chain = DAG.getNode(MipsISD::JmpLink, NodeTys, &Ops[0], Ops.size());
628 InFlag = Chain.getValue(1);
630 // Create the CALLSEQ_END node.
631 Chain = DAG.getCALLSEQ_END(Chain,
632 DAG.getConstant(NumBytes, getPointerTy()),
633 DAG.getConstant(0, getPointerTy()),
635 InFlag = Chain.getValue(1);
637 // Create a stack location to hold GP when PIC is used. This stack
638 // location is used on function prologue to save GP and also after all
639 // emited CALL's to restore GP.
640 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
641 // Function can have an arbitrary number of calls, so
642 // hold the LastArgStackLoc with the biggest offset.
644 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
645 if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
646 LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
647 // Create the frame index only once. SPOffset here can be anything
648 // (this will be fixed on processFunctionBeforeFrameFinalized)
649 if (MipsFI->getGPStackOffset() == -1) {
650 FI = MFI->CreateFixedObject(4, 0);
653 MipsFI->setGPStackOffset(LastArgStackLoc);
657 FI = MipsFI->getGPFI();
658 SDValue FIN = DAG.getFrameIndex(FI,getPointerTy());
659 SDValue GPLoad = DAG.getLoad(MVT::i32, Chain, FIN, NULL, 0);
660 Chain = GPLoad.getValue(1);
661 Chain = DAG.getCopyToReg(Chain, DAG.getRegister(Mips::GP, MVT::i32),
662 GPLoad, SDValue(0,0));
663 InFlag = Chain.getValue(1);
666 // Handle result values, copying them out of physregs into vregs that we
668 return SDValue(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
671 /// LowerCallResult - Lower the result values of an ISD::CALL into the
672 /// appropriate copies out of appropriate physical registers. This assumes that
673 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
674 /// being lowered. Returns a SDNode with the same number of values as the
676 SDNode *MipsTargetLowering::
677 LowerCallResult(SDValue Chain, SDValue InFlag, SDNode *TheCall,
678 unsigned CallingConv, SelectionDAG &DAG) {
680 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
682 // Assign locations to each value returned by this call.
683 SmallVector<CCValAssign, 16> RVLocs;
684 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
686 CCInfo.AnalyzeCallResult(TheCall, RetCC_Mips);
687 SmallVector<SDValue, 8> ResultVals;
689 // Copy all of the result registers out of their specified physreg.
690 for (unsigned i = 0; i != RVLocs.size(); ++i) {
691 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
692 RVLocs[i].getValVT(), InFlag).getValue(1);
693 InFlag = Chain.getValue(2);
694 ResultVals.push_back(Chain.getValue(0));
697 ResultVals.push_back(Chain);
699 // Merge everything together with a MERGE_VALUES node.
700 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
701 ResultVals.size()).Val;
704 //===----------------------------------------------------------------------===//
705 // FORMAL_ARGUMENTS Calling Convention Implementation
706 //===----------------------------------------------------------------------===//
708 /// Mips custom FORMAL_ARGUMENTS implementation
709 SDValue MipsTargetLowering::
710 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
712 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
716 assert(0 && "Unsupported calling convention");
718 return LowerCCCArguments(Op, DAG);
722 /// LowerCCCArguments - transform physical registers into
723 /// virtual registers and generate load operations for
724 /// arguments places on the stack.
726 SDValue MipsTargetLowering::
727 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
729 SDValue Root = Op.getOperand(0);
730 MachineFunction &MF = DAG.getMachineFunction();
731 MachineFrameInfo *MFI = MF.getFrameInfo();
732 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
734 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
735 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
737 unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
739 // GP must be live into PIC and non-PIC call target.
740 AddLiveIn(MF, Mips::GP, Mips::CPURegsRegisterClass);
742 // Assign locations to all of the incoming arguments.
743 SmallVector<CCValAssign, 16> ArgLocs;
744 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
746 CCInfo.AnalyzeFormalArguments(Op.Val, CC_Mips);
747 SmallVector<SDValue, 16> ArgValues;
750 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
752 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
754 CCValAssign &VA = ArgLocs[i];
756 // Arguments stored on registers
758 MVT RegVT = VA.getLocVT();
759 TargetRegisterClass *RC = 0;
761 if (RegVT == MVT::i32)
762 RC = Mips::CPURegsRegisterClass;
763 else if (RegVT == MVT::f32) {
764 if (Subtarget->isSingleFloat())
765 RC = Mips::FGR32RegisterClass;
767 RC = Mips::AFGR32RegisterClass;
768 } else if (RegVT == MVT::f64) {
769 if (!Subtarget->isSingleFloat())
770 RC = Mips::AFGR64RegisterClass;
772 assert(0 && "RegVT not supported by FORMAL_ARGUMENTS Lowering");
774 // Transform the arguments stored on
775 // physical registers into virtual ones
776 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
777 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
779 // If this is an 8 or 16-bit value, it is really passed promoted
780 // to 32 bits. Insert an assert[sz]ext to capture this, then
781 // truncate to the right size.
782 if (VA.getLocInfo() == CCValAssign::SExt)
783 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
784 DAG.getValueType(VA.getValVT()));
785 else if (VA.getLocInfo() == CCValAssign::ZExt)
786 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
787 DAG.getValueType(VA.getValVT()));
789 if (VA.getLocInfo() != CCValAssign::Full)
790 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
792 ArgValues.push_back(ArgValue);
794 // To meet ABI, when VARARGS are passed on registers, the registers
795 // must have their values written to the caller stack frame.
796 if ((isVarArg) && (Subtarget->isABI_O32())) {
797 if (StackPtr.Val == 0)
798 StackPtr = DAG.getRegister(StackReg, getPointerTy());
800 // The stack pointer offset is relative to the caller stack frame.
801 // Since the real stack size is unknown here, a negative SPOffset
802 // is used so there's a way to adjust these offsets when the stack
803 // size get known (on EliminateFrameIndex). A dummy SPOffset is
804 // used instead of a direct negative address (which is recorded to
805 // be used on emitPrologue) to avoid mis-calc of the first stack
806 // offset on PEI::calculateFrameObjectOffsets.
807 // Arguments are always 32-bit.
808 int FI = MFI->CreateFixedObject(4, 0);
809 MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
810 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
812 // emit ISD::STORE whichs stores the
813 // parameter value to a stack Location
814 ArgValues.push_back(DAG.getStore(Root, ArgValue, PtrOff, NULL, 0));
817 } else { // VA.isRegLoc()
820 assert(VA.isMemLoc());
822 // The stack pointer offset is relative to the caller stack frame.
823 // Since the real stack size is unknown here, a negative SPOffset
824 // is used so there's a way to adjust these offsets when the stack
825 // size get known (on EliminateFrameIndex). A dummy SPOffset is
826 // used instead of a direct negative address (which is recorded to
827 // be used on emitPrologue) to avoid mis-calc of the first stack
828 // offset on PEI::calculateFrameObjectOffsets.
829 // Arguments are always 32-bit.
830 unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
831 int FI = MFI->CreateFixedObject(ArgSize, 0);
832 MipsFI->recordLoadArgsFI(FI, -(ArgSize+
833 (FirstStackArgLoc + VA.getLocMemOffset())));
835 // Create load nodes to retrieve arguments from the stack
836 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
837 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
841 // The mips ABIs for returning structs by value requires that we copy
842 // the sret argument into $v0 for the return. Save the argument into
843 // a virtual register so that we can access it from the return points.
844 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
845 unsigned Reg = MipsFI->getSRetReturnReg();
847 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
848 MipsFI->setSRetReturnReg(Reg);
850 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
851 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
854 ArgValues.push_back(Root);
856 // Return the new list of results.
857 return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
858 ArgValues.size()).getValue(Op.ResNo);
861 //===----------------------------------------------------------------------===//
862 // Return Value Calling Convention Implementation
863 //===----------------------------------------------------------------------===//
865 SDValue MipsTargetLowering::
866 LowerRET(SDValue Op, SelectionDAG &DAG)
868 // CCValAssign - represent the assignment of
869 // the return value to a location
870 SmallVector<CCValAssign, 16> RVLocs;
871 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
872 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
874 // CCState - Info about the registers and stack slot.
875 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
877 // Analize return values of ISD::RET
878 CCInfo.AnalyzeReturn(Op.Val, RetCC_Mips);
880 // If this is the first return lowered for this function, add
881 // the regs to the liveout set for the function.
882 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
883 for (unsigned i = 0; i != RVLocs.size(); ++i)
884 if (RVLocs[i].isRegLoc())
885 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
888 // The chain is always operand #0
889 SDValue Chain = Op.getOperand(0);
892 // Copy the result values into the output registers.
893 for (unsigned i = 0; i != RVLocs.size(); ++i) {
894 CCValAssign &VA = RVLocs[i];
895 assert(VA.isRegLoc() && "Can only return in registers!");
897 // ISD::RET => ret chain, (regnum1,val1), ...
898 // So i*2+1 index only the regnums
899 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
901 // guarantee that all emitted copies are
902 // stuck together, avoiding something bad
903 Flag = Chain.getValue(1);
906 // The mips ABIs for returning structs by value requires that we copy
907 // the sret argument into $v0 for the return. We saved the argument into
908 // a virtual register in the entry block, so now we copy the value out
910 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
911 MachineFunction &MF = DAG.getMachineFunction();
912 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
913 unsigned Reg = MipsFI->getSRetReturnReg();
916 assert(0 && "sret virtual register not created in the entry block");
917 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
919 Chain = DAG.getCopyToReg(Chain, Mips::V0, Val, Flag);
920 Flag = Chain.getValue(1);
923 // Return on Mips is always a "jr $ra"
925 return DAG.getNode(MipsISD::Ret, MVT::Other,
926 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
928 return DAG.getNode(MipsISD::Ret, MVT::Other,
929 Chain, DAG.getRegister(Mips::RA, MVT::i32));
932 //===----------------------------------------------------------------------===//
933 // Mips Inline Assembly Support
934 //===----------------------------------------------------------------------===//
936 /// getConstraintType - Given a constraint letter, return the type of
937 /// constraint it is for this target.
938 MipsTargetLowering::ConstraintType MipsTargetLowering::
939 getConstraintType(const std::string &Constraint) const
941 // Mips specific constrainy
942 // GCC config/mips/constraints.md
944 // 'd' : An address register. Equivalent to r
945 // unless generating MIPS16 code.
946 // 'y' : Equivalent to r; retained for
947 // backwards compatibility.
948 // 'f' : Floating Point registers.
949 if (Constraint.size() == 1) {
950 switch (Constraint[0]) {
955 return C_RegisterClass;
959 return TargetLowering::getConstraintType(Constraint);
962 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
963 /// return a list of registers that can be used to satisfy the constraint.
964 /// This should only be used for C_RegisterClass constraints.
965 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
966 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
968 if (Constraint.size() == 1) {
969 switch (Constraint[0]) {
971 return std::make_pair(0U, Mips::CPURegsRegisterClass);
973 if (VT == MVT::f32) {
974 if (Subtarget->isSingleFloat())
975 return std::make_pair(0U, Mips::FGR32RegisterClass);
977 return std::make_pair(0U, Mips::AFGR32RegisterClass);
980 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
981 return std::make_pair(0U, Mips::AFGR64RegisterClass);
984 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
987 /// Given a register class constraint, like 'r', if this corresponds directly
988 /// to an LLVM register class, return a register of 0 and the register class
990 std::vector<unsigned> MipsTargetLowering::
991 getRegClassForInlineAsmConstraint(const std::string &Constraint,
994 if (Constraint.size() != 1)
995 return std::vector<unsigned>();
997 switch (Constraint[0]) {
1000 // GCC Mips Constraint Letters
1003 return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1004 Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1005 Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1009 if (VT == MVT::f32) {
1010 if (Subtarget->isSingleFloat())
1011 return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1012 Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1013 Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1014 Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1015 Mips::F30, Mips::F31, 0);
1017 return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1018 Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1019 Mips::F28, Mips::F30, 0);
1023 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1024 return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1025 Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1026 Mips::D14, Mips::D15, 0);
1028 return std::vector<unsigned>();