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