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