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