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