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