Speculatively revert 132758 and 132768 to try to fix the Windows buildbots.
[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::TlsGd:             return "MipsISD::TlsGd";
44   case MipsISD::TprelHi:           return "MipsISD::TprelHi";
45   case MipsISD::TprelLo:           return "MipsISD::TprelLo";
46   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
47   case MipsISD::Ret:               return "MipsISD::Ret";
48   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
49   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
50   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
51   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
52   case MipsISD::FPRound:           return "MipsISD::FPRound";
53   case MipsISD::MAdd:              return "MipsISD::MAdd";
54   case MipsISD::MAddu:             return "MipsISD::MAddu";
55   case MipsISD::MSub:              return "MipsISD::MSub";
56   case MipsISD::MSubu:             return "MipsISD::MSubu";
57   case MipsISD::DivRem:            return "MipsISD::DivRem";
58   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
59   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
60   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
61   case MipsISD::WrapperPIC:        return "MipsISD::WrapperPIC";
62   default:                         return NULL;
63   }
64 }
65
66 MipsTargetLowering::
67 MipsTargetLowering(MipsTargetMachine &TM)
68   : TargetLowering(TM, new MipsTargetObjectFile()) {
69   Subtarget = &TM.getSubtarget<MipsSubtarget>();
70
71   // Mips does not have i1 type, so use i32 for
72   // setcc operations results (slt, sgt, ...).
73   setBooleanContents(ZeroOrOneBooleanContent);
74
75   // Set up the register classes
76   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
77   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
78
79   // When dealing with single precision only, use libcalls
80   if (!Subtarget->isSingleFloat())
81     if (!Subtarget->isFP64bit())
82       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
83
84   // Load extented operations for i1 types must be promoted
85   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
86   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
87   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
88
89   // MIPS doesn't have extending float->double load/store
90   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
91   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
92
93   // Used by legalize types to correctly generate the setcc result.
94   // Without this, every float setcc comes with a AND/OR with the result,
95   // we don't want this, since the fpcmp result goes to a flag register,
96   // which is used implicitly by brcond and select operations.
97   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
98
99   // Mips Custom Operations
100   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
101   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
102   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
103   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
104   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
105   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
106   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
107   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
108   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
109   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
110   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
111
112   setOperationAction(ISD::SDIV, MVT::i32, Expand);
113   setOperationAction(ISD::SREM, MVT::i32, Expand);
114   setOperationAction(ISD::UDIV, MVT::i32, Expand);
115   setOperationAction(ISD::UREM, MVT::i32, Expand);
116
117   // Operations not directly supported by Mips.
118   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
119   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
120   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
121   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
122   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
124   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
125   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
126   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
127
128   if (!Subtarget->isMips32r2())
129     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
130
131   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
132   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
133   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
134   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Custom);
135   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Custom);
136   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
137   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
138   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
139   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
140   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
141   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
142   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
143   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
144   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
145   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
146   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
147
148   setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
149   setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
150
151   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
152   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
153   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
154
155   // Use the default for now
156   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
157   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
158   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
159
160   if (Subtarget->isSingleFloat())
161     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
162
163   if (!Subtarget->hasSEInReg()) {
164     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
165     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
166   }
167
168   if (!Subtarget->hasBitCount())
169     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
170
171   if (!Subtarget->hasSwap())
172     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
173
174   setTargetDAGCombine(ISD::ADDE);
175   setTargetDAGCombine(ISD::SUBE);
176   setTargetDAGCombine(ISD::SDIVREM);
177   setTargetDAGCombine(ISD::UDIVREM);
178   setTargetDAGCombine(ISD::SETCC);
179
180   setMinFunctionAlignment(2);
181
182   setStackPointerRegisterToSaveRestore(Mips::SP);
183   computeRegisterProperties();
184
185   setExceptionPointerRegister(Mips::A0);
186   setExceptionSelectorRegister(Mips::A1);
187 }
188
189 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
190   return MVT::i32;
191 }
192
193 // SelectMadd -
194 // Transforms a subgraph in CurDAG if the following pattern is found:
195 //  (addc multLo, Lo0), (adde multHi, Hi0),
196 // where,
197 //  multHi/Lo: product of multiplication
198 //  Lo0: initial value of Lo register
199 //  Hi0: initial value of Hi register
200 // Return true if pattern matching was successful.
201 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
202   // ADDENode's second operand must be a flag output of an ADDC node in order
203   // for the matching to be successful.
204   SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
205
206   if (ADDCNode->getOpcode() != ISD::ADDC)
207     return false;
208
209   SDValue MultHi = ADDENode->getOperand(0);
210   SDValue MultLo = ADDCNode->getOperand(0);
211   SDNode* MultNode = MultHi.getNode();
212   unsigned MultOpc = MultHi.getOpcode();
213
214   // MultHi and MultLo must be generated by the same node,
215   if (MultLo.getNode() != MultNode)
216     return false;
217
218   // and it must be a multiplication.
219   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
220     return false;
221
222   // MultLo amd MultHi must be the first and second output of MultNode
223   // respectively.
224   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
225     return false;
226
227   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
228   // of the values of MultNode, in which case MultNode will be removed in later
229   // phases.
230   // If there exist users other than ADDENode or ADDCNode, this function returns
231   // here, which will result in MultNode being mapped to a single MULT
232   // instruction node rather than a pair of MULT and MADD instructions being
233   // produced.
234   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
235     return false;
236
237   SDValue Chain = CurDAG->getEntryNode();
238   DebugLoc dl = ADDENode->getDebugLoc();
239
240   // create MipsMAdd(u) node
241   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
242
243   SDValue MAdd = CurDAG->getNode(MultOpc, dl,
244                                  MVT::Glue,
245                                  MultNode->getOperand(0),// Factor 0
246                                  MultNode->getOperand(1),// Factor 1
247                                  ADDCNode->getOperand(1),// Lo0
248                                  ADDENode->getOperand(1));// Hi0
249
250   // create CopyFromReg nodes
251   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
252                                               MAdd);
253   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
254                                               Mips::HI, MVT::i32,
255                                               CopyFromLo.getValue(2));
256
257   // replace uses of adde and addc here
258   if (!SDValue(ADDCNode, 0).use_empty())
259     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
260
261   if (!SDValue(ADDENode, 0).use_empty())
262     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
263
264   return true;
265 }
266
267 // SelectMsub -
268 // Transforms a subgraph in CurDAG if the following pattern is found:
269 //  (addc Lo0, multLo), (sube Hi0, multHi),
270 // where,
271 //  multHi/Lo: product of multiplication
272 //  Lo0: initial value of Lo register
273 //  Hi0: initial value of Hi register
274 // Return true if pattern matching was successful.
275 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
276   // SUBENode's second operand must be a flag output of an SUBC node in order
277   // for the matching to be successful.
278   SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
279
280   if (SUBCNode->getOpcode() != ISD::SUBC)
281     return false;
282
283   SDValue MultHi = SUBENode->getOperand(1);
284   SDValue MultLo = SUBCNode->getOperand(1);
285   SDNode* MultNode = MultHi.getNode();
286   unsigned MultOpc = MultHi.getOpcode();
287
288   // MultHi and MultLo must be generated by the same node,
289   if (MultLo.getNode() != MultNode)
290     return false;
291
292   // and it must be a multiplication.
293   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
294     return false;
295
296   // MultLo amd MultHi must be the first and second output of MultNode
297   // respectively.
298   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
299     return false;
300
301   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
302   // of the values of MultNode, in which case MultNode will be removed in later
303   // phases.
304   // If there exist users other than SUBENode or SUBCNode, this function returns
305   // here, which will result in MultNode being mapped to a single MULT
306   // instruction node rather than a pair of MULT and MSUB instructions being
307   // produced.
308   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
309     return false;
310
311   SDValue Chain = CurDAG->getEntryNode();
312   DebugLoc dl = SUBENode->getDebugLoc();
313
314   // create MipsSub(u) node
315   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
316
317   SDValue MSub = CurDAG->getNode(MultOpc, dl,
318                                  MVT::Glue,
319                                  MultNode->getOperand(0),// Factor 0
320                                  MultNode->getOperand(1),// Factor 1
321                                  SUBCNode->getOperand(0),// Lo0
322                                  SUBENode->getOperand(0));// Hi0
323
324   // create CopyFromReg nodes
325   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
326                                               MSub);
327   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
328                                               Mips::HI, MVT::i32,
329                                               CopyFromLo.getValue(2));
330
331   // replace uses of sube and subc here
332   if (!SDValue(SUBCNode, 0).use_empty())
333     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
334
335   if (!SDValue(SUBENode, 0).use_empty())
336     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
337
338   return true;
339 }
340
341 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
342                                   TargetLowering::DAGCombinerInfo &DCI,
343                                   const MipsSubtarget* Subtarget) {
344   if (DCI.isBeforeLegalize())
345     return SDValue();
346
347   if (Subtarget->isMips32() && SelectMadd(N, &DAG))
348     return SDValue(N, 0);
349
350   return SDValue();
351 }
352
353 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
354                                   TargetLowering::DAGCombinerInfo &DCI,
355                                   const MipsSubtarget* Subtarget) {
356   if (DCI.isBeforeLegalize())
357     return SDValue();
358
359   if (Subtarget->isMips32() && SelectMsub(N, &DAG))
360     return SDValue(N, 0);
361
362   return SDValue();
363 }
364
365 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
366                                     TargetLowering::DAGCombinerInfo &DCI,
367                                     const MipsSubtarget* Subtarget) {
368   if (DCI.isBeforeLegalizeOps())
369     return SDValue();
370
371   unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
372                                                   MipsISD::DivRemU;
373   DebugLoc dl = N->getDebugLoc();
374
375   SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
376                                N->getOperand(0), N->getOperand(1));
377   SDValue InChain = DAG.getEntryNode();
378   SDValue InGlue = DivRem;
379
380   // insert MFLO
381   if (N->hasAnyUseOfValue(0)) {
382     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, Mips::LO, MVT::i32,
383                                             InGlue);
384     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
385     InChain = CopyFromLo.getValue(1);
386     InGlue = CopyFromLo.getValue(2);
387   }
388
389   // insert MFHI
390   if (N->hasAnyUseOfValue(1)) {
391     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
392                                             Mips::HI, MVT::i32, InGlue);
393     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
394   }
395
396   return SDValue();
397 }
398
399 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
400   switch (CC) {
401   default: llvm_unreachable("Unknown fp condition code!");
402   case ISD::SETEQ:
403   case ISD::SETOEQ: return Mips::FCOND_OEQ;
404   case ISD::SETUNE: return Mips::FCOND_UNE;
405   case ISD::SETLT:
406   case ISD::SETOLT: return Mips::FCOND_OLT;
407   case ISD::SETGT:
408   case ISD::SETOGT: return Mips::FCOND_OGT;
409   case ISD::SETLE:
410   case ISD::SETOLE: return Mips::FCOND_OLE;
411   case ISD::SETGE:
412   case ISD::SETOGE: return Mips::FCOND_OGE;
413   case ISD::SETULT: return Mips::FCOND_ULT;
414   case ISD::SETULE: return Mips::FCOND_ULE;
415   case ISD::SETUGT: return Mips::FCOND_UGT;
416   case ISD::SETUGE: return Mips::FCOND_UGE;
417   case ISD::SETUO:  return Mips::FCOND_UN;
418   case ISD::SETO:   return Mips::FCOND_OR;
419   case ISD::SETNE:
420   case ISD::SETONE: return Mips::FCOND_ONE;
421   case ISD::SETUEQ: return Mips::FCOND_UEQ;
422   }
423 }
424
425
426 // Returns true if condition code has to be inverted.
427 static bool InvertFPCondCode(Mips::CondCode CC) {
428   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
429     return false;
430
431   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
432     return true;
433
434   assert(false && "Illegal Condition Code");
435   return false;
436 }
437
438 // Creates and returns an FPCmp node from a setcc node.
439 // Returns Op if setcc is not a floating point comparison.
440 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
441   // must be a SETCC node
442   if (Op.getOpcode() != ISD::SETCC)
443     return Op;
444
445   SDValue LHS = Op.getOperand(0);
446
447   if (!LHS.getValueType().isFloatingPoint())
448     return Op;
449
450   SDValue RHS = Op.getOperand(1);
451   DebugLoc dl = Op.getDebugLoc();
452
453   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
454   // node if necessary.
455   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
456
457   return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
458                      DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
459 }
460
461 // Creates and returns a CMovFPT/F node.
462 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
463                             SDValue False, DebugLoc DL) {
464   bool invert = InvertFPCondCode((Mips::CondCode)
465                                  cast<ConstantSDNode>(Cond.getOperand(2))
466                                  ->getSExtValue());
467
468   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
469                      True.getValueType(), True, False, Cond);
470 }
471
472 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
473                                    TargetLowering::DAGCombinerInfo &DCI,
474                                    const MipsSubtarget* Subtarget) {
475   if (DCI.isBeforeLegalizeOps())
476     return SDValue();
477
478   SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
479
480   if (Cond.getOpcode() != MipsISD::FPCmp)
481     return SDValue();
482
483   SDValue True  = DAG.getConstant(1, MVT::i32);
484   SDValue False = DAG.getConstant(0, MVT::i32);
485
486   return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
487 }
488
489 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
490   const {
491   SelectionDAG &DAG = DCI.DAG;
492   unsigned opc = N->getOpcode();
493
494   switch (opc) {
495   default: break;
496   case ISD::ADDE:
497     return PerformADDECombine(N, DAG, DCI, Subtarget);
498   case ISD::SUBE:
499     return PerformSUBECombine(N, DAG, DCI, Subtarget);
500   case ISD::SDIVREM:
501   case ISD::UDIVREM:
502     return PerformDivRemCombine(N, DAG, DCI, Subtarget);
503   case ISD::SETCC:
504     return PerformSETCCCombine(N, DAG, DCI, Subtarget);
505   }
506
507   return SDValue();
508 }
509
510 SDValue MipsTargetLowering::
511 LowerOperation(SDValue Op, SelectionDAG &DAG) const
512 {
513   switch (Op.getOpcode())
514   {
515     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
516     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
517     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
518     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
519     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
520     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
521     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
522     case ISD::SELECT:             return LowerSELECT(Op, DAG);
523     case ISD::VASTART:            return LowerVASTART(Op, DAG);
524     case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
525     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
526   }
527   return SDValue();
528 }
529
530 //===----------------------------------------------------------------------===//
531 //  Lower helper functions
532 //===----------------------------------------------------------------------===//
533
534 // AddLiveIn - This helper function adds the specified physical register to the
535 // MachineFunction as a live in value.  It also creates a corresponding
536 // virtual register for it.
537 static unsigned
538 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
539 {
540   assert(RC->contains(PReg) && "Not the correct regclass!");
541   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
542   MF.getRegInfo().addLiveIn(PReg, VReg);
543   return VReg;
544 }
545
546 // Get fp branch code (not opcode) from condition code.
547 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
548   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
549     return Mips::BRANCH_T;
550
551   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
552     return Mips::BRANCH_F;
553
554   return Mips::BRANCH_INVALID;
555 }
556
557 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
558                                         DebugLoc dl,
559                                         const MipsSubtarget* Subtarget,
560                                         const TargetInstrInfo *TII,
561                                         bool isFPCmp, unsigned Opc) {
562   // There is no need to expand CMov instructions if target has
563   // conditional moves.
564   if (Subtarget->hasCondMov())
565     return BB;
566
567   // To "insert" a SELECT_CC instruction, we actually have to insert the
568   // diamond control-flow pattern.  The incoming instruction knows the
569   // destination vreg to set, the condition code register to branch on, the
570   // true/false values to select between, and a branch opcode to use.
571   const BasicBlock *LLVM_BB = BB->getBasicBlock();
572   MachineFunction::iterator It = BB;
573   ++It;
574
575   //  thisMBB:
576   //  ...
577   //   TrueVal = ...
578   //   setcc r1, r2, r3
579   //   bNE   r1, r0, copy1MBB
580   //   fallthrough --> copy0MBB
581   MachineBasicBlock *thisMBB  = BB;
582   MachineFunction *F = BB->getParent();
583   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
584   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
585   F->insert(It, copy0MBB);
586   F->insert(It, sinkMBB);
587
588   // Transfer the remainder of BB and its successor edges to sinkMBB.
589   sinkMBB->splice(sinkMBB->begin(), BB,
590                   llvm::next(MachineBasicBlock::iterator(MI)),
591                   BB->end());
592   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
593
594   // Next, add the true and fallthrough blocks as its successors.
595   BB->addSuccessor(copy0MBB);
596   BB->addSuccessor(sinkMBB);
597
598   // Emit the right instruction according to the type of the operands compared
599   if (isFPCmp)
600     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
601   else
602     BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
603       .addReg(Mips::ZERO).addMBB(sinkMBB);
604
605   //  copy0MBB:
606   //   %FalseValue = ...
607   //   # fallthrough to sinkMBB
608   BB = copy0MBB;
609
610   // Update machine-CFG edges
611   BB->addSuccessor(sinkMBB);
612
613   //  sinkMBB:
614   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
615   //  ...
616   BB = sinkMBB;
617
618   if (isFPCmp)
619     BuildMI(*BB, BB->begin(), dl,
620             TII->get(Mips::PHI), MI->getOperand(0).getReg())
621       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
622       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
623   else
624     BuildMI(*BB, BB->begin(), dl,
625             TII->get(Mips::PHI), MI->getOperand(0).getReg())
626       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
627       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
628
629   MI->eraseFromParent();   // The pseudo instruction is gone now.
630   return BB;
631 }
632
633 MachineBasicBlock *
634 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
635                                                 MachineBasicBlock *BB) const {
636   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
637   DebugLoc dl = MI->getDebugLoc();
638
639   switch (MI->getOpcode()) {
640   default:
641     assert(false && "Unexpected instr type to insert");
642     return NULL;
643   case Mips::MOVT:
644   case Mips::MOVT_S:
645   case Mips::MOVT_D:
646     return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1F);
647   case Mips::MOVF:
648   case Mips::MOVF_S:
649   case Mips::MOVF_D:
650     return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1T);
651   case Mips::MOVZ_I:
652   case Mips::MOVZ_S:
653   case Mips::MOVZ_D:
654     return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BNE);
655   case Mips::MOVN_I:
656   case Mips::MOVN_S:
657   case Mips::MOVN_D:
658     return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BEQ);
659
660   case Mips::ATOMIC_LOAD_ADD_I8:
661     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
662   case Mips::ATOMIC_LOAD_ADD_I16:
663     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
664   case Mips::ATOMIC_LOAD_ADD_I32:
665     return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
666
667   case Mips::ATOMIC_LOAD_AND_I8:
668     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
669   case Mips::ATOMIC_LOAD_AND_I16:
670     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
671   case Mips::ATOMIC_LOAD_AND_I32:
672     return EmitAtomicBinary(MI, BB, 4, Mips::AND);
673
674   case Mips::ATOMIC_LOAD_OR_I8:
675     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
676   case Mips::ATOMIC_LOAD_OR_I16:
677     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
678   case Mips::ATOMIC_LOAD_OR_I32:
679     return EmitAtomicBinary(MI, BB, 4, Mips::OR);
680
681   case Mips::ATOMIC_LOAD_XOR_I8:
682     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
683   case Mips::ATOMIC_LOAD_XOR_I16:
684     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
685   case Mips::ATOMIC_LOAD_XOR_I32:
686     return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
687
688   case Mips::ATOMIC_LOAD_NAND_I8:
689     return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
690   case Mips::ATOMIC_LOAD_NAND_I16:
691     return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
692   case Mips::ATOMIC_LOAD_NAND_I32:
693     return EmitAtomicBinary(MI, BB, 4, 0, true);
694
695   case Mips::ATOMIC_LOAD_SUB_I8:
696     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
697   case Mips::ATOMIC_LOAD_SUB_I16:
698     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
699   case Mips::ATOMIC_LOAD_SUB_I32:
700     return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
701
702   case Mips::ATOMIC_SWAP_I8:
703     return EmitAtomicBinaryPartword(MI, BB, 1, 0);
704   case Mips::ATOMIC_SWAP_I16:
705     return EmitAtomicBinaryPartword(MI, BB, 2, 0);
706   case Mips::ATOMIC_SWAP_I32:
707     return EmitAtomicBinary(MI, BB, 4, 0);
708
709   case Mips::ATOMIC_CMP_SWAP_I8:
710     return EmitAtomicCmpSwapPartword(MI, BB, 1);
711   case Mips::ATOMIC_CMP_SWAP_I16:
712     return EmitAtomicCmpSwapPartword(MI, BB, 2);
713   case Mips::ATOMIC_CMP_SWAP_I32:
714     return EmitAtomicCmpSwap(MI, BB, 4);
715   }
716 }
717
718 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
719 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
720 MachineBasicBlock *
721 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
722                                      unsigned Size, unsigned BinOpcode,
723                                      bool Nand) const {
724   assert(Size == 4 && "Unsupported size for EmitAtomicBinary.");
725
726   MachineFunction *MF = BB->getParent();
727   MachineRegisterInfo &RegInfo = MF->getRegInfo();
728   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
729   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
730   DebugLoc dl = MI->getDebugLoc();
731
732   unsigned Dest = MI->getOperand(0).getReg();
733   unsigned Ptr = MI->getOperand(1).getReg();
734   unsigned Incr = MI->getOperand(2).getReg();
735
736   unsigned Oldval = RegInfo.createVirtualRegister(RC);
737   unsigned Tmp1 = RegInfo.createVirtualRegister(RC);
738   unsigned Tmp2 = RegInfo.createVirtualRegister(RC);
739
740   // insert new blocks after the current block
741   const BasicBlock *LLVM_BB = BB->getBasicBlock();
742   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
743   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
744   MachineFunction::iterator It = BB;
745   ++It;
746   MF->insert(It, loopMBB);
747   MF->insert(It, exitMBB);
748
749   // Transfer the remainder of BB and its successor edges to exitMBB.
750   exitMBB->splice(exitMBB->begin(), BB,
751                   llvm::next(MachineBasicBlock::iterator(MI)),
752                   BB->end());
753   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
754
755   //  thisMBB:
756   //    ...
757   //    sw incr, fi(sp)           // store incr to stack (when BinOpcode == 0)
758   //    fallthrough --> loopMBB
759
760   // Note: for atomic.swap (when BinOpcode == 0), storing incr to stack before
761   // the loop and then loading it from stack in block loopMBB is necessary to
762   // prevent MachineLICM pass to hoist "or" instruction out of the block
763   // loopMBB.
764
765   int fi = 0;
766   if (BinOpcode == 0 && !Nand) {
767     // Get or create a temporary stack location.
768     MipsFunctionInfo *MipsFI = MF->getInfo<MipsFunctionInfo>();
769     fi = MipsFI->getAtomicFrameIndex();
770     if (fi == -1) {
771       fi = MF->getFrameInfo()->CreateStackObject(Size, Size, false);
772       MipsFI->setAtomicFrameIndex(fi);
773     }
774
775     BuildMI(BB, dl, TII->get(Mips::SW))
776         .addReg(Incr).addImm(0).addFrameIndex(fi);
777   }
778   BB->addSuccessor(loopMBB);
779
780   //  loopMBB:
781   //    ll oldval, 0(ptr)
782   //    or dest, $0, oldval
783   //    <binop> tmp1, oldval, incr
784   //    sc tmp1, 0(ptr)
785   //    beq tmp1, $0, loopMBB
786   BB = loopMBB;
787   BuildMI(BB, dl, TII->get(Mips::LL), Oldval).addImm(0).addReg(Ptr);
788   BuildMI(BB, dl, TII->get(Mips::OR), Dest).addReg(Mips::ZERO).addReg(Oldval);
789   if (Nand) {
790     //  and tmp2, oldval, incr
791     //  nor tmp1, $0, tmp2
792     BuildMI(BB, dl, TII->get(Mips::AND), Tmp2).addReg(Oldval).addReg(Incr);
793     BuildMI(BB, dl, TII->get(Mips::NOR), Tmp1).addReg(Mips::ZERO).addReg(Tmp2);
794   } else if (BinOpcode) {
795     //  <binop> tmp1, oldval, incr
796     BuildMI(BB, dl, TII->get(BinOpcode), Tmp1).addReg(Oldval).addReg(Incr);
797   } else {
798     //  lw tmp2, fi(sp)              // load incr from stack
799     //  or tmp1, $zero, tmp2
800     BuildMI(BB, dl, TII->get(Mips::LW), Tmp2).addImm(0).addFrameIndex(fi);;
801     BuildMI(BB, dl, TII->get(Mips::OR), Tmp1).addReg(Mips::ZERO).addReg(Tmp2);
802   }
803   BuildMI(BB, dl, TII->get(Mips::SC), Tmp1).addReg(Tmp1).addImm(0).addReg(Ptr);
804   BuildMI(BB, dl, TII->get(Mips::BEQ))
805     .addReg(Tmp1).addReg(Mips::ZERO).addMBB(loopMBB);
806   BB->addSuccessor(loopMBB);
807   BB->addSuccessor(exitMBB);
808
809   MI->eraseFromParent();   // The instruction is gone now.
810
811   return BB;
812 }
813
814 MachineBasicBlock *
815 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
816                                              MachineBasicBlock *BB,
817                                              unsigned Size, unsigned BinOpcode,
818                                              bool Nand) const {
819   assert((Size == 1 || Size == 2) &&
820       "Unsupported size for EmitAtomicBinaryPartial.");
821
822   MachineFunction *MF = BB->getParent();
823   MachineRegisterInfo &RegInfo = MF->getRegInfo();
824   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
825   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
826   DebugLoc dl = MI->getDebugLoc();
827
828   unsigned Dest = MI->getOperand(0).getReg();
829   unsigned Ptr = MI->getOperand(1).getReg();
830   unsigned Incr = MI->getOperand(2).getReg();
831
832   unsigned Addr = RegInfo.createVirtualRegister(RC);
833   unsigned Shift = RegInfo.createVirtualRegister(RC);
834   unsigned Mask = RegInfo.createVirtualRegister(RC);
835   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
836   unsigned Newval = RegInfo.createVirtualRegister(RC);
837   unsigned Oldval = RegInfo.createVirtualRegister(RC);
838   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
839   unsigned Tmp1 = RegInfo.createVirtualRegister(RC);
840   unsigned Tmp2 = RegInfo.createVirtualRegister(RC);
841   unsigned Tmp3 = RegInfo.createVirtualRegister(RC);
842   unsigned Tmp4 = RegInfo.createVirtualRegister(RC);
843   unsigned Tmp5 = RegInfo.createVirtualRegister(RC);
844   unsigned Tmp6 = RegInfo.createVirtualRegister(RC);
845   unsigned Tmp7 = RegInfo.createVirtualRegister(RC);
846   unsigned Tmp8 = RegInfo.createVirtualRegister(RC);
847   unsigned Tmp9 = RegInfo.createVirtualRegister(RC);
848   unsigned Tmp10 = RegInfo.createVirtualRegister(RC);
849   unsigned Tmp11 = RegInfo.createVirtualRegister(RC);
850   unsigned Tmp12 = RegInfo.createVirtualRegister(RC);
851
852   // insert new blocks after the current block
853   const BasicBlock *LLVM_BB = BB->getBasicBlock();
854   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
855   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
856   MachineFunction::iterator It = BB;
857   ++It;
858   MF->insert(It, loopMBB);
859   MF->insert(It, exitMBB);
860
861   // Transfer the remainder of BB and its successor edges to exitMBB.
862   exitMBB->splice(exitMBB->begin(), BB,
863                   llvm::next(MachineBasicBlock::iterator(MI)),
864                   BB->end());
865   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
866
867   //  thisMBB:
868   //    addiu   tmp1,$0,-4                # 0xfffffffc
869   //    and     addr,ptr,tmp1
870   //    andi    tmp2,ptr,3
871   //    sll     shift,tmp2,3
872   //    ori     tmp3,$0,255               # 0xff
873   //    sll     mask,tmp3,shift
874   //    nor     mask2,$0,mask
875   //    andi    tmp4,incr,255
876   //    sll     incr2,tmp4,shift
877   //    sw      incr2, fi(sp)      // store incr2 to stack (when BinOpcode == 0)
878
879   // Note: for atomic.swap (when BinOpcode == 0), storing incr2 to stack before
880   // the loop and then loading it from stack in block loopMBB is necessary to
881   // prevent MachineLICM pass to hoist "or" instruction out of the block
882   // loopMBB.
883
884   int64_t MaskImm = (Size == 1) ? 255 : 65535;
885   BuildMI(BB, dl, TII->get(Mips::ADDiu), Tmp1).addReg(Mips::ZERO).addImm(-4);
886   BuildMI(BB, dl, TII->get(Mips::AND), Addr).addReg(Ptr).addReg(Tmp1);
887   BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp2).addReg(Ptr).addImm(3);
888   BuildMI(BB, dl, TII->get(Mips::SLL), Shift).addReg(Tmp2).addImm(3);
889   BuildMI(BB, dl, TII->get(Mips::ORi), Tmp3).addReg(Mips::ZERO).addImm(MaskImm);
890   BuildMI(BB, dl, TII->get(Mips::SLL), Mask).addReg(Tmp3).addReg(Shift);
891   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
892   if (BinOpcode != Mips::SUBu) {
893     BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp4).addReg(Incr).addImm(MaskImm);
894     BuildMI(BB, dl, TII->get(Mips::SLL), Incr2).addReg(Tmp4).addReg(Shift);
895   } else {
896     BuildMI(BB, dl, TII->get(Mips::SUBu), Tmp4).addReg(Mips::ZERO).addReg(Incr);
897     BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp5).addReg(Tmp4).addImm(MaskImm);
898     BuildMI(BB, dl, TII->get(Mips::SLL), Incr2).addReg(Tmp5).addReg(Shift);
899   }
900
901   int fi = 0;
902   if (BinOpcode == 0 && !Nand) {
903     // Get or create a temporary stack location.
904     MipsFunctionInfo *MipsFI = MF->getInfo<MipsFunctionInfo>();
905     fi = MipsFI->getAtomicFrameIndex();
906     if (fi == -1) {
907       fi = MF->getFrameInfo()->CreateStackObject(Size, Size, false);
908       MipsFI->setAtomicFrameIndex(fi);
909     }
910
911     BuildMI(BB, dl, TII->get(Mips::SW))
912         .addReg(Incr2).addImm(0).addFrameIndex(fi);
913   }
914   BB->addSuccessor(loopMBB);
915
916   // loopMBB:
917   //   ll      oldval,0(addr)
918   //   binop   tmp7,oldval,incr2
919   //   and     newval,tmp7,mask
920   //   and     tmp8,oldval,mask2
921   //   or      tmp9,tmp8,newval
922   //   sc      tmp9,0(addr)
923   //   beq     tmp9,$0,loopMBB
924   BB = loopMBB;
925   BuildMI(BB, dl, TII->get(Mips::LL), Oldval).addImm(0).addReg(Addr);
926   if (Nand) {
927     //  and tmp6, oldval, incr2
928     //  nor tmp7, $0, tmp6
929     BuildMI(BB, dl, TII->get(Mips::AND), Tmp6).addReg(Oldval).addReg(Incr2);
930     BuildMI(BB, dl, TII->get(Mips::NOR), Tmp7).addReg(Mips::ZERO).addReg(Tmp6);
931   } else if (BinOpcode == Mips::SUBu) {
932     //  addu tmp7, oldval, incr2
933     BuildMI(BB, dl, TII->get(Mips::ADDu), Tmp7).addReg(Oldval).addReg(Incr2);
934   } else if (BinOpcode) {
935     //  <binop> tmp7, oldval, incr2
936     BuildMI(BB, dl, TII->get(BinOpcode), Tmp7).addReg(Oldval).addReg(Incr2);
937   } else {
938     //  lw tmp6, fi(sp)              // load incr2 from stack
939     //  or tmp7, $zero, tmp6
940     BuildMI(BB, dl, TII->get(Mips::LW), Tmp6).addImm(0).addFrameIndex(fi);;
941     BuildMI(BB, dl, TII->get(Mips::OR), Tmp7).addReg(Mips::ZERO).addReg(Tmp6);
942   }
943   BuildMI(BB, dl, TII->get(Mips::AND), Newval).addReg(Tmp7).addReg(Mask);
944   BuildMI(BB, dl, TII->get(Mips::AND), Tmp8).addReg(Oldval).addReg(Mask2);
945   BuildMI(BB, dl, TII->get(Mips::OR), Tmp9).addReg(Tmp8).addReg(Newval);
946   BuildMI(BB, dl, TII->get(Mips::SC), Tmp9).addReg(Tmp9).addImm(0).addReg(Addr);
947   BuildMI(BB, dl, TII->get(Mips::BEQ))
948       .addReg(Tmp9).addReg(Mips::ZERO).addMBB(loopMBB);
949   BB->addSuccessor(loopMBB);
950   BB->addSuccessor(exitMBB);
951
952   //  exitMBB:
953   //    and     tmp10,oldval,mask
954   //    srl     tmp11,tmp10,shift
955   //    sll     tmp12,tmp11,24
956   //    sra     dest,tmp12,24
957   BB = exitMBB;
958   int64_t ShiftImm = (Size == 1) ? 24 : 16;
959   // reverse order
960   BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SRA), Dest)
961       .addReg(Tmp12).addImm(ShiftImm);
962   BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SLL), Tmp12)
963       .addReg(Tmp11).addImm(ShiftImm);
964   BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SRL), Tmp11)
965       .addReg(Tmp10).addReg(Shift);
966   BuildMI(*BB, BB->begin(), dl, TII->get(Mips::AND), Tmp10)
967     .addReg(Oldval).addReg(Mask);
968
969   MI->eraseFromParent();   // The instruction is gone now.
970
971   return BB;
972 }
973
974 MachineBasicBlock *
975 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
976                                       MachineBasicBlock *BB,
977                                       unsigned Size) const {
978   assert(Size == 4 && "Unsupported size for EmitAtomicCmpSwap.");
979
980   MachineFunction *MF = BB->getParent();
981   MachineRegisterInfo &RegInfo = MF->getRegInfo();
982   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
983   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
984   DebugLoc dl = MI->getDebugLoc();
985
986   unsigned Dest    = MI->getOperand(0).getReg();
987   unsigned Ptr     = MI->getOperand(1).getReg();
988   unsigned Oldval  = MI->getOperand(2).getReg();
989   unsigned Newval  = MI->getOperand(3).getReg();
990
991   unsigned Tmp1 = RegInfo.createVirtualRegister(RC);
992   unsigned Tmp2 = RegInfo.createVirtualRegister(RC);
993
994   // insert new blocks after the current block
995   const BasicBlock *LLVM_BB = BB->getBasicBlock();
996   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
997   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
998   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
999   MachineFunction::iterator It = BB;
1000   ++It;
1001   MF->insert(It, loop1MBB);
1002   MF->insert(It, loop2MBB);
1003   MF->insert(It, exitMBB);
1004
1005   // Transfer the remainder of BB and its successor edges to exitMBB.
1006   exitMBB->splice(exitMBB->begin(), BB,
1007                   llvm::next(MachineBasicBlock::iterator(MI)),
1008                   BB->end());
1009   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1010
1011   // Get or create a temporary stack location.
1012   MipsFunctionInfo *MipsFI = MF->getInfo<MipsFunctionInfo>();
1013   int fi = MipsFI->getAtomicFrameIndex();
1014   if (fi == -1) {
1015     fi = MF->getFrameInfo()->CreateStackObject(Size, Size, false);
1016     MipsFI->setAtomicFrameIndex(fi);
1017   }
1018
1019   //  thisMBB:
1020   //    ...
1021   //    sw newval, fi(sp)           // store newval to stack
1022   //    fallthrough --> loop1MBB
1023
1024   // Note: storing newval to stack before the loop and then loading it from
1025   // stack in block loop2MBB is necessary to prevent MachineLICM pass to
1026   // hoist "or" instruction out of the block loop2MBB.
1027
1028   BuildMI(BB, dl, TII->get(Mips::SW))
1029       .addReg(Newval).addImm(0).addFrameIndex(fi);
1030   BB->addSuccessor(loop1MBB);
1031
1032   // loop1MBB:
1033   //   ll dest, 0(ptr)
1034   //   bne dest, oldval, exitMBB
1035   BB = loop1MBB;
1036   BuildMI(BB, dl, TII->get(Mips::LL), Dest).addImm(0).addReg(Ptr);
1037   BuildMI(BB, dl, TII->get(Mips::BNE))
1038     .addReg(Dest).addReg(Oldval).addMBB(exitMBB);
1039   BB->addSuccessor(exitMBB);
1040   BB->addSuccessor(loop2MBB);
1041
1042   // loop2MBB:
1043   //   lw tmp2, fi(sp)              // load newval from stack
1044   //   or tmp1, $0, tmp2
1045   //   sc tmp1, 0(ptr)
1046   //   beq tmp1, $0, loop1MBB
1047   BB = loop2MBB;
1048   BuildMI(BB, dl, TII->get(Mips::LW), Tmp2).addImm(0).addFrameIndex(fi);;
1049   BuildMI(BB, dl, TII->get(Mips::OR), Tmp1).addReg(Mips::ZERO).addReg(Tmp2);
1050   BuildMI(BB, dl, TII->get(Mips::SC), Tmp1).addReg(Tmp1).addImm(0).addReg(Ptr);
1051   BuildMI(BB, dl, TII->get(Mips::BEQ))
1052     .addReg(Tmp1).addReg(Mips::ZERO).addMBB(loop1MBB);
1053   BB->addSuccessor(loop1MBB);
1054   BB->addSuccessor(exitMBB);
1055
1056   MI->eraseFromParent();   // The instruction is gone now.
1057
1058   return BB;
1059 }
1060
1061 MachineBasicBlock *
1062 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1063                                               MachineBasicBlock *BB,
1064                                               unsigned Size) const {
1065   assert((Size == 1 || Size == 2) &&
1066       "Unsupported size for EmitAtomicCmpSwapPartial.");
1067
1068   MachineFunction *MF = BB->getParent();
1069   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1070   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1071   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1072   DebugLoc dl = MI->getDebugLoc();
1073
1074   unsigned Dest    = MI->getOperand(0).getReg();
1075   unsigned Ptr     = MI->getOperand(1).getReg();
1076   unsigned Oldval  = MI->getOperand(2).getReg();
1077   unsigned Newval  = MI->getOperand(3).getReg();
1078
1079   unsigned Addr = RegInfo.createVirtualRegister(RC);
1080   unsigned Shift = RegInfo.createVirtualRegister(RC);
1081   unsigned Mask = RegInfo.createVirtualRegister(RC);
1082   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1083   unsigned Oldval2 = RegInfo.createVirtualRegister(RC);
1084   unsigned Oldval3 = RegInfo.createVirtualRegister(RC);
1085   unsigned Oldval4 = RegInfo.createVirtualRegister(RC);
1086   unsigned Newval2 = RegInfo.createVirtualRegister(RC);
1087   unsigned Tmp1 = RegInfo.createVirtualRegister(RC);
1088   unsigned Tmp2 = RegInfo.createVirtualRegister(RC);
1089   unsigned Tmp3 = RegInfo.createVirtualRegister(RC);
1090   unsigned Tmp4 = RegInfo.createVirtualRegister(RC);
1091   unsigned Tmp5 = RegInfo.createVirtualRegister(RC);
1092   unsigned Tmp6 = RegInfo.createVirtualRegister(RC);
1093   unsigned Tmp7 = RegInfo.createVirtualRegister(RC);
1094   unsigned Tmp8 = RegInfo.createVirtualRegister(RC);
1095   unsigned Tmp9 = RegInfo.createVirtualRegister(RC);
1096
1097   // insert new blocks after the current block
1098   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1099   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1100   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1101   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1102   MachineFunction::iterator It = BB;
1103   ++It;
1104   MF->insert(It, loop1MBB);
1105   MF->insert(It, loop2MBB);
1106   MF->insert(It, exitMBB);
1107
1108   // Transfer the remainder of BB and its successor edges to exitMBB.
1109   exitMBB->splice(exitMBB->begin(), BB,
1110                   llvm::next(MachineBasicBlock::iterator(MI)),
1111                   BB->end());
1112   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1113
1114   //  thisMBB:
1115   //    addiu   tmp1,$0,-4                # 0xfffffffc
1116   //    and     addr,ptr,tmp1
1117   //    andi    tmp2,ptr,3
1118   //    sll     shift,tmp2,3
1119   //    ori     tmp3,$0,255               # 0xff
1120   //    sll     mask,tmp3,shift
1121   //    nor     mask2,$0,mask
1122   //    andi    tmp4,oldval,255
1123   //    sll     oldval2,tmp4,shift
1124   //    andi    tmp5,newval,255
1125   //    sll     newval2,tmp5,shift
1126   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1127   BuildMI(BB, dl, TII->get(Mips::ADDiu), Tmp1).addReg(Mips::ZERO).addImm(-4);
1128   BuildMI(BB, dl, TII->get(Mips::AND), Addr).addReg(Ptr).addReg(Tmp1);
1129   BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp2).addReg(Ptr).addImm(3);
1130   BuildMI(BB, dl, TII->get(Mips::SLL), Shift).addReg(Tmp2).addImm(3);
1131   BuildMI(BB, dl, TII->get(Mips::ORi), Tmp3).addReg(Mips::ZERO).addImm(MaskImm);
1132   BuildMI(BB, dl, TII->get(Mips::SLL), Mask).addReg(Tmp3).addReg(Shift);
1133   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1134   BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp4).addReg(Oldval).addImm(MaskImm);
1135   BuildMI(BB, dl, TII->get(Mips::SLL), Oldval2).addReg(Tmp4).addReg(Shift);
1136   BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp5).addReg(Newval).addImm(MaskImm);
1137   BuildMI(BB, dl, TII->get(Mips::SLL), Newval2).addReg(Tmp5).addReg(Shift);
1138   BB->addSuccessor(loop1MBB);
1139
1140   //  loop1MBB:
1141   //    ll      oldval3,0(addr)
1142   //    and     oldval4,oldval3,mask
1143   //    bne     oldval4,oldval2,exitMBB
1144   BB = loop1MBB;
1145   BuildMI(BB, dl, TII->get(Mips::LL), Oldval3).addImm(0).addReg(Addr);
1146   BuildMI(BB, dl, TII->get(Mips::AND), Oldval4).addReg(Oldval3).addReg(Mask);
1147   BuildMI(BB, dl, TII->get(Mips::BNE))
1148       .addReg(Oldval4).addReg(Oldval2).addMBB(exitMBB);
1149   BB->addSuccessor(exitMBB);
1150   BB->addSuccessor(loop2MBB);
1151
1152   //  loop2MBB:
1153   //    and     tmp6,oldval3,mask2
1154   //    or      tmp7,tmp6,newval2
1155   //    sc      tmp7,0(addr)
1156   //    beq     tmp7,$0,loop1MBB
1157   BB = loop2MBB;
1158   BuildMI(BB, dl, TII->get(Mips::AND), Tmp6).addReg(Oldval3).addReg(Mask2);
1159   BuildMI(BB, dl, TII->get(Mips::OR), Tmp7).addReg(Tmp6).addReg(Newval2);
1160   BuildMI(BB, dl, TII->get(Mips::SC), Tmp7)
1161       .addReg(Tmp7).addImm(0).addReg(Addr);
1162   BuildMI(BB, dl, TII->get(Mips::BEQ))
1163       .addReg(Tmp7).addReg(Mips::ZERO).addMBB(loop1MBB);
1164   BB->addSuccessor(loop1MBB);
1165   BB->addSuccessor(exitMBB);
1166
1167   //  exitMBB:
1168   //    srl     tmp8,oldval4,shift
1169   //    sll     tmp9,tmp8,24
1170   //    sra     dest,tmp9,24
1171   BB = exitMBB;
1172   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1173   // reverse order
1174   BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SRA), Dest)
1175       .addReg(Tmp9).addImm(ShiftImm);
1176   BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SLL), Tmp9)
1177       .addReg(Tmp8).addImm(ShiftImm);
1178   BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SRL), Tmp8)
1179       .addReg(Oldval4).addReg(Shift);
1180
1181   MI->eraseFromParent();   // The instruction is gone now.
1182
1183   return BB;
1184 }
1185
1186 //===----------------------------------------------------------------------===//
1187 //  Misc Lower Operation implementation
1188 //===----------------------------------------------------------------------===//
1189 SDValue MipsTargetLowering::
1190 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1191 {
1192   unsigned StackAlignment =
1193     getTargetMachine().getFrameLowering()->getStackAlignment();
1194   assert(StackAlignment >=
1195          cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1196          "Cannot lower if the alignment of the allocated space is larger than \
1197           that of the stack.");
1198
1199   SDValue Chain = Op.getOperand(0);
1200   SDValue Size = Op.getOperand(1);
1201   DebugLoc dl = Op.getDebugLoc();
1202
1203   // Get a reference from Mips stack pointer
1204   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
1205
1206   // Subtract the dynamic size from the actual stack size to
1207   // obtain the new stack size.
1208   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
1209
1210   // The Sub result contains the new stack start address, so it
1211   // must be placed in the stack pointer register.
1212   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub,
1213                            SDValue());
1214   // Retrieve updated $sp. There is a glue input to prevent instructions that
1215   // clobber $sp from being inserted between copytoreg and copyfromreg.
1216   SDValue NewSP = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32,
1217                                      Chain.getValue(1));
1218
1219   // The stack space reserved by alloca is located right above the argument
1220   // area. It is aligned on a boundary that is a multiple of StackAlignment.
1221   MachineFunction &MF = DAG.getMachineFunction();
1222   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1223   unsigned SPOffset = (MipsFI->getMaxCallFrameSize() + StackAlignment - 1) /
1224                       StackAlignment * StackAlignment;
1225   SDValue AllocPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
1226                                  DAG.getConstant(SPOffset, MVT::i32));
1227
1228   // This node always has two return values: a new stack pointer
1229   // value and a chain
1230   SDValue Ops[2] = { AllocPtr, NewSP.getValue(1) };
1231   return DAG.getMergeValues(Ops, 2, dl);
1232 }
1233
1234 SDValue MipsTargetLowering::
1235 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1236 {
1237   // The first operand is the chain, the second is the condition, the third is
1238   // the block to branch to if the condition is true.
1239   SDValue Chain = Op.getOperand(0);
1240   SDValue Dest = Op.getOperand(2);
1241   DebugLoc dl = Op.getDebugLoc();
1242
1243   SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1244
1245   // Return if flag is not set by a floating point comparison.
1246   if (CondRes.getOpcode() != MipsISD::FPCmp)
1247     return Op;
1248
1249   SDValue CCNode  = CondRes.getOperand(2);
1250   Mips::CondCode CC =
1251     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1252   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1253
1254   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1255                      Dest, CondRes);
1256 }
1257
1258 SDValue MipsTargetLowering::
1259 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1260 {
1261   SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1262
1263   // Return if flag is not set by a floating point comparison.
1264   if (Cond.getOpcode() != MipsISD::FPCmp)
1265     return Op;
1266
1267   return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1268                       Op.getDebugLoc());
1269 }
1270
1271 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1272                                                SelectionDAG &DAG) const {
1273   // FIXME there isn't actually debug info here
1274   DebugLoc dl = Op.getDebugLoc();
1275   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1276
1277   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1278     SDVTList VTs = DAG.getVTList(MVT::i32);
1279
1280     MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1281
1282     // %gp_rel relocation
1283     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1284       SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1285                                               MipsII::MO_GPREL);
1286       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1287       SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1288       return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1289     }
1290     // %hi/%lo relocation
1291     SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1292                                               MipsII::MO_ABS_HI);
1293     SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1294                                               MipsII::MO_ABS_LO);
1295     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1296     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1297     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1298   }
1299
1300   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1301                                           MipsII::MO_GOT);
1302   GA = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, GA);
1303   SDValue ResNode = DAG.getLoad(MVT::i32, dl,
1304                                 DAG.getEntryNode(), GA, MachinePointerInfo(),
1305                                 false, false, 0);
1306   // On functions and global targets not internal linked only
1307   // a load from got/GP is necessary for PIC to work.
1308   if (!GV->hasInternalLinkage() &&
1309       (!GV->hasLocalLinkage() || isa<Function>(GV)))
1310     return ResNode;
1311   SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1312                                             MipsII::MO_ABS_LO);
1313   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1314   return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
1315 }
1316
1317 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1318                                               SelectionDAG &DAG) const {
1319   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1320   // FIXME there isn't actually debug info here
1321   DebugLoc dl = Op.getDebugLoc();
1322
1323   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1324     // %hi/%lo relocation
1325     SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1326                                        MipsII::MO_ABS_HI);
1327     SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1328                                        MipsII::MO_ABS_LO);
1329     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1330     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1331     return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1332   }
1333
1334   SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1335                                             MipsII::MO_GOT);
1336   BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffset);
1337   SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1338                                            MipsII::MO_ABS_LO);
1339   SDValue Load = DAG.getLoad(MVT::i32, dl,
1340                              DAG.getEntryNode(), BAGOTOffset,
1341                              MachinePointerInfo(), false, false, 0);
1342   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
1343   return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1344 }
1345
1346 SDValue MipsTargetLowering::
1347 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1348 {
1349   // If the relocation model is PIC, use the General Dynamic TLS Model,
1350   // otherwise use the Initial Exec or Local Exec TLS Model.
1351   // TODO: implement Local Dynamic TLS model
1352
1353   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1354   DebugLoc dl = GA->getDebugLoc();
1355   const GlobalValue *GV = GA->getGlobal();
1356   EVT PtrVT = getPointerTy();
1357
1358   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1359     // General Dynamic TLS Model
1360     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1361                                                  0, MipsII::MO_TLSGD);
1362     SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1363     SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1364     SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1365
1366     ArgListTy Args;
1367     ArgListEntry Entry;
1368     Entry.Node = Argument;
1369     Entry.Ty = (const Type *) Type::getInt32Ty(*DAG.getContext());
1370     Args.push_back(Entry);
1371     std::pair<SDValue, SDValue> CallResult =
1372         LowerCallTo(DAG.getEntryNode(),
1373                  (const Type *) Type::getInt32Ty(*DAG.getContext()),
1374                  false, false, false, false,
1375                  0, CallingConv::C, false, true,
1376                  DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1377
1378     return CallResult.first;
1379   } else {
1380     SDValue Offset;
1381     if (GV->isDeclaration()) {
1382       // Initial Exec TLS Model
1383       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1384                                               MipsII::MO_GOTTPREL);
1385       Offset = DAG.getLoad(MVT::i32, dl,
1386                                   DAG.getEntryNode(), TGA, MachinePointerInfo(),
1387                                   false, false, 0);
1388     } else {
1389       // Local Exec TLS Model
1390       SDVTList VTs = DAG.getVTList(MVT::i32);
1391       SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1392                                               MipsII::MO_TPREL_HI);
1393       SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1394                                               MipsII::MO_TPREL_LO);
1395       SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1396       SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1397       Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1398     }
1399
1400     SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1401     return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1402   }
1403 }
1404
1405 SDValue MipsTargetLowering::
1406 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1407 {
1408   SDValue ResNode;
1409   SDValue HiPart;
1410   // FIXME there isn't actually debug info here
1411   DebugLoc dl = Op.getDebugLoc();
1412   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1413   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1414
1415   EVT PtrVT = Op.getValueType();
1416   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
1417
1418   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1419
1420   if (!IsPIC) {
1421     SDValue Ops[] = { JTI };
1422     HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1423   } else {// Emit Load from Global Pointer
1424     JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1425     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1426                          MachinePointerInfo(),
1427                          false, false, 0);
1428   }
1429
1430   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1431                                          MipsII::MO_ABS_LO);
1432   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1433   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1434
1435   return ResNode;
1436 }
1437
1438 SDValue MipsTargetLowering::
1439 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1440 {
1441   SDValue ResNode;
1442   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1443   const Constant *C = N->getConstVal();
1444   // FIXME there isn't actually debug info here
1445   DebugLoc dl = Op.getDebugLoc();
1446
1447   // gp_rel relocation
1448   // FIXME: we should reference the constant pool using small data sections,
1449   // but the asm printer currently doesn't support this feature without
1450   // hacking it. This feature should come soon so we can uncomment the
1451   // stuff below.
1452   //if (IsInSmallSection(C->getType())) {
1453   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1454   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1455   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1456
1457   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1458     SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1459                                              N->getOffset(), MipsII::MO_ABS_HI);
1460     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1461                                              N->getOffset(), MipsII::MO_ABS_LO);
1462     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1463     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1464     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1465   } else {
1466     SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1467                                            N->getOffset(), MipsII::MO_GOT);
1468     CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1469     SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1470                                CP, MachinePointerInfo::getConstantPool(),
1471                                false, false, 0);
1472     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1473                                              N->getOffset(), MipsII::MO_ABS_LO);
1474     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1475     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1476   }
1477
1478   return ResNode;
1479 }
1480
1481 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1482   MachineFunction &MF = DAG.getMachineFunction();
1483   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1484
1485   DebugLoc dl = Op.getDebugLoc();
1486   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1487                                  getPointerTy());
1488
1489   // vastart just stores the address of the VarArgsFrameIndex slot into the
1490   // memory location argument.
1491   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1492   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1493                       MachinePointerInfo(SV),
1494                       false, false, 0);
1495 }
1496
1497 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1498   // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1499   DebugLoc dl = Op.getDebugLoc();
1500   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1501   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1502   SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1503                              DAG.getConstant(0x7fffffff, MVT::i32));
1504   SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1505                              DAG.getConstant(0x80000000, MVT::i32));
1506   SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1507   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1508 }
1509
1510 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1511   // FIXME:
1512   //  Use ext/ins instructions if target architecture is Mips32r2.
1513   //  Eliminate redundant mfc1 and mtc1 instructions.
1514   unsigned LoIdx = 0, HiIdx = 1;
1515
1516   if (!isLittle)
1517     std::swap(LoIdx, HiIdx);
1518
1519   DebugLoc dl = Op.getDebugLoc();
1520   SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1521                               Op.getOperand(0),
1522                               DAG.getConstant(LoIdx, MVT::i32));
1523   SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1524                             Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1525   SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1526                             Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1527   SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1528                              DAG.getConstant(0x7fffffff, MVT::i32));
1529   SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1530                              DAG.getConstant(0x80000000, MVT::i32));
1531   SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1532
1533   if (!isLittle)
1534     std::swap(Word0, Word1);
1535
1536   return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1537 }
1538
1539 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1540   const {
1541   EVT Ty = Op.getValueType();
1542
1543   assert(Ty == MVT::f32 || Ty == MVT::f64);
1544
1545   if (Ty == MVT::f32)
1546     return LowerFCOPYSIGN32(Op, DAG);
1547   else
1548     return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1549 }
1550
1551 SDValue MipsTargetLowering::
1552 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1553   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1554   assert((Depth == 0) &&
1555          "Frame address can only be determined for current frame.");
1556
1557   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1558   MFI->setFrameAddressIsTaken(true);
1559   EVT VT = Op.getValueType();
1560   DebugLoc dl = Op.getDebugLoc();
1561   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Mips::FP, VT);
1562   return FrameAddr;
1563 }
1564
1565 //===----------------------------------------------------------------------===//
1566 //                      Calling Convention Implementation
1567 //===----------------------------------------------------------------------===//
1568
1569 #include "MipsGenCallingConv.inc"
1570
1571 //===----------------------------------------------------------------------===//
1572 // TODO: Implement a generic logic using tblgen that can support this.
1573 // Mips O32 ABI rules:
1574 // ---
1575 // i32 - Passed in A0, A1, A2, A3 and stack
1576 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1577 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
1578 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1579 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1580 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
1581 //       go to stack.
1582 //
1583 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1584 //===----------------------------------------------------------------------===//
1585
1586 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1587                        MVT LocVT, CCValAssign::LocInfo LocInfo,
1588                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
1589
1590   static const unsigned IntRegsSize=4, FloatRegsSize=2;
1591
1592   static const unsigned IntRegs[] = {
1593       Mips::A0, Mips::A1, Mips::A2, Mips::A3
1594   };
1595   static const unsigned F32Regs[] = {
1596       Mips::F12, Mips::F14
1597   };
1598   static const unsigned F64Regs[] = {
1599       Mips::D6, Mips::D7
1600   };
1601
1602   // ByVal Args
1603   if (ArgFlags.isByVal()) {
1604     State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1605                       1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1606     unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1607     for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1608          r < std::min(IntRegsSize, NextReg); ++r)
1609       State.AllocateReg(IntRegs[r]);
1610     return false;
1611   }
1612
1613   // Promote i8 and i16
1614   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1615     LocVT = MVT::i32;
1616     if (ArgFlags.isSExt())
1617       LocInfo = CCValAssign::SExt;
1618     else if (ArgFlags.isZExt())
1619       LocInfo = CCValAssign::ZExt;
1620     else
1621       LocInfo = CCValAssign::AExt;
1622   }
1623
1624   unsigned Reg;
1625
1626   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1627   // is true: function is vararg, argument is 3rd or higher, there is previous
1628   // argument which is not f32 or f64.
1629   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1630       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1631   unsigned OrigAlign = ArgFlags.getOrigAlign();
1632   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1633
1634   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1635     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1636     // If this is the first part of an i64 arg,
1637     // the allocated register must be either A0 or A2.
1638     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1639       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1640     LocVT = MVT::i32;
1641   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1642     // Allocate int register and shadow next int register. If first
1643     // available register is Mips::A1 or Mips::A3, shadow it too.
1644     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1645     if (Reg == Mips::A1 || Reg == Mips::A3)
1646       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1647     State.AllocateReg(IntRegs, IntRegsSize);
1648     LocVT = MVT::i32;
1649   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1650     // we are guaranteed to find an available float register
1651     if (ValVT == MVT::f32) {
1652       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1653       // Shadow int register
1654       State.AllocateReg(IntRegs, IntRegsSize);
1655     } else {
1656       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1657       // Shadow int registers
1658       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1659       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1660         State.AllocateReg(IntRegs, IntRegsSize);
1661       State.AllocateReg(IntRegs, IntRegsSize);
1662     }
1663   } else
1664     llvm_unreachable("Cannot handle this ValVT.");
1665
1666   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1667   unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1668
1669   if (!Reg)
1670     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1671   else
1672     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1673
1674   return false; // CC must always match
1675 }
1676
1677 //===----------------------------------------------------------------------===//
1678 //                  Call Calling Convention Implementation
1679 //===----------------------------------------------------------------------===//
1680
1681 static const unsigned O32IntRegsSize = 4;
1682
1683 static const unsigned O32IntRegs[] = {
1684   Mips::A0, Mips::A1, Mips::A2, Mips::A3
1685 };
1686
1687 // Write ByVal Arg to arg registers and stack.
1688 static void
1689 WriteByValArg(SDValue& Chain, DebugLoc dl,
1690               SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1691               SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1692               MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1693               const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1694               MVT PtrType) {
1695   unsigned FirstWord = VA.getLocMemOffset() / 4;
1696   unsigned NumWords = (Flags.getByValSize() + 3) / 4;
1697   unsigned LastWord = FirstWord + NumWords;
1698   unsigned CurWord;
1699
1700   // copy the first 4 words of byval arg to registers A0 - A3
1701   for (CurWord = FirstWord; CurWord < std::min(LastWord, O32IntRegsSize);
1702        ++CurWord) {
1703     SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1704                                   DAG.getConstant((CurWord - FirstWord) * 4,
1705                                                   MVT::i32));
1706     SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1707                                   MachinePointerInfo(),
1708                                   false, false, 0);
1709     MemOpChains.push_back(LoadVal.getValue(1));
1710     unsigned DstReg = O32IntRegs[CurWord];
1711     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1712   }
1713
1714   // copy remaining part of byval arg to stack.
1715   if (CurWord < LastWord) {
1716     unsigned SizeInBytes = (LastWord - CurWord) * 4;
1717     SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1718                               DAG.getConstant((CurWord - FirstWord) * 4,
1719                                               MVT::i32));
1720     LastFI = MFI->CreateFixedObject(SizeInBytes, CurWord * 4, true);
1721     SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
1722     Chain = DAG.getMemcpy(Chain, dl, Dst, Src,
1723                           DAG.getConstant(SizeInBytes, MVT::i32),
1724                           /*Align*/4,
1725                           /*isVolatile=*/false, /*AlwaysInline=*/false,
1726                           MachinePointerInfo(0), MachinePointerInfo(0));
1727     MemOpChains.push_back(Chain);
1728   }
1729 }
1730
1731 /// LowerCall - functions arguments are copied from virtual regs to
1732 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1733 /// TODO: isTailCall.
1734 SDValue
1735 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1736                               CallingConv::ID CallConv, bool isVarArg,
1737                               bool &isTailCall,
1738                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1739                               const SmallVectorImpl<SDValue> &OutVals,
1740                               const SmallVectorImpl<ISD::InputArg> &Ins,
1741                               DebugLoc dl, SelectionDAG &DAG,
1742                               SmallVectorImpl<SDValue> &InVals) const {
1743   // MIPs target does not yet support tail call optimization.
1744   isTailCall = false;
1745
1746   MachineFunction &MF = DAG.getMachineFunction();
1747   MachineFrameInfo *MFI = MF.getFrameInfo();
1748   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
1749   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1750   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1751
1752   // Analyze operands of the call, assigning locations to each operand.
1753   SmallVector<CCValAssign, 16> ArgLocs;
1754   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1755                  getTargetMachine(), ArgLocs, *DAG.getContext());
1756
1757   if (Subtarget->isABI_O32())
1758     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
1759   else
1760     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1761
1762   // Get a count of how many bytes are to be pushed on the stack.
1763   unsigned NextStackOffset = CCInfo.getNextStackOffset();
1764
1765   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NextStackOffset,
1766                                                             true));
1767
1768   // If this is the first call, create a stack frame object that points to
1769   // a location to which .cprestore saves $gp.
1770   if (IsPIC && !MipsFI->getGPFI())
1771     MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
1772
1773   // Update size of the maximum argument space.
1774   // For O32, a minimum of four words (16 bytes) of argument space is
1775   // allocated.
1776   if (Subtarget->isABI_O32())
1777     NextStackOffset = std::max(NextStackOffset, (unsigned)16);
1778
1779   unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
1780
1781   if (MaxCallFrameSize < NextStackOffset) {
1782     MipsFI->setMaxCallFrameSize(NextStackOffset);
1783
1784     if (IsPIC) {
1785       // $gp restore slot must be aligned.
1786       unsigned StackAlignment = TFL->getStackAlignment();
1787       NextStackOffset = (NextStackOffset + StackAlignment - 1) /
1788                         StackAlignment * StackAlignment;
1789       int GPFI = MipsFI->getGPFI();
1790       MFI->setObjectOffset(GPFI, NextStackOffset);
1791     }
1792   }
1793
1794   // With EABI is it possible to have 16 args on registers.
1795   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1796   SmallVector<SDValue, 8> MemOpChains;
1797
1798   int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
1799
1800   // Walk the register/memloc assignments, inserting copies/loads.
1801   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1802     SDValue Arg = OutVals[i];
1803     CCValAssign &VA = ArgLocs[i];
1804
1805     // Promote the value if needed.
1806     switch (VA.getLocInfo()) {
1807     default: llvm_unreachable("Unknown loc info!");
1808     case CCValAssign::Full:
1809       if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1810         if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1811           Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1812         if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1813           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1814                                    Arg, DAG.getConstant(0, MVT::i32));
1815           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1816                                    Arg, DAG.getConstant(1, MVT::i32));
1817           if (!Subtarget->isLittle())
1818             std::swap(Lo, Hi);
1819           RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1820           RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1821           continue;
1822         }
1823       }
1824       break;
1825     case CCValAssign::SExt:
1826       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1827       break;
1828     case CCValAssign::ZExt:
1829       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1830       break;
1831     case CCValAssign::AExt:
1832       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1833       break;
1834     }
1835
1836     // Arguments that can be passed on register must be kept at
1837     // RegsToPass vector
1838     if (VA.isRegLoc()) {
1839       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1840       continue;
1841     }
1842
1843     // Register can't get to this point...
1844     assert(VA.isMemLoc());
1845
1846     // ByVal Arg.
1847     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1848     if (Flags.isByVal()) {
1849       assert(Subtarget->isABI_O32() &&
1850              "No support for ByVal args by ABIs other than O32 yet.");
1851       assert(Flags.getByValSize() &&
1852              "ByVal args of size 0 should have been ignored by front-end.");
1853       WriteByValArg(Chain, dl, RegsToPass, MemOpChains, LastFI, MFI, DAG, Arg,
1854                     VA, Flags, getPointerTy());
1855       continue;
1856     }
1857
1858     // Create the frame index object for this incoming parameter
1859     LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1860                                     VA.getLocMemOffset(), true);
1861     SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
1862
1863     // emit ISD::STORE whichs stores the
1864     // parameter value to a stack Location
1865     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1866                                        MachinePointerInfo(),
1867                                        false, false, 0));
1868   }
1869
1870   // Extend range of indices of frame objects for outgoing arguments that were
1871   // created during this function call. Skip this step if no such objects were
1872   // created.
1873   if (LastFI)
1874     MipsFI->extendOutArgFIRange(FirstFI, LastFI);
1875
1876   // Transform all store nodes into one single node because all store
1877   // nodes are independent of each other.
1878   if (!MemOpChains.empty())
1879     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1880                         &MemOpChains[0], MemOpChains.size());
1881
1882   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1883   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1884   // node so that legalize doesn't hack it.
1885   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1886   bool LoadSymAddr = false;
1887   SDValue CalleeLo;
1888
1889   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1890     if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
1891       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1892                                           getPointerTy(), 0,MipsII:: MO_GOT);
1893       CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
1894                                             0, MipsII::MO_ABS_LO);
1895     } else {
1896       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1897                                           getPointerTy(), 0, OpFlag);
1898     }
1899
1900     LoadSymAddr = true;
1901   }
1902   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1903     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1904                                 getPointerTy(), OpFlag);
1905     LoadSymAddr = true;
1906   }
1907
1908   SDValue InFlag;
1909
1910   // Create nodes that load address of callee and copy it to T9
1911   if (IsPIC) {
1912     if (LoadSymAddr) {
1913       // Load callee address
1914       Callee = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, Callee);
1915       SDValue LoadValue = DAG.getLoad(MVT::i32, dl, Chain, Callee,
1916                                       MachinePointerInfo::getGOT(),
1917                                       false, false, 0);
1918
1919       // Use GOT+LO if callee has internal linkage.
1920       if (CalleeLo.getNode()) {
1921         SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
1922         Callee = DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
1923       } else
1924         Callee = LoadValue;
1925
1926       // Use chain output from LoadValue
1927       Chain = LoadValue.getValue(1);
1928     }
1929
1930     // copy to T9
1931     Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
1932     InFlag = Chain.getValue(1);
1933     Callee = DAG.getRegister(Mips::T9, MVT::i32);
1934   }
1935
1936   // Build a sequence of copy-to-reg nodes chained together with token
1937   // chain and flag operands which copy the outgoing args into registers.
1938   // The InFlag in necessary since all emitted instructions must be
1939   // stuck together.
1940   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1941     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1942                              RegsToPass[i].second, InFlag);
1943     InFlag = Chain.getValue(1);
1944   }
1945
1946   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1947   //             = Chain, Callee, Reg#1, Reg#2, ...
1948   //
1949   // Returns a chain & a flag for retval copy to use.
1950   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1951   SmallVector<SDValue, 8> Ops;
1952   Ops.push_back(Chain);
1953   Ops.push_back(Callee);
1954
1955   // Add argument registers to the end of the list so that they are
1956   // known live into the call.
1957   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1958     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1959                                   RegsToPass[i].second.getValueType()));
1960
1961   if (InFlag.getNode())
1962     Ops.push_back(InFlag);
1963
1964   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1965   InFlag = Chain.getValue(1);
1966
1967   // Create the CALLSEQ_END node.
1968   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NextStackOffset, true),
1969                              DAG.getIntPtrConstant(0, true), InFlag);
1970   InFlag = Chain.getValue(1);
1971
1972   // Handle result values, copying them out of physregs into vregs that we
1973   // return.
1974   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1975                          Ins, dl, DAG, InVals);
1976 }
1977
1978 /// LowerCallResult - Lower the result values of a call into the
1979 /// appropriate copies out of appropriate physical registers.
1980 SDValue
1981 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1982                                     CallingConv::ID CallConv, bool isVarArg,
1983                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1984                                     DebugLoc dl, SelectionDAG &DAG,
1985                                     SmallVectorImpl<SDValue> &InVals) const {
1986   // Assign locations to each value returned by this call.
1987   SmallVector<CCValAssign, 16> RVLocs;
1988   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1989                  getTargetMachine(), RVLocs, *DAG.getContext());
1990
1991   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1992
1993   // Copy all of the result registers out of their specified physreg.
1994   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1995     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1996                                RVLocs[i].getValVT(), InFlag).getValue(1);
1997     InFlag = Chain.getValue(2);
1998     InVals.push_back(Chain.getValue(0));
1999   }
2000
2001   return Chain;
2002 }
2003
2004 //===----------------------------------------------------------------------===//
2005 //             Formal Arguments Calling Convention Implementation
2006 //===----------------------------------------------------------------------===//
2007 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2008                          std::vector<SDValue>& OutChains,
2009                          SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2010                          const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2011   unsigned LocMem = VA.getLocMemOffset();
2012   unsigned FirstWord = LocMem / 4;
2013
2014   // copy register A0 - A3 to frame object
2015   for (unsigned i = 0; i < NumWords; ++i) {
2016     unsigned CurWord = FirstWord + i;
2017     if (CurWord >= O32IntRegsSize)
2018       break;
2019
2020     unsigned SrcReg = O32IntRegs[CurWord];
2021     unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2022     SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2023                                    DAG.getConstant(i * 4, MVT::i32));
2024     SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2025                                  StorePtr, MachinePointerInfo(), false,
2026                                  false, 0);
2027     OutChains.push_back(Store);
2028   }
2029 }
2030
2031 /// LowerFormalArguments - transform physical registers into virtual registers
2032 /// and generate load operations for arguments places on the stack.
2033 SDValue
2034 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2035                                          CallingConv::ID CallConv,
2036                                          bool isVarArg,
2037                                          const SmallVectorImpl<ISD::InputArg>
2038                                          &Ins,
2039                                          DebugLoc dl, SelectionDAG &DAG,
2040                                          SmallVectorImpl<SDValue> &InVals)
2041                                           const {
2042   MachineFunction &MF = DAG.getMachineFunction();
2043   MachineFrameInfo *MFI = MF.getFrameInfo();
2044   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2045
2046   MipsFI->setVarArgsFrameIndex(0);
2047
2048   // Used with vargs to acumulate store chains.
2049   std::vector<SDValue> OutChains;
2050
2051   // Assign locations to all of the incoming arguments.
2052   SmallVector<CCValAssign, 16> ArgLocs;
2053   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2054                  getTargetMachine(), ArgLocs, *DAG.getContext());
2055
2056   if (Subtarget->isABI_O32())
2057     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2058   else
2059     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2060
2061   int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2062
2063   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2064     CCValAssign &VA = ArgLocs[i];
2065
2066     // Arguments stored on registers
2067     if (VA.isRegLoc()) {
2068       EVT RegVT = VA.getLocVT();
2069       unsigned ArgReg = VA.getLocReg();
2070       TargetRegisterClass *RC = 0;
2071
2072       if (RegVT == MVT::i32)
2073         RC = Mips::CPURegsRegisterClass;
2074       else if (RegVT == MVT::f32)
2075         RC = Mips::FGR32RegisterClass;
2076       else if (RegVT == MVT::f64) {
2077         if (!Subtarget->isSingleFloat())
2078           RC = Mips::AFGR64RegisterClass;
2079       } else
2080         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2081
2082       // Transform the arguments stored on
2083       // physical registers into virtual ones
2084       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2085       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2086
2087       // If this is an 8 or 16-bit value, it has been passed promoted
2088       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2089       // truncate to the right size.
2090       if (VA.getLocInfo() != CCValAssign::Full) {
2091         unsigned Opcode = 0;
2092         if (VA.getLocInfo() == CCValAssign::SExt)
2093           Opcode = ISD::AssertSext;
2094         else if (VA.getLocInfo() == CCValAssign::ZExt)
2095           Opcode = ISD::AssertZext;
2096         if (Opcode)
2097           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2098                                  DAG.getValueType(VA.getValVT()));
2099         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2100       }
2101
2102       // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
2103       if (Subtarget->isABI_O32()) {
2104         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
2105           ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
2106         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
2107           unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2108                                     VA.getLocReg()+1, RC);
2109           SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2110           if (!Subtarget->isLittle())
2111             std::swap(ArgValue, ArgValue2);
2112           ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2113                                  ArgValue, ArgValue2);
2114         }
2115       }
2116
2117       InVals.push_back(ArgValue);
2118     } else { // VA.isRegLoc()
2119
2120       // sanity check
2121       assert(VA.isMemLoc());
2122
2123       ISD::ArgFlagsTy Flags = Ins[i].Flags;
2124
2125       if (Flags.isByVal()) {
2126         assert(Subtarget->isABI_O32() &&
2127                "No support for ByVal args by ABIs other than O32 yet.");
2128         assert(Flags.getByValSize() &&
2129                "ByVal args of size 0 should have been ignored by front-end.");
2130         unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2131         LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2132                                         true);
2133         SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2134         InVals.push_back(FIN);
2135         ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2136
2137         continue;
2138       }
2139
2140       // The stack pointer offset is relative to the caller stack frame.
2141       LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2142                                       VA.getLocMemOffset(), true);
2143
2144       // Create load nodes to retrieve arguments from the stack
2145       SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2146       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2147                                    MachinePointerInfo::getFixedStack(LastFI),
2148                                    false, false, 0));
2149     }
2150   }
2151
2152   // The mips ABIs for returning structs by value requires that we copy
2153   // the sret argument into $v0 for the return. Save the argument into
2154   // a virtual register so that we can access it from the return points.
2155   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2156     unsigned Reg = MipsFI->getSRetReturnReg();
2157     if (!Reg) {
2158       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2159       MipsFI->setSRetReturnReg(Reg);
2160     }
2161     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2162     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2163   }
2164
2165   if (isVarArg && Subtarget->isABI_O32()) {
2166     // Record the frame index of the first variable argument
2167     // which is a value necessary to VASTART.
2168     unsigned NextStackOffset = CCInfo.getNextStackOffset();
2169     assert(NextStackOffset % 4 == 0 &&
2170            "NextStackOffset must be aligned to 4-byte boundaries.");
2171     LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2172     MipsFI->setVarArgsFrameIndex(LastFI);
2173
2174     // If NextStackOffset is smaller than o32's 16-byte reserved argument area,
2175     // copy the integer registers that have not been used for argument passing
2176     // to the caller's stack frame.
2177     for (; NextStackOffset < 16; NextStackOffset += 4) {
2178       TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
2179       unsigned Idx = NextStackOffset / 4;
2180       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), O32IntRegs[Idx], RC);
2181       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
2182       LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2183       SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2184       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2185                                        MachinePointerInfo(),
2186                                        false, false, 0));
2187     }
2188   }
2189
2190   MipsFI->setLastInArgFI(LastFI);
2191
2192   // All stores are grouped in one node to allow the matching between
2193   // the size of Ins and InVals. This only happens when on varg functions
2194   if (!OutChains.empty()) {
2195     OutChains.push_back(Chain);
2196     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2197                         &OutChains[0], OutChains.size());
2198   }
2199
2200   return Chain;
2201 }
2202
2203 //===----------------------------------------------------------------------===//
2204 //               Return Value Calling Convention Implementation
2205 //===----------------------------------------------------------------------===//
2206
2207 SDValue
2208 MipsTargetLowering::LowerReturn(SDValue Chain,
2209                                 CallingConv::ID CallConv, bool isVarArg,
2210                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
2211                                 const SmallVectorImpl<SDValue> &OutVals,
2212                                 DebugLoc dl, SelectionDAG &DAG) const {
2213
2214   // CCValAssign - represent the assignment of
2215   // the return value to a location
2216   SmallVector<CCValAssign, 16> RVLocs;
2217
2218   // CCState - Info about the registers and stack slot.
2219   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2220                  getTargetMachine(), RVLocs, *DAG.getContext());
2221
2222   // Analize return values.
2223   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2224
2225   // If this is the first return lowered for this function, add
2226   // the regs to the liveout set for the function.
2227   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2228     for (unsigned i = 0; i != RVLocs.size(); ++i)
2229       if (RVLocs[i].isRegLoc())
2230         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2231   }
2232
2233   SDValue Flag;
2234
2235   // Copy the result values into the output registers.
2236   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2237     CCValAssign &VA = RVLocs[i];
2238     assert(VA.isRegLoc() && "Can only return in registers!");
2239
2240     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2241                              OutVals[i], Flag);
2242
2243     // guarantee that all emitted copies are
2244     // stuck together, avoiding something bad
2245     Flag = Chain.getValue(1);
2246   }
2247
2248   // The mips ABIs for returning structs by value requires that we copy
2249   // the sret argument into $v0 for the return. We saved the argument into
2250   // a virtual register in the entry block, so now we copy the value out
2251   // and into $v0.
2252   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2253     MachineFunction &MF      = DAG.getMachineFunction();
2254     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2255     unsigned Reg = MipsFI->getSRetReturnReg();
2256
2257     if (!Reg)
2258       llvm_unreachable("sret virtual register not created in the entry block");
2259     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2260
2261     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2262     Flag = Chain.getValue(1);
2263   }
2264
2265   // Return on Mips is always a "jr $ra"
2266   if (Flag.getNode())
2267     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2268                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2269   else // Return Void
2270     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2271                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
2272 }
2273
2274 //===----------------------------------------------------------------------===//
2275 //                           Mips Inline Assembly Support
2276 //===----------------------------------------------------------------------===//
2277
2278 /// getConstraintType - Given a constraint letter, return the type of
2279 /// constraint it is for this target.
2280 MipsTargetLowering::ConstraintType MipsTargetLowering::
2281 getConstraintType(const std::string &Constraint) const
2282 {
2283   // Mips specific constrainy
2284   // GCC config/mips/constraints.md
2285   //
2286   // 'd' : An address register. Equivalent to r
2287   //       unless generating MIPS16 code.
2288   // 'y' : Equivalent to r; retained for
2289   //       backwards compatibility.
2290   // 'f' : Floating Point registers.
2291   if (Constraint.size() == 1) {
2292     switch (Constraint[0]) {
2293       default : break;
2294       case 'd':
2295       case 'y':
2296       case 'f':
2297         return C_RegisterClass;
2298         break;
2299     }
2300   }
2301   return TargetLowering::getConstraintType(Constraint);
2302 }
2303
2304 /// Examine constraint type and operand type and determine a weight value.
2305 /// This object must already have been set up with the operand type
2306 /// and the current alternative constraint selected.
2307 TargetLowering::ConstraintWeight
2308 MipsTargetLowering::getSingleConstraintMatchWeight(
2309     AsmOperandInfo &info, const char *constraint) const {
2310   ConstraintWeight weight = CW_Invalid;
2311   Value *CallOperandVal = info.CallOperandVal;
2312     // If we don't have a value, we can't do a match,
2313     // but allow it at the lowest weight.
2314   if (CallOperandVal == NULL)
2315     return CW_Default;
2316   const Type *type = CallOperandVal->getType();
2317   // Look at the constraint type.
2318   switch (*constraint) {
2319   default:
2320     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2321     break;
2322   case 'd':
2323   case 'y':
2324     if (type->isIntegerTy())
2325       weight = CW_Register;
2326     break;
2327   case 'f':
2328     if (type->isFloatTy())
2329       weight = CW_Register;
2330     break;
2331   }
2332   return weight;
2333 }
2334
2335 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
2336 /// return a list of registers that can be used to satisfy the constraint.
2337 /// This should only be used for C_RegisterClass constraints.
2338 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2339 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2340 {
2341   if (Constraint.size() == 1) {
2342     switch (Constraint[0]) {
2343     case 'r':
2344       return std::make_pair(0U, Mips::CPURegsRegisterClass);
2345     case 'f':
2346       if (VT == MVT::f32)
2347         return std::make_pair(0U, Mips::FGR32RegisterClass);
2348       if (VT == MVT::f64)
2349         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2350           return std::make_pair(0U, Mips::AFGR64RegisterClass);
2351     }
2352   }
2353   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2354 }
2355
2356 /// Given a register class constraint, like 'r', if this corresponds directly
2357 /// to an LLVM register class, return a register of 0 and the register class
2358 /// pointer.
2359 std::vector<unsigned> MipsTargetLowering::
2360 getRegClassForInlineAsmConstraint(const std::string &Constraint,
2361                                   EVT VT) const
2362 {
2363   if (Constraint.size() != 1)
2364     return std::vector<unsigned>();
2365
2366   switch (Constraint[0]) {
2367     default : break;
2368     case 'r':
2369     // GCC Mips Constraint Letters
2370     case 'd':
2371     case 'y':
2372       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
2373              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
2374              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
2375              Mips::T8, 0);
2376
2377     case 'f':
2378       if (VT == MVT::f32) {
2379         if (Subtarget->isSingleFloat())
2380           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
2381                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
2382                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
2383                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
2384                  Mips::F30, Mips::F31, 0);
2385         else
2386           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
2387                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
2388                  Mips::F28, Mips::F30, 0);
2389       }
2390
2391       if (VT == MVT::f64)
2392         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2393           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
2394                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
2395                  Mips::D14, Mips::D15, 0);
2396   }
2397   return std::vector<unsigned>();
2398 }
2399
2400 bool
2401 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2402   // The Mips target isn't yet aware of offsets.
2403   return false;
2404 }
2405
2406 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2407   if (VT != MVT::f32 && VT != MVT::f64)
2408     return false;
2409   if (Imm.isNegZero())
2410     return false;
2411   return Imm.isZero();
2412 }