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