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