Rename ISD::LOCATION to ISD::DBG_STOPPOINT to better reflect its
[oota-llvm.git] / lib / Target / Mips / MipsISelLowering.cpp
1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mips-lower"
16
17 #include "MipsISelLowering.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsTargetMachine.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/Support/Debug.h"
32 #include <queue>
33 #include <set>
34
35 using namespace llvm;
36
37 const char *MipsTargetLowering::
38 getTargetNodeName(unsigned Opcode) const 
39 {
40   switch (Opcode) 
41   {
42     case MipsISD::JmpLink   : return "MipsISD::JmpLink";
43     case MipsISD::Hi        : return "MipsISD::Hi";
44     case MipsISD::Lo        : return "MipsISD::Lo";
45     case MipsISD::Ret       : return "MipsISD::Ret";
46     case MipsISD::SelectCC  : return "MipsISD::SelectCC";
47     default                 : return NULL;
48   }
49 }
50
51 MipsTargetLowering::
52 MipsTargetLowering(MipsTargetMachine &TM): TargetLowering(TM) 
53 {
54   // Mips does not have i1 type, so use i32 for
55   // setcc operations results (slt, sgt, ...). 
56   setSetCCResultContents(ZeroOrOneSetCCResult);
57
58   // JumpTable targets must use GOT when using PIC_
59   setUsesGlobalOffsetTable(true);
60
61   // Set up the register classes
62   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
63
64   // Custom
65   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
66   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
67   setOperationAction(ISD::RET, MVT::Other, Custom);
68   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
69   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
70
71   // Load extented operations for i1 types must be promoted 
72   setLoadXAction(ISD::EXTLOAD,  MVT::i1,  Promote);
73   setLoadXAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
74   setLoadXAction(ISD::SEXTLOAD, MVT::i1,  Promote);
75
76   // Mips does not have these NodeTypes below.
77   setOperationAction(ISD::BR_JT,     MVT::Other, Expand);
78   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
79   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
80   setOperationAction(ISD::SELECT,    MVT::i32,   Expand);
81   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
82
83   // Mips not supported intrinsics.
84   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
85
86   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
87   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
88   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
89   setOperationAction(ISD::ROTL , MVT::i32, Expand);
90   setOperationAction(ISD::ROTR , MVT::i32, Expand);
91   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
92
93   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
94   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
95   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
96
97   // We don't have line number support yet.
98   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
99   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
100   setOperationAction(ISD::LABEL, MVT::Other, Expand);
101
102   // Use the default for now
103   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
104   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
105
106   setStackPointerRegisterToSaveRestore(Mips::SP);
107   computeRegisterProperties();
108 }
109
110
111 MVT MipsTargetLowering::getSetCCResultType(const SDOperand &) const {
112   return MVT::i32;
113 }
114
115
116 SDOperand MipsTargetLowering::
117 LowerOperation(SDOperand Op, SelectionDAG &DAG) 
118 {
119   switch (Op.getOpcode()) 
120   {
121     case ISD::CALL:             return LowerCALL(Op, DAG);
122     case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
123     case ISD::RET:              return LowerRET(Op, DAG);
124     case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
125     case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
126     case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
127     case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
128   }
129   return SDOperand();
130 }
131
132 MachineBasicBlock *
133 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
134                                                 MachineBasicBlock *BB) 
135 {
136   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
137   switch (MI->getOpcode()) {
138   default: assert(false && "Unexpected instr type to insert");
139   case Mips::Select_CC: {
140     // To "insert" a SELECT_CC instruction, we actually have to insert the
141     // diamond control-flow pattern.  The incoming instruction knows the
142     // destination vreg to set, the condition code register to branch on, the
143     // true/false values to select between, and a branch opcode to use.
144     const BasicBlock *LLVM_BB = BB->getBasicBlock();
145     ilist<MachineBasicBlock>::iterator It = BB;
146     ++It;
147
148     //  thisMBB:
149     //  ...
150     //   TrueVal = ...
151     //   setcc r1, r2, r3
152     //   bNE   r1, r0, copy1MBB
153     //   fallthrough --> copy0MBB
154     MachineBasicBlock *thisMBB  = BB;
155     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
156     MachineBasicBlock *sinkMBB  = new MachineBasicBlock(LLVM_BB);
157     BuildMI(BB, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
158       .addReg(Mips::ZERO).addMBB(sinkMBB);
159     MachineFunction *F = BB->getParent();
160     F->getBasicBlockList().insert(It, copy0MBB);
161     F->getBasicBlockList().insert(It, sinkMBB);
162     // Update machine-CFG edges by first adding all successors of the current
163     // block to the new block which will contain the Phi node for the select.
164     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
165         e = BB->succ_end(); i != e; ++i)
166       sinkMBB->addSuccessor(*i);
167     // Next, remove all successors of the current block, and add the true
168     // and fallthrough blocks as its successors.
169     while(!BB->succ_empty())
170       BB->removeSuccessor(BB->succ_begin());
171     BB->addSuccessor(copy0MBB);
172     BB->addSuccessor(sinkMBB);
173
174     //  copy0MBB:
175     //   %FalseValue = ...
176     //   # fallthrough to sinkMBB
177     BB = copy0MBB;
178
179     // Update machine-CFG edges
180     BB->addSuccessor(sinkMBB);
181
182     //  sinkMBB:
183     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
184     //  ...
185     BB = sinkMBB;
186     BuildMI(BB, TII->get(Mips::PHI), MI->getOperand(0).getReg())
187       .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
188       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB);
189
190     delete MI;   // The pseudo instruction is gone now.
191     return BB;
192   }
193   }
194 }
195
196 //===----------------------------------------------------------------------===//
197 //  Lower helper functions
198 //===----------------------------------------------------------------------===//
199
200 // AddLiveIn - This helper function adds the specified physical register to the
201 // MachineFunction as a live in value.  It also creates a corresponding
202 // virtual register for it.
203 static unsigned
204 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC) 
205 {
206   assert(RC->contains(PReg) && "Not the correct regclass!");
207   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
208   MF.getRegInfo().addLiveIn(PReg, VReg);
209   return VReg;
210 }
211
212 //===----------------------------------------------------------------------===//
213 //  Misc Lower Operation implementation
214 //===----------------------------------------------------------------------===//
215 SDOperand MipsTargetLowering::
216 LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) 
217 {
218   SDOperand ResNode;
219   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
220   SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
221   bool isPIC = (getTargetMachine().getRelocationModel() == Reloc::PIC_);
222
223   SDOperand HiPart; 
224   if (!isPIC) {
225     const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
226     SDOperand Ops[] = { GA };
227     HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
228   } else // Emit Load from Global Pointer
229     HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), GA, NULL, 0);
230
231   // On functions and global targets not internal linked only
232   // a load from got/GP is necessary for PIC to work.
233   if ((isPIC) && ((!GV->hasInternalLinkage()) || (isa<Function>(GV))))
234     return HiPart;
235
236   SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
237   ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
238
239   return ResNode;
240 }
241
242 SDOperand MipsTargetLowering::
243 LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG)
244 {
245   assert(0 && "TLS not implemented for MIPS.");
246   return SDOperand(); // Not reached
247 }
248
249 SDOperand MipsTargetLowering::
250 LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG) 
251 {
252   SDOperand LHS   = Op.getOperand(0); 
253   SDOperand RHS   = Op.getOperand(1); 
254   SDOperand True  = Op.getOperand(2);
255   SDOperand False = Op.getOperand(3);
256   SDOperand CC    = Op.getOperand(4);
257
258   const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
259   SDOperand Ops[] = { LHS, RHS, CC };
260   SDOperand SetCCRes = DAG.getNode(ISD::SETCC, VTs, 1, Ops, 3); 
261
262   return DAG.getNode(MipsISD::SelectCC, True.getValueType(), 
263                      SetCCRes, True, False);
264 }
265
266 SDOperand MipsTargetLowering::
267 LowerJumpTable(SDOperand Op, SelectionDAG &DAG) 
268 {
269   SDOperand ResNode;
270   SDOperand HiPart; 
271
272   MVT PtrVT = Op.getValueType();
273   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
274   SDOperand JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
275
276   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
277     const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
278     SDOperand Ops[] = { JTI };
279     HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
280   } else // Emit Load from Global Pointer
281     HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), JTI, NULL, 0);
282
283   SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, JTI);
284   ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
285
286   return ResNode;
287 }
288
289 //===----------------------------------------------------------------------===//
290 //                      Calling Convention Implementation
291 //
292 //  The lower operations present on calling convention works on this order:
293 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
294 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
295 //      LowerRET (virt regs --> phys regs)
296 //      LowerCALL (phys regs --> virt regs)
297 //
298 //===----------------------------------------------------------------------===//
299
300 #include "MipsGenCallingConv.inc"
301
302 //===----------------------------------------------------------------------===//
303 //                  CALL Calling Convention Implementation
304 //===----------------------------------------------------------------------===//
305
306 /// Mips custom CALL implementation
307 SDOperand MipsTargetLowering::
308 LowerCALL(SDOperand Op, SelectionDAG &DAG)
309 {
310   unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
311
312   // By now, only CallingConv::C implemented
313   switch (CallingConv) {
314     default:
315       assert(0 && "Unsupported calling convention");
316     case CallingConv::Fast:
317     case CallingConv::C:
318       return LowerCCCCallTo(Op, DAG, CallingConv);
319   }
320 }
321
322 /// LowerCCCCallTo - functions arguments are copied from virtual
323 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
324 /// CALLSEQ_END are emitted.
325 /// TODO: isVarArg, isTailCall, sret.
326 SDOperand MipsTargetLowering::
327 LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG, unsigned CC) 
328 {
329   MachineFunction &MF = DAG.getMachineFunction();
330
331   SDOperand Chain  = Op.getOperand(0);
332   SDOperand Callee = Op.getOperand(4);
333   bool isVarArg    = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
334
335   MachineFrameInfo *MFI = MF.getFrameInfo();
336
337   // Analyze operands of the call, assigning locations to each operand.
338   SmallVector<CCValAssign, 16> ArgLocs;
339   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
340
341   // To meet ABI, Mips must always allocate 16 bytes on
342   // the stack (even if less than 4 are used as arguments)
343   int VTsize = MVT(MVT::i32).getSizeInBits()/8;
344   MFI->CreateFixedObject(VTsize, (VTsize*3));
345
346   CCInfo.AnalyzeCallOperands(Op.Val, CC_Mips);
347   
348   // Get a count of how many bytes are to be pushed on the stack.
349   unsigned NumBytes = CCInfo.getNextStackOffset();
350   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
351                                  getPointerTy()));
352
353   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
354   SmallVector<SDOperand, 8> MemOpChains;
355
356   int LastStackLoc = 0;
357
358   // Walk the register/memloc assignments, inserting copies/loads.
359   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
360     CCValAssign &VA = ArgLocs[i];
361
362     // Arguments start after the 5 first operands of ISD::CALL
363     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
364     
365     // Promote the value if needed.
366     switch (VA.getLocInfo()) {
367     default: assert(0 && "Unknown loc info!");
368     case CCValAssign::Full: break;
369     case CCValAssign::SExt:
370       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
371       break;
372     case CCValAssign::ZExt:
373       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
374       break;
375     case CCValAssign::AExt:
376       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
377       break;
378     }
379     
380     // Arguments that can be passed on register must be kept at 
381     // RegsToPass vector
382     if (VA.isRegLoc()) {
383       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
384       continue;
385     }
386     
387     assert(VA.isMemLoc());
388     
389     // Create the frame index object for this incoming parameter
390     // This guarantees that when allocating Local Area the firsts
391     // 16 bytes which are alwayes reserved won't be overwritten.
392     LastStackLoc = (16 + VA.getLocMemOffset());
393     int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
394                                     LastStackLoc);
395
396     SDOperand PtrOff = DAG.getFrameIndex(FI,getPointerTy());
397
398     // emit ISD::STORE whichs stores the 
399     // parameter value to a stack Location
400     MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
401   }
402
403   // Transform all store nodes into one single node because
404   // all store nodes are independent of each other.
405   if (!MemOpChains.empty())     
406     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, 
407                         &MemOpChains[0], MemOpChains.size());
408
409   // Build a sequence of copy-to-reg nodes chained together with token 
410   // chain and flag operands which copy the outgoing args into registers.
411   // The InFlag in necessary since all emited instructions must be
412   // stuck together.
413   SDOperand InFlag;
414   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
415     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, 
416                              RegsToPass[i].second, InFlag);
417     InFlag = Chain.getValue(1);
418   }
419
420   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
421   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 
422   // node so that legalize doesn't hack it. 
423   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 
424     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
425   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
426     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
427
428
429   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
430   //             = Chain, Callee, Reg#1, Reg#2, ...  
431   //
432   // Returns a chain & a flag for retval copy to use.
433   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
434   SmallVector<SDOperand, 8> Ops;
435   Ops.push_back(Chain);
436   Ops.push_back(Callee);
437
438   // Add argument registers to the end of the list so that they are 
439   // known live into the call.
440   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
441     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
442                                   RegsToPass[i].second.getValueType()));
443
444   if (InFlag.Val)
445     Ops.push_back(InFlag);
446
447   Chain  = DAG.getNode(MipsISD::JmpLink, NodeTys, &Ops[0], Ops.size());
448   InFlag = Chain.getValue(1);
449
450   // Create the CALLSEQ_END node.
451   Chain = DAG.getCALLSEQ_END(Chain,
452                              DAG.getConstant(NumBytes, getPointerTy()),
453                              DAG.getConstant(0, getPointerTy()),
454                              InFlag);
455   InFlag = Chain.getValue(1);
456
457   // Create a stack location to hold GP when PIC is used. This stack 
458   // location is used on function prologue to save GP and also after all 
459   // emited CALL's to restore GP. 
460   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
461       // Function can have an arbitrary number of calls, so 
462       // hold the LastStackLoc with the biggest offset.
463       int FI;
464       MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
465       if (LastStackLoc >= MipsFI->getGPStackOffset()) {
466         LastStackLoc = (!LastStackLoc) ? (16) : (LastStackLoc+4);
467         // Create the frame index only once. SPOffset here can be anything 
468         // (this will be fixed on processFunctionBeforeFrameFinalized)
469         if (MipsFI->getGPStackOffset() == -1) {
470           FI = MFI->CreateFixedObject(4, 0);
471           MipsFI->setGPFI(FI);
472         }
473         MipsFI->setGPStackOffset(LastStackLoc);
474       }
475
476       // Reload GP value.
477       FI = MipsFI->getGPFI();
478       SDOperand FIN = DAG.getFrameIndex(FI,getPointerTy());
479       SDOperand GPLoad = DAG.getLoad(MVT::i32, Chain, FIN, NULL, 0);
480       Chain = GPLoad.getValue(1);
481       Chain = DAG.getCopyToReg(Chain, DAG.getRegister(Mips::GP, MVT::i32), 
482                                GPLoad, SDOperand(0,0));
483       InFlag = Chain.getValue(1);
484   }      
485
486   // Handle result values, copying them out of physregs into vregs that we
487   // return.
488   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
489 }
490
491 /// LowerCallResult - Lower the result values of an ISD::CALL into the
492 /// appropriate copies out of appropriate physical registers.  This assumes that
493 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
494 /// being lowered. Returns a SDNode with the same number of values as the 
495 /// ISD::CALL.
496 SDNode *MipsTargetLowering::
497 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
498         unsigned CallingConv, SelectionDAG &DAG) {
499   
500   bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
501
502   // Assign locations to each value returned by this call.
503   SmallVector<CCValAssign, 16> RVLocs;
504   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
505
506   CCInfo.AnalyzeCallResult(TheCall, RetCC_Mips);
507   SmallVector<SDOperand, 8> ResultVals;
508
509   // Copy all of the result registers out of their specified physreg.
510   for (unsigned i = 0; i != RVLocs.size(); ++i) {
511     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
512                                  RVLocs[i].getValVT(), InFlag).getValue(1);
513     InFlag = Chain.getValue(2);
514     ResultVals.push_back(Chain.getValue(0));
515   }
516   
517   ResultVals.push_back(Chain);
518
519   // Merge everything together with a MERGE_VALUES node.
520   return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
521                             ResultVals.size()).Val;
522 }
523
524 //===----------------------------------------------------------------------===//
525 //             FORMAL_ARGUMENTS Calling Convention Implementation
526 //===----------------------------------------------------------------------===//
527
528 /// Mips custom FORMAL_ARGUMENTS implementation
529 SDOperand MipsTargetLowering::
530 LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) 
531 {
532   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
533   switch(CC) 
534   {
535     default:
536       assert(0 && "Unsupported calling convention");
537     case CallingConv::C:
538       return LowerCCCArguments(Op, DAG);
539   }
540 }
541
542 /// LowerCCCArguments - transform physical registers into
543 /// virtual registers and generate load operations for
544 /// arguments places on the stack.
545 /// TODO: isVarArg, sret
546 SDOperand MipsTargetLowering::
547 LowerCCCArguments(SDOperand Op, SelectionDAG &DAG) 
548 {
549   SDOperand Root        = Op.getOperand(0);
550   MachineFunction &MF   = DAG.getMachineFunction();
551   MachineFrameInfo *MFI = MF.getFrameInfo();
552   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
553
554   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
555   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
556
557   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
558
559   // GP holds the GOT address on PIC calls.
560   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
561     AddLiveIn(MF, Mips::GP, Mips::CPURegsRegisterClass);
562
563   // Assign locations to all of the incoming arguments.
564   SmallVector<CCValAssign, 16> ArgLocs;
565   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
566
567   CCInfo.AnalyzeFormalArguments(Op.Val, CC_Mips);
568   SmallVector<SDOperand, 8> ArgValues;
569   SDOperand StackPtr;
570
571   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
572
573     CCValAssign &VA = ArgLocs[i];
574
575     // Arguments stored on registers
576     if (VA.isRegLoc()) {
577       MVT RegVT = VA.getLocVT();
578       TargetRegisterClass *RC;
579             
580       if (RegVT == MVT::i32)
581         RC = Mips::CPURegsRegisterClass;
582       else
583         assert(0 && "support only Mips::CPURegsRegisterClass");
584
585       // Transform the arguments stored on 
586       // physical registers into virtual ones
587       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
588       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
589       
590       // If this is an 8 or 16-bit value, it is really passed promoted 
591       // to 32 bits.  Insert an assert[sz]ext to capture this, then 
592       // truncate to the right size.
593       if (VA.getLocInfo() == CCValAssign::SExt)
594         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
595                                DAG.getValueType(VA.getValVT()));
596       else if (VA.getLocInfo() == CCValAssign::ZExt)
597         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
598                                DAG.getValueType(VA.getValVT()));
599       
600       if (VA.getLocInfo() != CCValAssign::Full)
601         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
602
603       ArgValues.push_back(ArgValue);
604
605       // To meet ABI, when VARARGS are passed on registers, the registers
606       // must have their values written to the caller stack frame. 
607       if (isVarArg) {
608
609         if (StackPtr.Val == 0)
610           StackPtr = DAG.getRegister(StackReg, getPointerTy());
611      
612         // The stack pointer offset is relative to the caller stack frame. 
613         // Since the real stack size is unknown here, a negative SPOffset 
614         // is used so there's a way to adjust these offsets when the stack
615         // size get known (on EliminateFrameIndex). A dummy SPOffset is 
616         // used instead of a direct negative address (which is recorded to
617         // be used on emitPrologue) to avoid mis-calc of the first stack 
618         // offset on PEI::calculateFrameObjectOffsets.
619         // Arguments are always 32-bit.
620         int FI = MFI->CreateFixedObject(4, 0);
621         MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
622         SDOperand PtrOff = DAG.getFrameIndex(FI, getPointerTy());
623       
624         // emit ISD::STORE whichs stores the 
625         // parameter value to a stack Location
626         ArgValues.push_back(DAG.getStore(Root, ArgValue, PtrOff, NULL, 0));
627       }
628
629     } else {
630       // sanity check
631       assert(VA.isMemLoc());
632       
633       // The stack pointer offset is relative to the caller stack frame. 
634       // Since the real stack size is unknown here, a negative SPOffset 
635       // is used so there's a way to adjust these offsets when the stack
636       // size get known (on EliminateFrameIndex). A dummy SPOffset is 
637       // used instead of a direct negative address (which is recorded to
638       // be used on emitPrologue) to avoid mis-calc of the first stack 
639       // offset on PEI::calculateFrameObjectOffsets.
640       // Arguments are always 32-bit.
641       int FI = MFI->CreateFixedObject(4, 0);
642       MipsFI->recordLoadArgsFI(FI, -(4+(16+VA.getLocMemOffset())));
643
644       // Create load nodes to retrieve arguments from the stack
645       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
646       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
647     }
648   }
649   ArgValues.push_back(Root);
650
651   // Return the new list of results.
652   return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
653                             ArgValues.size()).getValue(Op.ResNo);
654 }
655
656 //===----------------------------------------------------------------------===//
657 //               Return Value Calling Convention Implementation
658 //===----------------------------------------------------------------------===//
659
660 SDOperand MipsTargetLowering::
661 LowerRET(SDOperand Op, SelectionDAG &DAG)
662 {
663   // CCValAssign - represent the assignment of
664   // the return value to a location
665   SmallVector<CCValAssign, 16> RVLocs;
666   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
667   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
668
669   // CCState - Info about the registers and stack slot.
670   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
671
672   // Analize return values of ISD::RET
673   CCInfo.AnalyzeReturn(Op.Val, RetCC_Mips);
674
675   // If this is the first return lowered for this function, add 
676   // the regs to the liveout set for the function.
677   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
678     for (unsigned i = 0; i != RVLocs.size(); ++i)
679       if (RVLocs[i].isRegLoc())
680         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
681   }
682
683   // The chain is always operand #0
684   SDOperand Chain = Op.getOperand(0);
685   SDOperand Flag;
686
687   // Copy the result values into the output registers.
688   for (unsigned i = 0; i != RVLocs.size(); ++i) {
689     CCValAssign &VA = RVLocs[i];
690     assert(VA.isRegLoc() && "Can only return in registers!");
691
692     // ISD::RET => ret chain, (regnum1,val1), ...
693     // So i*2+1 index only the regnums
694     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
695
696     // guarantee that all emitted copies are
697     // stuck together, avoiding something bad
698     Flag = Chain.getValue(1);
699   }
700
701   // Return on Mips is always a "jr $ra"
702   if (Flag.Val)
703     return DAG.getNode(MipsISD::Ret, MVT::Other, 
704                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
705   else // Return Void
706     return DAG.getNode(MipsISD::Ret, MVT::Other, 
707                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
708 }
709
710 //===----------------------------------------------------------------------===//
711 //                           Mips Inline Assembly Support
712 //===----------------------------------------------------------------------===//
713
714 /// getConstraintType - Given a constraint letter, return the type of
715 /// constraint it is for this target.
716 MipsTargetLowering::ConstraintType MipsTargetLowering::
717 getConstraintType(const std::string &Constraint) const 
718 {
719   if (Constraint.size() == 1) {
720     // Mips specific constrainy 
721     // GCC config/mips/constraints.md
722     //
723     // 'd' : An address register. Equivalent to r 
724     //       unless generating MIPS16 code. 
725     // 'y' : Equivalent to r; retained for 
726     //       backwards compatibility. 
727     //
728     switch (Constraint[0]) {
729       default : break;
730       case 'd':     
731       case 'y': 
732         return C_RegisterClass;
733         break;
734     }
735   }
736   return TargetLowering::getConstraintType(Constraint);
737 }
738
739 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
740 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
741 {
742   if (Constraint.size() == 1) {
743     switch (Constraint[0]) {
744     case 'r':
745       return std::make_pair(0U, Mips::CPURegsRegisterClass);
746       break;
747     }
748   }
749   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
750 }
751
752 std::vector<unsigned> MipsTargetLowering::
753 getRegClassForInlineAsmConstraint(const std::string &Constraint,
754                                   MVT VT) const
755 {
756   if (Constraint.size() != 1)
757     return std::vector<unsigned>();
758
759   switch (Constraint[0]) {         
760     default : break;
761     case 'r':
762     // GCC Mips Constraint Letters
763     case 'd':     
764     case 'y': 
765       return make_vector<unsigned>(Mips::V0, Mips::V1, Mips::A0, 
766                                    Mips::A1, Mips::A2, Mips::A3, 
767                                    Mips::T0, Mips::T1, Mips::T2, 
768                                    Mips::T3, Mips::T4, Mips::T5, 
769                                    Mips::T6, Mips::T7, Mips::S0, 
770                                    Mips::S1, Mips::S2, Mips::S3, 
771                                    Mips::S4, Mips::S5, Mips::S6, 
772                                    Mips::S7, Mips::T8, Mips::T9, 0);
773       break;
774   }
775   return std::vector<unsigned>();
776 }