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