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