97798c02dcf922d10c2c1e60d652c377f594138a
[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 GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
773                                             MipsII::MO_ABS_HILO);
774     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GA, 1);
775     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
776     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
777
778   } else {
779     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
780                                             MipsII::MO_GOT);
781     SDValue ResNode = DAG.getLoad(MVT::i32, dl,
782                                   DAG.getEntryNode(), GA, MachinePointerInfo(),
783                                   false, false, 0);
784     // On functions and global targets not internal linked only
785     // a load from got/GP is necessary for PIC to work.
786     if (!GV->hasLocalLinkage() || isa<Function>(GV))
787       return ResNode;
788     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
789     return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
790   }
791
792   llvm_unreachable("Dont know how to handle GlobalAddress");
793   return SDValue(0,0);
794 }
795
796 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
797                                               SelectionDAG &DAG) const {
798   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
799     assert(false && "implement LowerBlockAddress for -static");
800     return SDValue(0, 0);
801   }
802   else {
803     // FIXME there isn't actually debug info here
804     DebugLoc dl = Op.getDebugLoc();
805     const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
806     SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
807                                               MipsII::MO_GOT);
808     SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
809                                              MipsII::MO_ABS_HILO);
810     SDValue Load = DAG.getLoad(MVT::i32, dl,
811                                DAG.getEntryNode(), BAGOTOffset,
812                                MachinePointerInfo(), false, false, 0);
813     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
814     return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
815   }
816 }
817
818 SDValue MipsTargetLowering::
819 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
820 {
821   llvm_unreachable("TLS not implemented for MIPS.");
822   return SDValue(); // Not reached
823 }
824
825 SDValue MipsTargetLowering::
826 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
827 {
828   SDValue ResNode;
829   SDValue HiPart;
830   // FIXME there isn't actually debug info here
831   DebugLoc dl = Op.getDebugLoc();
832   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
833   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HILO;
834
835   EVT PtrVT = Op.getValueType();
836   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
837
838   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
839
840   if (!IsPIC) {
841     SDValue Ops[] = { JTI };
842     HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
843   } else // Emit Load from Global Pointer
844     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
845                          MachinePointerInfo(),
846                          false, false, 0);
847
848   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTI);
849   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
850
851   return ResNode;
852 }
853
854 SDValue MipsTargetLowering::
855 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
856 {
857   SDValue ResNode;
858   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
859   const Constant *C = N->getConstVal();
860   // FIXME there isn't actually debug info here
861   DebugLoc dl = Op.getDebugLoc();
862
863   // gp_rel relocation
864   // FIXME: we should reference the constant pool using small data sections,
865   // but the asm printer currently doens't support this feature without
866   // hacking it. This feature should come soon so we can uncomment the
867   // stuff below.
868   //if (IsInSmallSection(C->getType())) {
869   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
870   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
871   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
872
873   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
874     SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
875                                       N->getOffset(), MipsII::MO_ABS_HILO);
876     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CP);
877     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
878     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
879   } else {
880     SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
881                                       N->getOffset(), MipsII::MO_GOT);
882     SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
883                                CP, MachinePointerInfo::getConstantPool(),
884                                false, false, 0);
885     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
886     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
887   }
888
889   return ResNode;
890 }
891
892 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
893   MachineFunction &MF = DAG.getMachineFunction();
894   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
895
896   DebugLoc dl = Op.getDebugLoc();
897   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
898                                  getPointerTy());
899
900   // vastart just stores the address of the VarArgsFrameIndex slot into the
901   // memory location argument.
902   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
903   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
904                       MachinePointerInfo(SV),
905                       false, false, 0);
906 }
907
908 //===----------------------------------------------------------------------===//
909 //                      Calling Convention Implementation
910 //===----------------------------------------------------------------------===//
911
912 #include "MipsGenCallingConv.inc"
913
914 //===----------------------------------------------------------------------===//
915 // TODO: Implement a generic logic using tblgen that can support this.
916 // Mips O32 ABI rules:
917 // ---
918 // i32 - Passed in A0, A1, A2, A3 and stack
919 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
920 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
921 // f64 - Only passed in two aliased f32 registers if no int reg has been used
922 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
923 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
924 //       go to stack.
925 //===----------------------------------------------------------------------===//
926
927 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
928                        MVT LocVT, CCValAssign::LocInfo LocInfo,
929                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
930
931   static const unsigned IntRegsSize=4, FloatRegsSize=2;
932
933   static const unsigned IntRegs[] = {
934       Mips::A0, Mips::A1, Mips::A2, Mips::A3
935   };
936   static const unsigned F32Regs[] = {
937       Mips::F12, Mips::F14
938   };
939   static const unsigned F64Regs[] = {
940       Mips::D6, Mips::D7
941   };
942
943   unsigned Reg = 0;
944   static bool IntRegUsed = false;
945
946   // This must be the first arg of the call if no regs have been allocated.
947   // Initialize IntRegUsed in that case.
948   if (IntRegs[State.getFirstUnallocated(IntRegs, IntRegsSize)] == Mips::A0 &&
949       F32Regs[State.getFirstUnallocated(F32Regs, FloatRegsSize)] == Mips::F12 &&
950       F64Regs[State.getFirstUnallocated(F64Regs, FloatRegsSize)] == Mips::D6)
951     IntRegUsed = false;
952
953   // Promote i8 and i16
954   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
955     LocVT = MVT::i32;
956     if (ArgFlags.isSExt())
957       LocInfo = CCValAssign::SExt;
958     else if (ArgFlags.isZExt())
959       LocInfo = CCValAssign::ZExt;
960     else
961       LocInfo = CCValAssign::AExt;
962   }
963
964   if (ValVT == MVT::i32) {
965     Reg = State.AllocateReg(IntRegs, IntRegsSize);
966     IntRegUsed = true;
967   } else if (ValVT == MVT::f32) {
968     // An int reg has to be marked allocated regardless of whether or not
969     // IntRegUsed is true.
970     Reg = State.AllocateReg(IntRegs, IntRegsSize);
971
972     if (IntRegUsed) {
973       if (Reg) // Int reg is available
974         LocVT = MVT::i32;
975     } else {
976       unsigned FReg = State.AllocateReg(F32Regs, FloatRegsSize);
977       if (FReg) // F32 reg is available
978         Reg = FReg;
979       else if (Reg) // No F32 regs are available, but an int reg is available.
980         LocVT = MVT::i32;
981     }
982   } else if (ValVT == MVT::f64) {
983     // Int regs have to be marked allocated regardless of whether or not
984     // IntRegUsed is true.
985     Reg = State.AllocateReg(IntRegs, IntRegsSize);
986     if (Reg == Mips::A1)
987       Reg = State.AllocateReg(IntRegs, IntRegsSize);
988     else if (Reg == Mips::A3)
989       Reg = 0;
990     State.AllocateReg(IntRegs, IntRegsSize);
991
992     // At this point, Reg is A0, A2 or 0, and all the unavailable integer regs
993     // are marked as allocated.
994     if (IntRegUsed) {
995       if (Reg)// if int reg is available
996         LocVT = MVT::i32;
997     } else {
998       unsigned FReg = State.AllocateReg(F64Regs, FloatRegsSize);
999       if (FReg) // F64 reg is available.
1000         Reg = FReg;
1001       else if (Reg) // No F64 regs are available, but an int reg is available.
1002         LocVT = MVT::i32;
1003     }
1004   } else
1005     assert(false && "cannot handle this ValVT");
1006
1007   if (!Reg) {
1008     unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1009     unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
1010     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1011   } else
1012     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1013
1014   return false; // CC must always match
1015 }
1016
1017 static bool CC_MipsO32_VarArgs(unsigned ValNo, MVT ValVT,
1018                        MVT LocVT, CCValAssign::LocInfo LocInfo,
1019                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
1020
1021   static const unsigned IntRegsSize=4;
1022
1023   static const unsigned IntRegs[] = {
1024       Mips::A0, Mips::A1, Mips::A2, Mips::A3
1025   };
1026
1027   // Promote i8 and i16
1028   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1029     LocVT = MVT::i32;
1030     if (ArgFlags.isSExt())
1031       LocInfo = CCValAssign::SExt;
1032     else if (ArgFlags.isZExt())
1033       LocInfo = CCValAssign::ZExt;
1034     else
1035       LocInfo = CCValAssign::AExt;
1036   }
1037
1038   unsigned Reg;
1039
1040   if (ValVT == MVT::i32 || ValVT == MVT::f32) {
1041     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1042     LocVT = MVT::i32;
1043   } else if (ValVT == MVT::f64) {
1044     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1045     if (Reg == Mips::A1 || Reg == Mips::A3)
1046       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1047     State.AllocateReg(IntRegs, IntRegsSize);
1048     LocVT = MVT::i32;
1049   } else
1050     llvm_unreachable("Cannot handle this ValVT.");
1051
1052   if (!Reg) {
1053     unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1054     unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
1055     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1056   } else
1057     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1058
1059   return false; // CC must always match
1060 }
1061
1062 //===----------------------------------------------------------------------===//
1063 //                  Call Calling Convention Implementation
1064 //===----------------------------------------------------------------------===//
1065
1066 /// LowerCall - functions arguments are copied from virtual regs to
1067 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1068 /// TODO: isTailCall.
1069 SDValue
1070 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1071                               CallingConv::ID CallConv, bool isVarArg,
1072                               bool &isTailCall,
1073                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1074                               const SmallVectorImpl<SDValue> &OutVals,
1075                               const SmallVectorImpl<ISD::InputArg> &Ins,
1076                               DebugLoc dl, SelectionDAG &DAG,
1077                               SmallVectorImpl<SDValue> &InVals) const {
1078   // MIPs target does not yet support tail call optimization.
1079   isTailCall = false;
1080
1081   MachineFunction &MF = DAG.getMachineFunction();
1082   MachineFrameInfo *MFI = MF.getFrameInfo();
1083   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1084
1085   // Analyze operands of the call, assigning locations to each operand.
1086   SmallVector<CCValAssign, 16> ArgLocs;
1087   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1088                  *DAG.getContext());
1089
1090   // To meet O32 ABI, Mips must always allocate 16 bytes on
1091   // the stack (even if less than 4 are used as arguments)
1092   if (Subtarget->isABI_O32()) {
1093     int VTsize = MVT(MVT::i32).getSizeInBits()/8;
1094     MFI->CreateFixedObject(VTsize, (VTsize*3), true);
1095     CCInfo.AnalyzeCallOperands(Outs,
1096                      isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1097   } else
1098     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1099
1100   // Get a count of how many bytes are to be pushed on the stack.
1101   unsigned NumBytes = CCInfo.getNextStackOffset();
1102   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1103
1104   // With EABI is it possible to have 16 args on registers.
1105   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1106   SmallVector<SDValue, 8> MemOpChains;
1107
1108   // First/LastArgStackLoc contains the first/last
1109   // "at stack" argument location.
1110   int LastArgStackLoc = 0;
1111   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1112
1113   // Walk the register/memloc assignments, inserting copies/loads.
1114   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1115     SDValue Arg = OutVals[i];
1116     CCValAssign &VA = ArgLocs[i];
1117
1118     // Promote the value if needed.
1119     switch (VA.getLocInfo()) {
1120     default: llvm_unreachable("Unknown loc info!");
1121     case CCValAssign::Full:
1122       if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1123         if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1124           Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1125         if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1126           Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1127           SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1128                                    DAG.getConstant(0, getPointerTy()));
1129           SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1130                                    DAG.getConstant(1, getPointerTy()));
1131           RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1132           RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1133           continue;
1134         }
1135       }
1136       break;
1137     case CCValAssign::SExt:
1138       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1139       break;
1140     case CCValAssign::ZExt:
1141       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1142       break;
1143     case CCValAssign::AExt:
1144       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1145       break;
1146     }
1147
1148     // Arguments that can be passed on register must be kept at
1149     // RegsToPass vector
1150     if (VA.isRegLoc()) {
1151       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1152       continue;
1153     }
1154
1155     // Register can't get to this point...
1156     assert(VA.isMemLoc());
1157
1158     // Create the frame index object for this incoming parameter
1159     // This guarantees that when allocating Local Area the firsts
1160     // 16 bytes which are alwayes reserved won't be overwritten
1161     // if O32 ABI is used. For EABI the first address is zero.
1162     LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
1163     int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1164                                     LastArgStackLoc, true);
1165
1166     SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
1167
1168     // emit ISD::STORE whichs stores the
1169     // parameter value to a stack Location
1170     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1171                                        MachinePointerInfo(),
1172                                        false, false, 0));
1173   }
1174
1175   // Transform all store nodes into one single node because all store
1176   // nodes are independent of each other.
1177   if (!MemOpChains.empty())
1178     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1179                         &MemOpChains[0], MemOpChains.size());
1180
1181   // Build a sequence of copy-to-reg nodes chained together with token
1182   // chain and flag operands which copy the outgoing args into registers.
1183   // The InFlag in necessary since all emited instructions must be
1184   // stuck together.
1185   SDValue InFlag;
1186   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1187     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1188                              RegsToPass[i].second, InFlag);
1189     InFlag = Chain.getValue(1);
1190   }
1191
1192   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1193   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1194   // node so that legalize doesn't hack it.
1195   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1196   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1197     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1198                                 getPointerTy(), 0, OpFlag);
1199   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1200     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1201                                 getPointerTy(), OpFlag);
1202
1203   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1204   //             = Chain, Callee, Reg#1, Reg#2, ...
1205   //
1206   // Returns a chain & a flag for retval copy to use.
1207   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1208   SmallVector<SDValue, 8> Ops;
1209   Ops.push_back(Chain);
1210   Ops.push_back(Callee);
1211
1212   // Add argument registers to the end of the list so that they are
1213   // known live into the call.
1214   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1215     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1216                                   RegsToPass[i].second.getValueType()));
1217
1218   if (InFlag.getNode())
1219     Ops.push_back(InFlag);
1220
1221   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1222   InFlag = Chain.getValue(1);
1223
1224   // Create a stack location to hold GP when PIC is used. This stack
1225   // location is used on function prologue to save GP and also after all
1226   // emited CALL's to restore GP.
1227   if (IsPIC) {
1228       // Function can have an arbitrary number of calls, so
1229       // hold the LastArgStackLoc with the biggest offset.
1230       int FI;
1231       MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1232       if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
1233         LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
1234         // Create the frame index only once. SPOffset here can be anything
1235         // (this will be fixed on processFunctionBeforeFrameFinalized)
1236         if (MipsFI->getGPStackOffset() == -1) {
1237           FI = MFI->CreateFixedObject(4, 0, true);
1238           MipsFI->setGPFI(FI);
1239         }
1240         MipsFI->setGPStackOffset(LastArgStackLoc);
1241       }
1242
1243       // Reload GP value.
1244       FI = MipsFI->getGPFI();
1245       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1246       SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN,
1247                                    MachinePointerInfo::getFixedStack(FI),
1248                                    false, false, 0);
1249       Chain = GPLoad.getValue(1);
1250       Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32),
1251                                GPLoad, SDValue(0,0));
1252       InFlag = Chain.getValue(1);
1253   }
1254
1255   // Create the CALLSEQ_END node.
1256   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1257                              DAG.getIntPtrConstant(0, true), InFlag);
1258   InFlag = Chain.getValue(1);
1259
1260   // Handle result values, copying them out of physregs into vregs that we
1261   // return.
1262   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1263                          Ins, dl, DAG, InVals);
1264 }
1265
1266 /// LowerCallResult - Lower the result values of a call into the
1267 /// appropriate copies out of appropriate physical registers.
1268 SDValue
1269 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1270                                     CallingConv::ID CallConv, bool isVarArg,
1271                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1272                                     DebugLoc dl, SelectionDAG &DAG,
1273                                     SmallVectorImpl<SDValue> &InVals) const {
1274
1275   // Assign locations to each value returned by this call.
1276   SmallVector<CCValAssign, 16> RVLocs;
1277   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1278                  RVLocs, *DAG.getContext());
1279
1280   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1281
1282   // Copy all of the result registers out of their specified physreg.
1283   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1284     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1285                                RVLocs[i].getValVT(), InFlag).getValue(1);
1286     InFlag = Chain.getValue(2);
1287     InVals.push_back(Chain.getValue(0));
1288   }
1289
1290   return Chain;
1291 }
1292
1293 //===----------------------------------------------------------------------===//
1294 //             Formal Arguments Calling Convention Implementation
1295 //===----------------------------------------------------------------------===//
1296
1297 /// LowerFormalArguments - transform physical registers into virtual registers
1298 /// and generate load operations for arguments places on the stack.
1299 SDValue
1300 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
1301                                         CallingConv::ID CallConv, bool isVarArg,
1302                                         const SmallVectorImpl<ISD::InputArg>
1303                                         &Ins,
1304                                         DebugLoc dl, SelectionDAG &DAG,
1305                                         SmallVectorImpl<SDValue> &InVals)
1306                                           const {
1307
1308   MachineFunction &MF = DAG.getMachineFunction();
1309   MachineFrameInfo *MFI = MF.getFrameInfo();
1310   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1311
1312   MipsFI->setVarArgsFrameIndex(0);
1313
1314   // Used with vargs to acumulate store chains.
1315   std::vector<SDValue> OutChains;
1316
1317   // Keep track of the last register used for arguments
1318   unsigned ArgRegEnd = 0;
1319
1320   // Assign locations to all of the incoming arguments.
1321   SmallVector<CCValAssign, 16> ArgLocs;
1322   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1323                  ArgLocs, *DAG.getContext());
1324
1325   if (Subtarget->isABI_O32())
1326     CCInfo.AnalyzeFormalArguments(Ins,
1327                         isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1328   else
1329     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
1330
1331   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1332   unsigned LastStackArgEndOffset = 0;
1333   EVT LastRegArgValVT;
1334
1335   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1336     CCValAssign &VA = ArgLocs[i];
1337
1338     // Arguments stored on registers
1339     if (VA.isRegLoc()) {
1340       EVT RegVT = VA.getLocVT();
1341       ArgRegEnd = VA.getLocReg();
1342       LastRegArgValVT = VA.getValVT();
1343       TargetRegisterClass *RC = 0;
1344
1345       if (RegVT == MVT::i32)
1346         RC = Mips::CPURegsRegisterClass;
1347       else if (RegVT == MVT::f32)
1348         RC = Mips::FGR32RegisterClass;
1349       else if (RegVT == MVT::f64) {
1350         if (!Subtarget->isSingleFloat())
1351           RC = Mips::AFGR64RegisterClass;
1352       } else
1353         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
1354
1355       // Transform the arguments stored on
1356       // physical registers into virtual ones
1357       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1358       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1359
1360       // If this is an 8 or 16-bit value, it has been passed promoted
1361       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1362       // truncate to the right size.
1363       if (VA.getLocInfo() != CCValAssign::Full) {
1364         unsigned Opcode = 0;
1365         if (VA.getLocInfo() == CCValAssign::SExt)
1366           Opcode = ISD::AssertSext;
1367         else if (VA.getLocInfo() == CCValAssign::ZExt)
1368           Opcode = ISD::AssertZext;
1369         if (Opcode)
1370           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
1371                                  DAG.getValueType(VA.getValVT()));
1372         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1373       }
1374
1375       // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
1376       if (Subtarget->isABI_O32()) {
1377         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
1378           ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1379         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
1380           unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
1381                                     VA.getLocReg()+1, RC);
1382           SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
1383           SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, ArgValue, 
1384                                        ArgValue2);
1385           ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Pair);
1386         }
1387       }
1388
1389       InVals.push_back(ArgValue);
1390     } else { // VA.isRegLoc()
1391
1392       // sanity check
1393       assert(VA.isMemLoc());
1394
1395       // The last argument is not a register anymore
1396       ArgRegEnd = 0;
1397
1398       // The stack pointer offset is relative to the caller stack frame.
1399       // Since the real stack size is unknown here, a negative SPOffset
1400       // is used so there's a way to adjust these offsets when the stack
1401       // size get known (on EliminateFrameIndex). A dummy SPOffset is
1402       // used instead of a direct negative address (which is recorded to
1403       // be used on emitPrologue) to avoid mis-calc of the first stack
1404       // offset on PEI::calculateFrameObjectOffsets.
1405       unsigned ArgSize = VA.getValVT().getSizeInBits()/8;
1406       LastStackArgEndOffset = FirstStackArgLoc + VA.getLocMemOffset() + ArgSize;
1407       int FI = MFI->CreateFixedObject(ArgSize, 0, true);
1408       MipsFI->recordLoadArgsFI(FI, -(4 +
1409         (FirstStackArgLoc + VA.getLocMemOffset())));
1410
1411       // Create load nodes to retrieve arguments from the stack
1412       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1413       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1414                                    MachinePointerInfo::getFixedStack(FI),
1415                                    false, false, 0));
1416     }
1417   }
1418
1419   // The mips ABIs for returning structs by value requires that we copy
1420   // the sret argument into $v0 for the return. Save the argument into
1421   // a virtual register so that we can access it from the return points.
1422   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1423     unsigned Reg = MipsFI->getSRetReturnReg();
1424     if (!Reg) {
1425       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1426       MipsFI->setSRetReturnReg(Reg);
1427     }
1428     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1429     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1430   }
1431
1432   // To meet ABI, when VARARGS are passed on registers, the registers
1433   // must have their values written to the caller stack frame. If the last
1434   // argument was placed in the stack, there's no need to save any register.
1435   if (isVarArg && Subtarget->isABI_O32()) {
1436     if (ArgRegEnd) {
1437       // Last named formal argument is passed in register.
1438
1439       // The last register argument that must be saved is Mips::A3
1440       TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
1441       if (LastRegArgValVT == MVT::f64)
1442         ArgRegEnd++;
1443
1444       if (ArgRegEnd < Mips::A3) {
1445         // Both the last named formal argument and the first variable
1446         // argument are passed in registers.
1447         for (++ArgRegEnd; ArgRegEnd <= Mips::A3; ++ArgRegEnd) {
1448           unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1449           SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
1450
1451           int FI = MFI->CreateFixedObject(4, 0, true);
1452           MipsFI->recordStoreVarArgsFI(FI, -(4+(ArgRegEnd-Mips::A0)*4));
1453           SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
1454           OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
1455                                            MachinePointerInfo(),
1456                                            false, false, 0));
1457
1458           // Record the frame index of the first variable argument
1459           // which is a value necessary to VASTART.
1460           if (!MipsFI->getVarArgsFrameIndex()) {
1461             MFI->setObjectAlignment(FI, 4);
1462             MipsFI->setVarArgsFrameIndex(FI);
1463           }
1464         }
1465       } else {
1466         // Last named formal argument is in register Mips::A3, and the first
1467         // variable argument is on stack. Record the frame index of the first
1468         // variable argument.
1469         int FI = MFI->CreateFixedObject(4, 0, true);
1470         MFI->setObjectAlignment(FI, 4);
1471         MipsFI->recordStoreVarArgsFI(FI, -20);
1472         MipsFI->setVarArgsFrameIndex(FI);
1473       }
1474     } else {
1475       // Last named formal argument and all the variable arguments are passed
1476       // on stack. Record the frame index of the first variable argument.
1477       int FI = MFI->CreateFixedObject(4, 0, true);
1478       MFI->setObjectAlignment(FI, 4);
1479       MipsFI->recordStoreVarArgsFI(FI, -(4+LastStackArgEndOffset));
1480       MipsFI->setVarArgsFrameIndex(FI);
1481     }
1482   }
1483
1484   // All stores are grouped in one node to allow the matching between
1485   // the size of Ins and InVals. This only happens when on varg functions
1486   if (!OutChains.empty()) {
1487     OutChains.push_back(Chain);
1488     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1489                         &OutChains[0], OutChains.size());
1490   }
1491
1492   return Chain;
1493 }
1494
1495 //===----------------------------------------------------------------------===//
1496 //               Return Value Calling Convention Implementation
1497 //===----------------------------------------------------------------------===//
1498
1499 SDValue
1500 MipsTargetLowering::LowerReturn(SDValue Chain,
1501                                 CallingConv::ID CallConv, bool isVarArg,
1502                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
1503                                 const SmallVectorImpl<SDValue> &OutVals,
1504                                 DebugLoc dl, SelectionDAG &DAG) const {
1505
1506   // CCValAssign - represent the assignment of
1507   // the return value to a location
1508   SmallVector<CCValAssign, 16> RVLocs;
1509
1510   // CCState - Info about the registers and stack slot.
1511   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1512                  RVLocs, *DAG.getContext());
1513
1514   // Analize return values.
1515   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1516
1517   // If this is the first return lowered for this function, add
1518   // the regs to the liveout set for the function.
1519   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1520     for (unsigned i = 0; i != RVLocs.size(); ++i)
1521       if (RVLocs[i].isRegLoc())
1522         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1523   }
1524
1525   SDValue Flag;
1526
1527   // Copy the result values into the output registers.
1528   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1529     CCValAssign &VA = RVLocs[i];
1530     assert(VA.isRegLoc() && "Can only return in registers!");
1531
1532     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1533                              OutVals[i], Flag);
1534
1535     // guarantee that all emitted copies are
1536     // stuck together, avoiding something bad
1537     Flag = Chain.getValue(1);
1538   }
1539
1540   // The mips ABIs for returning structs by value requires that we copy
1541   // the sret argument into $v0 for the return. We saved the argument into
1542   // a virtual register in the entry block, so now we copy the value out
1543   // and into $v0.
1544   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1545     MachineFunction &MF      = DAG.getMachineFunction();
1546     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1547     unsigned Reg = MipsFI->getSRetReturnReg();
1548
1549     if (!Reg)
1550       llvm_unreachable("sret virtual register not created in the entry block");
1551     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1552
1553     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1554     Flag = Chain.getValue(1);
1555   }
1556
1557   // Return on Mips is always a "jr $ra"
1558   if (Flag.getNode())
1559     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1560                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1561   else // Return Void
1562     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1563                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
1564 }
1565
1566 //===----------------------------------------------------------------------===//
1567 //                           Mips Inline Assembly Support
1568 //===----------------------------------------------------------------------===//
1569
1570 /// getConstraintType - Given a constraint letter, return the type of
1571 /// constraint it is for this target.
1572 MipsTargetLowering::ConstraintType MipsTargetLowering::
1573 getConstraintType(const std::string &Constraint) const
1574 {
1575   // Mips specific constrainy
1576   // GCC config/mips/constraints.md
1577   //
1578   // 'd' : An address register. Equivalent to r
1579   //       unless generating MIPS16 code.
1580   // 'y' : Equivalent to r; retained for
1581   //       backwards compatibility.
1582   // 'f' : Floating Point registers.
1583   if (Constraint.size() == 1) {
1584     switch (Constraint[0]) {
1585       default : break;
1586       case 'd':
1587       case 'y':
1588       case 'f':
1589         return C_RegisterClass;
1590         break;
1591     }
1592   }
1593   return TargetLowering::getConstraintType(Constraint);
1594 }
1595
1596 /// Examine constraint type and operand type and determine a weight value.
1597 /// This object must already have been set up with the operand type
1598 /// and the current alternative constraint selected.
1599 TargetLowering::ConstraintWeight
1600 MipsTargetLowering::getSingleConstraintMatchWeight(
1601     AsmOperandInfo &info, const char *constraint) const {
1602   ConstraintWeight weight = CW_Invalid;
1603   Value *CallOperandVal = info.CallOperandVal;
1604     // If we don't have a value, we can't do a match,
1605     // but allow it at the lowest weight.
1606   if (CallOperandVal == NULL)
1607     return CW_Default;
1608   const Type *type = CallOperandVal->getType();
1609   // Look at the constraint type.
1610   switch (*constraint) {
1611   default:
1612     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1613     break;
1614   case 'd':
1615   case 'y':
1616     if (type->isIntegerTy())
1617       weight = CW_Register;
1618     break;
1619   case 'f':
1620     if (type->isFloatTy())
1621       weight = CW_Register;
1622     break;
1623   }
1624   return weight;
1625 }
1626
1627 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1628 /// return a list of registers that can be used to satisfy the constraint.
1629 /// This should only be used for C_RegisterClass constraints.
1630 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1631 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
1632 {
1633   if (Constraint.size() == 1) {
1634     switch (Constraint[0]) {
1635     case 'r':
1636       return std::make_pair(0U, Mips::CPURegsRegisterClass);
1637     case 'f':
1638       if (VT == MVT::f32)
1639         return std::make_pair(0U, Mips::FGR32RegisterClass);
1640       if (VT == MVT::f64)
1641         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1642           return std::make_pair(0U, Mips::AFGR64RegisterClass);
1643     }
1644   }
1645   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1646 }
1647
1648 /// Given a register class constraint, like 'r', if this corresponds directly
1649 /// to an LLVM register class, return a register of 0 and the register class
1650 /// pointer.
1651 std::vector<unsigned> MipsTargetLowering::
1652 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1653                                   EVT VT) const
1654 {
1655   if (Constraint.size() != 1)
1656     return std::vector<unsigned>();
1657
1658   switch (Constraint[0]) {
1659     default : break;
1660     case 'r':
1661     // GCC Mips Constraint Letters
1662     case 'd':
1663     case 'y':
1664       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1665              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1666              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1667              Mips::T8, 0);
1668
1669     case 'f':
1670       if (VT == MVT::f32) {
1671         if (Subtarget->isSingleFloat())
1672           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1673                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1674                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1675                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1676                  Mips::F30, Mips::F31, 0);
1677         else
1678           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1679                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1680                  Mips::F28, Mips::F30, 0);
1681       }
1682
1683       if (VT == MVT::f64)
1684         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1685           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1686                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1687                  Mips::D14, Mips::D15, 0);
1688   }
1689   return std::vector<unsigned>();
1690 }
1691
1692 bool
1693 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1694   // The Mips target isn't yet aware of offsets.
1695   return false;
1696 }
1697
1698 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1699   if (VT != MVT::f32 && VT != MVT::f64)
1700     return false;
1701   if (Imm.isNegZero())
1702     return false;
1703   return Imm.isZero();
1704 }