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