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