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