93e7a23ac47584d0089ef33890ac32a1324aa77c
[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 <algorithm>
17 #include "MipsISelLowering.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsTargetObjectFile.h"
21 #include "MipsSubtarget.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.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::FPBrcond:          return "MipsISD::FPBrcond";
46   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
47   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
48   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
49   case MipsISD::FPRound:           return "MipsISD::FPRound";
50   case MipsISD::MAdd:              return "MipsISD::MAdd";
51   case MipsISD::MAddu:             return "MipsISD::MAddu";
52   case MipsISD::MSub:              return "MipsISD::MSub";
53   case MipsISD::MSubu:             return "MipsISD::MSubu";
54   case MipsISD::DivRem:            return "MipsISD::DivRem";
55   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
56   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
57   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
58   default: return NULL;
59   }
60 }
61
62 MipsTargetLowering::
63 MipsTargetLowering(MipsTargetMachine &TM)
64   : TargetLowering(TM, new MipsTargetObjectFile()) {
65   Subtarget = &TM.getSubtarget<MipsSubtarget>();
66
67   // Mips does not have i1 type, so use i32 for
68   // setcc operations results (slt, sgt, ...).
69   setBooleanContents(ZeroOrOneBooleanContent);
70
71   // Set up the register classes
72   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
73   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
74
75   // When dealing with single precision only, use libcalls
76   if (!Subtarget->isSingleFloat())
77     if (!Subtarget->isFP64bit())
78       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
79
80   // Load extented operations for i1 types must be promoted
81   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
82   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
83   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
84
85   // MIPS doesn't have extending float->double load/store
86   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
87   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
88
89   // Used by legalize types to correctly generate the setcc result.
90   // Without this, every float setcc comes with a AND/OR with the result,
91   // we don't want this, since the fpcmp result goes to a flag register,
92   // which is used implicitly by brcond and select operations.
93   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
94
95   // Mips Custom Operations
96   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
97   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
98   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
99   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
100   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
101   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
102   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
103   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
104   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
105   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
106   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
107   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
108
109   setOperationAction(ISD::SDIV, MVT::i32, Expand);
110   setOperationAction(ISD::SREM, MVT::i32, Expand);
111   setOperationAction(ISD::UDIV, MVT::i32, Expand);
112   setOperationAction(ISD::UREM, MVT::i32, Expand);
113
114   // Operations not directly supported by Mips.
115   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
116   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
117   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
118   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
119   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
120   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
121   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
122   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
123   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
124
125   if (!Subtarget->isMips32r2())
126     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
127
128   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
129   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
130   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
131   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Expand);
132   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Expand);
133   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
134   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
135   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
136   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
137   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
138   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
139   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
140   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
141   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
142   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
143   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
144
145   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
146
147   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
148   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
149   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
150
151   // Use the default for now
152   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
153   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
154   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
155
156   if (Subtarget->isSingleFloat())
157     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
158
159   if (!Subtarget->hasSEInReg()) {
160     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
161     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
162   }
163
164   if (!Subtarget->hasBitCount())
165     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
166
167   if (!Subtarget->hasSwap())
168     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
169
170   setTargetDAGCombine(ISD::ADDE);
171   setTargetDAGCombine(ISD::SUBE);
172   setTargetDAGCombine(ISD::SDIVREM);
173   setTargetDAGCombine(ISD::UDIVREM);
174   setTargetDAGCombine(ISD::SETCC);
175
176   setMinFunctionAlignment(2);
177
178   setStackPointerRegisterToSaveRestore(Mips::SP);
179   computeRegisterProperties();
180 }
181
182 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
183   return MVT::i32;
184 }
185
186 // SelectMadd -
187 // Transforms a subgraph in CurDAG if the following pattern is found:
188 //  (addc multLo, Lo0), (adde multHi, Hi0),
189 // where,
190 //  multHi/Lo: product of multiplication
191 //  Lo0: initial value of Lo register
192 //  Hi0: initial value of Hi register
193 // Return true if pattern matching was successful.
194 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
195   // ADDENode's second operand must be a flag output of an ADDC node in order
196   // for the matching to be successful.
197   SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
198
199   if (ADDCNode->getOpcode() != ISD::ADDC)
200     return false;
201
202   SDValue MultHi = ADDENode->getOperand(0);
203   SDValue MultLo = ADDCNode->getOperand(0);
204   SDNode* MultNode = MultHi.getNode();
205   unsigned MultOpc = MultHi.getOpcode();
206
207   // MultHi and MultLo must be generated by the same node,
208   if (MultLo.getNode() != MultNode)
209     return false;
210
211   // and it must be a multiplication.
212   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
213     return false;
214
215   // MultLo amd MultHi must be the first and second output of MultNode
216   // respectively.
217   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
218     return false;
219
220   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
221   // of the values of MultNode, in which case MultNode will be removed in later
222   // phases.
223   // If there exist users other than ADDENode or ADDCNode, this function returns
224   // here, which will result in MultNode being mapped to a single MULT
225   // instruction node rather than a pair of MULT and MADD instructions being
226   // produced.
227   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
228     return false;
229
230   SDValue Chain = CurDAG->getEntryNode();
231   DebugLoc dl = ADDENode->getDebugLoc();
232
233   // create MipsMAdd(u) node
234   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
235
236   SDValue MAdd = CurDAG->getNode(MultOpc, dl,
237                                  MVT::Glue,
238                                  MultNode->getOperand(0),// Factor 0
239                                  MultNode->getOperand(1),// Factor 1
240                                  ADDCNode->getOperand(1),// Lo0
241                                  ADDENode->getOperand(1));// Hi0
242
243   // create CopyFromReg nodes
244   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
245                                               MAdd);
246   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
247                                               Mips::HI, MVT::i32,
248                                               CopyFromLo.getValue(2));
249
250   // replace uses of adde and addc here
251   if (!SDValue(ADDCNode, 0).use_empty())
252     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
253
254   if (!SDValue(ADDENode, 0).use_empty())
255     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
256
257   return true;
258 }
259
260 // SelectMsub -
261 // Transforms a subgraph in CurDAG if the following pattern is found:
262 //  (addc Lo0, multLo), (sube Hi0, multHi),
263 // where,
264 //  multHi/Lo: product of multiplication
265 //  Lo0: initial value of Lo register
266 //  Hi0: initial value of Hi register
267 // Return true if pattern matching was successful.
268 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
269   // SUBENode's second operand must be a flag output of an SUBC node in order
270   // for the matching to be successful.
271   SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
272
273   if (SUBCNode->getOpcode() != ISD::SUBC)
274     return false;
275
276   SDValue MultHi = SUBENode->getOperand(1);
277   SDValue MultLo = SUBCNode->getOperand(1);
278   SDNode* MultNode = MultHi.getNode();
279   unsigned MultOpc = MultHi.getOpcode();
280
281   // MultHi and MultLo must be generated by the same node,
282   if (MultLo.getNode() != MultNode)
283     return false;
284
285   // and it must be a multiplication.
286   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
287     return false;
288
289   // MultLo amd MultHi must be the first and second output of MultNode
290   // respectively.
291   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
292     return false;
293
294   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
295   // of the values of MultNode, in which case MultNode will be removed in later
296   // phases.
297   // If there exist users other than SUBENode or SUBCNode, this function returns
298   // here, which will result in MultNode being mapped to a single MULT
299   // instruction node rather than a pair of MULT and MSUB instructions being
300   // produced.
301   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
302     return false;
303
304   SDValue Chain = CurDAG->getEntryNode();
305   DebugLoc dl = SUBENode->getDebugLoc();
306
307   // create MipsSub(u) node
308   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
309
310   SDValue MSub = CurDAG->getNode(MultOpc, dl,
311                                  MVT::Glue,
312                                  MultNode->getOperand(0),// Factor 0
313                                  MultNode->getOperand(1),// Factor 1
314                                  SUBCNode->getOperand(0),// Lo0
315                                  SUBENode->getOperand(0));// Hi0
316
317   // create CopyFromReg nodes
318   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
319                                               MSub);
320   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
321                                               Mips::HI, MVT::i32,
322                                               CopyFromLo.getValue(2));
323
324   // replace uses of sube and subc here
325   if (!SDValue(SUBCNode, 0).use_empty())
326     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
327
328   if (!SDValue(SUBENode, 0).use_empty())
329     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
330
331   return true;
332 }
333
334 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
335                                   TargetLowering::DAGCombinerInfo &DCI,
336                                   const MipsSubtarget* Subtarget) {
337   if (DCI.isBeforeLegalize())
338     return SDValue();
339
340   if (Subtarget->isMips32() && SelectMadd(N, &DAG))
341     return SDValue(N, 0);
342
343   return SDValue();
344 }
345
346 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
347                                   TargetLowering::DAGCombinerInfo &DCI,
348                                   const MipsSubtarget* Subtarget) {
349   if (DCI.isBeforeLegalize())
350     return SDValue();
351
352   if (Subtarget->isMips32() && SelectMsub(N, &DAG))
353     return SDValue(N, 0);
354
355   return SDValue();
356 }
357
358 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
359                                     TargetLowering::DAGCombinerInfo &DCI,
360                                     const MipsSubtarget* Subtarget) {
361   if (DCI.isBeforeLegalizeOps())
362     return SDValue();
363
364   unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
365                                                   MipsISD::DivRemU;
366   DebugLoc dl = N->getDebugLoc();
367
368   SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
369                                N->getOperand(0), N->getOperand(1));
370   SDValue InChain = DAG.getEntryNode();
371   SDValue InGlue = DivRem;
372
373   // insert MFLO
374   if (N->hasAnyUseOfValue(0)) {
375     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, Mips::LO, MVT::i32,
376                                             InGlue);
377     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
378     InChain = CopyFromLo.getValue(1);
379     InGlue = CopyFromLo.getValue(2);
380   }
381
382   // insert MFHI
383   if (N->hasAnyUseOfValue(1)) {
384     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
385                                             Mips::HI, MVT::i32, InGlue);
386     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
387   }
388
389   return SDValue();
390 }
391
392 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
393   switch (CC) {
394   default: llvm_unreachable("Unknown fp condition code!");
395   case ISD::SETEQ:
396   case ISD::SETOEQ: return Mips::FCOND_OEQ;
397   case ISD::SETUNE: return Mips::FCOND_UNE;
398   case ISD::SETLT:
399   case ISD::SETOLT: return Mips::FCOND_OLT;
400   case ISD::SETGT:
401   case ISD::SETOGT: return Mips::FCOND_OGT;
402   case ISD::SETLE:
403   case ISD::SETOLE: return Mips::FCOND_OLE;
404   case ISD::SETGE:
405   case ISD::SETOGE: return Mips::FCOND_OGE;
406   case ISD::SETULT: return Mips::FCOND_ULT;
407   case ISD::SETULE: return Mips::FCOND_ULE;
408   case ISD::SETUGT: return Mips::FCOND_UGT;
409   case ISD::SETUGE: return Mips::FCOND_UGE;
410   case ISD::SETUO:  return Mips::FCOND_UN;
411   case ISD::SETO:   return Mips::FCOND_OR;
412   case ISD::SETNE:
413   case ISD::SETONE: return Mips::FCOND_ONE;
414   case ISD::SETUEQ: return Mips::FCOND_UEQ;
415   }
416 }
417
418
419 // Returns true if condition code has to be inverted.
420 static bool InvertFPCondCode(Mips::CondCode CC) {
421   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
422     return false;
423
424   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
425     return true;
426
427   assert(false && "Illegal Condition Code");
428   return false;
429 }
430
431 // Creates and returns an FPCmp node from a setcc node.
432 // Returns Op if setcc is not a floating point comparison.
433 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
434   // must be a SETCC node
435   if (Op.getOpcode() != ISD::SETCC)
436     return Op;
437
438   SDValue LHS = Op.getOperand(0);
439
440   if (!LHS.getValueType().isFloatingPoint())
441     return Op;
442
443   SDValue RHS = Op.getOperand(1);
444   DebugLoc dl = Op.getDebugLoc();
445
446   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
447   // node if necessary.
448   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
449
450   return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
451                      DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
452 }
453
454 // Creates and returns a CMovFPT/F node.
455 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
456                             SDValue False, DebugLoc DL) {
457   bool invert = InvertFPCondCode((Mips::CondCode)
458                                  cast<ConstantSDNode>(Cond.getOperand(2))
459                                  ->getSExtValue());
460
461   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
462                      True.getValueType(), True, False, Cond);
463 }
464
465 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
466                                    TargetLowering::DAGCombinerInfo &DCI,
467                                    const MipsSubtarget* Subtarget) {
468   if (DCI.isBeforeLegalizeOps())
469     return SDValue();
470
471   SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
472
473   if (Cond.getOpcode() != MipsISD::FPCmp)
474     return SDValue();
475
476   SDValue True  = DAG.getConstant(1, MVT::i32);
477   SDValue False = DAG.getConstant(0, MVT::i32);
478
479   return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
480 }
481
482 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
483   const {
484   SelectionDAG &DAG = DCI.DAG;
485   unsigned opc = N->getOpcode();
486
487   switch (opc) {
488   default: break;
489   case ISD::ADDE:
490     return PerformADDECombine(N, DAG, DCI, Subtarget);
491   case ISD::SUBE:
492     return PerformSUBECombine(N, DAG, DCI, Subtarget);
493   case ISD::SDIVREM:
494   case ISD::UDIVREM:
495     return PerformDivRemCombine(N, DAG, DCI, Subtarget);
496   case ISD::SETCC:
497     return PerformSETCCCombine(N, DAG, DCI, Subtarget);
498   }
499
500   return SDValue();
501 }
502
503 SDValue MipsTargetLowering::
504 LowerOperation(SDValue Op, SelectionDAG &DAG) const
505 {
506   switch (Op.getOpcode())
507   {
508     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
509     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
510     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
511     case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
512     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
513     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
514     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
515     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
516     case ISD::SELECT:             return LowerSELECT(Op, DAG);
517     case ISD::VASTART:            return LowerVASTART(Op, DAG);
518   }
519   return SDValue();
520 }
521
522 //===----------------------------------------------------------------------===//
523 //  Lower helper functions
524 //===----------------------------------------------------------------------===//
525
526 // AddLiveIn - This helper function adds the specified physical register to the
527 // MachineFunction as a live in value.  It also creates a corresponding
528 // virtual register for it.
529 static unsigned
530 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
531 {
532   assert(RC->contains(PReg) && "Not the correct regclass!");
533   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
534   MF.getRegInfo().addLiveIn(PReg, VReg);
535   return VReg;
536 }
537
538 // Get fp branch code (not opcode) from condition code.
539 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
540   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
541     return Mips::BRANCH_T;
542
543   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
544     return Mips::BRANCH_F;
545
546   return Mips::BRANCH_INVALID;
547 }
548
549 MachineBasicBlock *
550 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
551                                                 MachineBasicBlock *BB) const {
552   // There is no need to expand CMov instructions if target has
553   // conditional moves.
554   if (Subtarget->hasCondMov())
555     return BB;
556
557   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
558   bool isFPCmp = false;
559   DebugLoc dl = MI->getDebugLoc();
560   unsigned Opc;
561
562   switch (MI->getOpcode()) {
563   default: assert(false && "Unexpected instr type to insert");
564   case Mips::MOVT:
565   case Mips::MOVT_S:
566   case Mips::MOVT_D:
567     isFPCmp = true;
568     Opc = Mips::BC1F;
569     break;
570   case Mips::MOVF:
571   case Mips::MOVF_S:
572   case Mips::MOVF_D:
573     isFPCmp = true;
574     Opc = Mips::BC1T;
575     break;
576   case Mips::MOVZ_I:
577   case Mips::MOVZ_S:
578   case Mips::MOVZ_D:
579     Opc = Mips::BNE;
580     break;
581   case Mips::MOVN_I:
582   case Mips::MOVN_S:
583   case Mips::MOVN_D:
584     Opc = Mips::BEQ;
585     break;
586   }
587
588   // To "insert" a SELECT_CC instruction, we actually have to insert the
589   // diamond control-flow pattern.  The incoming instruction knows the
590   // destination vreg to set, the condition code register to branch on, the
591   // true/false values to select between, and a branch opcode to use.
592   const BasicBlock *LLVM_BB = BB->getBasicBlock();
593   MachineFunction::iterator It = BB;
594   ++It;
595
596   //  thisMBB:
597   //  ...
598   //   TrueVal = ...
599   //   setcc r1, r2, r3
600   //   bNE   r1, r0, copy1MBB
601   //   fallthrough --> copy0MBB
602   MachineBasicBlock *thisMBB  = BB;
603   MachineFunction *F = BB->getParent();
604   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
605   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
606   F->insert(It, copy0MBB);
607   F->insert(It, sinkMBB);
608
609   // Transfer the remainder of BB and its successor edges to sinkMBB.
610   sinkMBB->splice(sinkMBB->begin(), BB,
611                   llvm::next(MachineBasicBlock::iterator(MI)),
612                   BB->end());
613   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
614
615   // Next, add the true and fallthrough blocks as its successors.
616   BB->addSuccessor(copy0MBB);
617   BB->addSuccessor(sinkMBB);
618
619   // Emit the right instruction according to the type of the operands compared
620   if (isFPCmp)
621     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
622   else
623     BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
624       .addReg(Mips::ZERO).addMBB(sinkMBB);
625
626
627   //  copy0MBB:
628   //   %FalseValue = ...
629   //   # fallthrough to sinkMBB
630   BB = copy0MBB;
631
632   // Update machine-CFG edges
633   BB->addSuccessor(sinkMBB);
634
635   //  sinkMBB:
636   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
637   //  ...
638   BB = sinkMBB;
639
640   if (isFPCmp)
641     BuildMI(*BB, BB->begin(), dl,
642             TII->get(Mips::PHI), MI->getOperand(0).getReg())
643       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
644       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
645   else
646     BuildMI(*BB, BB->begin(), dl,
647             TII->get(Mips::PHI), MI->getOperand(0).getReg())
648       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
649       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
650
651   MI->eraseFromParent();   // The pseudo instruction is gone now.
652   return BB;
653 }
654
655 //===----------------------------------------------------------------------===//
656 //  Misc Lower Operation implementation
657 //===----------------------------------------------------------------------===//
658
659 SDValue MipsTargetLowering::
660 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const
661 {
662   if (!Subtarget->isMips1())
663     return Op;
664
665   MachineFunction &MF = DAG.getMachineFunction();
666   unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
667
668   SDValue Chain = DAG.getEntryNode();
669   DebugLoc dl = Op.getDebugLoc();
670   SDValue Src = Op.getOperand(0);
671
672   // Set the condition register
673   SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
674   CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
675   CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
676
677   SDValue Cst = DAG.getConstant(3, MVT::i32);
678   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
679   Cst = DAG.getConstant(2, MVT::i32);
680   SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
681
682   SDValue InFlag(0, 0);
683   CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
684
685   // Emit the round instruction and bit convert to integer
686   SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
687                               Src, CondReg.getValue(1));
688   SDValue BitCvt = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Trunc);
689   return BitCvt;
690 }
691
692 SDValue MipsTargetLowering::
693 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
694 {
695   unsigned StackAlignment =
696     getTargetMachine().getFrameLowering()->getStackAlignment();
697   assert(StackAlignment >=
698          cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
699          "Cannot lower if the alignment of the allocated space is larger than \
700           that of the stack.");
701
702   SDValue Chain = Op.getOperand(0);
703   SDValue Size = Op.getOperand(1);
704   DebugLoc dl = Op.getDebugLoc();
705
706   // Get a reference from Mips stack pointer
707   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
708
709   // Subtract the dynamic size from the actual stack size to
710   // obtain the new stack size.
711   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
712
713   // The Sub result contains the new stack start address, so it
714   // must be placed in the stack pointer register.
715   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub,
716                            SDValue());
717   SDValue NewSP = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32,
718                                      Chain.getValue(1));
719   
720   // Align the allocated space.
721   MachineFunction &MF = DAG.getMachineFunction();
722   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
723   unsigned SPOffset = (MipsFI->getMaxCallFrameSize() + StackAlignment - 1) /
724                       StackAlignment * StackAlignment;
725   SDValue AllocPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
726                                  DAG.getConstant(SPOffset, MVT::i32));
727
728   // This node always has two return values: a new stack pointer
729   // value and a chain
730   SDValue Ops[2] = { AllocPtr, NewSP.getValue(1) };
731   return DAG.getMergeValues(Ops, 2, dl);
732 }
733
734 SDValue MipsTargetLowering::
735 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
736 {
737   // The first operand is the chain, the second is the condition, the third is
738   // the block to branch to if the condition is true.
739   SDValue Chain = Op.getOperand(0);
740   SDValue Dest = Op.getOperand(2);
741   DebugLoc dl = Op.getDebugLoc();
742
743   SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
744
745   // Return if flag is not set by a floating point comparison.
746   if (CondRes.getOpcode() != MipsISD::FPCmp)
747     return Op;
748
749   SDValue CCNode  = CondRes.getOperand(2);
750   Mips::CondCode CC =
751     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
752   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
753
754   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
755                      Dest, CondRes);
756 }
757
758 SDValue MipsTargetLowering::
759 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
760 {
761   SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
762
763   // Return if flag is not set by a floating point comparison.
764   if (Cond.getOpcode() != MipsISD::FPCmp)
765     return Op;
766
767   return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
768                       Op.getDebugLoc());
769 }
770
771 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
772                                                SelectionDAG &DAG) const {
773   // FIXME there isn't actually debug info here
774   DebugLoc dl = Op.getDebugLoc();
775   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
776
777   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
778     SDVTList VTs = DAG.getVTList(MVT::i32);
779
780     MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
781
782     // %gp_rel relocation
783     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
784       SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
785                                               MipsII::MO_GPREL);
786       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
787       SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
788       return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
789     }
790     // %hi/%lo relocation
791     SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
792                                               MipsII::MO_ABS_HI);
793     SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
794                                               MipsII::MO_ABS_LO);
795     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
796     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
797     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
798   } else {
799     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
800                                             MipsII::MO_GOT);
801     SDValue ResNode = DAG.getLoad(MVT::i32, dl,
802                                   DAG.getEntryNode(), GA, MachinePointerInfo(),
803                                   false, false, 0);
804     // On functions and global targets not internal linked only
805     // a load from got/GP is necessary for PIC to work.
806     if (!GV->hasInternalLinkage() &&
807         (!GV->hasLocalLinkage() || isa<Function>(GV)))
808       return ResNode;
809     SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
810                                               MipsII::MO_ABS_LO);
811     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
812     return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
813   }
814
815   llvm_unreachable("Dont know how to handle GlobalAddress");
816   return SDValue(0,0);
817 }
818
819 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
820                                               SelectionDAG &DAG) const {
821   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
822   // FIXME there isn't actually debug info here
823   DebugLoc dl = Op.getDebugLoc();
824
825   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
826     // %hi/%lo relocation
827     SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
828                                        MipsII::MO_ABS_HI);
829     SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
830                                        MipsII::MO_ABS_LO);
831     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
832     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
833     return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
834   }
835
836   SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
837                                             MipsII::MO_GOT);
838   SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
839                                            MipsII::MO_ABS_LO);
840   SDValue Load = DAG.getLoad(MVT::i32, dl,
841                              DAG.getEntryNode(), BAGOTOffset,
842                              MachinePointerInfo(), false, false, 0);
843   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
844   return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
845 }
846
847 SDValue MipsTargetLowering::
848 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
849 {
850   llvm_unreachable("TLS not implemented for MIPS.");
851   return SDValue(); // Not reached
852 }
853
854 SDValue MipsTargetLowering::
855 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
856 {
857   SDValue ResNode;
858   SDValue HiPart;
859   // FIXME there isn't actually debug info here
860   DebugLoc dl = Op.getDebugLoc();
861   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
862   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
863
864   EVT PtrVT = Op.getValueType();
865   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
866
867   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
868
869   if (!IsPIC) {
870     SDValue Ops[] = { JTI };
871     HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
872   } else // Emit Load from Global Pointer
873     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
874                          MachinePointerInfo(),
875                          false, false, 0);
876
877   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
878                                          MipsII::MO_ABS_LO);
879   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
880   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
881
882   return ResNode;
883 }
884
885 SDValue MipsTargetLowering::
886 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
887 {
888   SDValue ResNode;
889   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
890   const Constant *C = N->getConstVal();
891   // FIXME there isn't actually debug info here
892   DebugLoc dl = Op.getDebugLoc();
893
894   // gp_rel relocation
895   // FIXME: we should reference the constant pool using small data sections,
896   // but the asm printer currently doesn't support this feature without
897   // hacking it. This feature should come soon so we can uncomment the
898   // stuff below.
899   //if (IsInSmallSection(C->getType())) {
900   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
901   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
902   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
903
904   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
905     SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
906                                              N->getOffset(), MipsII::MO_ABS_HI);
907     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
908                                              N->getOffset(), MipsII::MO_ABS_LO);
909     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
910     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
911     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
912   } else {
913     SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
914                                            N->getOffset(), MipsII::MO_GOT);
915     SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
916                                CP, MachinePointerInfo::getConstantPool(),
917                                false, false, 0);
918     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
919                                              N->getOffset(), MipsII::MO_ABS_LO);
920     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
921     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
922   }
923
924   return ResNode;
925 }
926
927 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
928   MachineFunction &MF = DAG.getMachineFunction();
929   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
930
931   DebugLoc dl = Op.getDebugLoc();
932   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
933                                  getPointerTy());
934
935   // vastart just stores the address of the VarArgsFrameIndex slot into the
936   // memory location argument.
937   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
938   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
939                       MachinePointerInfo(SV),
940                       false, false, 0);
941 }
942
943 //===----------------------------------------------------------------------===//
944 //                      Calling Convention Implementation
945 //===----------------------------------------------------------------------===//
946
947 #include "MipsGenCallingConv.inc"
948
949 //===----------------------------------------------------------------------===//
950 // TODO: Implement a generic logic using tblgen that can support this.
951 // Mips O32 ABI rules:
952 // ---
953 // i32 - Passed in A0, A1, A2, A3 and stack
954 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
955 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
956 // f64 - Only passed in two aliased f32 registers if no int reg has been used
957 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
958 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
959 //       go to stack.
960 //
961 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
962 //===----------------------------------------------------------------------===//
963
964 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
965                        MVT LocVT, CCValAssign::LocInfo LocInfo,
966                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
967
968   static const unsigned IntRegsSize=4, FloatRegsSize=2;
969
970   static const unsigned IntRegs[] = {
971       Mips::A0, Mips::A1, Mips::A2, Mips::A3
972   };
973   static const unsigned F32Regs[] = {
974       Mips::F12, Mips::F14
975   };
976   static const unsigned F64Regs[] = {
977       Mips::D6, Mips::D7
978   };
979
980   // ByVal Args
981   if (ArgFlags.isByVal()) {
982     State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
983                       1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
984     unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
985     for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
986          r < std::min(IntRegsSize, NextReg); ++r)
987       State.AllocateReg(IntRegs[r]);
988     return false;
989   }
990
991   // Promote i8 and i16
992   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
993     LocVT = MVT::i32;
994     if (ArgFlags.isSExt())
995       LocInfo = CCValAssign::SExt;
996     else if (ArgFlags.isZExt())
997       LocInfo = CCValAssign::ZExt;
998     else
999       LocInfo = CCValAssign::AExt;
1000   }
1001
1002   unsigned Reg;
1003
1004   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1005   // is true: function is vararg, argument is 3rd or higher, there is previous
1006   // argument which is not f32 or f64.
1007   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1008       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1009   unsigned OrigAlign = ArgFlags.getOrigAlign();
1010   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1011
1012   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1013     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1014     // If this is the first part of an i64 arg,
1015     // the allocated register must be either A0 or A2.
1016     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1017       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1018     LocVT = MVT::i32;
1019   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1020     // Allocate int register and shadow next int register. If first
1021     // available register is Mips::A1 or Mips::A3, shadow it too.
1022     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1023     if (Reg == Mips::A1 || Reg == Mips::A3)
1024       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1025     State.AllocateReg(IntRegs, IntRegsSize);
1026     LocVT = MVT::i32;
1027   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1028     // we are guaranteed to find an available float register
1029     if (ValVT == MVT::f32) {
1030       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1031       // Shadow int register
1032       State.AllocateReg(IntRegs, IntRegsSize);
1033     } else {
1034       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1035       // Shadow int registers
1036       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1037       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1038         State.AllocateReg(IntRegs, IntRegsSize);
1039       State.AllocateReg(IntRegs, IntRegsSize);
1040     }
1041   } else
1042     llvm_unreachable("Cannot handle this ValVT.");
1043
1044   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1045   unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1046
1047   if (!Reg)
1048     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1049   else
1050     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1051
1052   return false; // CC must always match
1053 }
1054
1055 //===----------------------------------------------------------------------===//
1056 //                  Call Calling Convention Implementation
1057 //===----------------------------------------------------------------------===//
1058
1059 static const unsigned O32IntRegsSize = 4;
1060
1061 static const unsigned O32IntRegs[] = {
1062   Mips::A0, Mips::A1, Mips::A2, Mips::A3
1063 };
1064
1065 // Write ByVal Arg to arg registers and stack.
1066 static void
1067 WriteByValArg(SDValue& Chain, DebugLoc dl,
1068               SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1069               SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1070               MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1071               const CCValAssign &VA, const ISD::ArgFlagsTy& Flags, MVT PtrType) {
1072   unsigned FirstWord = VA.getLocMemOffset() / 4;
1073   unsigned NumWords = (Flags.getByValSize() + 3) / 4;
1074   unsigned LastWord = FirstWord + NumWords;
1075   unsigned CurWord;
1076
1077   // copy the first 4 words of byval arg to registers A0 - A3
1078   for (CurWord = FirstWord; CurWord < std::min(LastWord, O32IntRegsSize);
1079        ++CurWord) {
1080     SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1081                                   DAG.getConstant((CurWord - FirstWord) * 4,
1082                                                   MVT::i32));
1083     SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1084                                   MachinePointerInfo(),
1085                                   false, false, 0);
1086     MemOpChains.push_back(LoadVal.getValue(1));
1087     unsigned DstReg = O32IntRegs[CurWord];
1088     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1089   }
1090
1091   // copy remaining part of byval arg to stack.
1092   if (CurWord < LastWord) {
1093     unsigned SizeInBytes = (LastWord - CurWord) * 4; 
1094     SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1095                               DAG.getConstant((CurWord - FirstWord) * 4,
1096                                               MVT::i32));
1097     LastFI = MFI->CreateFixedObject(SizeInBytes, CurWord * 4, true);
1098     SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
1099     Chain = DAG.getMemcpy(Chain, dl, Dst, Src,
1100                           DAG.getConstant(SizeInBytes, MVT::i32),
1101                           /*Align*/4,
1102                           /*isVolatile=*/false, /*AlwaysInline=*/false,
1103                           MachinePointerInfo(0), MachinePointerInfo(0));
1104     MemOpChains.push_back(Chain);
1105   }
1106 }
1107
1108 /// LowerCall - functions arguments are copied from virtual regs to
1109 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1110 /// TODO: isTailCall.
1111 SDValue
1112 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1113                               CallingConv::ID CallConv, bool isVarArg,
1114                               bool &isTailCall,
1115                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1116                               const SmallVectorImpl<SDValue> &OutVals,
1117                               const SmallVectorImpl<ISD::InputArg> &Ins,
1118                               DebugLoc dl, SelectionDAG &DAG,
1119                               SmallVectorImpl<SDValue> &InVals) const {
1120   // MIPs target does not yet support tail call optimization.
1121   isTailCall = false;
1122
1123   MachineFunction &MF = DAG.getMachineFunction();
1124   MachineFrameInfo *MFI = MF.getFrameInfo();
1125   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
1126   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1127   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1128
1129   // Analyze operands of the call, assigning locations to each operand.
1130   SmallVector<CCValAssign, 16> ArgLocs;
1131   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1132                  *DAG.getContext());
1133
1134   if (Subtarget->isABI_O32())
1135     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
1136   else
1137     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1138
1139   // Get a count of how many bytes are to be pushed on the stack.
1140   unsigned NumBytes = CCInfo.getNextStackOffset();
1141   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1142
1143   // With EABI is it possible to have 16 args on registers.
1144   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1145   SmallVector<SDValue, 8> MemOpChains;
1146
1147   MipsFI->setHasCall();
1148
1149   // Create GP frame object if this is the first call. 
1150   // SPOffset will be updated after call frame size is known.
1151   if (IsPIC && !MipsFI->getGPFI())
1152     MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
1153
1154   int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0; 
1155
1156   // Walk the register/memloc assignments, inserting copies/loads.
1157   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1158     SDValue Arg = OutVals[i];
1159     CCValAssign &VA = ArgLocs[i];
1160
1161     // Promote the value if needed.
1162     switch (VA.getLocInfo()) {
1163     default: llvm_unreachable("Unknown loc info!");
1164     case CCValAssign::Full:
1165       if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1166         if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1167           Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1168         if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1169           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1170                                    Arg, DAG.getConstant(0, MVT::i32));
1171           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1172                                    Arg, DAG.getConstant(1, MVT::i32));
1173           if (!Subtarget->isLittle())
1174             std::swap(Lo, Hi);
1175           RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1176           RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1177           continue;
1178         }
1179       }
1180       break;
1181     case CCValAssign::SExt:
1182       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1183       break;
1184     case CCValAssign::ZExt:
1185       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1186       break;
1187     case CCValAssign::AExt:
1188       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1189       break;
1190     }
1191
1192     // Arguments that can be passed on register must be kept at
1193     // RegsToPass vector
1194     if (VA.isRegLoc()) {
1195       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1196       continue;
1197     }
1198
1199     // Register can't get to this point...
1200     assert(VA.isMemLoc());
1201
1202     // ByVal Arg. 
1203     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1204     if (Flags.isByVal()) {
1205       assert(Subtarget->isABI_O32() &&
1206              "No support for ByVal args by ABIs other than O32 yet.");
1207       assert(Flags.getByValSize() &&
1208              "ByVal args of size 0 should have been ignored by front-end.");
1209       WriteByValArg(Chain, dl, RegsToPass, MemOpChains, LastFI, MFI, DAG, Arg,
1210                     VA, Flags, getPointerTy());
1211       continue;
1212     }
1213
1214     // Create the frame index object for this incoming parameter
1215     // This guarantees that when allocating Local Area the firsts
1216     // 16 bytes which are alwayes reserved won't be overwritten
1217     // if O32 ABI is used. For EABI the first address is zero.
1218     LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8, 
1219                                     VA.getLocMemOffset(), true);
1220     SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
1221
1222     // emit ISD::STORE whichs stores the
1223     // parameter value to a stack Location
1224     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1225                                        MachinePointerInfo(),
1226                                        false, false, 0));
1227   }
1228
1229   // Transform all store nodes into one single node because all store
1230   // nodes are independent of each other.
1231   if (!MemOpChains.empty())
1232     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1233                         &MemOpChains[0], MemOpChains.size());
1234
1235   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1236   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1237   // node so that legalize doesn't hack it.
1238   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1239   bool LoadSymAddr = false;
1240   SDValue CalleeLo;
1241
1242   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1243     if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
1244       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1245                                           getPointerTy(), 0,MipsII:: MO_GOT);
1246       CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
1247                                             0, MipsII::MO_ABS_LO);
1248     } else {
1249       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1250                                           getPointerTy(), 0, OpFlag);
1251     }
1252
1253     LoadSymAddr = true;
1254   }
1255   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1256     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1257                                 getPointerTy(), OpFlag);
1258     LoadSymAddr = true;
1259   }
1260
1261   SDValue InFlag;
1262
1263   // Create nodes that load address of callee and copy it to T9
1264   if (IsPIC) {
1265     if (LoadSymAddr) {
1266       // Load callee address
1267       SDValue LoadValue = DAG.getLoad(MVT::i32, dl, Chain, Callee,
1268                                       MachinePointerInfo::getGOT(),
1269                                       false, false, 0);
1270
1271       // Use GOT+LO if callee has internal linkage.
1272       if (CalleeLo.getNode()) {
1273         SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
1274         Callee = DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
1275       } else
1276         Callee = LoadValue;
1277
1278       // Use chain output from LoadValue 
1279       Chain = LoadValue.getValue(1);
1280     }
1281
1282     // copy to T9
1283     Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
1284     InFlag = Chain.getValue(1);
1285     Callee = DAG.getRegister(Mips::T9, MVT::i32);
1286   }
1287
1288   // Build a sequence of copy-to-reg nodes chained together with token
1289   // chain and flag operands which copy the outgoing args into registers.
1290   // The InFlag in necessary since all emitted instructions must be
1291   // stuck together.
1292   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1293     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1294                              RegsToPass[i].second, InFlag);
1295     InFlag = Chain.getValue(1);
1296   }
1297
1298   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1299   //             = Chain, Callee, Reg#1, Reg#2, ...
1300   //
1301   // Returns a chain & a flag for retval copy to use.
1302   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1303   SmallVector<SDValue, 8> Ops;
1304   Ops.push_back(Chain);
1305   Ops.push_back(Callee);
1306
1307   // Add argument registers to the end of the list so that they are
1308   // known live into the call.
1309   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1310     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1311                                   RegsToPass[i].second.getValueType()));
1312
1313   if (InFlag.getNode())
1314     Ops.push_back(InFlag);
1315
1316   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1317   InFlag = Chain.getValue(1);
1318
1319   // Create a stack location to hold GP when PIC is used. This stack
1320   // location is used on function prologue to save GP and also after all
1321   // emitted CALL's to restore GP.
1322   if (IsPIC) {
1323     // Function can have an arbitrary number of calls, so
1324     // hold the LastArgStackLoc with the biggest offset.
1325     int MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
1326     unsigned NextStackOffset = CCInfo.getNextStackOffset();
1327
1328     // For O32, a minimum of four words (16 bytes) of argument space is
1329     // allocated.
1330     if (Subtarget->isABI_O32())
1331       NextStackOffset = std::max(NextStackOffset, (unsigned)16);
1332
1333     if (MaxCallFrameSize < (int)NextStackOffset) {
1334       MipsFI->setMaxCallFrameSize(NextStackOffset);
1335
1336       // $gp restore slot must be aligned.
1337       unsigned StackAlignment = TFL->getStackAlignment();
1338       NextStackOffset = (NextStackOffset + StackAlignment - 1) / 
1339                         StackAlignment * StackAlignment;
1340       int GPFI = MipsFI->getGPFI();
1341       MFI->setObjectOffset(GPFI, NextStackOffset);
1342     }
1343   }
1344
1345   // Extend range of indices of frame objects for outgoing arguments that were
1346   // created during this function call. Skip this step if no such objects were
1347   // created.
1348   if (LastFI)
1349     MipsFI->extendOutArgFIRange(FirstFI, LastFI);
1350
1351   // Create the CALLSEQ_END node.
1352   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1353                              DAG.getIntPtrConstant(0, true), InFlag);
1354   InFlag = Chain.getValue(1);
1355
1356   // Handle result values, copying them out of physregs into vregs that we
1357   // return.
1358   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1359                          Ins, dl, DAG, InVals);
1360 }
1361
1362 /// LowerCallResult - Lower the result values of a call into the
1363 /// appropriate copies out of appropriate physical registers.
1364 SDValue
1365 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1366                                     CallingConv::ID CallConv, bool isVarArg,
1367                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1368                                     DebugLoc dl, SelectionDAG &DAG,
1369                                     SmallVectorImpl<SDValue> &InVals) const {
1370
1371   // Assign locations to each value returned by this call.
1372   SmallVector<CCValAssign, 16> RVLocs;
1373   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1374                  RVLocs, *DAG.getContext());
1375
1376   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1377
1378   // Copy all of the result registers out of their specified physreg.
1379   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1380     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1381                                RVLocs[i].getValVT(), InFlag).getValue(1);
1382     InFlag = Chain.getValue(2);
1383     InVals.push_back(Chain.getValue(0));
1384   }
1385
1386   return Chain;
1387 }
1388
1389 //===----------------------------------------------------------------------===//
1390 //             Formal Arguments Calling Convention Implementation
1391 //===----------------------------------------------------------------------===//
1392 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
1393                          std::vector<SDValue>& OutChains,
1394                          SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
1395                          const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
1396   unsigned LocMem = VA.getLocMemOffset();
1397   unsigned FirstWord = LocMem / 4;
1398
1399   // copy register A0 - A3 to frame object
1400   for (unsigned i = 0; i < NumWords; ++i) {
1401     unsigned CurWord = FirstWord + i;
1402     if (CurWord >= O32IntRegsSize)
1403       break;
1404
1405     unsigned SrcReg = O32IntRegs[CurWord];
1406     unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
1407     SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
1408                                    DAG.getConstant(i * 4, MVT::i32));
1409     SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
1410                                  StorePtr, MachinePointerInfo(), false,
1411                                  false, 0);
1412     OutChains.push_back(Store);
1413   }
1414 }
1415
1416 /// LowerFormalArguments - transform physical registers into virtual registers
1417 /// and generate load operations for arguments places on the stack.
1418 SDValue
1419 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
1420                                          CallingConv::ID CallConv,
1421                                          bool isVarArg,
1422                                          const SmallVectorImpl<ISD::InputArg>
1423                                          &Ins,
1424                                          DebugLoc dl, SelectionDAG &DAG,
1425                                          SmallVectorImpl<SDValue> &InVals)
1426                                           const {
1427
1428   MachineFunction &MF = DAG.getMachineFunction();
1429   MachineFrameInfo *MFI = MF.getFrameInfo();
1430   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1431
1432   MipsFI->setVarArgsFrameIndex(0);
1433
1434   // Used with vargs to acumulate store chains.
1435   std::vector<SDValue> OutChains;
1436
1437   // Assign locations to all of the incoming arguments.
1438   SmallVector<CCValAssign, 16> ArgLocs;
1439   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1440                  ArgLocs, *DAG.getContext());
1441
1442   if (Subtarget->isABI_O32())
1443     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
1444   else
1445     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
1446
1447   int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
1448
1449   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1450     CCValAssign &VA = ArgLocs[i];
1451
1452     // Arguments stored on registers
1453     if (VA.isRegLoc()) {
1454       EVT RegVT = VA.getLocVT();
1455       unsigned ArgReg = VA.getLocReg();
1456       TargetRegisterClass *RC = 0;
1457
1458       if (RegVT == MVT::i32)
1459         RC = Mips::CPURegsRegisterClass;
1460       else if (RegVT == MVT::f32)
1461         RC = Mips::FGR32RegisterClass;
1462       else if (RegVT == MVT::f64) {
1463         if (!Subtarget->isSingleFloat())
1464           RC = Mips::AFGR64RegisterClass;
1465       } else
1466         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
1467
1468       // Transform the arguments stored on
1469       // physical registers into virtual ones
1470       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
1471       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1472
1473       // If this is an 8 or 16-bit value, it has been passed promoted
1474       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1475       // truncate to the right size.
1476       if (VA.getLocInfo() != CCValAssign::Full) {
1477         unsigned Opcode = 0;
1478         if (VA.getLocInfo() == CCValAssign::SExt)
1479           Opcode = ISD::AssertSext;
1480         else if (VA.getLocInfo() == CCValAssign::ZExt)
1481           Opcode = ISD::AssertZext;
1482         if (Opcode)
1483           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
1484                                  DAG.getValueType(VA.getValVT()));
1485         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1486       }
1487
1488       // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
1489       if (Subtarget->isABI_O32()) {
1490         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
1491           ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1492         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
1493           unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
1494                                     VA.getLocReg()+1, RC);
1495           SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
1496           if (!Subtarget->isLittle())
1497             std::swap(ArgValue, ArgValue2);
1498           ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
1499                                  ArgValue, ArgValue2);
1500         }
1501       }
1502
1503       InVals.push_back(ArgValue);
1504     } else { // VA.isRegLoc()
1505
1506       // sanity check
1507       assert(VA.isMemLoc());
1508
1509       ISD::ArgFlagsTy Flags = Ins[i].Flags;
1510
1511       if (Flags.isByVal()) {
1512         assert(Subtarget->isABI_O32() &&
1513                "No support for ByVal args by ABIs other than O32 yet.");
1514         assert(Flags.getByValSize() &&
1515                "ByVal args of size 0 should have been ignored by front-end.");
1516         unsigned NumWords = (Flags.getByValSize() + 3) / 4;
1517         LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
1518                                         true);
1519         SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
1520         InVals.push_back(FIN);
1521         ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
1522
1523         continue;
1524       }
1525
1526       // The stack pointer offset is relative to the caller stack frame.
1527       // Since the real stack size is unknown here, a negative SPOffset
1528       // is used so there's a way to adjust these offsets when the stack
1529       // size get known (on EliminateFrameIndex). A dummy SPOffset is
1530       // used instead of a direct negative address (which is recorded to
1531       // be used on emitPrologue) to avoid mis-calc of the first stack
1532       // offset on PEI::calculateFrameObjectOffsets.
1533       LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1534                                       VA.getLocMemOffset(), true);
1535
1536       // Create load nodes to retrieve arguments from the stack
1537       SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
1538       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1539                                    MachinePointerInfo::getFixedStack(LastFI),
1540                                    false, false, 0));
1541     }
1542   }
1543
1544   // The mips ABIs for returning structs by value requires that we copy
1545   // the sret argument into $v0 for the return. Save the argument into
1546   // a virtual register so that we can access it from the return points.
1547   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1548     unsigned Reg = MipsFI->getSRetReturnReg();
1549     if (!Reg) {
1550       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1551       MipsFI->setSRetReturnReg(Reg);
1552     }
1553     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1554     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1555   }
1556
1557   // To meet ABI, when VARARGS are passed on registers, the registers
1558   // must have their values written to the caller stack frame. If the last
1559   // argument was placed in the stack, there's no need to save any register.
1560   if (isVarArg && Subtarget->isABI_O32()) {
1561     // Record the frame index of the first variable argument
1562     // which is a value necessary to VASTART.    
1563     unsigned NextStackOffset = CCInfo.getNextStackOffset();
1564     assert(NextStackOffset % 4 == 0 &&
1565            "NextStackOffset must be aligned to 4-byte boundaries.");
1566     LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
1567     MipsFI->setVarArgsFrameIndex(LastFI);
1568     
1569    // Copy variable arguments passed in registers to stack.
1570     for (; NextStackOffset < 16; NextStackOffset += 4) {
1571       TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
1572       unsigned Idx = NextStackOffset / 4;
1573       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), O32IntRegs[Idx], RC);
1574       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
1575       LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
1576       SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
1577       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
1578                                        MachinePointerInfo(),
1579                                        false, false, 0));
1580     }
1581   }
1582
1583   MipsFI->setLastInArgFI(LastFI);
1584
1585   // All stores are grouped in one node to allow the matching between
1586   // the size of Ins and InVals. This only happens when on varg functions
1587   if (!OutChains.empty()) {
1588     OutChains.push_back(Chain);
1589     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1590                         &OutChains[0], OutChains.size());
1591   }
1592
1593   return Chain;
1594 }
1595
1596 //===----------------------------------------------------------------------===//
1597 //               Return Value Calling Convention Implementation
1598 //===----------------------------------------------------------------------===//
1599
1600 SDValue
1601 MipsTargetLowering::LowerReturn(SDValue Chain,
1602                                 CallingConv::ID CallConv, bool isVarArg,
1603                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
1604                                 const SmallVectorImpl<SDValue> &OutVals,
1605                                 DebugLoc dl, SelectionDAG &DAG) const {
1606
1607   // CCValAssign - represent the assignment of
1608   // the return value to a location
1609   SmallVector<CCValAssign, 16> RVLocs;
1610
1611   // CCState - Info about the registers and stack slot.
1612   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1613                  RVLocs, *DAG.getContext());
1614
1615   // Analize return values.
1616   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1617
1618   // If this is the first return lowered for this function, add
1619   // the regs to the liveout set for the function.
1620   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1621     for (unsigned i = 0; i != RVLocs.size(); ++i)
1622       if (RVLocs[i].isRegLoc())
1623         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1624   }
1625
1626   SDValue Flag;
1627
1628   // Copy the result values into the output registers.
1629   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1630     CCValAssign &VA = RVLocs[i];
1631     assert(VA.isRegLoc() && "Can only return in registers!");
1632
1633     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1634                              OutVals[i], Flag);
1635
1636     // guarantee that all emitted copies are
1637     // stuck together, avoiding something bad
1638     Flag = Chain.getValue(1);
1639   }
1640
1641   // The mips ABIs for returning structs by value requires that we copy
1642   // the sret argument into $v0 for the return. We saved the argument into
1643   // a virtual register in the entry block, so now we copy the value out
1644   // and into $v0.
1645   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1646     MachineFunction &MF      = DAG.getMachineFunction();
1647     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1648     unsigned Reg = MipsFI->getSRetReturnReg();
1649
1650     if (!Reg)
1651       llvm_unreachable("sret virtual register not created in the entry block");
1652     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1653
1654     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1655     Flag = Chain.getValue(1);
1656   }
1657
1658   // Return on Mips is always a "jr $ra"
1659   if (Flag.getNode())
1660     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1661                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1662   else // Return Void
1663     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1664                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
1665 }
1666
1667 //===----------------------------------------------------------------------===//
1668 //                           Mips Inline Assembly Support
1669 //===----------------------------------------------------------------------===//
1670
1671 /// getConstraintType - Given a constraint letter, return the type of
1672 /// constraint it is for this target.
1673 MipsTargetLowering::ConstraintType MipsTargetLowering::
1674 getConstraintType(const std::string &Constraint) const
1675 {
1676   // Mips specific constrainy
1677   // GCC config/mips/constraints.md
1678   //
1679   // 'd' : An address register. Equivalent to r
1680   //       unless generating MIPS16 code.
1681   // 'y' : Equivalent to r; retained for
1682   //       backwards compatibility.
1683   // 'f' : Floating Point registers.
1684   if (Constraint.size() == 1) {
1685     switch (Constraint[0]) {
1686       default : break;
1687       case 'd':
1688       case 'y':
1689       case 'f':
1690         return C_RegisterClass;
1691         break;
1692     }
1693   }
1694   return TargetLowering::getConstraintType(Constraint);
1695 }
1696
1697 /// Examine constraint type and operand type and determine a weight value.
1698 /// This object must already have been set up with the operand type
1699 /// and the current alternative constraint selected.
1700 TargetLowering::ConstraintWeight
1701 MipsTargetLowering::getSingleConstraintMatchWeight(
1702     AsmOperandInfo &info, const char *constraint) const {
1703   ConstraintWeight weight = CW_Invalid;
1704   Value *CallOperandVal = info.CallOperandVal;
1705     // If we don't have a value, we can't do a match,
1706     // but allow it at the lowest weight.
1707   if (CallOperandVal == NULL)
1708     return CW_Default;
1709   const Type *type = CallOperandVal->getType();
1710   // Look at the constraint type.
1711   switch (*constraint) {
1712   default:
1713     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1714     break;
1715   case 'd':
1716   case 'y':
1717     if (type->isIntegerTy())
1718       weight = CW_Register;
1719     break;
1720   case 'f':
1721     if (type->isFloatTy())
1722       weight = CW_Register;
1723     break;
1724   }
1725   return weight;
1726 }
1727
1728 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1729 /// return a list of registers that can be used to satisfy the constraint.
1730 /// This should only be used for C_RegisterClass constraints.
1731 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1732 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
1733 {
1734   if (Constraint.size() == 1) {
1735     switch (Constraint[0]) {
1736     case 'r':
1737       return std::make_pair(0U, Mips::CPURegsRegisterClass);
1738     case 'f':
1739       if (VT == MVT::f32)
1740         return std::make_pair(0U, Mips::FGR32RegisterClass);
1741       if (VT == MVT::f64)
1742         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1743           return std::make_pair(0U, Mips::AFGR64RegisterClass);
1744     }
1745   }
1746   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1747 }
1748
1749 /// Given a register class constraint, like 'r', if this corresponds directly
1750 /// to an LLVM register class, return a register of 0 and the register class
1751 /// pointer.
1752 std::vector<unsigned> MipsTargetLowering::
1753 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1754                                   EVT VT) const
1755 {
1756   if (Constraint.size() != 1)
1757     return std::vector<unsigned>();
1758
1759   switch (Constraint[0]) {
1760     default : break;
1761     case 'r':
1762     // GCC Mips Constraint Letters
1763     case 'd':
1764     case 'y':
1765       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1766              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1767              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1768              Mips::T8, 0);
1769
1770     case 'f':
1771       if (VT == MVT::f32) {
1772         if (Subtarget->isSingleFloat())
1773           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1774                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1775                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1776                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1777                  Mips::F30, Mips::F31, 0);
1778         else
1779           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1780                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1781                  Mips::F28, Mips::F30, 0);
1782       }
1783
1784       if (VT == MVT::f64)
1785         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1786           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1787                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1788                  Mips::D14, Mips::D15, 0);
1789   }
1790   return std::vector<unsigned>();
1791 }
1792
1793 bool
1794 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1795   // The Mips target isn't yet aware of offsets.
1796   return false;
1797 }
1798
1799 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1800   if (VT != MVT::f32 && VT != MVT::f64)
1801     return false;
1802   if (Imm.isNegZero())
1803     return false;
1804   return Imm.isZero();
1805 }