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