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::f32, Custom);
90 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
91 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
93 // Operations not directly supported by Mips.
94 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
95 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
96 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
97 setOperationAction(ISD::SELECT, MVT::i32, Expand);
98 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
99 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
100 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
101 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
102 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
103 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
104 setOperationAction(ISD::ROTL, MVT::i32, Expand);
105 setOperationAction(ISD::ROTR, MVT::i32, Expand);
106 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
107 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
108 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
109 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
111 // We don't have line number support yet.
112 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
113 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
114 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
115 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
117 // Use the default for now
118 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
119 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
120 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
122 if (Subtarget->isSingleFloat())
123 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
125 if (!Subtarget->hasSEInReg()) {
126 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
130 setStackPointerRegisterToSaveRestore(Mips::SP);
131 computeRegisterProperties();
135 MVT MipsTargetLowering::getSetCCResultType(const SDOperand &) const {
140 SDOperand MipsTargetLowering::
141 LowerOperation(SDOperand Op, SelectionDAG &DAG)
143 switch (Op.getOpcode())
145 case ISD::CALL: return LowerCALL(Op, DAG);
146 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
147 case ISD::RET: return LowerRET(Op, DAG);
148 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
149 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
150 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
151 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
152 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
158 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
159 MachineBasicBlock *BB)
161 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
162 switch (MI->getOpcode()) {
163 default: assert(false && "Unexpected instr type to insert");
164 case Mips::Select_CC: {
165 // To "insert" a SELECT_CC instruction, we actually have to insert the
166 // diamond control-flow pattern. The incoming instruction knows the
167 // destination vreg to set, the condition code register to branch on, the
168 // true/false values to select between, and a branch opcode to use.
169 const BasicBlock *LLVM_BB = BB->getBasicBlock();
170 MachineFunction::iterator It = BB;
177 // bNE r1, r0, copy1MBB
178 // fallthrough --> copy0MBB
179 MachineBasicBlock *thisMBB = BB;
180 MachineFunction *F = BB->getParent();
181 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
182 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
183 BuildMI(BB, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
184 .addReg(Mips::ZERO).addMBB(sinkMBB);
185 F->insert(It, copy0MBB);
186 F->insert(It, sinkMBB);
187 // Update machine-CFG edges by first adding all successors of the current
188 // block to the new block which will contain the Phi node for the select.
189 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
190 e = BB->succ_end(); i != e; ++i)
191 sinkMBB->addSuccessor(*i);
192 // Next, remove all successors of the current block, and add the true
193 // and fallthrough blocks as its successors.
194 while(!BB->succ_empty())
195 BB->removeSuccessor(BB->succ_begin());
196 BB->addSuccessor(copy0MBB);
197 BB->addSuccessor(sinkMBB);
201 // # fallthrough to sinkMBB
204 // Update machine-CFG edges
205 BB->addSuccessor(sinkMBB);
208 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
211 BuildMI(BB, TII->get(Mips::PHI), MI->getOperand(0).getReg())
212 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
213 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB);
215 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
221 //===----------------------------------------------------------------------===//
222 // Lower helper functions
223 //===----------------------------------------------------------------------===//
225 // AddLiveIn - This helper function adds the specified physical register to the
226 // MachineFunction as a live in value. It also creates a corresponding
227 // virtual register for it.
229 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
231 assert(RC->contains(PReg) && "Not the correct regclass!");
232 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
233 MF.getRegInfo().addLiveIn(PReg, VReg);
237 // Discover if this global address can be placed into small data/bss section.
238 // This should happen for globals with size less than small section size
239 // threshold in no abicall environments. Data in this section must be addressed
240 // using gp_rel operator.
241 bool MipsTargetLowering::IsGlobalInSmallSection(GlobalValue *GV)
243 const TargetData *TD = getTargetData();
244 const GlobalVariable *GVA = dyn_cast<GlobalVariable>(GV);
249 const Type *Ty = GV->getType()->getElementType();
250 unsigned Size = TD->getABITypeSize(Ty);
252 // if this is a internal constant string, there is a special
253 // section for it, but not in small data/bss.
254 if (GVA->hasInitializer() && GV->hasInternalLinkage()) {
255 Constant *C = GVA->getInitializer();
256 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
257 if (CVA && CVA->isCString())
261 if (Size > 0 && (Size <= Subtarget->getSSectionThreshold()))
267 //===----------------------------------------------------------------------===//
268 // Misc Lower Operation implementation
269 //===----------------------------------------------------------------------===//
270 SDOperand MipsTargetLowering::
271 LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG)
273 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
274 SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
276 if (!Subtarget->hasABICall()) {
277 if (isa<Function>(GV)) return GA;
278 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
279 SDOperand Ops[] = { GA };
281 if (IsGlobalInSmallSection(GV)) { // %gp_rel relocation
282 SDOperand GPRelNode = DAG.getNode(MipsISD::GPRel, VTs, 1, Ops, 1);
283 SDOperand GOT = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, MVT::i32);
284 return DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
286 // %hi/%lo relocation
287 SDOperand HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
288 SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
289 return DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
291 } else { // Abicall relocations, TODO: make this cleaner.
292 SDOperand ResNode = DAG.getLoad(MVT::i32, DAG.getEntryNode(), GA, NULL, 0);
293 // On functions and global targets not internal linked only
294 // a load from got/GP is necessary for PIC to work.
295 if (!GV->hasInternalLinkage() || isa<Function>(GV))
297 SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
298 return DAG.getNode(ISD::ADD, MVT::i32, ResNode, Lo);
301 assert(0 && "Dont know how to handle GlobalAddress");
302 return SDOperand(0,0);
305 SDOperand MipsTargetLowering::
306 LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG)
308 assert(0 && "TLS not implemented for MIPS.");
309 return SDOperand(); // Not reached
312 SDOperand MipsTargetLowering::
313 LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG)
315 SDOperand LHS = Op.getOperand(0);
316 SDOperand RHS = Op.getOperand(1);
317 SDOperand True = Op.getOperand(2);
318 SDOperand False = Op.getOperand(3);
319 SDOperand CC = Op.getOperand(4);
321 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
322 SDOperand Ops[] = { LHS, RHS, CC };
323 SDOperand SetCCRes = DAG.getNode(ISD::SETCC, VTs, 1, Ops, 3);
325 return DAG.getNode(MipsISD::SelectCC, True.getValueType(),
326 SetCCRes, True, False);
329 SDOperand MipsTargetLowering::
330 LowerJumpTable(SDOperand Op, SelectionDAG &DAG)
335 MVT PtrVT = Op.getValueType();
336 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
337 SDOperand JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
339 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
340 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
341 SDOperand Ops[] = { JTI };
342 HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
343 } else // Emit Load from Global Pointer
344 HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), JTI, NULL, 0);
346 SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, JTI);
347 ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
352 SDOperand MipsTargetLowering::
353 LowerConstantPool(SDOperand Op, SelectionDAG &DAG)
355 assert(0 && "ConstantPool not implemented for MIPS.");
356 return SDOperand(); // Not reached
359 //===----------------------------------------------------------------------===//
360 // Calling Convention Implementation
362 // The lower operations present on calling convention works on this order:
363 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
364 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
365 // LowerRET (virt regs --> phys regs)
366 // LowerCALL (phys regs --> virt regs)
368 //===----------------------------------------------------------------------===//
370 #include "MipsGenCallingConv.inc"
372 //===----------------------------------------------------------------------===//
373 // CALL Calling Convention Implementation
374 //===----------------------------------------------------------------------===//
376 /// Mips custom CALL implementation
377 SDOperand MipsTargetLowering::
378 LowerCALL(SDOperand Op, SelectionDAG &DAG)
380 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
382 // By now, only CallingConv::C implemented
383 switch (CallingConv) {
385 assert(0 && "Unsupported calling convention");
386 case CallingConv::Fast:
388 return LowerCCCCallTo(Op, DAG, CallingConv);
392 /// LowerCCCCallTo - functions arguments are copied from virtual
393 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
394 /// CALLSEQ_END are emitted.
395 /// TODO: isVarArg, isTailCall.
396 SDOperand MipsTargetLowering::
397 LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG, unsigned CC)
399 MachineFunction &MF = DAG.getMachineFunction();
401 SDOperand Chain = Op.getOperand(0);
402 SDOperand Callee = Op.getOperand(4);
403 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
405 MachineFrameInfo *MFI = MF.getFrameInfo();
407 // Analyze operands of the call, assigning locations to each operand.
408 SmallVector<CCValAssign, 16> ArgLocs;
409 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
411 // To meet O32 ABI, Mips must always allocate 16 bytes on
412 // the stack (even if less than 4 are used as arguments)
413 if (Subtarget->isABI_O32()) {
414 int VTsize = MVT(MVT::i32).getSizeInBits()/8;
415 MFI->CreateFixedObject(VTsize, (VTsize*3));
418 CCInfo.AnalyzeCallOperands(Op.Val, CC_Mips);
420 // Get a count of how many bytes are to be pushed on the stack.
421 unsigned NumBytes = CCInfo.getNextStackOffset();
422 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
425 // With EABI is it possible to have 16 args on registers.
426 SmallVector<std::pair<unsigned, SDOperand>, 16> RegsToPass;
427 SmallVector<SDOperand, 8> MemOpChains;
429 // First/LastArgStackLoc contains the first/last
430 // "at stack" argument location.
431 int LastArgStackLoc = 0;
432 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
434 // Walk the register/memloc assignments, inserting copies/loads.
435 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
436 CCValAssign &VA = ArgLocs[i];
438 // Arguments start after the 5 first operands of ISD::CALL
439 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
441 // Promote the value if needed.
442 switch (VA.getLocInfo()) {
443 default: assert(0 && "Unknown loc info!");
444 case CCValAssign::Full: break;
445 case CCValAssign::SExt:
446 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
448 case CCValAssign::ZExt:
449 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
451 case CCValAssign::AExt:
452 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
456 // Arguments that can be passed on register must be kept at
459 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
463 // Register cant get to this point...
464 assert(VA.isMemLoc());
466 // Create the frame index object for this incoming parameter
467 // This guarantees that when allocating Local Area the firsts
468 // 16 bytes which are alwayes reserved won't be overwritten
469 // if O32 ABI is used. For EABI the first address is zero.
470 LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
471 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
474 SDOperand PtrOff = DAG.getFrameIndex(FI,getPointerTy());
476 // emit ISD::STORE whichs stores the
477 // parameter value to a stack Location
478 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
481 // Transform all store nodes into one single node because all store
482 // nodes are independent of each other.
483 if (!MemOpChains.empty())
484 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
485 &MemOpChains[0], MemOpChains.size());
487 // Build a sequence of copy-to-reg nodes chained together with token
488 // chain and flag operands which copy the outgoing args into registers.
489 // The InFlag in necessary since all emited instructions must be
492 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
493 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first,
494 RegsToPass[i].second, InFlag);
495 InFlag = Chain.getValue(1);
498 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
499 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
500 // node so that legalize doesn't hack it.
501 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
502 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
503 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
504 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
507 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
508 // = Chain, Callee, Reg#1, Reg#2, ...
510 // Returns a chain & a flag for retval copy to use.
511 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
512 SmallVector<SDOperand, 8> Ops;
513 Ops.push_back(Chain);
514 Ops.push_back(Callee);
516 // Add argument registers to the end of the list so that they are
517 // known live into the call.
518 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
519 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
520 RegsToPass[i].second.getValueType()));
523 Ops.push_back(InFlag);
525 Chain = DAG.getNode(MipsISD::JmpLink, NodeTys, &Ops[0], Ops.size());
526 InFlag = Chain.getValue(1);
528 // Create the CALLSEQ_END node.
529 Chain = DAG.getCALLSEQ_END(Chain,
530 DAG.getConstant(NumBytes, getPointerTy()),
531 DAG.getConstant(0, getPointerTy()),
533 InFlag = Chain.getValue(1);
535 // Create a stack location to hold GP when PIC is used. This stack
536 // location is used on function prologue to save GP and also after all
537 // emited CALL's to restore GP.
538 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
539 // Function can have an arbitrary number of calls, so
540 // hold the LastArgStackLoc with the biggest offset.
542 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
543 if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
544 LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
545 // Create the frame index only once. SPOffset here can be anything
546 // (this will be fixed on processFunctionBeforeFrameFinalized)
547 if (MipsFI->getGPStackOffset() == -1) {
548 FI = MFI->CreateFixedObject(4, 0);
551 MipsFI->setGPStackOffset(LastArgStackLoc);
555 FI = MipsFI->getGPFI();
556 SDOperand FIN = DAG.getFrameIndex(FI,getPointerTy());
557 SDOperand GPLoad = DAG.getLoad(MVT::i32, Chain, FIN, NULL, 0);
558 Chain = GPLoad.getValue(1);
559 Chain = DAG.getCopyToReg(Chain, DAG.getRegister(Mips::GP, MVT::i32),
560 GPLoad, SDOperand(0,0));
561 InFlag = Chain.getValue(1);
564 // Handle result values, copying them out of physregs into vregs that we
566 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
569 /// LowerCallResult - Lower the result values of an ISD::CALL into the
570 /// appropriate copies out of appropriate physical registers. This assumes that
571 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
572 /// being lowered. Returns a SDNode with the same number of values as the
574 SDNode *MipsTargetLowering::
575 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
576 unsigned CallingConv, SelectionDAG &DAG) {
578 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
580 // Assign locations to each value returned by this call.
581 SmallVector<CCValAssign, 16> RVLocs;
582 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
584 CCInfo.AnalyzeCallResult(TheCall, RetCC_Mips);
585 SmallVector<SDOperand, 8> ResultVals;
587 // Copy all of the result registers out of their specified physreg.
588 for (unsigned i = 0; i != RVLocs.size(); ++i) {
589 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
590 RVLocs[i].getValVT(), InFlag).getValue(1);
591 InFlag = Chain.getValue(2);
592 ResultVals.push_back(Chain.getValue(0));
595 ResultVals.push_back(Chain);
597 // Merge everything together with a MERGE_VALUES node.
598 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
599 ResultVals.size()).Val;
602 //===----------------------------------------------------------------------===//
603 // FORMAL_ARGUMENTS Calling Convention Implementation
604 //===----------------------------------------------------------------------===//
606 /// Mips custom FORMAL_ARGUMENTS implementation
607 SDOperand MipsTargetLowering::
608 LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG)
610 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
614 assert(0 && "Unsupported calling convention");
616 return LowerCCCArguments(Op, DAG);
620 /// LowerCCCArguments - transform physical registers into
621 /// virtual registers and generate load operations for
622 /// arguments places on the stack.
624 SDOperand MipsTargetLowering::
625 LowerCCCArguments(SDOperand Op, SelectionDAG &DAG)
627 SDOperand Root = Op.getOperand(0);
628 MachineFunction &MF = DAG.getMachineFunction();
629 MachineFrameInfo *MFI = MF.getFrameInfo();
630 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
632 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
633 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
635 unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
637 // GP must be live into PIC and non-PIC call target.
638 AddLiveIn(MF, Mips::GP, Mips::CPURegsRegisterClass);
640 // Assign locations to all of the incoming arguments.
641 SmallVector<CCValAssign, 16> ArgLocs;
642 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
644 CCInfo.AnalyzeFormalArguments(Op.Val, CC_Mips);
645 SmallVector<SDOperand, 16> ArgValues;
648 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
650 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
652 CCValAssign &VA = ArgLocs[i];
654 // Arguments stored on registers
656 MVT RegVT = VA.getLocVT();
657 TargetRegisterClass *RC = 0;
659 if (RegVT == MVT::i32)
660 RC = Mips::CPURegsRegisterClass;
661 else if (RegVT == MVT::f32) {
662 if (Subtarget->isSingleFloat())
663 RC = Mips::FGR32RegisterClass;
665 RC = Mips::AFGR32RegisterClass;
666 } else if (RegVT == MVT::f64) {
667 if (!Subtarget->isSingleFloat())
668 RC = Mips::AFGR64RegisterClass;
670 assert(0 && "RegVT not supported by FORMAL_ARGUMENTS Lowering");
672 // Transform the arguments stored on
673 // physical registers into virtual ones
674 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
675 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
677 // If this is an 8 or 16-bit value, it is really passed promoted
678 // to 32 bits. Insert an assert[sz]ext to capture this, then
679 // truncate to the right size.
680 if (VA.getLocInfo() == CCValAssign::SExt)
681 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
682 DAG.getValueType(VA.getValVT()));
683 else if (VA.getLocInfo() == CCValAssign::ZExt)
684 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
685 DAG.getValueType(VA.getValVT()));
687 if (VA.getLocInfo() != CCValAssign::Full)
688 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
690 ArgValues.push_back(ArgValue);
692 // To meet ABI, when VARARGS are passed on registers, the registers
693 // must have their values written to the caller stack frame.
694 if ((isVarArg) && (Subtarget->isABI_O32())) {
695 if (StackPtr.Val == 0)
696 StackPtr = DAG.getRegister(StackReg, getPointerTy());
698 // The stack pointer offset is relative to the caller stack frame.
699 // Since the real stack size is unknown here, a negative SPOffset
700 // is used so there's a way to adjust these offsets when the stack
701 // size get known (on EliminateFrameIndex). A dummy SPOffset is
702 // used instead of a direct negative address (which is recorded to
703 // be used on emitPrologue) to avoid mis-calc of the first stack
704 // offset on PEI::calculateFrameObjectOffsets.
705 // Arguments are always 32-bit.
706 int FI = MFI->CreateFixedObject(4, 0);
707 MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
708 SDOperand PtrOff = DAG.getFrameIndex(FI, getPointerTy());
710 // emit ISD::STORE whichs stores the
711 // parameter value to a stack Location
712 ArgValues.push_back(DAG.getStore(Root, ArgValue, PtrOff, NULL, 0));
715 } else { // VA.isRegLoc()
718 assert(VA.isMemLoc());
720 // The stack pointer offset is relative to the caller stack frame.
721 // Since the real stack size is unknown here, a negative SPOffset
722 // is used so there's a way to adjust these offsets when the stack
723 // size get known (on EliminateFrameIndex). A dummy SPOffset is
724 // used instead of a direct negative address (which is recorded to
725 // be used on emitPrologue) to avoid mis-calc of the first stack
726 // offset on PEI::calculateFrameObjectOffsets.
727 // Arguments are always 32-bit.
728 unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
729 int FI = MFI->CreateFixedObject(ArgSize, 0);
730 MipsFI->recordLoadArgsFI(FI, -(ArgSize+
731 (FirstStackArgLoc + VA.getLocMemOffset())));
733 // Create load nodes to retrieve arguments from the stack
734 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
735 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
739 // The mips ABIs for returning structs by value requires that we copy
740 // the sret argument into $v0 for the return. Save the argument into
741 // a virtual register so that we can access it from the return points.
742 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
743 unsigned Reg = MipsFI->getSRetReturnReg();
745 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
746 MipsFI->setSRetReturnReg(Reg);
748 SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
749 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
752 ArgValues.push_back(Root);
754 // Return the new list of results.
755 return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
756 ArgValues.size()).getValue(Op.ResNo);
759 //===----------------------------------------------------------------------===//
760 // Return Value Calling Convention Implementation
761 //===----------------------------------------------------------------------===//
763 SDOperand MipsTargetLowering::
764 LowerRET(SDOperand Op, SelectionDAG &DAG)
766 // CCValAssign - represent the assignment of
767 // the return value to a location
768 SmallVector<CCValAssign, 16> RVLocs;
769 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
770 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
772 // CCState - Info about the registers and stack slot.
773 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
775 // Analize return values of ISD::RET
776 CCInfo.AnalyzeReturn(Op.Val, RetCC_Mips);
778 // If this is the first return lowered for this function, add
779 // the regs to the liveout set for the function.
780 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
781 for (unsigned i = 0; i != RVLocs.size(); ++i)
782 if (RVLocs[i].isRegLoc())
783 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
786 // The chain is always operand #0
787 SDOperand Chain = Op.getOperand(0);
790 // Copy the result values into the output registers.
791 for (unsigned i = 0; i != RVLocs.size(); ++i) {
792 CCValAssign &VA = RVLocs[i];
793 assert(VA.isRegLoc() && "Can only return in registers!");
795 // ISD::RET => ret chain, (regnum1,val1), ...
796 // So i*2+1 index only the regnums
797 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
799 // guarantee that all emitted copies are
800 // stuck together, avoiding something bad
801 Flag = Chain.getValue(1);
804 // The mips ABIs for returning structs by value requires that we copy
805 // the sret argument into $v0 for the return. We saved the argument into
806 // a virtual register in the entry block, so now we copy the value out
808 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
809 MachineFunction &MF = DAG.getMachineFunction();
810 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
811 unsigned Reg = MipsFI->getSRetReturnReg();
814 assert(0 && "sret virtual register not created in the entry block");
815 SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
817 Chain = DAG.getCopyToReg(Chain, Mips::V0, Val, Flag);
818 Flag = Chain.getValue(1);
821 // Return on Mips is always a "jr $ra"
823 return DAG.getNode(MipsISD::Ret, MVT::Other,
824 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
826 return DAG.getNode(MipsISD::Ret, MVT::Other,
827 Chain, DAG.getRegister(Mips::RA, MVT::i32));
830 //===----------------------------------------------------------------------===//
831 // Mips Inline Assembly Support
832 //===----------------------------------------------------------------------===//
834 /// getConstraintType - Given a constraint letter, return the type of
835 /// constraint it is for this target.
836 MipsTargetLowering::ConstraintType MipsTargetLowering::
837 getConstraintType(const std::string &Constraint) const
839 // Mips specific constrainy
840 // GCC config/mips/constraints.md
842 // 'd' : An address register. Equivalent to r
843 // unless generating MIPS16 code.
844 // 'y' : Equivalent to r; retained for
845 // backwards compatibility.
846 // 'f' : Floating Point registers.
847 if (Constraint.size() == 1) {
848 switch (Constraint[0]) {
853 return C_RegisterClass;
857 return TargetLowering::getConstraintType(Constraint);
860 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
861 /// return a list of registers that can be used to satisfy the constraint.
862 /// This should only be used for C_RegisterClass constraints.
863 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
864 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
866 if (Constraint.size() == 1) {
867 switch (Constraint[0]) {
869 return std::make_pair(0U, Mips::CPURegsRegisterClass);
871 if (VT == MVT::f32) {
872 if (Subtarget->isSingleFloat())
873 return std::make_pair(0U, Mips::FGR32RegisterClass);
875 return std::make_pair(0U, Mips::AFGR32RegisterClass);
878 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
879 return std::make_pair(0U, Mips::AFGR64RegisterClass);
882 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
885 /// Given a register class constraint, like 'r', if this corresponds directly
886 /// to an LLVM register class, return a register of 0 and the register class
888 std::vector<unsigned> MipsTargetLowering::
889 getRegClassForInlineAsmConstraint(const std::string &Constraint,
892 if (Constraint.size() != 1)
893 return std::vector<unsigned>();
895 switch (Constraint[0]) {
898 // GCC Mips Constraint Letters
901 return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
902 Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
903 Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
907 if (VT == MVT::f32) {
908 if (Subtarget->isSingleFloat())
909 return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
910 Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
911 Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
912 Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
913 Mips::F30, Mips::F31, 0);
915 return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
916 Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
917 Mips::F28, Mips::F30, 0);
921 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
922 return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
923 Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
924 Mips::D14, Mips::D15, 0);
926 return std::vector<unsigned>();