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