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