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