Rip all of the global variable lowering logic out of TargetAsmInfo. Since
[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 "MipsSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 using namespace llvm;
37
38 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
39   switch (Opcode) {
40     case MipsISD::JmpLink    : return "MipsISD::JmpLink";
41     case MipsISD::Hi         : return "MipsISD::Hi";
42     case MipsISD::Lo         : return "MipsISD::Lo";
43     case MipsISD::GPRel      : return "MipsISD::GPRel";
44     case MipsISD::Ret        : return "MipsISD::Ret";
45     case MipsISD::CMov       : return "MipsISD::CMov";
46     case MipsISD::SelectCC   : return "MipsISD::SelectCC";
47     case MipsISD::FPSelectCC : return "MipsISD::FPSelectCC";
48     case MipsISD::FPBrcond   : return "MipsISD::FPBrcond";
49     case MipsISD::FPCmp      : return "MipsISD::FPCmp";
50     case MipsISD::FPRound    : return "MipsISD::FPRound";
51     default                  : return NULL;
52   }
53 }
54
55 MipsTargetLowering::
56 MipsTargetLowering(MipsTargetMachine &TM)
57   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
58   Subtarget = &TM.getSubtarget<MipsSubtarget>();
59
60   // Mips does not have i1 type, so use i32 for
61   // setcc operations results (slt, sgt, ...). 
62   setBooleanContents(ZeroOrOneBooleanContent);
63
64   // JumpTable targets must use GOT when using PIC_
65   setUsesGlobalOffsetTable(true);
66
67   // Set up the register classes
68   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
69   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
70
71   // When dealing with single precision only, use libcalls
72   if (!Subtarget->isSingleFloat())
73     if (!Subtarget->isFP64bit())
74       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
75
76   // Legal fp constants
77   addLegalFPImmediate(APFloat(+0.0f));
78
79   // Load extented operations for i1 types must be promoted 
80   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
81   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
82   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
83
84   // MIPS doesn't have extending float->double load/store
85   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
86   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
87
88   // Used by legalize types to correctly generate the setcc result. 
89   // Without this, every float setcc comes with a AND/OR with the result, 
90   // we don't want this, since the fpcmp result goes to a flag register, 
91   // which is used implicitly by brcond and select operations.
92   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
93
94   // Mips Custom Operations
95   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
96   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
97   setOperationAction(ISD::RET,                MVT::Other, Custom);
98   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
99   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
100   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
101   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
102   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
103   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
104   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
105   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
106   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
107   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
108
109   // We custom lower AND/OR to handle the case where the DAG contain 'ands/ors' 
110   // with operands comming from setcc fp comparions. This is necessary since 
111   // the result from these setcc are in a flag registers (FCR31).
112   setOperationAction(ISD::AND,              MVT::i32,   Custom);
113   setOperationAction(ISD::OR,               MVT::i32,   Custom);
114
115   // Operations not directly supported by Mips.
116   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
117   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
118   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
119   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
120   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
122   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
123   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
124   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
125   setOperationAction(ISD::ROTR,              MVT::i32,   Expand);
126   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
127   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
128   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
129   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Expand);
130   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Expand);
131   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
132   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
133   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
134   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
135   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
136   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
137   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
138   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
139
140   // We don't have line number support yet.
141   setOperationAction(ISD::DBG_STOPPOINT,     MVT::Other, Expand);
142   setOperationAction(ISD::DEBUG_LOC,         MVT::Other, Expand);
143   setOperationAction(ISD::DBG_LABEL,         MVT::Other, Expand);
144   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
145
146   // Use the default for now
147   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
148   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
149   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
150
151   if (Subtarget->isSingleFloat())
152     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
153
154   if (!Subtarget->hasSEInReg()) {
155     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
156     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
157   }
158
159   if (!Subtarget->hasBitCount())
160     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
161
162   if (!Subtarget->hasSwap())
163     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
164
165   setStackPointerRegisterToSaveRestore(Mips::SP);
166   computeRegisterProperties();
167 }
168
169 MVT MipsTargetLowering::getSetCCResultType(MVT VT) const {
170   return MVT::i32;
171 }
172
173 /// getFunctionAlignment - Return the Log2 alignment of this function.
174 unsigned MipsTargetLowering::getFunctionAlignment(const Function *) const {
175   return 2;
176 }
177
178 SDValue MipsTargetLowering::
179 LowerOperation(SDValue Op, SelectionDAG &DAG) 
180 {
181   switch (Op.getOpcode()) 
182   {
183     case ISD::AND:                return LowerANDOR(Op, DAG);
184     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
185     case ISD::CALL:               return LowerCALL(Op, DAG);
186     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
187     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
188     case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
189     case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
190     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
191     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
192     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
193     case ISD::OR:                 return LowerANDOR(Op, DAG);
194     case ISD::RET:                return LowerRET(Op, DAG);
195     case ISD::SELECT:             return LowerSELECT(Op, DAG);
196     case ISD::SETCC:              return LowerSETCC(Op, DAG);
197   }
198   return SDValue();
199 }
200
201 //===----------------------------------------------------------------------===//
202 //  Lower helper functions
203 //===----------------------------------------------------------------------===//
204
205 // AddLiveIn - This helper function adds the specified physical register to the
206 // MachineFunction as a live in value.  It also creates a corresponding
207 // virtual register for it.
208 static unsigned
209 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC) 
210 {
211   assert(RC->contains(PReg) && "Not the correct regclass!");
212   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
213   MF.getRegInfo().addLiveIn(PReg, VReg);
214   return VReg;
215 }
216
217 // Get fp branch code (not opcode) from condition code.
218 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
219   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
220     return Mips::BRANCH_T;
221
222   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
223     return Mips::BRANCH_F;
224
225   return Mips::BRANCH_INVALID;
226 }
227   
228 static unsigned FPBranchCodeToOpc(Mips::FPBranchCode BC) {
229   switch(BC) {
230     default:
231       llvm_unreachable("Unknown branch code");
232     case Mips::BRANCH_T  : return Mips::BC1T;
233     case Mips::BRANCH_F  : return Mips::BC1F;
234     case Mips::BRANCH_TL : return Mips::BC1TL;
235     case Mips::BRANCH_FL : return Mips::BC1FL;
236   }
237 }
238
239 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
240   switch (CC) {
241   default: llvm_unreachable("Unknown fp condition code!");
242   case ISD::SETEQ:  
243   case ISD::SETOEQ: return Mips::FCOND_EQ;
244   case ISD::SETUNE: return Mips::FCOND_OGL;
245   case ISD::SETLT:  
246   case ISD::SETOLT: return Mips::FCOND_OLT;
247   case ISD::SETGT:  
248   case ISD::SETOGT: return Mips::FCOND_OGT;
249   case ISD::SETLE:  
250   case ISD::SETOLE: return Mips::FCOND_OLE; 
251   case ISD::SETGE:
252   case ISD::SETOGE: return Mips::FCOND_OGE;
253   case ISD::SETULT: return Mips::FCOND_ULT;
254   case ISD::SETULE: return Mips::FCOND_ULE; 
255   case ISD::SETUGT: return Mips::FCOND_UGT;
256   case ISD::SETUGE: return Mips::FCOND_UGE;
257   case ISD::SETUO:  return Mips::FCOND_UN; 
258   case ISD::SETO:   return Mips::FCOND_OR;
259   case ISD::SETNE:  
260   case ISD::SETONE: return Mips::FCOND_NEQ;
261   case ISD::SETUEQ: return Mips::FCOND_UEQ;
262   }
263 }
264
265 MachineBasicBlock *
266 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
267                                                 MachineBasicBlock *BB) const {
268   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
269   bool isFPCmp = false;
270   DebugLoc dl = MI->getDebugLoc();
271
272   switch (MI->getOpcode()) {
273   default: assert(false && "Unexpected instr type to insert");
274   case Mips::Select_FCC:
275   case Mips::Select_FCC_S32:
276   case Mips::Select_FCC_D32:
277     isFPCmp = true; // FALL THROUGH
278   case Mips::Select_CC:
279   case Mips::Select_CC_S32:
280   case Mips::Select_CC_D32: {
281     // To "insert" a SELECT_CC instruction, we actually have to insert the
282     // diamond control-flow pattern.  The incoming instruction knows the
283     // destination vreg to set, the condition code register to branch on, the
284     // true/false values to select between, and a branch opcode to use.
285     const BasicBlock *LLVM_BB = BB->getBasicBlock();
286     MachineFunction::iterator It = BB;
287     ++It;
288
289     //  thisMBB:
290     //  ...
291     //   TrueVal = ...
292     //   setcc r1, r2, r3
293     //   bNE   r1, r0, copy1MBB
294     //   fallthrough --> copy0MBB
295     MachineBasicBlock *thisMBB  = BB;
296     MachineFunction *F = BB->getParent();
297     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
298     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
299
300     // Emit the right instruction according to the type of the operands compared
301     if (isFPCmp) {
302       // Find the condiction code present in the setcc operation.
303       Mips::CondCode CC = (Mips::CondCode)MI->getOperand(4).getImm();
304       // Get the branch opcode from the branch code.
305       unsigned Opc = FPBranchCodeToOpc(GetFPBranchCodeFromCond(CC));
306       BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
307     } else
308       BuildMI(BB, dl, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
309         .addReg(Mips::ZERO).addMBB(sinkMBB);
310
311     F->insert(It, copy0MBB);
312     F->insert(It, sinkMBB);
313     // Update machine-CFG edges by first adding all successors of the current
314     // block to the new block which will contain the Phi node for the select.
315     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
316         e = BB->succ_end(); i != e; ++i)
317       sinkMBB->addSuccessor(*i);
318     // Next, remove all successors of the current block, and add the true
319     // and fallthrough blocks as its successors.
320     while(!BB->succ_empty())
321       BB->removeSuccessor(BB->succ_begin());
322     BB->addSuccessor(copy0MBB);
323     BB->addSuccessor(sinkMBB);
324
325     //  copy0MBB:
326     //   %FalseValue = ...
327     //   # fallthrough to sinkMBB
328     BB = copy0MBB;
329
330     // Update machine-CFG edges
331     BB->addSuccessor(sinkMBB);
332
333     //  sinkMBB:
334     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
335     //  ...
336     BB = sinkMBB;
337     BuildMI(BB, dl, TII->get(Mips::PHI), MI->getOperand(0).getReg())
338       .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
339       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB);
340
341     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
342     return BB;
343   }
344   }
345 }
346
347 //===----------------------------------------------------------------------===//
348 //  Misc Lower Operation implementation
349 //===----------------------------------------------------------------------===//
350
351 SDValue MipsTargetLowering::
352 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG)
353 {
354   if (!Subtarget->isMips1())
355     return Op;
356
357   MachineFunction &MF = DAG.getMachineFunction();
358   unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
359
360   SDValue Chain = DAG.getEntryNode();
361   DebugLoc dl = Op.getDebugLoc();
362   SDValue Src = Op.getOperand(0);
363
364   // Set the condition register
365   SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
366   CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
367   CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
368
369   SDValue Cst = DAG.getConstant(3, MVT::i32);
370   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
371   Cst = DAG.getConstant(2, MVT::i32);
372   SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
373
374   SDValue InFlag(0, 0);
375   CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
376
377   // Emit the round instruction and bit convert to integer
378   SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
379                               Src, CondReg.getValue(1));
380   SDValue BitCvt = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Trunc);
381   return BitCvt;
382 }
383
384 SDValue MipsTargetLowering::
385 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG)
386 {
387   SDValue Chain = Op.getOperand(0);
388   SDValue Size = Op.getOperand(1);
389   DebugLoc dl = Op.getDebugLoc();
390
391   // Get a reference from Mips stack pointer
392   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
393
394   // Subtract the dynamic size from the actual stack size to
395   // obtain the new stack size.
396   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
397
398   // The Sub result contains the new stack start address, so it 
399   // must be placed in the stack pointer register.
400   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
401   
402   // This node always has two return values: a new stack pointer 
403   // value and a chain
404   SDValue Ops[2] = { Sub, Chain };
405   return DAG.getMergeValues(Ops, 2, dl);
406 }
407
408 SDValue MipsTargetLowering::
409 LowerANDOR(SDValue Op, SelectionDAG &DAG)
410 {
411   SDValue LHS   = Op.getOperand(0);
412   SDValue RHS   = Op.getOperand(1);
413   DebugLoc dl   = Op.getDebugLoc();
414
415   if (LHS.getOpcode() != MipsISD::FPCmp || RHS.getOpcode() != MipsISD::FPCmp)
416     return Op;
417
418   SDValue True  = DAG.getConstant(1, MVT::i32);
419   SDValue False = DAG.getConstant(0, MVT::i32);
420
421   SDValue LSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
422                              LHS, True, False, LHS.getOperand(2));
423   SDValue RSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
424                              RHS, True, False, RHS.getOperand(2));
425
426   return DAG.getNode(Op.getOpcode(), dl, MVT::i32, LSEL, RSEL);
427 }
428
429 SDValue MipsTargetLowering::
430 LowerBRCOND(SDValue Op, SelectionDAG &DAG)
431 {
432   // The first operand is the chain, the second is the condition, the third is 
433   // the block to branch to if the condition is true.
434   SDValue Chain = Op.getOperand(0);
435   SDValue Dest = Op.getOperand(2);
436   DebugLoc dl = Op.getDebugLoc();
437
438   if (Op.getOperand(1).getOpcode() != MipsISD::FPCmp)
439     return Op;
440   
441   SDValue CondRes = Op.getOperand(1);
442   SDValue CCNode  = CondRes.getOperand(2);
443   Mips::CondCode CC =
444     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
445   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32); 
446
447   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode, 
448              Dest, CondRes);
449 }
450
451 SDValue MipsTargetLowering::
452 LowerSETCC(SDValue Op, SelectionDAG &DAG)
453 {
454   // The operands to this are the left and right operands to compare (ops #0, 
455   // and #1) and the condition code to compare them with (op #2) as a 
456   // CondCodeSDNode.
457   SDValue LHS = Op.getOperand(0); 
458   SDValue RHS = Op.getOperand(1);
459   DebugLoc dl = Op.getDebugLoc();
460
461   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
462   
463   return DAG.getNode(MipsISD::FPCmp, dl, Op.getValueType(), LHS, RHS, 
464                  DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
465 }
466
467 SDValue MipsTargetLowering::
468 LowerSELECT(SDValue Op, SelectionDAG &DAG) 
469 {
470   SDValue Cond  = Op.getOperand(0); 
471   SDValue True  = Op.getOperand(1);
472   SDValue False = Op.getOperand(2);
473   DebugLoc dl = Op.getDebugLoc();
474
475   // if the incomming condition comes from a integer compare, the select 
476   // operation must be SelectCC or a conditional move if the subtarget 
477   // supports it.
478   if (Cond.getOpcode() != MipsISD::FPCmp) {
479     if (Subtarget->hasCondMov() && !True.getValueType().isFloatingPoint())
480       return Op;
481     return DAG.getNode(MipsISD::SelectCC, dl, True.getValueType(), 
482                        Cond, True, False);
483   }
484
485   // if the incomming condition comes from fpcmp, the select
486   // operation must use FPSelectCC.
487   SDValue CCNode = Cond.getOperand(2);
488   return DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
489                      Cond, True, False, CCNode);
490 }
491
492 SDValue MipsTargetLowering::
493 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) 
494 {
495   // FIXME there isn't actually debug info here
496   DebugLoc dl = Op.getDebugLoc();
497   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
498   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
499
500   if (!Subtarget->hasABICall()) {
501     SDVTList VTs = DAG.getVTList(MVT::i32);
502     // %hi/%lo relocation
503     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GA, 1);
504     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
505     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
506
507   } else { // Abicall relocations, TODO: make this cleaner.
508     SDValue ResNode = DAG.getLoad(MVT::i32, dl, 
509                                   DAG.getEntryNode(), GA, NULL, 0);
510     // On functions and global targets not internal linked only
511     // a load from got/GP is necessary for PIC to work.
512     if (!GV->hasLocalLinkage() || isa<Function>(GV))
513       return ResNode;
514     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
515     return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
516   }
517
518   llvm_unreachable("Dont know how to handle GlobalAddress");
519   return SDValue(0,0);
520 }
521
522 SDValue MipsTargetLowering::
523 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
524 {
525   llvm_unreachable("TLS not implemented for MIPS.");
526   return SDValue(); // Not reached
527 }
528
529 SDValue MipsTargetLowering::
530 LowerJumpTable(SDValue Op, SelectionDAG &DAG) 
531 {
532   SDValue ResNode;
533   SDValue HiPart; 
534   // FIXME there isn't actually debug info here
535   DebugLoc dl = Op.getDebugLoc();
536
537   MVT PtrVT = Op.getValueType();
538   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
539   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
540
541   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
542     SDVTList VTs = DAG.getVTList(MVT::i32);
543     SDValue Ops[] = { JTI };
544     HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, Ops, 1);
545   } else // Emit Load from Global Pointer
546     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI, NULL, 0);
547
548   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTI);
549   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
550
551   return ResNode;
552 }
553
554 SDValue MipsTargetLowering::
555 LowerConstantPool(SDValue Op, SelectionDAG &DAG) 
556 {
557   SDValue ResNode;
558   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
559   Constant *C = N->getConstVal();
560   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
561   // FIXME there isn't actually debug info here
562   DebugLoc dl = Op.getDebugLoc();
563
564   // gp_rel relocation
565   // FIXME: we should reference the constant pool using small data sections, 
566   // but the asm printer currently doens't support this feature without
567   // hacking it. This feature should come soon so we can uncomment the 
568   // stuff below.
569   //if (!Subtarget->hasABICall() &&  
570   //    IsInSmallSection(getTargetData()->getTypeAllocSize(C->getType()))) {
571   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
572   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
573   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode); 
574   //} else { // %hi/%lo relocation
575     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CP);
576     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
577     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
578   //}
579
580   return ResNode;
581 }
582
583 //===----------------------------------------------------------------------===//
584 //                      Calling Convention Implementation
585 //
586 //  The lower operations present on calling convention works on this order:
587 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
588 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
589 //      LowerRET (virt regs --> phys regs)
590 //      LowerCALL (phys regs --> virt regs)
591 //
592 //===----------------------------------------------------------------------===//
593
594 #include "MipsGenCallingConv.inc"
595
596 //===----------------------------------------------------------------------===//
597 // TODO: Implement a generic logic using tblgen that can support this. 
598 // Mips O32 ABI rules:
599 // ---
600 // i32 - Passed in A0, A1, A2, A3 and stack
601 // f32 - Only passed in f32 registers if no int reg has been used yet to hold 
602 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
603 // f64 - Only passed in two aliased f32 registers if no int reg has been used 
604 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is 
605 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
606 //       go to stack.
607 //===----------------------------------------------------------------------===//
608
609 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
610                        MVT LocVT, CCValAssign::LocInfo LocInfo,
611                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
612
613   static const unsigned IntRegsSize=4, FloatRegsSize=2; 
614
615   static const unsigned IntRegs[] = {
616       Mips::A0, Mips::A1, Mips::A2, Mips::A3
617   };
618   static const unsigned F32Regs[] = {
619       Mips::F12, Mips::F14
620   };
621   static const unsigned F64Regs[] = {
622       Mips::D6, Mips::D7
623   };
624
625   unsigned Reg=0;
626   unsigned UnallocIntReg = State.getFirstUnallocated(IntRegs, IntRegsSize);
627   bool IntRegUsed = (IntRegs[UnallocIntReg] != (unsigned (Mips::A0)));
628
629   // Promote i8 and i16
630   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
631     LocVT = MVT::i32;
632     if (ArgFlags.isSExt())
633       LocInfo = CCValAssign::SExt;
634     else if (ArgFlags.isZExt())
635       LocInfo = CCValAssign::ZExt;
636     else
637       LocInfo = CCValAssign::AExt;
638   }
639
640   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && IntRegUsed)) {
641     Reg = State.AllocateReg(IntRegs, IntRegsSize);
642     IntRegUsed = true;
643     LocVT = MVT::i32;
644   }
645
646   if (ValVT.isFloatingPoint() && !IntRegUsed) {
647     if (ValVT == MVT::f32)
648       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
649     else
650       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
651   }
652
653   if (ValVT == MVT::f64 && IntRegUsed) {
654     if (UnallocIntReg != IntRegsSize) {
655       // If we hit register A3 as the first not allocated, we must
656       // mark it as allocated (shadow) and use the stack instead.
657       if (IntRegs[UnallocIntReg] != (unsigned (Mips::A3)))
658         Reg = Mips::A2;
659       for (;UnallocIntReg < IntRegsSize; ++UnallocIntReg)
660         State.AllocateReg(UnallocIntReg);
661     } 
662     LocVT = MVT::i32;
663   }
664
665   if (!Reg) {
666     unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
667     unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
668     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
669   } else
670     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
671
672   return false; // CC must always match
673 }
674
675 //===----------------------------------------------------------------------===//
676 //                  CALL Calling Convention Implementation
677 //===----------------------------------------------------------------------===//
678
679 /// LowerCALL - functions arguments are copied from virtual regs to 
680 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
681 /// TODO: isVarArg, isTailCall.
682 SDValue MipsTargetLowering::
683 LowerCALL(SDValue Op, SelectionDAG &DAG)
684 {
685   MachineFunction &MF = DAG.getMachineFunction();
686
687   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
688   SDValue Chain = TheCall->getChain();
689   SDValue Callee = TheCall->getCallee();
690   bool isVarArg = TheCall->isVarArg();
691   unsigned CC = TheCall->getCallingConv();
692   DebugLoc dl = TheCall->getDebugLoc();
693
694   MachineFrameInfo *MFI = MF.getFrameInfo();
695
696   // Analyze operands of the call, assigning locations to each operand.
697   SmallVector<CCValAssign, 16> ArgLocs;
698   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
699
700   // To meet O32 ABI, Mips must always allocate 16 bytes on
701   // the stack (even if less than 4 are used as arguments)
702   if (Subtarget->isABI_O32()) {
703     int VTsize = MVT(MVT::i32).getSizeInBits()/8;
704     MFI->CreateFixedObject(VTsize, (VTsize*3));
705     CCInfo.AnalyzeCallOperands(TheCall, CC_MipsO32);
706   } else
707     CCInfo.AnalyzeCallOperands(TheCall, CC_Mips);
708   
709   // Get a count of how many bytes are to be pushed on the stack.
710   unsigned NumBytes = CCInfo.getNextStackOffset();
711   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
712
713   // With EABI is it possible to have 16 args on registers.
714   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
715   SmallVector<SDValue, 8> MemOpChains;
716
717   // First/LastArgStackLoc contains the first/last 
718   // "at stack" argument location.
719   int LastArgStackLoc = 0;
720   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
721
722   // Walk the register/memloc assignments, inserting copies/loads.
723   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
724     SDValue Arg = TheCall->getArg(i);
725     CCValAssign &VA = ArgLocs[i];
726
727     // Promote the value if needed.
728     switch (VA.getLocInfo()) {
729     default: llvm_unreachable("Unknown loc info!");
730     case CCValAssign::Full: 
731       if (Subtarget->isABI_O32() && VA.isRegLoc()) {
732         if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
733           Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Arg);
734         if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
735           Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
736           SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
737                                    DAG.getConstant(0, getPointerTy()));
738           SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
739                                    DAG.getConstant(1, getPointerTy()));
740           RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
741           RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
742           continue;
743         }  
744       }
745       break;
746     case CCValAssign::SExt:
747       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
748       break;
749     case CCValAssign::ZExt:
750       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
751       break;
752     case CCValAssign::AExt:
753       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
754       break;
755     }
756     
757     // Arguments that can be passed on register must be kept at 
758     // RegsToPass vector
759     if (VA.isRegLoc()) {
760       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
761       continue;
762     }
763     
764     // Register can't get to this point...
765     assert(VA.isMemLoc());
766     
767     // Create the frame index object for this incoming parameter
768     // This guarantees that when allocating Local Area the firsts
769     // 16 bytes which are alwayes reserved won't be overwritten
770     // if O32 ABI is used. For EABI the first address is zero.
771     LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
772     int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
773                                     LastArgStackLoc);
774
775     SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
776
777     // emit ISD::STORE whichs stores the 
778     // parameter value to a stack Location
779     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0));
780   }
781
782   // Transform all store nodes into one single node because all store
783   // nodes are independent of each other.
784   if (!MemOpChains.empty())     
785     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
786                         &MemOpChains[0], MemOpChains.size());
787
788   // Build a sequence of copy-to-reg nodes chained together with token 
789   // chain and flag operands which copy the outgoing args into registers.
790   // The InFlag in necessary since all emited instructions must be
791   // stuck together.
792   SDValue InFlag;
793   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
794     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 
795                              RegsToPass[i].second, InFlag);
796     InFlag = Chain.getValue(1);
797   }
798
799   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
800   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 
801   // node so that legalize doesn't hack it. 
802   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 
803     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
804   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
805     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
806
807   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
808   //             = Chain, Callee, Reg#1, Reg#2, ...  
809   //
810   // Returns a chain & a flag for retval copy to use.
811   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
812   SmallVector<SDValue, 8> Ops;
813   Ops.push_back(Chain);
814   Ops.push_back(Callee);
815
816   // Add argument registers to the end of the list so that they are 
817   // known live into the call.
818   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
819     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
820                                   RegsToPass[i].second.getValueType()));
821
822   if (InFlag.getNode())
823     Ops.push_back(InFlag);
824
825   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
826   InFlag = Chain.getValue(1);
827
828   // Create the CALLSEQ_END node.
829   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
830                              DAG.getIntPtrConstant(0, true), InFlag);
831   InFlag = Chain.getValue(1);
832
833   // Create a stack location to hold GP when PIC is used. This stack 
834   // location is used on function prologue to save GP and also after all 
835   // emited CALL's to restore GP. 
836   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
837       // Function can have an arbitrary number of calls, so 
838       // hold the LastArgStackLoc with the biggest offset.
839       int FI;
840       MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
841       if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
842         LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
843         // Create the frame index only once. SPOffset here can be anything 
844         // (this will be fixed on processFunctionBeforeFrameFinalized)
845         if (MipsFI->getGPStackOffset() == -1) {
846           FI = MFI->CreateFixedObject(4, 0);
847           MipsFI->setGPFI(FI);
848         }
849         MipsFI->setGPStackOffset(LastArgStackLoc);
850       }
851
852       // Reload GP value.
853       FI = MipsFI->getGPFI();
854       SDValue FIN = DAG.getFrameIndex(FI,getPointerTy());
855       SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN, NULL, 0);
856       Chain = GPLoad.getValue(1);
857       Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32), 
858                                GPLoad, SDValue(0,0));
859       InFlag = Chain.getValue(1);
860   }      
861
862   // Handle result values, copying them out of physregs into vregs that we
863   // return.
864   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG), Op.getResNo());
865 }
866
867 /// LowerCallResult - Lower the result values of an ISD::CALL into the
868 /// appropriate copies out of appropriate physical registers.  This assumes that
869 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
870 /// being lowered. Returns a SDNode with the same number of values as the 
871 /// ISD::CALL.
872 SDNode *MipsTargetLowering::
873 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall, 
874         unsigned CallingConv, SelectionDAG &DAG) {
875   
876   bool isVarArg = TheCall->isVarArg();
877   DebugLoc dl = TheCall->getDebugLoc();
878
879   // Assign locations to each value returned by this call.
880   SmallVector<CCValAssign, 16> RVLocs;
881   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
882                  RVLocs, *DAG.getContext());
883
884   CCInfo.AnalyzeCallResult(TheCall, RetCC_Mips);
885   SmallVector<SDValue, 8> ResultVals;
886
887   // Copy all of the result registers out of their specified physreg.
888   for (unsigned i = 0; i != RVLocs.size(); ++i) {
889     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
890                                  RVLocs[i].getValVT(), InFlag).getValue(1);
891     InFlag = Chain.getValue(2);
892     ResultVals.push_back(Chain.getValue(0));
893   }
894   
895   ResultVals.push_back(Chain);
896
897   // Merge everything together with a MERGE_VALUES node.
898   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
899                      &ResultVals[0], ResultVals.size()).getNode();
900 }
901
902 //===----------------------------------------------------------------------===//
903 //             FORMAL_ARGUMENTS Calling Convention Implementation
904 //===----------------------------------------------------------------------===//
905
906 /// LowerFORMAL_ARGUMENTS - transform physical registers into
907 /// virtual registers and generate load operations for
908 /// arguments places on the stack.
909 /// TODO: isVarArg
910 SDValue MipsTargetLowering::
911 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) 
912 {
913   SDValue Root = Op.getOperand(0);
914   MachineFunction &MF = DAG.getMachineFunction();
915   MachineFrameInfo *MFI = MF.getFrameInfo();
916   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
917   DebugLoc dl = Op.getDebugLoc();
918
919   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
920   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
921
922   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
923
924   // Assign locations to all of the incoming arguments.
925   SmallVector<CCValAssign, 16> ArgLocs;
926   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
927
928   if (Subtarget->isABI_O32())
929     CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_MipsO32);
930   else
931     CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_Mips);
932
933   SmallVector<SDValue, 16> ArgValues;
934   SDValue StackPtr;
935
936   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
937
938   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
939     CCValAssign &VA = ArgLocs[i];
940
941     // Arguments stored on registers
942     if (VA.isRegLoc()) {
943       MVT RegVT = VA.getLocVT();
944       TargetRegisterClass *RC = 0;
945
946       if (RegVT == MVT::i32)
947         RC = Mips::CPURegsRegisterClass; 
948       else if (RegVT == MVT::f32) 
949         RC = Mips::FGR32RegisterClass;
950       else if (RegVT == MVT::f64) {
951         if (!Subtarget->isSingleFloat()) 
952           RC = Mips::AFGR64RegisterClass;
953       } else  
954         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
955
956       // Transform the arguments stored on 
957       // physical registers into virtual ones
958       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
959       SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
960       
961       // If this is an 8 or 16-bit value, it has been passed promoted 
962       // to 32 bits.  Insert an assert[sz]ext to capture this, then 
963       // truncate to the right size.
964       if (VA.getLocInfo() != CCValAssign::Full) {
965         unsigned Opcode = 0;
966         if (VA.getLocInfo() == CCValAssign::SExt)
967           Opcode = ISD::AssertSext;
968         else if (VA.getLocInfo() == CCValAssign::ZExt)
969           Opcode = ISD::AssertZext;
970         if (Opcode)
971           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue, 
972                                  DAG.getValueType(VA.getValVT()));
973         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
974       }
975
976       // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64 
977       if (Subtarget->isABI_O32()) {
978         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32) 
979           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue);
980         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
981           unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(), 
982                                     VA.getLocReg()+1, RC);
983           SDValue ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg2, RegVT);
984           SDValue Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue);
985           SDValue Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue2);
986           ArgValue = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::f64, Lo, Hi);
987         }
988       }
989
990       ArgValues.push_back(ArgValue);
991
992       // To meet ABI, when VARARGS are passed on registers, the registers
993       // must have their values written to the caller stack frame. 
994       if ((isVarArg) && (Subtarget->isABI_O32())) {
995         if (StackPtr.getNode() == 0)
996           StackPtr = DAG.getRegister(StackReg, getPointerTy());
997      
998         // The stack pointer offset is relative to the caller stack frame. 
999         // Since the real stack size is unknown here, a negative SPOffset 
1000         // is used so there's a way to adjust these offsets when the stack
1001         // size get known (on EliminateFrameIndex). A dummy SPOffset is 
1002         // used instead of a direct negative address (which is recorded to
1003         // be used on emitPrologue) to avoid mis-calc of the first stack 
1004         // offset on PEI::calculateFrameObjectOffsets.
1005         // Arguments are always 32-bit.
1006         int FI = MFI->CreateFixedObject(4, 0);
1007         MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
1008         SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
1009       
1010         // emit ISD::STORE whichs stores the 
1011         // parameter value to a stack Location
1012         ArgValues.push_back(DAG.getStore(Root, dl, ArgValue, PtrOff, NULL, 0));
1013       }
1014
1015     } else { // VA.isRegLoc()
1016
1017       // sanity check
1018       assert(VA.isMemLoc());
1019       
1020       // The stack pointer offset is relative to the caller stack frame. 
1021       // Since the real stack size is unknown here, a negative SPOffset 
1022       // is used so there's a way to adjust these offsets when the stack
1023       // size get known (on EliminateFrameIndex). A dummy SPOffset is 
1024       // used instead of a direct negative address (which is recorded to
1025       // be used on emitPrologue) to avoid mis-calc of the first stack 
1026       // offset on PEI::calculateFrameObjectOffsets.
1027       // Arguments are always 32-bit.
1028       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1029       int FI = MFI->CreateFixedObject(ArgSize, 0);
1030       MipsFI->recordLoadArgsFI(FI, -(ArgSize+
1031         (FirstStackArgLoc + VA.getLocMemOffset())));
1032
1033       // Create load nodes to retrieve arguments from the stack
1034       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1035       ArgValues.push_back(DAG.getLoad(VA.getValVT(), dl, Root, FIN, NULL, 0));
1036     }
1037   }
1038
1039   // The mips ABIs for returning structs by value requires that we copy
1040   // the sret argument into $v0 for the return. Save the argument into
1041   // a virtual register so that we can access it from the return points.
1042   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1043     unsigned Reg = MipsFI->getSRetReturnReg();
1044     if (!Reg) {
1045       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1046       MipsFI->setSRetReturnReg(Reg);
1047     }
1048     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1049     Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1050   }
1051
1052   ArgValues.push_back(Root);
1053
1054   // Return the new list of results.
1055   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1056                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1057 }
1058
1059 //===----------------------------------------------------------------------===//
1060 //               Return Value Calling Convention Implementation
1061 //===----------------------------------------------------------------------===//
1062
1063 SDValue MipsTargetLowering::
1064 LowerRET(SDValue Op, SelectionDAG &DAG)
1065 {
1066   // CCValAssign - represent the assignment of
1067   // the return value to a location
1068   SmallVector<CCValAssign, 16> RVLocs;
1069   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
1070   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1071   DebugLoc dl = Op.getDebugLoc();
1072
1073   // CCState - Info about the registers and stack slot.
1074   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, *DAG.getContext());
1075
1076   // Analize return values of ISD::RET
1077   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_Mips);
1078
1079   // If this is the first return lowered for this function, add 
1080   // the regs to the liveout set for the function.
1081   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1082     for (unsigned i = 0; i != RVLocs.size(); ++i)
1083       if (RVLocs[i].isRegLoc())
1084         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1085   }
1086
1087   // The chain is always operand #0
1088   SDValue Chain = Op.getOperand(0);
1089   SDValue Flag;
1090
1091   // Copy the result values into the output registers.
1092   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1093     CCValAssign &VA = RVLocs[i];
1094     assert(VA.isRegLoc() && "Can only return in registers!");
1095
1096     // ISD::RET => ret chain, (regnum1,val1), ...
1097     // So i*2+1 index only the regnums
1098     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
1099                              Op.getOperand(i*2+1), Flag);
1100
1101     // guarantee that all emitted copies are
1102     // stuck together, avoiding something bad
1103     Flag = Chain.getValue(1);
1104   }
1105
1106   // The mips ABIs for returning structs by value requires that we copy
1107   // the sret argument into $v0 for the return. We saved the argument into
1108   // a virtual register in the entry block, so now we copy the value out
1109   // and into $v0.
1110   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1111     MachineFunction &MF      = DAG.getMachineFunction();
1112     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1113     unsigned Reg = MipsFI->getSRetReturnReg();
1114
1115     if (!Reg) 
1116       llvm_unreachable("sret virtual register not created in the entry block");
1117     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1118
1119     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1120     Flag = Chain.getValue(1);
1121   }
1122
1123   // Return on Mips is always a "jr $ra"
1124   if (Flag.getNode())
1125     return DAG.getNode(MipsISD::Ret, dl, MVT::Other, 
1126                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1127   else // Return Void
1128     return DAG.getNode(MipsISD::Ret, dl, MVT::Other, 
1129                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
1130 }
1131
1132 //===----------------------------------------------------------------------===//
1133 //                           Mips Inline Assembly Support
1134 //===----------------------------------------------------------------------===//
1135
1136 /// getConstraintType - Given a constraint letter, return the type of
1137 /// constraint it is for this target.
1138 MipsTargetLowering::ConstraintType MipsTargetLowering::
1139 getConstraintType(const std::string &Constraint) const 
1140 {
1141   // Mips specific constrainy 
1142   // GCC config/mips/constraints.md
1143   //
1144   // 'd' : An address register. Equivalent to r 
1145   //       unless generating MIPS16 code. 
1146   // 'y' : Equivalent to r; retained for 
1147   //       backwards compatibility. 
1148   // 'f' : Floating Point registers.      
1149   if (Constraint.size() == 1) {
1150     switch (Constraint[0]) {
1151       default : break;
1152       case 'd':     
1153       case 'y': 
1154       case 'f':
1155         return C_RegisterClass;
1156         break;
1157     }
1158   }
1159   return TargetLowering::getConstraintType(Constraint);
1160 }
1161
1162 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1163 /// return a list of registers that can be used to satisfy the constraint.
1164 /// This should only be used for C_RegisterClass constraints.
1165 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1166 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
1167 {
1168   if (Constraint.size() == 1) {
1169     switch (Constraint[0]) {
1170     case 'r':
1171       return std::make_pair(0U, Mips::CPURegsRegisterClass);
1172     case 'f':
1173       if (VT == MVT::f32)
1174         return std::make_pair(0U, Mips::FGR32RegisterClass);
1175       if (VT == MVT::f64)    
1176         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1177           return std::make_pair(0U, Mips::AFGR64RegisterClass);
1178     }
1179   }
1180   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1181 }
1182
1183 /// Given a register class constraint, like 'r', if this corresponds directly
1184 /// to an LLVM register class, return a register of 0 and the register class
1185 /// pointer.
1186 std::vector<unsigned> MipsTargetLowering::
1187 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1188                                   MVT VT) const
1189 {
1190   if (Constraint.size() != 1)
1191     return std::vector<unsigned>();
1192
1193   switch (Constraint[0]) {         
1194     default : break;
1195     case 'r':
1196     // GCC Mips Constraint Letters
1197     case 'd':     
1198     case 'y': 
1199       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3, 
1200              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1, 
1201              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7, 
1202              Mips::T8, 0);
1203
1204     case 'f':
1205       if (VT == MVT::f32) {
1206         if (Subtarget->isSingleFloat())
1207           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1208                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1209                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1210                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1211                  Mips::F30, Mips::F31, 0);
1212         else
1213           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8, 
1214                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26, 
1215                  Mips::F28, Mips::F30, 0);
1216       }
1217
1218       if (VT == MVT::f64)    
1219         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1220           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4, 
1221                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13, 
1222                  Mips::D14, Mips::D15, 0);
1223   }
1224   return std::vector<unsigned>();
1225 }
1226
1227 bool
1228 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1229   // The Mips target isn't yet aware of offsets.
1230   return false;
1231 }