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