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