Make psuedo FEXT_T8I816_ins a custom inserter. It should be expanded
[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 <set>
16 #include "MipsISelLowering.h"
17 #include "InstPrinter/MipsInstPrinter.h"
18 #include "MCTargetDesc/MipsBaseInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsSubtarget.h"
21 #include "MipsTargetMachine.h"
22 #include "MipsTargetObjectFile.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40
41 using namespace llvm;
42
43 STATISTIC(NumTailCalls, "Number of tail calls");
44
45 static cl::opt<bool>
46 EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
47                     cl::desc("MIPS: Enable tail calls."), cl::init(false));
48
49 static cl::opt<bool>
50 LargeGOT("mxgot", cl::Hidden,
51          cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
52
53 static cl::opt<bool>
54 Mips16HardFloat("mips16-hard-float", cl::NotHidden,
55                 cl::desc("MIPS: mips16 hard float enable."),
56                 cl::init(false));
57
58 static cl::opt<bool> DontExpandCondPseudos16(
59   "mips16-dont-expand-cond-pseudo",
60   cl::init(false),
61   cl::desc("Dont expand conditional move related "
62            "pseudos for Mips 16"),
63   cl::Hidden);
64
65
66 static const uint16_t O32IntRegs[4] = {
67   Mips::A0, Mips::A1, Mips::A2, Mips::A3
68 };
69
70 static const uint16_t Mips64IntRegs[8] = {
71   Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
72   Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
73 };
74
75 static const uint16_t Mips64DPRegs[8] = {
76   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
77   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
78 };
79
80 // If I is a shifted mask, set the size (Size) and the first bit of the
81 // mask (Pos), and return true.
82 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
83 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
84   if (!isShiftedMask_64(I))
85      return false;
86
87   Size = CountPopulation_64(I);
88   Pos = CountTrailingZeros_64(I);
89   return true;
90 }
91
92 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
93   MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
94   return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
95 }
96
97 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
98   EVT Ty = Op.getValueType();
99
100   if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
101     return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
102                                       Flag);
103   if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
104     return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
105   if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
106     return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
107   if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
108     return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
109   if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
110     return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111                                      N->getOffset(), Flag);
112
113   llvm_unreachable("Unexpected node type.");
114   return SDValue();
115 }
116
117 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
118   DebugLoc DL = Op.getDebugLoc();
119   EVT Ty = Op.getValueType();
120   SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
121   SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
122   return DAG.getNode(ISD::ADD, DL, Ty,
123                      DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
124                      DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
125 }
126
127 static SDValue getAddrLocal(SDValue Op, SelectionDAG &DAG, bool HasMips64) {
128   DebugLoc DL = Op.getDebugLoc();
129   EVT Ty = Op.getValueType();
130   unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
131   SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
132                             getTargetNode(Op, DAG, GOTFlag));
133   SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
134                              MachinePointerInfo::getGOT(), false, false, false,
135                              0);
136   unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
137   SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
138   return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
139 }
140
141 static SDValue getAddrGlobal(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
142   DebugLoc DL = Op.getDebugLoc();
143   EVT Ty = Op.getValueType();
144   SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
145                             getTargetNode(Op, DAG, Flag));
146   return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
147                      MachinePointerInfo::getGOT(), false, false, false, 0);
148 }
149
150 static SDValue getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
151                                      unsigned HiFlag, unsigned LoFlag) {
152   DebugLoc DL = Op.getDebugLoc();
153   EVT Ty = Op.getValueType();
154   SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
155   Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, GetGlobalReg(DAG, Ty));
156   SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
157                                 getTargetNode(Op, DAG, LoFlag));
158   return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
159                      MachinePointerInfo::getGOT(), false, false, false, 0);
160 }
161
162 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
163   switch (Opcode) {
164   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
165   case MipsISD::TailCall:          return "MipsISD::TailCall";
166   case MipsISD::Hi:                return "MipsISD::Hi";
167   case MipsISD::Lo:                return "MipsISD::Lo";
168   case MipsISD::GPRel:             return "MipsISD::GPRel";
169   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
170   case MipsISD::Ret:               return "MipsISD::Ret";
171   case MipsISD::EH_RETURN:         return "MipsISD::EH_RETURN";
172   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
173   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
174   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
175   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
176   case MipsISD::FPRound:           return "MipsISD::FPRound";
177   case MipsISD::MAdd:              return "MipsISD::MAdd";
178   case MipsISD::MAddu:             return "MipsISD::MAddu";
179   case MipsISD::MSub:              return "MipsISD::MSub";
180   case MipsISD::MSubu:             return "MipsISD::MSubu";
181   case MipsISD::DivRem:            return "MipsISD::DivRem";
182   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
183   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
184   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
185   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
186   case MipsISD::Sync:              return "MipsISD::Sync";
187   case MipsISD::Ext:               return "MipsISD::Ext";
188   case MipsISD::Ins:               return "MipsISD::Ins";
189   case MipsISD::LWL:               return "MipsISD::LWL";
190   case MipsISD::LWR:               return "MipsISD::LWR";
191   case MipsISD::SWL:               return "MipsISD::SWL";
192   case MipsISD::SWR:               return "MipsISD::SWR";
193   case MipsISD::LDL:               return "MipsISD::LDL";
194   case MipsISD::LDR:               return "MipsISD::LDR";
195   case MipsISD::SDL:               return "MipsISD::SDL";
196   case MipsISD::SDR:               return "MipsISD::SDR";
197   case MipsISD::EXTP:              return "MipsISD::EXTP";
198   case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
199   case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
200   case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
201   case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
202   case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
203   case MipsISD::SHILO:             return "MipsISD::SHILO";
204   case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
205   case MipsISD::MULT:              return "MipsISD::MULT";
206   case MipsISD::MULTU:             return "MipsISD::MULTU";
207   case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSPDSP";
208   case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
209   case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
210   case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
211   default:                         return NULL;
212   }
213 }
214
215 namespace {
216   struct ltstr {
217     bool operator()(const char *s1, const char *s2) const
218     {
219       return strcmp(s1, s2) < 0;
220     }
221   };
222
223   std::set<const char*, ltstr> noHelperNeeded;
224 }
225
226 void MipsTargetLowering::SetMips16LibcallName
227   (RTLIB::Libcall l, const char *Name) {
228   setLibcallName(l, Name);
229   noHelperNeeded.insert(Name);
230 }
231
232 void MipsTargetLowering::setMips16HardFloatLibCalls() {
233   SetMips16LibcallName(RTLIB::ADD_F32, "__mips16_addsf3");
234   SetMips16LibcallName(RTLIB::ADD_F64, "__mips16_adddf3");
235   SetMips16LibcallName(RTLIB::SUB_F32, "__mips16_subsf3");
236   SetMips16LibcallName(RTLIB::SUB_F64, "__mips16_subdf3");
237   SetMips16LibcallName(RTLIB::MUL_F32, "__mips16_mulsf3");
238   SetMips16LibcallName(RTLIB::MUL_F64, "__mips16_muldf3");
239   SetMips16LibcallName(RTLIB::DIV_F32, "__mips16_divsf3");
240   SetMips16LibcallName(RTLIB::DIV_F64, "__mips16_divdf3");
241   SetMips16LibcallName(RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2");
242   SetMips16LibcallName(RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2");
243   SetMips16LibcallName(RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi");
244   SetMips16LibcallName(RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi");
245   SetMips16LibcallName(RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf");
246   SetMips16LibcallName(RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf");
247   SetMips16LibcallName(RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf");
248   SetMips16LibcallName(RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf");
249   SetMips16LibcallName(RTLIB::OEQ_F32, "__mips16_eqsf2");
250   SetMips16LibcallName(RTLIB::OEQ_F64, "__mips16_eqdf2");
251   SetMips16LibcallName(RTLIB::UNE_F32, "__mips16_nesf2");
252   SetMips16LibcallName(RTLIB::UNE_F64, "__mips16_nedf2");
253   SetMips16LibcallName(RTLIB::OGE_F32, "__mips16_gesf2");
254   SetMips16LibcallName(RTLIB::OGE_F64, "__mips16_gedf2");
255   SetMips16LibcallName(RTLIB::OLT_F32, "__mips16_ltsf2");
256   SetMips16LibcallName(RTLIB::OLT_F64, "__mips16_ltdf2");
257   SetMips16LibcallName(RTLIB::OLE_F32, "__mips16_lesf2");
258   SetMips16LibcallName(RTLIB::OLE_F64, "__mips16_ledf2");
259   SetMips16LibcallName(RTLIB::OGT_F32, "__mips16_gtsf2");
260   SetMips16LibcallName(RTLIB::OGT_F64, "__mips16_gtdf2");
261   SetMips16LibcallName(RTLIB::UO_F32, "__mips16_unordsf2");
262   SetMips16LibcallName(RTLIB::UO_F64, "__mips16_unorddf2");
263   SetMips16LibcallName(RTLIB::O_F32, "__mips16_unordsf2");
264   SetMips16LibcallName(RTLIB::O_F64, "__mips16_unorddf2");
265 }
266
267 MipsTargetLowering::
268 MipsTargetLowering(MipsTargetMachine &TM)
269   : TargetLowering(TM, new MipsTargetObjectFile()),
270     Subtarget(&TM.getSubtarget<MipsSubtarget>()),
271     HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
272     IsO32(Subtarget->isABI_O32()) {
273
274   // Mips does not have i1 type, so use i32 for
275   // setcc operations results (slt, sgt, ...).
276   setBooleanContents(ZeroOrOneBooleanContent);
277   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
278
279   // Set up the register classes
280   addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
281
282   if (HasMips64)
283     addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
284
285   if (Subtarget->inMips16Mode()) {
286     addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
287     if (Mips16HardFloat)
288       setMips16HardFloatLibCalls();
289   }
290
291   if (Subtarget->hasDSP()) {
292     MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
293
294     for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
295       addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
296
297       // Expand all builtin opcodes.
298       for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
299         setOperationAction(Opc, VecTys[i], Expand);
300
301       setOperationAction(ISD::LOAD, VecTys[i], Legal);
302       setOperationAction(ISD::STORE, VecTys[i], Legal);
303       setOperationAction(ISD::BITCAST, VecTys[i], Legal);
304     }
305   }
306
307   if (!TM.Options.UseSoftFloat) {
308     addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
309
310     // When dealing with single precision only, use libcalls
311     if (!Subtarget->isSingleFloat()) {
312       if (HasMips64)
313         addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
314       else
315         addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
316     }
317   }
318
319   // Load extented operations for i1 types must be promoted
320   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
321   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
322   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
323
324   // MIPS doesn't have extending float->double load/store
325   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
326   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
327
328   // Used by legalize types to correctly generate the setcc result.
329   // Without this, every float setcc comes with a AND/OR with the result,
330   // we don't want this, since the fpcmp result goes to a flag register,
331   // which is used implicitly by brcond and select operations.
332   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
333
334   // Mips Custom Operations
335   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
336   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
337   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
338   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
339   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
340   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
341   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
342   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
343   setOperationAction(ISD::SELECT_CC,          MVT::f32,   Custom);
344   setOperationAction(ISD::SELECT_CC,          MVT::f64,   Custom);
345   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
346   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
347   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
348   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
349   setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
350   setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
351   if (Subtarget->inMips16Mode()) {
352     setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
353     setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Expand);
354   }
355   else {
356     setOperationAction(ISD::MEMBARRIER,         MVT::Other, Custom);
357     setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Custom);
358   }
359   if (!Subtarget->inMips16Mode()) {
360     setOperationAction(ISD::LOAD,               MVT::i32, Custom);
361     setOperationAction(ISD::STORE,              MVT::i32, Custom);
362   }
363
364   if (!TM.Options.NoNaNsFPMath) {
365     setOperationAction(ISD::FABS,             MVT::f32,   Custom);
366     setOperationAction(ISD::FABS,             MVT::f64,   Custom);
367   }
368
369   if (HasMips64) {
370     setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
371     setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
372     setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
373     setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
374     setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
375     setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
376     setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
377     setOperationAction(ISD::STORE,              MVT::i64,   Custom);
378   }
379
380   if (!HasMips64) {
381     setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
382     setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
383     setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
384   }
385
386   setOperationAction(ISD::ADD,                MVT::i32,   Custom);
387   if (HasMips64)
388     setOperationAction(ISD::ADD,                MVT::i64,   Custom);
389
390   setOperationAction(ISD::SDIV, MVT::i32, Expand);
391   setOperationAction(ISD::SREM, MVT::i32, Expand);
392   setOperationAction(ISD::UDIV, MVT::i32, Expand);
393   setOperationAction(ISD::UREM, MVT::i32, Expand);
394   setOperationAction(ISD::SDIV, MVT::i64, Expand);
395   setOperationAction(ISD::SREM, MVT::i64, Expand);
396   setOperationAction(ISD::UDIV, MVT::i64, Expand);
397   setOperationAction(ISD::UREM, MVT::i64, Expand);
398
399   // Operations not directly supported by Mips.
400   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
401   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
402   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
403   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
404   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
405   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
406   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
408   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
409   setOperationAction(ISD::CTPOP,             MVT::i64,   Expand);
410   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
411   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
412   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
413   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
414   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
415   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
416   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
417   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
418   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
419   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
420
421   if (!Subtarget->hasMips32r2())
422     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
423
424   if (!Subtarget->hasMips64r2())
425     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
426
427   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
428   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
429   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
430   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
431   setOperationAction(ISD::FSINCOS,           MVT::f32,   Expand);
432   setOperationAction(ISD::FSINCOS,           MVT::f64,   Expand);
433   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
434   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
435   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
436   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
437   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
438   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
439   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
440   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
441   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
442   setOperationAction(ISD::FREM,              MVT::f32,   Expand);
443   setOperationAction(ISD::FREM,              MVT::f64,   Expand);
444
445   if (!TM.Options.NoNaNsFPMath) {
446     setOperationAction(ISD::FNEG,             MVT::f32,   Expand);
447     setOperationAction(ISD::FNEG,             MVT::f64,   Expand);
448   }
449
450   setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
451   setOperationAction(ISD::EXCEPTIONADDR,     MVT::i64, Expand);
452   setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
453   setOperationAction(ISD::EHSELECTION,       MVT::i64, Expand);
454
455   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
456
457   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
458   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
459   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
460
461   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
462   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
463
464   // Use the default for now
465   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
466   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
467
468   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);
469   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i64,    Expand);
470   setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);
471   setOperationAction(ISD::ATOMIC_STORE,      MVT::i64,    Expand);
472
473   if (Subtarget->inMips16Mode()) {
474     setOperationAction(ISD::ATOMIC_CMP_SWAP,       MVT::i32,    Expand);
475     setOperationAction(ISD::ATOMIC_SWAP,           MVT::i32,    Expand);
476     setOperationAction(ISD::ATOMIC_LOAD_ADD,       MVT::i32,    Expand);
477     setOperationAction(ISD::ATOMIC_LOAD_SUB,       MVT::i32,    Expand);
478     setOperationAction(ISD::ATOMIC_LOAD_AND,       MVT::i32,    Expand);
479     setOperationAction(ISD::ATOMIC_LOAD_OR,        MVT::i32,    Expand);
480     setOperationAction(ISD::ATOMIC_LOAD_XOR,       MVT::i32,    Expand);
481     setOperationAction(ISD::ATOMIC_LOAD_NAND,      MVT::i32,    Expand);
482     setOperationAction(ISD::ATOMIC_LOAD_MIN,       MVT::i32,    Expand);
483     setOperationAction(ISD::ATOMIC_LOAD_MAX,       MVT::i32,    Expand);
484     setOperationAction(ISD::ATOMIC_LOAD_UMIN,      MVT::i32,    Expand);
485     setOperationAction(ISD::ATOMIC_LOAD_UMAX,      MVT::i32,    Expand);
486   }
487
488   setInsertFencesForAtomic(true);
489
490   if (!Subtarget->hasSEInReg()) {
491     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
492     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
493   }
494
495   if (!Subtarget->hasBitCount()) {
496     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
497     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
498   }
499
500   if (!Subtarget->hasSwap()) {
501     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
502     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
503   }
504
505   if (HasMips64) {
506     setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
507     setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
508     setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
509     setTruncStoreAction(MVT::i64, MVT::i32, Custom);
510   }
511
512   setTargetDAGCombine(ISD::ADDE);
513   setTargetDAGCombine(ISD::SUBE);
514   setTargetDAGCombine(ISD::SDIVREM);
515   setTargetDAGCombine(ISD::UDIVREM);
516   setTargetDAGCombine(ISD::SELECT);
517   setTargetDAGCombine(ISD::AND);
518   setTargetDAGCombine(ISD::OR);
519   setTargetDAGCombine(ISD::ADD);
520
521   setMinFunctionAlignment(HasMips64 ? 3 : 2);
522
523   setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
524   computeRegisterProperties();
525
526   setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
527   setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
528
529   MaxStoresPerMemcpy = 16;
530 }
531
532 bool
533 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
534   MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
535
536   if (Subtarget->inMips16Mode())
537     return false;
538
539   switch (SVT) {
540   case MVT::i64:
541   case MVT::i32:
542     if (Fast)
543       *Fast = true;
544     return true;
545   default:
546     return false;
547   }
548 }
549
550 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
551   if (!VT.isVector())
552     return MVT::i32;
553   return VT.changeVectorElementTypeToInteger();
554 }
555
556 // SelectMadd -
557 // Transforms a subgraph in CurDAG if the following pattern is found:
558 //  (addc multLo, Lo0), (adde multHi, Hi0),
559 // where,
560 //  multHi/Lo: product of multiplication
561 //  Lo0: initial value of Lo register
562 //  Hi0: initial value of Hi register
563 // Return true if pattern matching was successful.
564 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
565   // ADDENode's second operand must be a flag output of an ADDC node in order
566   // for the matching to be successful.
567   SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
568
569   if (ADDCNode->getOpcode() != ISD::ADDC)
570     return false;
571
572   SDValue MultHi = ADDENode->getOperand(0);
573   SDValue MultLo = ADDCNode->getOperand(0);
574   SDNode *MultNode = MultHi.getNode();
575   unsigned MultOpc = MultHi.getOpcode();
576
577   // MultHi and MultLo must be generated by the same node,
578   if (MultLo.getNode() != MultNode)
579     return false;
580
581   // and it must be a multiplication.
582   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
583     return false;
584
585   // MultLo amd MultHi must be the first and second output of MultNode
586   // respectively.
587   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
588     return false;
589
590   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
591   // of the values of MultNode, in which case MultNode will be removed in later
592   // phases.
593   // If there exist users other than ADDENode or ADDCNode, this function returns
594   // here, which will result in MultNode being mapped to a single MULT
595   // instruction node rather than a pair of MULT and MADD instructions being
596   // produced.
597   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
598     return false;
599
600   SDValue Chain = CurDAG->getEntryNode();
601   DebugLoc dl = ADDENode->getDebugLoc();
602
603   // create MipsMAdd(u) node
604   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
605
606   SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
607                                  MultNode->getOperand(0),// Factor 0
608                                  MultNode->getOperand(1),// Factor 1
609                                  ADDCNode->getOperand(1),// Lo0
610                                  ADDENode->getOperand(1));// Hi0
611
612   // create CopyFromReg nodes
613   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
614                                               MAdd);
615   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
616                                               Mips::HI, MVT::i32,
617                                               CopyFromLo.getValue(2));
618
619   // replace uses of adde and addc here
620   if (!SDValue(ADDCNode, 0).use_empty())
621     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
622
623   if (!SDValue(ADDENode, 0).use_empty())
624     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
625
626   return true;
627 }
628
629 // SelectMsub -
630 // Transforms a subgraph in CurDAG if the following pattern is found:
631 //  (addc Lo0, multLo), (sube Hi0, multHi),
632 // where,
633 //  multHi/Lo: product of multiplication
634 //  Lo0: initial value of Lo register
635 //  Hi0: initial value of Hi register
636 // Return true if pattern matching was successful.
637 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
638   // SUBENode's second operand must be a flag output of an SUBC node in order
639   // for the matching to be successful.
640   SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
641
642   if (SUBCNode->getOpcode() != ISD::SUBC)
643     return false;
644
645   SDValue MultHi = SUBENode->getOperand(1);
646   SDValue MultLo = SUBCNode->getOperand(1);
647   SDNode *MultNode = MultHi.getNode();
648   unsigned MultOpc = MultHi.getOpcode();
649
650   // MultHi and MultLo must be generated by the same node,
651   if (MultLo.getNode() != MultNode)
652     return false;
653
654   // and it must be a multiplication.
655   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
656     return false;
657
658   // MultLo amd MultHi must be the first and second output of MultNode
659   // respectively.
660   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
661     return false;
662
663   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
664   // of the values of MultNode, in which case MultNode will be removed in later
665   // phases.
666   // If there exist users other than SUBENode or SUBCNode, this function returns
667   // here, which will result in MultNode being mapped to a single MULT
668   // instruction node rather than a pair of MULT and MSUB instructions being
669   // produced.
670   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
671     return false;
672
673   SDValue Chain = CurDAG->getEntryNode();
674   DebugLoc dl = SUBENode->getDebugLoc();
675
676   // create MipsSub(u) node
677   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
678
679   SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
680                                  MultNode->getOperand(0),// Factor 0
681                                  MultNode->getOperand(1),// Factor 1
682                                  SUBCNode->getOperand(0),// Lo0
683                                  SUBENode->getOperand(0));// Hi0
684
685   // create CopyFromReg nodes
686   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
687                                               MSub);
688   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
689                                               Mips::HI, MVT::i32,
690                                               CopyFromLo.getValue(2));
691
692   // replace uses of sube and subc here
693   if (!SDValue(SUBCNode, 0).use_empty())
694     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
695
696   if (!SDValue(SUBENode, 0).use_empty())
697     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
698
699   return true;
700 }
701
702 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
703                                   TargetLowering::DAGCombinerInfo &DCI,
704                                   const MipsSubtarget *Subtarget) {
705   if (DCI.isBeforeLegalize())
706     return SDValue();
707
708   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
709       SelectMadd(N, &DAG))
710     return SDValue(N, 0);
711
712   return SDValue();
713 }
714
715 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
716                                   TargetLowering::DAGCombinerInfo &DCI,
717                                   const MipsSubtarget *Subtarget) {
718   if (DCI.isBeforeLegalize())
719     return SDValue();
720
721   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
722       SelectMsub(N, &DAG))
723     return SDValue(N, 0);
724
725   return SDValue();
726 }
727
728 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
729                                     TargetLowering::DAGCombinerInfo &DCI,
730                                     const MipsSubtarget *Subtarget) {
731   if (DCI.isBeforeLegalizeOps())
732     return SDValue();
733
734   EVT Ty = N->getValueType(0);
735   unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
736   unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
737   unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
738                                                   MipsISD::DivRemU;
739   DebugLoc dl = N->getDebugLoc();
740
741   SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
742                                N->getOperand(0), N->getOperand(1));
743   SDValue InChain = DAG.getEntryNode();
744   SDValue InGlue = DivRem;
745
746   // insert MFLO
747   if (N->hasAnyUseOfValue(0)) {
748     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
749                                             InGlue);
750     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
751     InChain = CopyFromLo.getValue(1);
752     InGlue = CopyFromLo.getValue(2);
753   }
754
755   // insert MFHI
756   if (N->hasAnyUseOfValue(1)) {
757     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
758                                             HI, Ty, InGlue);
759     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
760   }
761
762   return SDValue();
763 }
764
765 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
766   switch (CC) {
767   default: llvm_unreachable("Unknown fp condition code!");
768   case ISD::SETEQ:
769   case ISD::SETOEQ: return Mips::FCOND_OEQ;
770   case ISD::SETUNE: return Mips::FCOND_UNE;
771   case ISD::SETLT:
772   case ISD::SETOLT: return Mips::FCOND_OLT;
773   case ISD::SETGT:
774   case ISD::SETOGT: return Mips::FCOND_OGT;
775   case ISD::SETLE:
776   case ISD::SETOLE: return Mips::FCOND_OLE;
777   case ISD::SETGE:
778   case ISD::SETOGE: return Mips::FCOND_OGE;
779   case ISD::SETULT: return Mips::FCOND_ULT;
780   case ISD::SETULE: return Mips::FCOND_ULE;
781   case ISD::SETUGT: return Mips::FCOND_UGT;
782   case ISD::SETUGE: return Mips::FCOND_UGE;
783   case ISD::SETUO:  return Mips::FCOND_UN;
784   case ISD::SETO:   return Mips::FCOND_OR;
785   case ISD::SETNE:
786   case ISD::SETONE: return Mips::FCOND_ONE;
787   case ISD::SETUEQ: return Mips::FCOND_UEQ;
788   }
789 }
790
791
792 // Returns true if condition code has to be inverted.
793 static bool InvertFPCondCode(Mips::CondCode CC) {
794   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
795     return false;
796
797   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
798          "Illegal Condition Code");
799
800   return true;
801 }
802
803 // Creates and returns an FPCmp node from a setcc node.
804 // Returns Op if setcc is not a floating point comparison.
805 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
806   // must be a SETCC node
807   if (Op.getOpcode() != ISD::SETCC)
808     return Op;
809
810   SDValue LHS = Op.getOperand(0);
811
812   if (!LHS.getValueType().isFloatingPoint())
813     return Op;
814
815   SDValue RHS = Op.getOperand(1);
816   DebugLoc dl = Op.getDebugLoc();
817
818   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
819   // node if necessary.
820   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
821
822   return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
823                      DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
824 }
825
826 // Creates and returns a CMovFPT/F node.
827 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
828                             SDValue False, DebugLoc DL) {
829   bool invert = InvertFPCondCode((Mips::CondCode)
830                                  cast<ConstantSDNode>(Cond.getOperand(2))
831                                  ->getSExtValue());
832
833   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
834                      True.getValueType(), True, False, Cond);
835 }
836
837 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
838                                     TargetLowering::DAGCombinerInfo &DCI,
839                                     const MipsSubtarget *Subtarget) {
840   if (DCI.isBeforeLegalizeOps())
841     return SDValue();
842
843   SDValue SetCC = N->getOperand(0);
844
845   if ((SetCC.getOpcode() != ISD::SETCC) ||
846       !SetCC.getOperand(0).getValueType().isInteger())
847     return SDValue();
848
849   SDValue False = N->getOperand(2);
850   EVT FalseTy = False.getValueType();
851
852   if (!FalseTy.isInteger())
853     return SDValue();
854
855   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
856
857   if (!CN || CN->getZExtValue())
858     return SDValue();
859
860   const DebugLoc DL = N->getDebugLoc();
861   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
862   SDValue True = N->getOperand(1);
863
864   SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
865                        SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
866
867   return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
868 }
869
870 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
871                                  TargetLowering::DAGCombinerInfo &DCI,
872                                  const MipsSubtarget *Subtarget) {
873   // Pattern match EXT.
874   //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
875   //  => ext $dst, $src, size, pos
876   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
877     return SDValue();
878
879   SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
880   unsigned ShiftRightOpc = ShiftRight.getOpcode();
881
882   // Op's first operand must be a shift right.
883   if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
884     return SDValue();
885
886   // The second operand of the shift must be an immediate.
887   ConstantSDNode *CN;
888   if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
889     return SDValue();
890
891   uint64_t Pos = CN->getZExtValue();
892   uint64_t SMPos, SMSize;
893
894   // Op's second operand must be a shifted mask.
895   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
896       !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
897     return SDValue();
898
899   // Return if the shifted mask does not start at bit 0 or the sum of its size
900   // and Pos exceeds the word's size.
901   EVT ValTy = N->getValueType(0);
902   if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
903     return SDValue();
904
905   return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
906                      ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
907                      DAG.getConstant(SMSize, MVT::i32));
908 }
909
910 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
911                                 TargetLowering::DAGCombinerInfo &DCI,
912                                 const MipsSubtarget *Subtarget) {
913   // Pattern match INS.
914   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
915   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
916   //  => ins $dst, $src, size, pos, $src1
917   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
918     return SDValue();
919
920   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
921   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
922   ConstantSDNode *CN;
923
924   // See if Op's first operand matches (and $src1 , mask0).
925   if (And0.getOpcode() != ISD::AND)
926     return SDValue();
927
928   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
929       !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
930     return SDValue();
931
932   // See if Op's second operand matches (and (shl $src, pos), mask1).
933   if (And1.getOpcode() != ISD::AND)
934     return SDValue();
935
936   if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
937       !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
938     return SDValue();
939
940   // The shift masks must have the same position and size.
941   if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
942     return SDValue();
943
944   SDValue Shl = And1.getOperand(0);
945   if (Shl.getOpcode() != ISD::SHL)
946     return SDValue();
947
948   if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
949     return SDValue();
950
951   unsigned Shamt = CN->getZExtValue();
952
953   // Return if the shift amount and the first bit position of mask are not the
954   // same.
955   EVT ValTy = N->getValueType(0);
956   if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
957     return SDValue();
958
959   return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
960                      DAG.getConstant(SMPos0, MVT::i32),
961                      DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
962 }
963
964 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
965                                  TargetLowering::DAGCombinerInfo &DCI,
966                                  const MipsSubtarget *Subtarget) {
967   // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
968
969   if (DCI.isBeforeLegalizeOps())
970     return SDValue();
971
972   SDValue Add = N->getOperand(1);
973
974   if (Add.getOpcode() != ISD::ADD)
975     return SDValue();
976
977   SDValue Lo = Add.getOperand(1);
978
979   if ((Lo.getOpcode() != MipsISD::Lo) ||
980       (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
981     return SDValue();
982
983   EVT ValTy = N->getValueType(0);
984   DebugLoc DL = N->getDebugLoc();
985
986   SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
987                              Add.getOperand(0));
988   return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
989 }
990
991 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
992   const {
993   SelectionDAG &DAG = DCI.DAG;
994   unsigned opc = N->getOpcode();
995
996   switch (opc) {
997   default: break;
998   case ISD::ADDE:
999     return PerformADDECombine(N, DAG, DCI, Subtarget);
1000   case ISD::SUBE:
1001     return PerformSUBECombine(N, DAG, DCI, Subtarget);
1002   case ISD::SDIVREM:
1003   case ISD::UDIVREM:
1004     return PerformDivRemCombine(N, DAG, DCI, Subtarget);
1005   case ISD::SELECT:
1006     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
1007   case ISD::AND:
1008     return PerformANDCombine(N, DAG, DCI, Subtarget);
1009   case ISD::OR:
1010     return PerformORCombine(N, DAG, DCI, Subtarget);
1011   case ISD::ADD:
1012     return PerformADDCombine(N, DAG, DCI, Subtarget);
1013   }
1014
1015   return SDValue();
1016 }
1017
1018 void
1019 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1020                                           SmallVectorImpl<SDValue> &Results,
1021                                           SelectionDAG &DAG) const {
1022   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1023
1024   for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1025     Results.push_back(Res.getValue(I));
1026 }
1027
1028 void
1029 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1030                                        SmallVectorImpl<SDValue> &Results,
1031                                        SelectionDAG &DAG) const {
1032   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1033
1034   for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1035     Results.push_back(Res.getValue(I));
1036 }
1037
1038 SDValue MipsTargetLowering::
1039 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1040 {
1041   switch (Op.getOpcode())
1042   {
1043     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
1044     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1045     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1046     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
1047     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
1048     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
1049     case ISD::SELECT:             return LowerSELECT(Op, DAG);
1050     case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1051     case ISD::SETCC:              return LowerSETCC(Op, DAG);
1052     case ISD::VASTART:            return LowerVASTART(Op, DAG);
1053     case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
1054     case ISD::FABS:               return LowerFABS(Op, DAG);
1055     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1056     case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1057     case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
1058     case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, DAG);
1059     case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
1060     case ISD::SHL_PARTS:          return LowerShiftLeftParts(Op, DAG);
1061     case ISD::SRA_PARTS:          return LowerShiftRightParts(Op, DAG, true);
1062     case ISD::SRL_PARTS:          return LowerShiftRightParts(Op, DAG, false);
1063     case ISD::LOAD:               return LowerLOAD(Op, DAG);
1064     case ISD::STORE:              return LowerSTORE(Op, DAG);
1065     case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1066     case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
1067     case ISD::ADD:                return LowerADD(Op, DAG);
1068   }
1069   return SDValue();
1070 }
1071
1072 //===----------------------------------------------------------------------===//
1073 //  Lower helper functions
1074 //===----------------------------------------------------------------------===//
1075
1076 // AddLiveIn - This helper function adds the specified physical register to the
1077 // MachineFunction as a live in value.  It also creates a corresponding
1078 // virtual register for it.
1079 static unsigned
1080 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1081 {
1082   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1083   MF.getRegInfo().addLiveIn(PReg, VReg);
1084   return VReg;
1085 }
1086
1087 // Get fp branch code (not opcode) from condition code.
1088 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1089   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1090     return Mips::BRANCH_T;
1091
1092   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1093          "Invalid CondCode.");
1094
1095   return Mips::BRANCH_F;
1096 }
1097
1098 /*
1099 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1100                                         DebugLoc dl,
1101                                         const MipsSubtarget *Subtarget,
1102                                         const TargetInstrInfo *TII,
1103                                         bool isFPCmp, unsigned Opc) {
1104   // There is no need to expand CMov instructions if target has
1105   // conditional moves.
1106   if (Subtarget->hasCondMov())
1107     return BB;
1108
1109   // To "insert" a SELECT_CC instruction, we actually have to insert the
1110   // diamond control-flow pattern.  The incoming instruction knows the
1111   // destination vreg to set, the condition code register to branch on, the
1112   // true/false values to select between, and a branch opcode to use.
1113   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1114   MachineFunction::iterator It = BB;
1115   ++It;
1116
1117   //  thisMBB:
1118   //  ...
1119   //   TrueVal = ...
1120   //   setcc r1, r2, r3
1121   //   bNE   r1, r0, copy1MBB
1122   //   fallthrough --> copy0MBB
1123   MachineBasicBlock *thisMBB  = BB;
1124   MachineFunction *F = BB->getParent();
1125   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1126   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1127   F->insert(It, copy0MBB);
1128   F->insert(It, sinkMBB);
1129
1130   // Transfer the remainder of BB and its successor edges to sinkMBB.
1131   sinkMBB->splice(sinkMBB->begin(), BB,
1132                   llvm::next(MachineBasicBlock::iterator(MI)),
1133                   BB->end());
1134   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1135
1136   // Next, add the true and fallthrough blocks as its successors.
1137   BB->addSuccessor(copy0MBB);
1138   BB->addSuccessor(sinkMBB);
1139
1140   // Emit the right instruction according to the type of the operands compared
1141   if (isFPCmp)
1142     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1143   else
1144     BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1145       .addReg(Mips::ZERO).addMBB(sinkMBB);
1146
1147   //  copy0MBB:
1148   //   %FalseValue = ...
1149   //   # fallthrough to sinkMBB
1150   BB = copy0MBB;
1151
1152   // Update machine-CFG edges
1153   BB->addSuccessor(sinkMBB);
1154
1155   //  sinkMBB:
1156   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1157   //  ...
1158   BB = sinkMBB;
1159
1160   if (isFPCmp)
1161     BuildMI(*BB, BB->begin(), dl,
1162             TII->get(Mips::PHI), MI->getOperand(0).getReg())
1163       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1164       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1165   else
1166     BuildMI(*BB, BB->begin(), dl,
1167             TII->get(Mips::PHI), MI->getOperand(0).getReg())
1168       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1169       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1170
1171   MI->eraseFromParent();   // The pseudo instruction is gone now.
1172   return BB;
1173 }
1174 */
1175
1176 MachineBasicBlock *
1177 MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1178   // $bb:
1179   //  bposge32_pseudo $vr0
1180   //  =>
1181   // $bb:
1182   //  bposge32 $tbb
1183   // $fbb:
1184   //  li $vr2, 0
1185   //  b $sink
1186   // $tbb:
1187   //  li $vr1, 1
1188   // $sink:
1189   //  $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1190
1191   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1192   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1193   const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1194   DebugLoc DL = MI->getDebugLoc();
1195   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1196   MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1197   MachineFunction *F = BB->getParent();
1198   MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1199   MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1200   MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
1201   F->insert(It, FBB);
1202   F->insert(It, TBB);
1203   F->insert(It, Sink);
1204
1205   // Transfer the remainder of BB and its successor edges to Sink.
1206   Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1207                BB->end());
1208   Sink->transferSuccessorsAndUpdatePHIs(BB);
1209
1210   // Add successors.
1211   BB->addSuccessor(FBB);
1212   BB->addSuccessor(TBB);
1213   FBB->addSuccessor(Sink);
1214   TBB->addSuccessor(Sink);
1215
1216   // Insert the real bposge32 instruction to $BB.
1217   BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1218
1219   // Fill $FBB.
1220   unsigned VR2 = RegInfo.createVirtualRegister(RC);
1221   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1222     .addReg(Mips::ZERO).addImm(0);
1223   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1224
1225   // Fill $TBB.
1226   unsigned VR1 = RegInfo.createVirtualRegister(RC);
1227   BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1228     .addReg(Mips::ZERO).addImm(1);
1229
1230   // Insert phi function to $Sink.
1231   BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1232           MI->getOperand(0).getReg())
1233     .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1234
1235   MI->eraseFromParent();   // The pseudo instruction is gone now.
1236   return Sink;
1237 }
1238
1239 MachineBasicBlock *MipsTargetLowering::EmitSel16(unsigned Opc, MachineInstr *MI,
1240                              MachineBasicBlock *BB) const {
1241   if (DontExpandCondPseudos16)
1242     return BB;
1243   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1244   DebugLoc dl = MI->getDebugLoc();
1245   // To "insert" a SELECT_CC instruction, we actually have to insert the
1246   // diamond control-flow pattern.  The incoming instruction knows the
1247   // destination vreg to set, the condition code register to branch on, the
1248   // true/false values to select between, and a branch opcode to use.
1249   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1250   MachineFunction::iterator It = BB;
1251   ++It;
1252
1253   //  thisMBB:
1254   //  ...
1255   //   TrueVal = ...
1256   //   setcc r1, r2, r3
1257   //   bNE   r1, r0, copy1MBB
1258   //   fallthrough --> copy0MBB
1259   MachineBasicBlock *thisMBB  = BB;
1260   MachineFunction *F = BB->getParent();
1261   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1262   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1263   F->insert(It, copy0MBB);
1264   F->insert(It, sinkMBB);
1265
1266   // Transfer the remainder of BB and its successor edges to sinkMBB.
1267   sinkMBB->splice(sinkMBB->begin(), BB,
1268                   llvm::next(MachineBasicBlock::iterator(MI)),
1269                   BB->end());
1270   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1271
1272   // Next, add the true and fallthrough blocks as its successors.
1273   BB->addSuccessor(copy0MBB);
1274   BB->addSuccessor(sinkMBB);
1275
1276   BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(3).getReg())
1277     .addMBB(sinkMBB);
1278
1279   //  copy0MBB:
1280   //   %FalseValue = ...
1281   //   # fallthrough to sinkMBB
1282   BB = copy0MBB;
1283
1284   // Update machine-CFG edges
1285   BB->addSuccessor(sinkMBB);
1286
1287   //  sinkMBB:
1288   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1289   //  ...
1290   BB = sinkMBB;
1291
1292   BuildMI(*BB, BB->begin(), dl,
1293           TII->get(Mips::PHI), MI->getOperand(0).getReg())
1294     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1295     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1296
1297   MI->eraseFromParent();   // The pseudo instruction is gone now.
1298   return BB;
1299 }
1300
1301 MachineBasicBlock *MipsTargetLowering::EmitSelT16
1302   (unsigned Opc1, unsigned Opc2,
1303    MachineInstr *MI, MachineBasicBlock *BB) const {
1304   if (DontExpandCondPseudos16)
1305     return BB;
1306   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1307   DebugLoc dl = MI->getDebugLoc();
1308   // To "insert" a SELECT_CC instruction, we actually have to insert the
1309   // diamond control-flow pattern.  The incoming instruction knows the
1310   // destination vreg to set, the condition code register to branch on, the
1311   // true/false values to select between, and a branch opcode to use.
1312   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1313   MachineFunction::iterator It = BB;
1314   ++It;
1315
1316   //  thisMBB:
1317   //  ...
1318   //   TrueVal = ...
1319   //   setcc r1, r2, r3
1320   //   bNE   r1, r0, copy1MBB
1321   //   fallthrough --> copy0MBB
1322   MachineBasicBlock *thisMBB  = BB;
1323   MachineFunction *F = BB->getParent();
1324   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1325   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1326   F->insert(It, copy0MBB);
1327   F->insert(It, sinkMBB);
1328
1329   // Transfer the remainder of BB and its successor edges to sinkMBB.
1330   sinkMBB->splice(sinkMBB->begin(), BB,
1331                   llvm::next(MachineBasicBlock::iterator(MI)),
1332                   BB->end());
1333   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1334
1335   // Next, add the true and fallthrough blocks as its successors.
1336   BB->addSuccessor(copy0MBB);
1337   BB->addSuccessor(sinkMBB);
1338
1339   BuildMI(BB, dl, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
1340     .addReg(MI->getOperand(4).getReg());
1341   BuildMI(BB, dl, TII->get(Opc1)).addMBB(sinkMBB);
1342
1343   //  copy0MBB:
1344   //   %FalseValue = ...
1345   //   # fallthrough to sinkMBB
1346   BB = copy0MBB;
1347
1348   // Update machine-CFG edges
1349   BB->addSuccessor(sinkMBB);
1350
1351   //  sinkMBB:
1352   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1353   //  ...
1354   BB = sinkMBB;
1355
1356   BuildMI(*BB, BB->begin(), dl,
1357           TII->get(Mips::PHI), MI->getOperand(0).getReg())
1358     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1359     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1360
1361   MI->eraseFromParent();   // The pseudo instruction is gone now.
1362   return BB;
1363
1364 }
1365
1366
1367 MachineBasicBlock *MipsTargetLowering::EmitSeliT16
1368   (unsigned Opc1, unsigned Opc2,
1369    MachineInstr *MI, MachineBasicBlock *BB) const {
1370   if (DontExpandCondPseudos16)
1371     return BB;
1372   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1373   DebugLoc dl = MI->getDebugLoc();
1374   // To "insert" a SELECT_CC instruction, we actually have to insert the
1375   // diamond control-flow pattern.  The incoming instruction knows the
1376   // destination vreg to set, the condition code register to branch on, the
1377   // true/false values to select between, and a branch opcode to use.
1378   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1379   MachineFunction::iterator It = BB;
1380   ++It;
1381
1382   //  thisMBB:
1383   //  ...
1384   //   TrueVal = ...
1385   //   setcc r1, r2, r3
1386   //   bNE   r1, r0, copy1MBB
1387   //   fallthrough --> copy0MBB
1388   MachineBasicBlock *thisMBB  = BB;
1389   MachineFunction *F = BB->getParent();
1390   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1391   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1392   F->insert(It, copy0MBB);
1393   F->insert(It, sinkMBB);
1394
1395   // Transfer the remainder of BB and its successor edges to sinkMBB.
1396   sinkMBB->splice(sinkMBB->begin(), BB,
1397                   llvm::next(MachineBasicBlock::iterator(MI)),
1398                   BB->end());
1399   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1400
1401   // Next, add the true and fallthrough blocks as its successors.
1402   BB->addSuccessor(copy0MBB);
1403   BB->addSuccessor(sinkMBB);
1404
1405   BuildMI(BB, dl, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
1406     .addImm(MI->getOperand(4).getImm());
1407   BuildMI(BB, dl, TII->get(Opc1)).addMBB(sinkMBB);
1408
1409   //  copy0MBB:
1410   //   %FalseValue = ...
1411   //   # fallthrough to sinkMBB
1412   BB = copy0MBB;
1413
1414   // Update machine-CFG edges
1415   BB->addSuccessor(sinkMBB);
1416
1417   //  sinkMBB:
1418   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1419   //  ...
1420   BB = sinkMBB;
1421
1422   BuildMI(*BB, BB->begin(), dl,
1423           TII->get(Mips::PHI), MI->getOperand(0).getReg())
1424     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1425     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1426
1427   MI->eraseFromParent();   // The pseudo instruction is gone now.
1428   return BB;
1429
1430 }
1431
1432
1433 MachineBasicBlock
1434   *MipsTargetLowering::EmitFEXT_T8I816_ins(unsigned BtOpc, unsigned CmpOpc,
1435                            MachineInstr *MI,
1436                            MachineBasicBlock *BB) const {
1437   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1438   unsigned regX = MI->getOperand(0).getReg();
1439   unsigned regY = MI->getOperand(1).getReg();
1440   MachineBasicBlock *target = MI->getOperand(2).getMBB();
1441   BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(CmpOpc)).addReg(regX).addReg(regY);
1442   BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(BtOpc)).addMBB(target);
1443   MI->eraseFromParent();   // The pseudo instruction is gone now.
1444   return BB;
1445 }
1446 MachineBasicBlock *
1447 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1448                                                 MachineBasicBlock *BB) const {
1449   switch (MI->getOpcode()) {
1450   default:
1451     llvm_unreachable("Unexpected instr type to insert");
1452   case Mips::ATOMIC_LOAD_ADD_I8:
1453   case Mips::ATOMIC_LOAD_ADD_I8_P8:
1454     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1455   case Mips::ATOMIC_LOAD_ADD_I16:
1456   case Mips::ATOMIC_LOAD_ADD_I16_P8:
1457     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1458   case Mips::ATOMIC_LOAD_ADD_I32:
1459   case Mips::ATOMIC_LOAD_ADD_I32_P8:
1460     return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1461   case Mips::ATOMIC_LOAD_ADD_I64:
1462   case Mips::ATOMIC_LOAD_ADD_I64_P8:
1463     return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1464
1465   case Mips::ATOMIC_LOAD_AND_I8:
1466   case Mips::ATOMIC_LOAD_AND_I8_P8:
1467     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1468   case Mips::ATOMIC_LOAD_AND_I16:
1469   case Mips::ATOMIC_LOAD_AND_I16_P8:
1470     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1471   case Mips::ATOMIC_LOAD_AND_I32:
1472   case Mips::ATOMIC_LOAD_AND_I32_P8:
1473     return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1474   case Mips::ATOMIC_LOAD_AND_I64:
1475   case Mips::ATOMIC_LOAD_AND_I64_P8:
1476     return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1477
1478   case Mips::ATOMIC_LOAD_OR_I8:
1479   case Mips::ATOMIC_LOAD_OR_I8_P8:
1480     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1481   case Mips::ATOMIC_LOAD_OR_I16:
1482   case Mips::ATOMIC_LOAD_OR_I16_P8:
1483     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1484   case Mips::ATOMIC_LOAD_OR_I32:
1485   case Mips::ATOMIC_LOAD_OR_I32_P8:
1486     return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1487   case Mips::ATOMIC_LOAD_OR_I64:
1488   case Mips::ATOMIC_LOAD_OR_I64_P8:
1489     return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1490
1491   case Mips::ATOMIC_LOAD_XOR_I8:
1492   case Mips::ATOMIC_LOAD_XOR_I8_P8:
1493     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1494   case Mips::ATOMIC_LOAD_XOR_I16:
1495   case Mips::ATOMIC_LOAD_XOR_I16_P8:
1496     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1497   case Mips::ATOMIC_LOAD_XOR_I32:
1498   case Mips::ATOMIC_LOAD_XOR_I32_P8:
1499     return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1500   case Mips::ATOMIC_LOAD_XOR_I64:
1501   case Mips::ATOMIC_LOAD_XOR_I64_P8:
1502     return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1503
1504   case Mips::ATOMIC_LOAD_NAND_I8:
1505   case Mips::ATOMIC_LOAD_NAND_I8_P8:
1506     return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1507   case Mips::ATOMIC_LOAD_NAND_I16:
1508   case Mips::ATOMIC_LOAD_NAND_I16_P8:
1509     return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1510   case Mips::ATOMIC_LOAD_NAND_I32:
1511   case Mips::ATOMIC_LOAD_NAND_I32_P8:
1512     return EmitAtomicBinary(MI, BB, 4, 0, true);
1513   case Mips::ATOMIC_LOAD_NAND_I64:
1514   case Mips::ATOMIC_LOAD_NAND_I64_P8:
1515     return EmitAtomicBinary(MI, BB, 8, 0, true);
1516
1517   case Mips::ATOMIC_LOAD_SUB_I8:
1518   case Mips::ATOMIC_LOAD_SUB_I8_P8:
1519     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1520   case Mips::ATOMIC_LOAD_SUB_I16:
1521   case Mips::ATOMIC_LOAD_SUB_I16_P8:
1522     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1523   case Mips::ATOMIC_LOAD_SUB_I32:
1524   case Mips::ATOMIC_LOAD_SUB_I32_P8:
1525     return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1526   case Mips::ATOMIC_LOAD_SUB_I64:
1527   case Mips::ATOMIC_LOAD_SUB_I64_P8:
1528     return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1529
1530   case Mips::ATOMIC_SWAP_I8:
1531   case Mips::ATOMIC_SWAP_I8_P8:
1532     return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1533   case Mips::ATOMIC_SWAP_I16:
1534   case Mips::ATOMIC_SWAP_I16_P8:
1535     return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1536   case Mips::ATOMIC_SWAP_I32:
1537   case Mips::ATOMIC_SWAP_I32_P8:
1538     return EmitAtomicBinary(MI, BB, 4, 0);
1539   case Mips::ATOMIC_SWAP_I64:
1540   case Mips::ATOMIC_SWAP_I64_P8:
1541     return EmitAtomicBinary(MI, BB, 8, 0);
1542
1543   case Mips::ATOMIC_CMP_SWAP_I8:
1544   case Mips::ATOMIC_CMP_SWAP_I8_P8:
1545     return EmitAtomicCmpSwapPartword(MI, BB, 1);
1546   case Mips::ATOMIC_CMP_SWAP_I16:
1547   case Mips::ATOMIC_CMP_SWAP_I16_P8:
1548     return EmitAtomicCmpSwapPartword(MI, BB, 2);
1549   case Mips::ATOMIC_CMP_SWAP_I32:
1550   case Mips::ATOMIC_CMP_SWAP_I32_P8:
1551     return EmitAtomicCmpSwap(MI, BB, 4);
1552   case Mips::ATOMIC_CMP_SWAP_I64:
1553   case Mips::ATOMIC_CMP_SWAP_I64_P8:
1554     return EmitAtomicCmpSwap(MI, BB, 8);
1555   case Mips::BPOSGE32_PSEUDO:
1556     return EmitBPOSGE32(MI, BB);
1557   case Mips::SelBeqZ:
1558     return EmitSel16(Mips::BeqzRxImm16, MI, BB);
1559   case Mips::SelBneZ:
1560     return EmitSel16(Mips::BnezRxImm16, MI, BB);
1561   case Mips::SelTBteqZCmpi:
1562     return EmitSeliT16(Mips::BteqzX16, Mips::CmpiRxImmX16, MI, BB);
1563   case Mips::SelTBteqZSlti:
1564     return EmitSeliT16(Mips::BteqzX16, Mips::SltiRxImmX16, MI, BB);
1565   case Mips::SelTBteqZSltiu:
1566     return EmitSeliT16(Mips::BteqzX16, Mips::SltiuRxImmX16, MI, BB);
1567   case Mips::SelTBtneZCmpi:
1568     return EmitSeliT16(Mips::BtnezX16, Mips::CmpiRxImmX16, MI, BB);
1569   case Mips::SelTBtneZSlti:
1570     return EmitSeliT16(Mips::BtnezX16, Mips::SltiRxImmX16, MI, BB);
1571   case Mips::SelTBtneZSltiu:
1572     return EmitSeliT16(Mips::BtnezX16, Mips::SltiuRxImmX16, MI, BB);
1573   case Mips::SelTBteqZCmp:
1574     return EmitSelT16(Mips::BteqzX16, Mips::CmpRxRy16, MI, BB);
1575   case Mips::SelTBteqZSlt:
1576     return EmitSelT16(Mips::BteqzX16, Mips::SltRxRy16, MI, BB);
1577   case Mips::SelTBteqZSltu:
1578     return EmitSelT16(Mips::BteqzX16, Mips::SltuRxRy16, MI, BB);
1579   case Mips::SelTBtneZCmp:
1580     return EmitSelT16(Mips::BtnezX16, Mips::CmpRxRy16, MI, BB);
1581   case Mips::SelTBtneZSlt:
1582     return EmitSelT16(Mips::BtnezX16, Mips::SltRxRy16, MI, BB);
1583   case Mips::SelTBtneZSltu:
1584     return EmitSelT16(Mips::BtnezX16, Mips::SltuRxRy16, MI, BB);
1585   case Mips::BteqzT8CmpX16:
1586     return EmitFEXT_T8I816_ins(Mips::BteqzX16, Mips::CmpRxRy16, MI, BB);
1587   case Mips::BteqzT8SltX16:
1588     return EmitFEXT_T8I816_ins(Mips::BteqzX16, Mips::SltRxRy16, MI, BB);
1589   case Mips::BteqzT8SltuX16:
1590     // TBD: figure out a way to get this or remove the instruction
1591     // altogether.
1592     return EmitFEXT_T8I816_ins(Mips::BteqzX16, Mips::SltuRxRy16, MI, BB);
1593   case Mips::BtnezT8CmpX16:
1594     return EmitFEXT_T8I816_ins(Mips::BtnezX16, Mips::CmpRxRy16, MI, BB);
1595   case Mips::BtnezT8SltX16:
1596     return EmitFEXT_T8I816_ins(Mips::BtnezX16, Mips::SltRxRy16, MI, BB);
1597   case Mips::BtnezT8SltuX16:
1598     // TBD: figure out a way to get this or remove the instruction
1599     // altogether.
1600     return EmitFEXT_T8I816_ins(Mips::BtnezX16, Mips::SltuRxRy16, MI, BB);
1601   }
1602 }
1603
1604 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1605 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1606 MachineBasicBlock *
1607 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1608                                      unsigned Size, unsigned BinOpcode,
1609                                      bool Nand) const {
1610   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1611
1612   MachineFunction *MF = BB->getParent();
1613   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1614   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1615   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1616   DebugLoc dl = MI->getDebugLoc();
1617   unsigned LL, SC, AND, NOR, ZERO, BEQ;
1618
1619   if (Size == 4) {
1620     LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1621     SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1622     AND = Mips::AND;
1623     NOR = Mips::NOR;
1624     ZERO = Mips::ZERO;
1625     BEQ = Mips::BEQ;
1626   }
1627   else {
1628     LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1629     SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1630     AND = Mips::AND64;
1631     NOR = Mips::NOR64;
1632     ZERO = Mips::ZERO_64;
1633     BEQ = Mips::BEQ64;
1634   }
1635
1636   unsigned OldVal = MI->getOperand(0).getReg();
1637   unsigned Ptr = MI->getOperand(1).getReg();
1638   unsigned Incr = MI->getOperand(2).getReg();
1639
1640   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1641   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1642   unsigned Success = RegInfo.createVirtualRegister(RC);
1643
1644   // insert new blocks after the current block
1645   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1646   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1647   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1648   MachineFunction::iterator It = BB;
1649   ++It;
1650   MF->insert(It, loopMBB);
1651   MF->insert(It, exitMBB);
1652
1653   // Transfer the remainder of BB and its successor edges to exitMBB.
1654   exitMBB->splice(exitMBB->begin(), BB,
1655                   llvm::next(MachineBasicBlock::iterator(MI)),
1656                   BB->end());
1657   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1658
1659   //  thisMBB:
1660   //    ...
1661   //    fallthrough --> loopMBB
1662   BB->addSuccessor(loopMBB);
1663   loopMBB->addSuccessor(loopMBB);
1664   loopMBB->addSuccessor(exitMBB);
1665
1666   //  loopMBB:
1667   //    ll oldval, 0(ptr)
1668   //    <binop> storeval, oldval, incr
1669   //    sc success, storeval, 0(ptr)
1670   //    beq success, $0, loopMBB
1671   BB = loopMBB;
1672   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1673   if (Nand) {
1674     //  and andres, oldval, incr
1675     //  nor storeval, $0, andres
1676     BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1677     BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1678   } else if (BinOpcode) {
1679     //  <binop> storeval, oldval, incr
1680     BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1681   } else {
1682     StoreVal = Incr;
1683   }
1684   BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1685   BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1686
1687   MI->eraseFromParent();   // The instruction is gone now.
1688
1689   return exitMBB;
1690 }
1691
1692 MachineBasicBlock *
1693 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1694                                              MachineBasicBlock *BB,
1695                                              unsigned Size, unsigned BinOpcode,
1696                                              bool Nand) const {
1697   assert((Size == 1 || Size == 2) &&
1698       "Unsupported size for EmitAtomicBinaryPartial.");
1699
1700   MachineFunction *MF = BB->getParent();
1701   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1702   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1703   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1704   DebugLoc dl = MI->getDebugLoc();
1705   unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1706   unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1707
1708   unsigned Dest = MI->getOperand(0).getReg();
1709   unsigned Ptr = MI->getOperand(1).getReg();
1710   unsigned Incr = MI->getOperand(2).getReg();
1711
1712   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1713   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1714   unsigned Mask = RegInfo.createVirtualRegister(RC);
1715   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1716   unsigned NewVal = RegInfo.createVirtualRegister(RC);
1717   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1718   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1719   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1720   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1721   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1722   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1723   unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1724   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1725   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1726   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1727   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1728   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1729   unsigned Success = RegInfo.createVirtualRegister(RC);
1730
1731   // insert new blocks after the current block
1732   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1733   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1734   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1735   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1736   MachineFunction::iterator It = BB;
1737   ++It;
1738   MF->insert(It, loopMBB);
1739   MF->insert(It, sinkMBB);
1740   MF->insert(It, exitMBB);
1741
1742   // Transfer the remainder of BB and its successor edges to exitMBB.
1743   exitMBB->splice(exitMBB->begin(), BB,
1744                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1745   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1746
1747   BB->addSuccessor(loopMBB);
1748   loopMBB->addSuccessor(loopMBB);
1749   loopMBB->addSuccessor(sinkMBB);
1750   sinkMBB->addSuccessor(exitMBB);
1751
1752   //  thisMBB:
1753   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1754   //    and     alignedaddr,ptr,masklsb2
1755   //    andi    ptrlsb2,ptr,3
1756   //    sll     shiftamt,ptrlsb2,3
1757   //    ori     maskupper,$0,255               # 0xff
1758   //    sll     mask,maskupper,shiftamt
1759   //    nor     mask2,$0,mask
1760   //    sll     incr2,incr,shiftamt
1761
1762   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1763   BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1764     .addReg(Mips::ZERO).addImm(-4);
1765   BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1766     .addReg(Ptr).addReg(MaskLSB2);
1767   BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1768   BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1769   BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1770     .addReg(Mips::ZERO).addImm(MaskImm);
1771   BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1772     .addReg(ShiftAmt).addReg(MaskUpper);
1773   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1774   BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1775
1776   // atomic.load.binop
1777   // loopMBB:
1778   //   ll      oldval,0(alignedaddr)
1779   //   binop   binopres,oldval,incr2
1780   //   and     newval,binopres,mask
1781   //   and     maskedoldval0,oldval,mask2
1782   //   or      storeval,maskedoldval0,newval
1783   //   sc      success,storeval,0(alignedaddr)
1784   //   beq     success,$0,loopMBB
1785
1786   // atomic.swap
1787   // loopMBB:
1788   //   ll      oldval,0(alignedaddr)
1789   //   and     newval,incr2,mask
1790   //   and     maskedoldval0,oldval,mask2
1791   //   or      storeval,maskedoldval0,newval
1792   //   sc      success,storeval,0(alignedaddr)
1793   //   beq     success,$0,loopMBB
1794
1795   BB = loopMBB;
1796   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1797   if (Nand) {
1798     //  and andres, oldval, incr2
1799     //  nor binopres, $0, andres
1800     //  and newval, binopres, mask
1801     BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1802     BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1803       .addReg(Mips::ZERO).addReg(AndRes);
1804     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1805   } else if (BinOpcode) {
1806     //  <binop> binopres, oldval, incr2
1807     //  and newval, binopres, mask
1808     BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1809     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1810   } else {// atomic.swap
1811     //  and newval, incr2, mask
1812     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1813   }
1814
1815   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1816     .addReg(OldVal).addReg(Mask2);
1817   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1818     .addReg(MaskedOldVal0).addReg(NewVal);
1819   BuildMI(BB, dl, TII->get(SC), Success)
1820     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1821   BuildMI(BB, dl, TII->get(Mips::BEQ))
1822     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1823
1824   //  sinkMBB:
1825   //    and     maskedoldval1,oldval,mask
1826   //    srl     srlres,maskedoldval1,shiftamt
1827   //    sll     sllres,srlres,24
1828   //    sra     dest,sllres,24
1829   BB = sinkMBB;
1830   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1831
1832   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1833     .addReg(OldVal).addReg(Mask);
1834   BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1835       .addReg(ShiftAmt).addReg(MaskedOldVal1);
1836   BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1837       .addReg(SrlRes).addImm(ShiftImm);
1838   BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1839       .addReg(SllRes).addImm(ShiftImm);
1840
1841   MI->eraseFromParent();   // The instruction is gone now.
1842
1843   return exitMBB;
1844 }
1845
1846 MachineBasicBlock *
1847 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1848                                       MachineBasicBlock *BB,
1849                                       unsigned Size) const {
1850   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1851
1852   MachineFunction *MF = BB->getParent();
1853   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1854   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1855   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1856   DebugLoc dl = MI->getDebugLoc();
1857   unsigned LL, SC, ZERO, BNE, BEQ;
1858
1859   if (Size == 4) {
1860     LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1861     SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1862     ZERO = Mips::ZERO;
1863     BNE = Mips::BNE;
1864     BEQ = Mips::BEQ;
1865   }
1866   else {
1867     LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1868     SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1869     ZERO = Mips::ZERO_64;
1870     BNE = Mips::BNE64;
1871     BEQ = Mips::BEQ64;
1872   }
1873
1874   unsigned Dest    = MI->getOperand(0).getReg();
1875   unsigned Ptr     = MI->getOperand(1).getReg();
1876   unsigned OldVal  = MI->getOperand(2).getReg();
1877   unsigned NewVal  = MI->getOperand(3).getReg();
1878
1879   unsigned Success = RegInfo.createVirtualRegister(RC);
1880
1881   // insert new blocks after the current block
1882   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1883   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1884   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1885   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1886   MachineFunction::iterator It = BB;
1887   ++It;
1888   MF->insert(It, loop1MBB);
1889   MF->insert(It, loop2MBB);
1890   MF->insert(It, exitMBB);
1891
1892   // Transfer the remainder of BB and its successor edges to exitMBB.
1893   exitMBB->splice(exitMBB->begin(), BB,
1894                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1895   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1896
1897   //  thisMBB:
1898   //    ...
1899   //    fallthrough --> loop1MBB
1900   BB->addSuccessor(loop1MBB);
1901   loop1MBB->addSuccessor(exitMBB);
1902   loop1MBB->addSuccessor(loop2MBB);
1903   loop2MBB->addSuccessor(loop1MBB);
1904   loop2MBB->addSuccessor(exitMBB);
1905
1906   // loop1MBB:
1907   //   ll dest, 0(ptr)
1908   //   bne dest, oldval, exitMBB
1909   BB = loop1MBB;
1910   BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1911   BuildMI(BB, dl, TII->get(BNE))
1912     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1913
1914   // loop2MBB:
1915   //   sc success, newval, 0(ptr)
1916   //   beq success, $0, loop1MBB
1917   BB = loop2MBB;
1918   BuildMI(BB, dl, TII->get(SC), Success)
1919     .addReg(NewVal).addReg(Ptr).addImm(0);
1920   BuildMI(BB, dl, TII->get(BEQ))
1921     .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1922
1923   MI->eraseFromParent();   // The instruction is gone now.
1924
1925   return exitMBB;
1926 }
1927
1928 MachineBasicBlock *
1929 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1930                                               MachineBasicBlock *BB,
1931                                               unsigned Size) const {
1932   assert((Size == 1 || Size == 2) &&
1933       "Unsupported size for EmitAtomicCmpSwapPartial.");
1934
1935   MachineFunction *MF = BB->getParent();
1936   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1937   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1938   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1939   DebugLoc dl = MI->getDebugLoc();
1940   unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1941   unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1942
1943   unsigned Dest    = MI->getOperand(0).getReg();
1944   unsigned Ptr     = MI->getOperand(1).getReg();
1945   unsigned CmpVal  = MI->getOperand(2).getReg();
1946   unsigned NewVal  = MI->getOperand(3).getReg();
1947
1948   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1949   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1950   unsigned Mask = RegInfo.createVirtualRegister(RC);
1951   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1952   unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1953   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1954   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1955   unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1956   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1957   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1958   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1959   unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1960   unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1961   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1962   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1963   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1964   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1965   unsigned Success = RegInfo.createVirtualRegister(RC);
1966
1967   // insert new blocks after the current block
1968   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1969   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1970   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1971   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1972   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1973   MachineFunction::iterator It = BB;
1974   ++It;
1975   MF->insert(It, loop1MBB);
1976   MF->insert(It, loop2MBB);
1977   MF->insert(It, sinkMBB);
1978   MF->insert(It, exitMBB);
1979
1980   // Transfer the remainder of BB and its successor edges to exitMBB.
1981   exitMBB->splice(exitMBB->begin(), BB,
1982                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1983   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1984
1985   BB->addSuccessor(loop1MBB);
1986   loop1MBB->addSuccessor(sinkMBB);
1987   loop1MBB->addSuccessor(loop2MBB);
1988   loop2MBB->addSuccessor(loop1MBB);
1989   loop2MBB->addSuccessor(sinkMBB);
1990   sinkMBB->addSuccessor(exitMBB);
1991
1992   // FIXME: computation of newval2 can be moved to loop2MBB.
1993   //  thisMBB:
1994   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1995   //    and     alignedaddr,ptr,masklsb2
1996   //    andi    ptrlsb2,ptr,3
1997   //    sll     shiftamt,ptrlsb2,3
1998   //    ori     maskupper,$0,255               # 0xff
1999   //    sll     mask,maskupper,shiftamt
2000   //    nor     mask2,$0,mask
2001   //    andi    maskedcmpval,cmpval,255
2002   //    sll     shiftedcmpval,maskedcmpval,shiftamt
2003   //    andi    maskednewval,newval,255
2004   //    sll     shiftednewval,maskednewval,shiftamt
2005   int64_t MaskImm = (Size == 1) ? 255 : 65535;
2006   BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
2007     .addReg(Mips::ZERO).addImm(-4);
2008   BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
2009     .addReg(Ptr).addReg(MaskLSB2);
2010   BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
2011   BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
2012   BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
2013     .addReg(Mips::ZERO).addImm(MaskImm);
2014   BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
2015     .addReg(ShiftAmt).addReg(MaskUpper);
2016   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
2017   BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
2018     .addReg(CmpVal).addImm(MaskImm);
2019   BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
2020     .addReg(ShiftAmt).addReg(MaskedCmpVal);
2021   BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
2022     .addReg(NewVal).addImm(MaskImm);
2023   BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
2024     .addReg(ShiftAmt).addReg(MaskedNewVal);
2025
2026   //  loop1MBB:
2027   //    ll      oldval,0(alginedaddr)
2028   //    and     maskedoldval0,oldval,mask
2029   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
2030   BB = loop1MBB;
2031   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
2032   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
2033     .addReg(OldVal).addReg(Mask);
2034   BuildMI(BB, dl, TII->get(Mips::BNE))
2035     .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
2036
2037   //  loop2MBB:
2038   //    and     maskedoldval1,oldval,mask2
2039   //    or      storeval,maskedoldval1,shiftednewval
2040   //    sc      success,storeval,0(alignedaddr)
2041   //    beq     success,$0,loop1MBB
2042   BB = loop2MBB;
2043   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
2044     .addReg(OldVal).addReg(Mask2);
2045   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
2046     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
2047   BuildMI(BB, dl, TII->get(SC), Success)
2048       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
2049   BuildMI(BB, dl, TII->get(Mips::BEQ))
2050       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
2051
2052   //  sinkMBB:
2053   //    srl     srlres,maskedoldval0,shiftamt
2054   //    sll     sllres,srlres,24
2055   //    sra     dest,sllres,24
2056   BB = sinkMBB;
2057   int64_t ShiftImm = (Size == 1) ? 24 : 16;
2058
2059   BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
2060       .addReg(ShiftAmt).addReg(MaskedOldVal0);
2061   BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
2062       .addReg(SrlRes).addImm(ShiftImm);
2063   BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
2064       .addReg(SllRes).addImm(ShiftImm);
2065
2066   MI->eraseFromParent();   // The instruction is gone now.
2067
2068   return exitMBB;
2069 }
2070
2071 //===----------------------------------------------------------------------===//
2072 //  Misc Lower Operation implementation
2073 //===----------------------------------------------------------------------===//
2074 SDValue MipsTargetLowering::
2075 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
2076 {
2077   // The first operand is the chain, the second is the condition, the third is
2078   // the block to branch to if the condition is true.
2079   SDValue Chain = Op.getOperand(0);
2080   SDValue Dest = Op.getOperand(2);
2081   DebugLoc dl = Op.getDebugLoc();
2082
2083   SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
2084
2085   // Return if flag is not set by a floating point comparison.
2086   if (CondRes.getOpcode() != MipsISD::FPCmp)
2087     return Op;
2088
2089   SDValue CCNode  = CondRes.getOperand(2);
2090   Mips::CondCode CC =
2091     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2092   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
2093
2094   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
2095                      Dest, CondRes);
2096 }
2097
2098 SDValue MipsTargetLowering::
2099 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
2100 {
2101   SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
2102
2103   // Return if flag is not set by a floating point comparison.
2104   if (Cond.getOpcode() != MipsISD::FPCmp)
2105     return Op;
2106
2107   return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2108                       Op.getDebugLoc());
2109 }
2110
2111 SDValue MipsTargetLowering::
2112 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
2113 {
2114   DebugLoc DL = Op.getDebugLoc();
2115   EVT Ty = Op.getOperand(0).getValueType();
2116   SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
2117                              Op.getOperand(0), Op.getOperand(1),
2118                              Op.getOperand(4));
2119
2120   return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
2121                      Op.getOperand(3));
2122 }
2123
2124 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2125   SDValue Cond = CreateFPCmp(DAG, Op);
2126
2127   assert(Cond.getOpcode() == MipsISD::FPCmp &&
2128          "Floating point operand expected.");
2129
2130   SDValue True  = DAG.getConstant(1, MVT::i32);
2131   SDValue False = DAG.getConstant(0, MVT::i32);
2132
2133   return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
2134 }
2135
2136 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
2137                                                SelectionDAG &DAG) const {
2138   // FIXME there isn't actually debug info here
2139   DebugLoc dl = Op.getDebugLoc();
2140   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2141
2142   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
2143     const MipsTargetObjectFile &TLOF =
2144       (const MipsTargetObjectFile&)getObjFileLowering();
2145
2146     // %gp_rel relocation
2147     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
2148       SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
2149                                               MipsII::MO_GPREL);
2150       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
2151                                       DAG.getVTList(MVT::i32), &GA, 1);
2152       SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
2153       return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
2154     }
2155
2156     // %hi/%lo relocation
2157     return getAddrNonPIC(Op, DAG);
2158   }
2159
2160   if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
2161     return getAddrLocal(Op, DAG, HasMips64);
2162
2163   if (LargeGOT)
2164     return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
2165                                  MipsII::MO_GOT_LO16);
2166
2167   return getAddrGlobal(Op, DAG,
2168                        HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
2169 }
2170
2171 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
2172                                               SelectionDAG &DAG) const {
2173   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2174     return getAddrNonPIC(Op, DAG);
2175
2176   return getAddrLocal(Op, DAG, HasMips64);
2177 }
2178
2179 SDValue MipsTargetLowering::
2180 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2181 {
2182   // If the relocation model is PIC, use the General Dynamic TLS Model or
2183   // Local Dynamic TLS model, otherwise use the Initial Exec or
2184   // Local Exec TLS Model.
2185
2186   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2187   DebugLoc dl = GA->getDebugLoc();
2188   const GlobalValue *GV = GA->getGlobal();
2189   EVT PtrVT = getPointerTy();
2190
2191   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2192
2193   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2194     // General Dynamic and Local Dynamic TLS Model.
2195     unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2196                                                       : MipsII::MO_TLSGD;
2197
2198     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
2199     SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
2200                                    GetGlobalReg(DAG, PtrVT), TGA);
2201     unsigned PtrSize = PtrVT.getSizeInBits();
2202     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2203
2204     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2205
2206     ArgListTy Args;
2207     ArgListEntry Entry;
2208     Entry.Node = Argument;
2209     Entry.Ty = PtrTy;
2210     Args.push_back(Entry);
2211
2212     TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
2213                   false, false, false, false, 0, CallingConv::C,
2214                   /*isTailCall=*/false, /*doesNotRet=*/false,
2215                   /*isReturnValueUsed=*/true,
2216                   TlsGetAddr, Args, DAG, dl);
2217     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2218
2219     SDValue Ret = CallResult.first;
2220
2221     if (model != TLSModel::LocalDynamic)
2222       return Ret;
2223
2224     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2225                                                MipsII::MO_DTPREL_HI);
2226     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
2227     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2228                                                MipsII::MO_DTPREL_LO);
2229     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
2230     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
2231     return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
2232   }
2233
2234   SDValue Offset;
2235   if (model == TLSModel::InitialExec) {
2236     // Initial Exec TLS Model
2237     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2238                                              MipsII::MO_GOTTPREL);
2239     TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
2240                       TGA);
2241     Offset = DAG.getLoad(PtrVT, dl,
2242                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
2243                          false, false, false, 0);
2244   } else {
2245     // Local Exec TLS Model
2246     assert(model == TLSModel::LocalExec);
2247     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2248                                                MipsII::MO_TPREL_HI);
2249     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2250                                                MipsII::MO_TPREL_LO);
2251     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
2252     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
2253     Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
2254   }
2255
2256   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
2257   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2258 }
2259
2260 SDValue MipsTargetLowering::
2261 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2262 {
2263   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2264     return getAddrNonPIC(Op, DAG);
2265
2266   return getAddrLocal(Op, DAG, HasMips64);
2267 }
2268
2269 SDValue MipsTargetLowering::
2270 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2271 {
2272   // gp_rel relocation
2273   // FIXME: we should reference the constant pool using small data sections,
2274   // but the asm printer currently doesn't support this feature without
2275   // hacking it. This feature should come soon so we can uncomment the
2276   // stuff below.
2277   //if (IsInSmallSection(C->getType())) {
2278   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
2279   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
2280   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2281
2282   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2283     return getAddrNonPIC(Op, DAG);
2284
2285   return getAddrLocal(Op, DAG, HasMips64);
2286 }
2287
2288 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2289   MachineFunction &MF = DAG.getMachineFunction();
2290   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2291
2292   DebugLoc dl = Op.getDebugLoc();
2293   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2294                                  getPointerTy());
2295
2296   // vastart just stores the address of the VarArgsFrameIndex slot into the
2297   // memory location argument.
2298   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2299   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
2300                       MachinePointerInfo(SV), false, false, 0);
2301 }
2302
2303 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2304   EVT TyX = Op.getOperand(0).getValueType();
2305   EVT TyY = Op.getOperand(1).getValueType();
2306   SDValue Const1 = DAG.getConstant(1, MVT::i32);
2307   SDValue Const31 = DAG.getConstant(31, MVT::i32);
2308   DebugLoc DL = Op.getDebugLoc();
2309   SDValue Res;
2310
2311   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2312   // to i32.
2313   SDValue X = (TyX == MVT::f32) ?
2314     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2315     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2316                 Const1);
2317   SDValue Y = (TyY == MVT::f32) ?
2318     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2319     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2320                 Const1);
2321
2322   if (HasR2) {
2323     // ext  E, Y, 31, 1  ; extract bit31 of Y
2324     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
2325     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2326     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2327   } else {
2328     // sll SllX, X, 1
2329     // srl SrlX, SllX, 1
2330     // srl SrlY, Y, 31
2331     // sll SllY, SrlX, 31
2332     // or  Or, SrlX, SllY
2333     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2334     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2335     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2336     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2337     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2338   }
2339
2340   if (TyX == MVT::f32)
2341     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2342
2343   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2344                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2345   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2346 }
2347
2348 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2349   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2350   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2351   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2352   SDValue Const1 = DAG.getConstant(1, MVT::i32);
2353   DebugLoc DL = Op.getDebugLoc();
2354
2355   // Bitcast to integer nodes.
2356   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2357   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2358
2359   if (HasR2) {
2360     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
2361     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
2362     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2363                             DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2364
2365     if (WidthX > WidthY)
2366       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2367     else if (WidthY > WidthX)
2368       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2369
2370     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2371                             DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2372     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2373   }
2374
2375   // (d)sll SllX, X, 1
2376   // (d)srl SrlX, SllX, 1
2377   // (d)srl SrlY, Y, width(Y)-1
2378   // (d)sll SllY, SrlX, width(Y)-1
2379   // or     Or, SrlX, SllY
2380   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2381   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2382   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2383                              DAG.getConstant(WidthY - 1, MVT::i32));
2384
2385   if (WidthX > WidthY)
2386     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2387   else if (WidthY > WidthX)
2388     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2389
2390   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2391                              DAG.getConstant(WidthX - 1, MVT::i32));
2392   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2393   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2394 }
2395
2396 SDValue
2397 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2398   if (Subtarget->hasMips64())
2399     return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2400
2401   return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2402 }
2403
2404 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2405   SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2406   DebugLoc DL = Op.getDebugLoc();
2407
2408   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2409   // to i32.
2410   SDValue X = (Op.getValueType() == MVT::f32) ?
2411     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2412     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2413                 Const1);
2414
2415   // Clear MSB.
2416   if (HasR2)
2417     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2418                       DAG.getRegister(Mips::ZERO, MVT::i32),
2419                       DAG.getConstant(31, MVT::i32), Const1, X);
2420   else {
2421     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2422     Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2423   }
2424
2425   if (Op.getValueType() == MVT::f32)
2426     return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2427
2428   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2429                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2430   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2431 }
2432
2433 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2434   SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2435   DebugLoc DL = Op.getDebugLoc();
2436
2437   // Bitcast to integer node.
2438   SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2439
2440   // Clear MSB.
2441   if (HasR2)
2442     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2443                       DAG.getRegister(Mips::ZERO_64, MVT::i64),
2444                       DAG.getConstant(63, MVT::i32), Const1, X);
2445   else {
2446     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2447     Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2448   }
2449
2450   return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2451 }
2452
2453 SDValue
2454 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2455   if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2456     return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2457
2458   return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2459 }
2460
2461 SDValue MipsTargetLowering::
2462 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2463   // check the depth
2464   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2465          "Frame address can only be determined for current frame.");
2466
2467   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2468   MFI->setFrameAddressIsTaken(true);
2469   EVT VT = Op.getValueType();
2470   DebugLoc dl = Op.getDebugLoc();
2471   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2472                                          IsN64 ? Mips::FP_64 : Mips::FP, VT);
2473   return FrameAddr;
2474 }
2475
2476 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2477                                             SelectionDAG &DAG) const {
2478   // check the depth
2479   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2480          "Return address can be determined only for current frame.");
2481
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   MachineFrameInfo *MFI = MF.getFrameInfo();
2484   MVT VT = Op.getSimpleValueType();
2485   unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2486   MFI->setReturnAddressIsTaken(true);
2487
2488   // Return RA, which contains the return address. Mark it an implicit live-in.
2489   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2490   return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2491 }
2492
2493 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2494 // generated from __builtin_eh_return (offset, handler)
2495 // The effect of this is to adjust the stack pointer by "offset"
2496 // and then branch to "handler".
2497 SDValue MipsTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2498                                                                      const {
2499   MachineFunction &MF = DAG.getMachineFunction();
2500   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2501
2502   MipsFI->setCallsEhReturn();
2503   SDValue Chain     = Op.getOperand(0);
2504   SDValue Offset    = Op.getOperand(1);
2505   SDValue Handler   = Op.getOperand(2);
2506   DebugLoc DL       = Op.getDebugLoc();
2507   EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2508
2509   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2510   // EH_RETURN nodes, so that instructions are emitted back-to-back.
2511   unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
2512   unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
2513   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2514   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2515   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2516                      DAG.getRegister(OffsetReg, Ty),
2517                      DAG.getRegister(AddrReg, getPointerTy()),
2518                      Chain.getValue(1));
2519 }
2520
2521 // TODO: set SType according to the desired memory barrier behavior.
2522 SDValue
2523 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2524   unsigned SType = 0;
2525   DebugLoc dl = Op.getDebugLoc();
2526   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2527                      DAG.getConstant(SType, MVT::i32));
2528 }
2529
2530 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2531                                               SelectionDAG &DAG) const {
2532   // FIXME: Need pseudo-fence for 'singlethread' fences
2533   // FIXME: Set SType for weaker fences where supported/appropriate.
2534   unsigned SType = 0;
2535   DebugLoc dl = Op.getDebugLoc();
2536   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2537                      DAG.getConstant(SType, MVT::i32));
2538 }
2539
2540 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2541                                                 SelectionDAG &DAG) const {
2542   DebugLoc DL = Op.getDebugLoc();
2543   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2544   SDValue Shamt = Op.getOperand(2);
2545
2546   // if shamt < 32:
2547   //  lo = (shl lo, shamt)
2548   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2549   // else:
2550   //  lo = 0
2551   //  hi = (shl lo, shamt[4:0])
2552   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2553                             DAG.getConstant(-1, MVT::i32));
2554   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2555                                       DAG.getConstant(1, MVT::i32));
2556   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2557                                      Not);
2558   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2559   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2560   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2561   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2562                              DAG.getConstant(0x20, MVT::i32));
2563   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2564                    DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2565   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2566
2567   SDValue Ops[2] = {Lo, Hi};
2568   return DAG.getMergeValues(Ops, 2, DL);
2569 }
2570
2571 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2572                                                  bool IsSRA) const {
2573   DebugLoc DL = Op.getDebugLoc();
2574   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2575   SDValue Shamt = Op.getOperand(2);
2576
2577   // if shamt < 32:
2578   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2579   //  if isSRA:
2580   //    hi = (sra hi, shamt)
2581   //  else:
2582   //    hi = (srl hi, shamt)
2583   // else:
2584   //  if isSRA:
2585   //   lo = (sra hi, shamt[4:0])
2586   //   hi = (sra hi, 31)
2587   //  else:
2588   //   lo = (srl hi, shamt[4:0])
2589   //   hi = 0
2590   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2591                             DAG.getConstant(-1, MVT::i32));
2592   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2593                                      DAG.getConstant(1, MVT::i32));
2594   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2595   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2596   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2597   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2598                                      Hi, Shamt);
2599   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2600                              DAG.getConstant(0x20, MVT::i32));
2601   SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2602                                 DAG.getConstant(31, MVT::i32));
2603   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2604   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2605                    IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2606                    ShiftRightHi);
2607
2608   SDValue Ops[2] = {Lo, Hi};
2609   return DAG.getMergeValues(Ops, 2, DL);
2610 }
2611
2612 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2613                             SDValue Chain, SDValue Src, unsigned Offset) {
2614   SDValue Ptr = LD->getBasePtr();
2615   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2616   EVT BasePtrVT = Ptr.getValueType();
2617   DebugLoc DL = LD->getDebugLoc();
2618   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2619
2620   if (Offset)
2621     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2622                       DAG.getConstant(Offset, BasePtrVT));
2623
2624   SDValue Ops[] = { Chain, Ptr, Src };
2625   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2626                                  LD->getMemOperand());
2627 }
2628
2629 // Expand an unaligned 32 or 64-bit integer load node.
2630 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2631   LoadSDNode *LD = cast<LoadSDNode>(Op);
2632   EVT MemVT = LD->getMemoryVT();
2633
2634   // Return if load is aligned or if MemVT is neither i32 nor i64.
2635   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2636       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2637     return SDValue();
2638
2639   bool IsLittle = Subtarget->isLittle();
2640   EVT VT = Op.getValueType();
2641   ISD::LoadExtType ExtType = LD->getExtensionType();
2642   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2643
2644   assert((VT == MVT::i32) || (VT == MVT::i64));
2645
2646   // Expand
2647   //  (set dst, (i64 (load baseptr)))
2648   // to
2649   //  (set tmp, (ldl (add baseptr, 7), undef))
2650   //  (set dst, (ldr baseptr, tmp))
2651   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2652     SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2653                                IsLittle ? 7 : 0);
2654     return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2655                         IsLittle ? 0 : 7);
2656   }
2657
2658   SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2659                              IsLittle ? 3 : 0);
2660   SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2661                              IsLittle ? 0 : 3);
2662
2663   // Expand
2664   //  (set dst, (i32 (load baseptr))) or
2665   //  (set dst, (i64 (sextload baseptr))) or
2666   //  (set dst, (i64 (extload baseptr)))
2667   // to
2668   //  (set tmp, (lwl (add baseptr, 3), undef))
2669   //  (set dst, (lwr baseptr, tmp))
2670   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2671       (ExtType == ISD::EXTLOAD))
2672     return LWR;
2673
2674   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2675
2676   // Expand
2677   //  (set dst, (i64 (zextload baseptr)))
2678   // to
2679   //  (set tmp0, (lwl (add baseptr, 3), undef))
2680   //  (set tmp1, (lwr baseptr, tmp0))
2681   //  (set tmp2, (shl tmp1, 32))
2682   //  (set dst, (srl tmp2, 32))
2683   DebugLoc DL = LD->getDebugLoc();
2684   SDValue Const32 = DAG.getConstant(32, MVT::i32);
2685   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2686   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2687   SDValue Ops[] = { SRL, LWR.getValue(1) };
2688   return DAG.getMergeValues(Ops, 2, DL);
2689 }
2690
2691 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2692                              SDValue Chain, unsigned Offset) {
2693   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2694   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2695   DebugLoc DL = SD->getDebugLoc();
2696   SDVTList VTList = DAG.getVTList(MVT::Other);
2697
2698   if (Offset)
2699     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2700                       DAG.getConstant(Offset, BasePtrVT));
2701
2702   SDValue Ops[] = { Chain, Value, Ptr };
2703   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2704                                  SD->getMemOperand());
2705 }
2706
2707 // Expand an unaligned 32 or 64-bit integer store node.
2708 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2709   StoreSDNode *SD = cast<StoreSDNode>(Op);
2710   EVT MemVT = SD->getMemoryVT();
2711
2712   // Return if store is aligned or if MemVT is neither i32 nor i64.
2713   if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2714       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2715     return SDValue();
2716
2717   bool IsLittle = Subtarget->isLittle();
2718   SDValue Value = SD->getValue(), Chain = SD->getChain();
2719   EVT VT = Value.getValueType();
2720
2721   // Expand
2722   //  (store val, baseptr) or
2723   //  (truncstore val, baseptr)
2724   // to
2725   //  (swl val, (add baseptr, 3))
2726   //  (swr val, baseptr)
2727   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2728     SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2729                                 IsLittle ? 3 : 0);
2730     return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2731   }
2732
2733   assert(VT == MVT::i64);
2734
2735   // Expand
2736   //  (store val, baseptr)
2737   // to
2738   //  (sdl val, (add baseptr, 7))
2739   //  (sdr val, baseptr)
2740   SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2741   return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2742 }
2743
2744 // This function expands mips intrinsic nodes which have 64-bit input operands
2745 // or output values.
2746 //
2747 // out64 = intrinsic-node in64
2748 // =>
2749 // lo = copy (extract-element (in64, 0))
2750 // hi = copy (extract-element (in64, 1))
2751 // mips-specific-node
2752 // v0 = copy lo
2753 // v1 = copy hi
2754 // out64 = merge-values (v0, v1)
2755 //
2756 static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2757                             unsigned Opc, bool HasI64In, bool HasI64Out) {
2758   DebugLoc DL = Op.getDebugLoc();
2759   bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2760   SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2761   SmallVector<SDValue, 3> Ops;
2762
2763   if (HasI64In) {
2764     SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2765                                Op->getOperand(1 + HasChainIn),
2766                                DAG.getConstant(0, MVT::i32));
2767     SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2768                                Op->getOperand(1 + HasChainIn),
2769                                DAG.getConstant(1, MVT::i32));
2770
2771     Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2772     Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2773
2774     Ops.push_back(Chain);
2775     Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2776     Ops.push_back(Chain.getValue(1));
2777   } else {
2778     Ops.push_back(Chain);
2779     Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2780   }
2781
2782   if (!HasI64Out)
2783     return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2784                        Ops.begin(), Ops.size());
2785
2786   SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2787                              Ops.begin(), Ops.size());
2788   SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2789                                      Intr.getValue(1));
2790   SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2791                                      OutLo.getValue(2));
2792   SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2793
2794   if (!HasChainIn)
2795     return Out;
2796
2797   SDValue Vals[] = { Out, OutHi.getValue(1) };
2798   return DAG.getMergeValues(Vals, 2, DL);
2799 }
2800
2801 SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2802                                                     SelectionDAG &DAG) const {
2803   switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2804   default:
2805     return SDValue();
2806   case Intrinsic::mips_shilo:
2807     return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2808   case Intrinsic::mips_dpau_h_qbl:
2809     return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2810   case Intrinsic::mips_dpau_h_qbr:
2811     return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2812   case Intrinsic::mips_dpsu_h_qbl:
2813     return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2814   case Intrinsic::mips_dpsu_h_qbr:
2815     return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2816   case Intrinsic::mips_dpa_w_ph:
2817     return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2818   case Intrinsic::mips_dps_w_ph:
2819     return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2820   case Intrinsic::mips_dpax_w_ph:
2821     return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2822   case Intrinsic::mips_dpsx_w_ph:
2823     return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2824   case Intrinsic::mips_mulsa_w_ph:
2825     return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2826   case Intrinsic::mips_mult:
2827     return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2828   case Intrinsic::mips_multu:
2829     return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2830   case Intrinsic::mips_madd:
2831     return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2832   case Intrinsic::mips_maddu:
2833     return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2834   case Intrinsic::mips_msub:
2835     return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2836   case Intrinsic::mips_msubu:
2837     return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2838   }
2839 }
2840
2841 SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2842                                                    SelectionDAG &DAG) const {
2843   switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2844   default:
2845     return SDValue();
2846   case Intrinsic::mips_extp:
2847     return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2848   case Intrinsic::mips_extpdp:
2849     return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2850   case Intrinsic::mips_extr_w:
2851     return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2852   case Intrinsic::mips_extr_r_w:
2853     return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2854   case Intrinsic::mips_extr_rs_w:
2855     return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2856   case Intrinsic::mips_extr_s_h:
2857     return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2858   case Intrinsic::mips_mthlip:
2859     return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2860   case Intrinsic::mips_mulsaq_s_w_ph:
2861     return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2862   case Intrinsic::mips_maq_s_w_phl:
2863     return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2864   case Intrinsic::mips_maq_s_w_phr:
2865     return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2866   case Intrinsic::mips_maq_sa_w_phl:
2867     return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2868   case Intrinsic::mips_maq_sa_w_phr:
2869     return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2870   case Intrinsic::mips_dpaq_s_w_ph:
2871     return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2872   case Intrinsic::mips_dpsq_s_w_ph:
2873     return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2874   case Intrinsic::mips_dpaq_sa_l_w:
2875     return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2876   case Intrinsic::mips_dpsq_sa_l_w:
2877     return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2878   case Intrinsic::mips_dpaqx_s_w_ph:
2879     return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2880   case Intrinsic::mips_dpaqx_sa_w_ph:
2881     return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2882   case Intrinsic::mips_dpsqx_s_w_ph:
2883     return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2884   case Intrinsic::mips_dpsqx_sa_w_ph:
2885     return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2886   }
2887 }
2888
2889 SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2890   if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2891       || cast<ConstantSDNode>
2892         (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2893       || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2894     return SDValue();
2895
2896   // The pattern
2897   //   (add (frameaddr 0), (frame_to_args_offset))
2898   // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2899   //   (add FrameObject, 0)
2900   // where FrameObject is a fixed StackObject with offset 0 which points to
2901   // the old stack pointer.
2902   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2903   EVT ValTy = Op->getValueType(0);
2904   int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2905   SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2906   return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2907                      DAG.getConstant(0, ValTy));
2908 }
2909
2910 //===----------------------------------------------------------------------===//
2911 //                      Calling Convention Implementation
2912 //===----------------------------------------------------------------------===//
2913
2914 //===----------------------------------------------------------------------===//
2915 // TODO: Implement a generic logic using tblgen that can support this.
2916 // Mips O32 ABI rules:
2917 // ---
2918 // i32 - Passed in A0, A1, A2, A3 and stack
2919 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2920 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
2921 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2922 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2923 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
2924 //       go to stack.
2925 //
2926 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2927 //===----------------------------------------------------------------------===//
2928
2929 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2930                        MVT LocVT, CCValAssign::LocInfo LocInfo,
2931                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
2932
2933   static const unsigned IntRegsSize=4, FloatRegsSize=2;
2934
2935   static const uint16_t IntRegs[] = {
2936       Mips::A0, Mips::A1, Mips::A2, Mips::A3
2937   };
2938   static const uint16_t F32Regs[] = {
2939       Mips::F12, Mips::F14
2940   };
2941   static const uint16_t F64Regs[] = {
2942       Mips::D6, Mips::D7
2943   };
2944
2945   // Do not process byval args here.
2946   if (ArgFlags.isByVal())
2947     return true;
2948
2949   // Promote i8 and i16
2950   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2951     LocVT = MVT::i32;
2952     if (ArgFlags.isSExt())
2953       LocInfo = CCValAssign::SExt;
2954     else if (ArgFlags.isZExt())
2955       LocInfo = CCValAssign::ZExt;
2956     else
2957       LocInfo = CCValAssign::AExt;
2958   }
2959
2960   unsigned Reg;
2961
2962   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2963   // is true: function is vararg, argument is 3rd or higher, there is previous
2964   // argument which is not f32 or f64.
2965   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2966       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2967   unsigned OrigAlign = ArgFlags.getOrigAlign();
2968   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2969
2970   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2971     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2972     // If this is the first part of an i64 arg,
2973     // the allocated register must be either A0 or A2.
2974     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2975       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2976     LocVT = MVT::i32;
2977   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2978     // Allocate int register and shadow next int register. If first
2979     // available register is Mips::A1 or Mips::A3, shadow it too.
2980     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2981     if (Reg == Mips::A1 || Reg == Mips::A3)
2982       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2983     State.AllocateReg(IntRegs, IntRegsSize);
2984     LocVT = MVT::i32;
2985   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2986     // we are guaranteed to find an available float register
2987     if (ValVT == MVT::f32) {
2988       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2989       // Shadow int register
2990       State.AllocateReg(IntRegs, IntRegsSize);
2991     } else {
2992       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2993       // Shadow int registers
2994       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2995       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2996         State.AllocateReg(IntRegs, IntRegsSize);
2997       State.AllocateReg(IntRegs, IntRegsSize);
2998     }
2999   } else
3000     llvm_unreachable("Cannot handle this ValVT.");
3001
3002   if (!Reg) {
3003     unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
3004                                           OrigAlign);
3005     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
3006   } else
3007     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3008
3009   return false;
3010 }
3011
3012 #include "MipsGenCallingConv.inc"
3013
3014 //===----------------------------------------------------------------------===//
3015 //                  Call Calling Convention Implementation
3016 //===----------------------------------------------------------------------===//
3017
3018 static const unsigned O32IntRegsSize = 4;
3019
3020 // Return next O32 integer argument register.
3021 static unsigned getNextIntArgReg(unsigned Reg) {
3022   assert((Reg == Mips::A0) || (Reg == Mips::A2));
3023   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
3024 }
3025
3026 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3027 /// for tail call optimization.
3028 bool MipsTargetLowering::
3029 IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
3030                                   unsigned NextStackOffset,
3031                                   const MipsFunctionInfo& FI) const {
3032   if (!EnableMipsTailCalls)
3033     return false;
3034
3035   // No tail call optimization for mips16.
3036   if (Subtarget->inMips16Mode())
3037     return false;
3038
3039   // Return false if either the callee or caller has a byval argument.
3040   if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
3041     return false;
3042
3043   // Return true if the callee's argument area is no larger than the
3044   // caller's.
3045   return NextStackOffset <= FI.getIncomingArgSize();
3046 }
3047
3048 SDValue
3049 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3050                                    SDValue Chain, SDValue Arg, DebugLoc DL,
3051                                    bool IsTailCall, SelectionDAG &DAG) const {
3052   if (!IsTailCall) {
3053     SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
3054                                  DAG.getIntPtrConstant(Offset));
3055     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
3056                         false, 0);
3057   }
3058
3059   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3060   int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3061   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3062   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
3063                       /*isVolatile=*/ true, false, 0);
3064 }
3065
3066 //
3067 // The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
3068 // cleaner way to do all of this but it will have to wait until the traditional
3069 // gcc mechanism is completed.
3070 //
3071 // For Pic, in order for Mips16 code to call Mips32 code which according the abi
3072 // have either arguments or returned values placed in floating point registers,
3073 // we use a set of helper functions. (This includes functions which return type
3074 //  complex which on Mips are returned in a pair of floating point registers).
3075 //
3076 // This is an encoding that we inherited from gcc.
3077 // In Mips traditional O32, N32 ABI, floating point numbers are passed in
3078 // floating point argument registers 1,2 only when the first and optionally
3079 // the second arguments are float (sf) or double (df).
3080 // For Mips16 we are only concerned with the situations where floating point
3081 // arguments are being passed in floating point registers by the ABI, because
3082 // Mips16 mode code cannot execute floating point instructions to load those
3083 // values and hence helper functions are needed.
3084 // The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
3085 // the helper function suffixs for these are:
3086 //                        0,  1,    5,        9,         2,   6,        10
3087 // this suffix can then be calculated as follows:
3088 // for a given argument Arg:
3089 //     Arg1x, Arg2x = 1 :  Arg is sf
3090 //                    2 :  Arg is df
3091 //                    0:   Arg is neither sf or df
3092 // So this stub is the string for number Arg1x + Arg2x*4.
3093 // However not all numbers between 0 and 10 are possible, we check anyway and
3094 // assert if the impossible exists.
3095 //
3096
3097 unsigned int MipsTargetLowering::getMips16HelperFunctionStubNumber
3098   (ArgListTy &Args) const {
3099   unsigned int resultNum = 0;
3100   if (Args.size() >= 1) {
3101     Type *t = Args[0].Ty;
3102     if (t->isFloatTy()) {
3103       resultNum = 1;
3104     }
3105     else if (t->isDoubleTy()) {
3106       resultNum = 2;
3107     }
3108   }
3109   if (resultNum) {
3110     if (Args.size() >=2) {
3111       Type *t = Args[1].Ty;
3112       if (t->isFloatTy()) {
3113         resultNum += 4;
3114       }
3115       else if (t->isDoubleTy()) {
3116         resultNum += 8;
3117       }
3118     }
3119   }
3120   return resultNum;
3121 }
3122
3123 //
3124 // prefixs are attached to stub numbers depending on the return type .
3125 // return type: float  sf_
3126 //              double df_
3127 //              single complex sc_
3128 //              double complext dc_
3129 //              others  NO PREFIX
3130 //
3131 //
3132 // The full name of a helper function is__mips16_call_stub +
3133 //    return type dependent prefix + stub number
3134 //
3135 //
3136 // This is something that probably should be in a different source file and
3137 // perhaps done differently but my main purpose is to not waste runtime
3138 // on something that we can enumerate in the source. Another possibility is
3139 // to have a python script to generate these mapping tables. This will do
3140 // for now. There are a whole series of helper function mapping arrays, one
3141 // for each return type class as outlined above. There there are 11 possible
3142 //  entries. Ones with 0 are ones which should never be selected
3143 //
3144 // All the arrays are similar except for ones which return neither
3145 // sf, df, sc, dc, in which only care about ones which have sf or df as a
3146 // first parameter.
3147 //
3148 #define P_ "__mips16_call_stub_"
3149 #define MAX_STUB_NUMBER 10
3150 #define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
3151 #define T P "0" , T1
3152 #define P P_
3153 static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
3154   {0, T1 };
3155 #undef P
3156 #define P P_ "sf_"
3157 static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
3158   { T };
3159 #undef P
3160 #define P P_ "df_"
3161 static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
3162   { T };
3163 #undef P
3164 #define P P_ "sc_"
3165 static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
3166   { T };
3167 #undef P
3168 #define P P_ "dc_"
3169 static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
3170   { T };
3171 #undef P
3172 #undef P_
3173
3174
3175 const char* MipsTargetLowering::
3176   getMips16HelperFunction
3177     (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
3178   const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
3179 #ifndef NDEBUG
3180   const unsigned int maxStubNum = 10;
3181   assert(stubNum <= maxStubNum);
3182   const bool validStubNum[maxStubNum+1] =
3183     {true, true, true, false, false, true, true, false, false, true, true};
3184   assert(validStubNum[stubNum]);
3185 #endif
3186   const char *result;
3187   if (RetTy->isFloatTy()) {
3188     result = sfMips16Helper[stubNum];
3189   }
3190   else if (RetTy ->isDoubleTy()) {
3191     result = dfMips16Helper[stubNum];
3192   }
3193   else if (RetTy->isStructTy()) {
3194     // check if it's complex
3195     if (RetTy->getNumContainedTypes() == 2) {
3196       if ((RetTy->getContainedType(0)->isFloatTy()) &&
3197           (RetTy->getContainedType(1)->isFloatTy())) {
3198         result = scMips16Helper[stubNum];
3199       }
3200       else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
3201                (RetTy->getContainedType(1)->isDoubleTy())) {
3202         result = dcMips16Helper[stubNum];
3203       }
3204       else {
3205         llvm_unreachable("Uncovered condition");
3206       }
3207     }
3208     else {
3209       llvm_unreachable("Uncovered condition");
3210     }
3211   }
3212   else {
3213     if (stubNum == 0) {
3214       needHelper = false;
3215       return "";
3216     }
3217     result = vMips16Helper[stubNum];
3218   }
3219   needHelper = true;
3220   return result;
3221 }
3222
3223 /// LowerCall - functions arguments are copied from virtual regs to
3224 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3225 SDValue
3226 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3227                               SmallVectorImpl<SDValue> &InVals) const {
3228   SelectionDAG &DAG                     = CLI.DAG;
3229   DebugLoc &dl                          = CLI.DL;
3230   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3231   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
3232   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
3233   SDValue Chain                         = CLI.Chain;
3234   SDValue Callee                        = CLI.Callee;
3235   bool &isTailCall                      = CLI.IsTailCall;
3236   CallingConv::ID CallConv              = CLI.CallConv;
3237   bool isVarArg                         = CLI.IsVarArg;
3238
3239   const char* mips16HelperFunction = 0;
3240   bool needMips16Helper = false;
3241
3242   if (Subtarget->inMips16Mode() && getTargetMachine().Options.UseSoftFloat &&
3243       Mips16HardFloat) {
3244     //
3245     // currently we don't have symbols tagged with the mips16 or mips32
3246     // qualifier so we will assume that we don't know what kind it is.
3247     // and generate the helper
3248     //
3249     bool lookupHelper = true;
3250     if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3251       if (noHelperNeeded.find(S->getSymbol()) != noHelperNeeded.end()) {
3252         lookupHelper = false;
3253       }
3254     }
3255     if (lookupHelper) mips16HelperFunction =
3256       getMips16HelperFunction(CLI.RetTy, CLI.Args, needMips16Helper);
3257
3258   }
3259   MachineFunction &MF = DAG.getMachineFunction();
3260   MachineFrameInfo *MFI = MF.getFrameInfo();
3261   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
3262   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
3263
3264   // Analyze operands of the call, assigning locations to each operand.
3265   SmallVector<CCValAssign, 16> ArgLocs;
3266   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3267                  getTargetMachine(), ArgLocs, *DAG.getContext());
3268   MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
3269
3270   MipsCCInfo.analyzeCallOperands(Outs, isVarArg);
3271
3272   // Get a count of how many bytes are to be pushed on the stack.
3273   unsigned NextStackOffset = CCInfo.getNextStackOffset();
3274
3275   // Check if it's really possible to do a tail call.
3276   if (isTailCall)
3277     isTailCall =
3278       IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
3279                                         *MF.getInfo<MipsFunctionInfo>());
3280
3281   if (isTailCall)
3282     ++NumTailCalls;
3283
3284   // Chain is the output chain of the last Load/Store or CopyToReg node.
3285   // ByValChain is the output chain of the last Memcpy node created for copying
3286   // byval arguments to the stack.
3287   unsigned StackAlignment = TFL->getStackAlignment();
3288   NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
3289   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
3290
3291   if (!isTailCall)
3292     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
3293
3294   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
3295                                         IsN64 ? Mips::SP_64 : Mips::SP,
3296                                         getPointerTy());
3297
3298   // With EABI is it possible to have 16 args on registers.
3299   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3300   SmallVector<SDValue, 8> MemOpChains;
3301   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3302
3303   // Walk the register/memloc assignments, inserting copies/loads.
3304   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3305     SDValue Arg = OutVals[i];
3306     CCValAssign &VA = ArgLocs[i];
3307     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3308     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3309
3310     // ByVal Arg.
3311     if (Flags.isByVal()) {
3312       assert(Flags.getByValSize() &&
3313              "ByVal args of size 0 should have been ignored by front-end.");
3314       assert(ByValArg != MipsCCInfo.byval_end());
3315       assert(!isTailCall &&
3316              "Do not tail-call optimize if there is a byval argument.");
3317       passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3318                    MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
3319       ++ByValArg;
3320       continue;
3321     }
3322
3323     // Promote the value if needed.
3324     switch (VA.getLocInfo()) {
3325     default: llvm_unreachable("Unknown loc info!");
3326     case CCValAssign::Full:
3327       if (VA.isRegLoc()) {
3328         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3329             (ValVT == MVT::f64 && LocVT == MVT::i64))
3330           Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
3331         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3332           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3333                                    Arg, DAG.getConstant(0, MVT::i32));
3334           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3335                                    Arg, DAG.getConstant(1, MVT::i32));
3336           if (!Subtarget->isLittle())
3337             std::swap(Lo, Hi);
3338           unsigned LocRegLo = VA.getLocReg();
3339           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3340           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3341           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3342           continue;
3343         }
3344       }
3345       break;
3346     case CCValAssign::SExt:
3347       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
3348       break;
3349     case CCValAssign::ZExt:
3350       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
3351       break;
3352     case CCValAssign::AExt:
3353       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
3354       break;
3355     }
3356
3357     // Arguments that can be passed on register must be kept at
3358     // RegsToPass vector
3359     if (VA.isRegLoc()) {
3360       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3361       continue;
3362     }
3363
3364     // Register can't get to this point...
3365     assert(VA.isMemLoc());
3366
3367     // emit ISD::STORE whichs stores the
3368     // parameter value to a stack Location
3369     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3370                                          Chain, Arg, dl, isTailCall, DAG));
3371   }
3372
3373   // Transform all store nodes into one single node because all store
3374   // nodes are independent of each other.
3375   if (!MemOpChains.empty())
3376     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3377                         &MemOpChains[0], MemOpChains.size());
3378
3379   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3380   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3381   // node so that legalize doesn't hack it.
3382   bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
3383   bool GlobalOrExternal = false, InternalLinkage = false;
3384   SDValue CalleeLo;
3385
3386   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3387     if (IsPICCall) {
3388       InternalLinkage = G->getGlobal()->hasInternalLinkage();
3389
3390       if (InternalLinkage)
3391         Callee = getAddrLocal(Callee, DAG, HasMips64);
3392       else if (LargeGOT)
3393         Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3394                                        MipsII::MO_CALL_LO16);
3395       else
3396         Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3397     } else
3398       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
3399                                           MipsII::MO_NO_FLAG);
3400     GlobalOrExternal = true;
3401   }
3402   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3403     if (!IsN64 && !IsPIC) // !N64 && static
3404       Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3405                                             MipsII::MO_NO_FLAG);
3406     else if (LargeGOT)
3407       Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3408                                      MipsII::MO_CALL_LO16);
3409     else // N64 || PIC
3410       Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3411
3412     GlobalOrExternal = true;
3413   }
3414
3415   SDValue JumpTarget = Callee;
3416
3417   // T9 should contain the address of the callee function if
3418   // -reloction-model=pic or it is an indirect call.
3419   if (IsPICCall || !GlobalOrExternal) {
3420     unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
3421     unsigned V0Reg = Mips::V0;
3422     if (needMips16Helper) {
3423       RegsToPass.push_front(std::make_pair(V0Reg, Callee));
3424       JumpTarget = DAG.getExternalSymbol(
3425         mips16HelperFunction, getPointerTy());
3426       JumpTarget = getAddrGlobal(JumpTarget, DAG, MipsII::MO_GOT);
3427     }
3428     else {
3429       RegsToPass.push_front(std::make_pair(T9Reg, Callee));
3430
3431       if (!Subtarget->inMips16Mode())
3432         JumpTarget = SDValue();
3433     }
3434   }
3435
3436   // Insert node "GP copy globalreg" before call to function.
3437   //
3438   // R_MIPS_CALL* operators (emitted when non-internal functions are called
3439   // in PIC mode) allow symbols to be resolved via lazy binding.
3440   // The lazy binding stub requires GP to point to the GOT.
3441   if (IsPICCall && !InternalLinkage) {
3442     unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
3443     EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
3444     RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
3445   }
3446
3447   // Build a sequence of copy-to-reg nodes chained together with token
3448   // chain and flag operands which copy the outgoing args into registers.
3449   // The InFlag in necessary since all emitted instructions must be
3450   // stuck together.
3451   SDValue InFlag;
3452
3453   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3454     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3455                              RegsToPass[i].second, InFlag);
3456     InFlag = Chain.getValue(1);
3457   }
3458
3459   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
3460   //             = Chain, Callee, Reg#1, Reg#2, ...
3461   //
3462   // Returns a chain & a flag for retval copy to use.
3463   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3464   SmallVector<SDValue, 8> Ops(1, Chain);
3465
3466   if (JumpTarget.getNode())
3467     Ops.push_back(JumpTarget);
3468
3469   // Add argument registers to the end of the list so that they are
3470   // known live into the call.
3471   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3472     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3473                                   RegsToPass[i].second.getValueType()));
3474
3475   // Add a register mask operand representing the call-preserved registers.
3476   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3477   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3478   assert(Mask && "Missing call preserved mask for calling convention");
3479   Ops.push_back(DAG.getRegisterMask(Mask));
3480
3481   if (InFlag.getNode())
3482     Ops.push_back(InFlag);
3483
3484   if (isTailCall)
3485     return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
3486
3487   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
3488   InFlag = Chain.getValue(1);
3489
3490   // Create the CALLSEQ_END node.
3491   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3492                              DAG.getIntPtrConstant(0, true), InFlag);
3493   InFlag = Chain.getValue(1);
3494
3495   // Handle result values, copying them out of physregs into vregs that we
3496   // return.
3497   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3498                          Ins, dl, DAG, InVals);
3499 }
3500
3501 /// LowerCallResult - Lower the result values of a call into the
3502 /// appropriate copies out of appropriate physical registers.
3503 SDValue
3504 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3505                                     CallingConv::ID CallConv, bool isVarArg,
3506                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3507                                     DebugLoc dl, SelectionDAG &DAG,
3508                                     SmallVectorImpl<SDValue> &InVals) const {
3509   // Assign locations to each value returned by this call.
3510   SmallVector<CCValAssign, 16> RVLocs;
3511   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3512                  getTargetMachine(), RVLocs, *DAG.getContext());
3513
3514   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3515
3516   // Copy all of the result registers out of their specified physreg.
3517   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3518     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3519                                RVLocs[i].getValVT(), InFlag).getValue(1);
3520     InFlag = Chain.getValue(2);
3521     InVals.push_back(Chain.getValue(0));
3522   }
3523
3524   return Chain;
3525 }
3526
3527 //===----------------------------------------------------------------------===//
3528 //             Formal Arguments Calling Convention Implementation
3529 //===----------------------------------------------------------------------===//
3530 /// LowerFormalArguments - transform physical registers into virtual registers
3531 /// and generate load operations for arguments places on the stack.
3532 SDValue
3533 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3534                                          CallingConv::ID CallConv,
3535                                          bool isVarArg,
3536                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3537                                          DebugLoc dl, SelectionDAG &DAG,
3538                                          SmallVectorImpl<SDValue> &InVals)
3539                                           const {
3540   MachineFunction &MF = DAG.getMachineFunction();
3541   MachineFrameInfo *MFI = MF.getFrameInfo();
3542   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3543
3544   MipsFI->setVarArgsFrameIndex(0);
3545
3546   // Used with vargs to acumulate store chains.
3547   std::vector<SDValue> OutChains;
3548
3549   // Assign locations to all of the incoming arguments.
3550   SmallVector<CCValAssign, 16> ArgLocs;
3551   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3552                  getTargetMachine(), ArgLocs, *DAG.getContext());
3553   MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
3554
3555   MipsCCInfo.analyzeFormalArguments(Ins);
3556   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3557                            MipsCCInfo.hasByValArg());
3558
3559   Function::const_arg_iterator FuncArg =
3560     DAG.getMachineFunction().getFunction()->arg_begin();
3561   unsigned CurArgIdx = 0;
3562   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3563
3564   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3565     CCValAssign &VA = ArgLocs[i];
3566     std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3567     CurArgIdx = Ins[i].OrigArgIndex;
3568     EVT ValVT = VA.getValVT();
3569     ISD::ArgFlagsTy Flags = Ins[i].Flags;
3570     bool IsRegLoc = VA.isRegLoc();
3571
3572     if (Flags.isByVal()) {
3573       assert(Flags.getByValSize() &&
3574              "ByVal args of size 0 should have been ignored by front-end.");
3575       assert(ByValArg != MipsCCInfo.byval_end());
3576       copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3577                     MipsCCInfo, *ByValArg);
3578       ++ByValArg;
3579       continue;
3580     }
3581
3582     // Arguments stored on registers
3583     if (IsRegLoc) {
3584       EVT RegVT = VA.getLocVT();
3585       unsigned ArgReg = VA.getLocReg();
3586       const TargetRegisterClass *RC;
3587
3588       if (RegVT == MVT::i32)
3589         RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3590                                         &Mips::CPURegsRegClass;
3591       else if (RegVT == MVT::i64)
3592         RC = &Mips::CPU64RegsRegClass;
3593       else if (RegVT == MVT::f32)
3594         RC = &Mips::FGR32RegClass;
3595       else if (RegVT == MVT::f64)
3596         RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3597       else
3598         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3599
3600       // Transform the arguments stored on
3601       // physical registers into virtual ones
3602       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3603       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3604
3605       // If this is an 8 or 16-bit value, it has been passed promoted
3606       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3607       // truncate to the right size.
3608       if (VA.getLocInfo() != CCValAssign::Full) {
3609         unsigned Opcode = 0;
3610         if (VA.getLocInfo() == CCValAssign::SExt)
3611           Opcode = ISD::AssertSext;
3612         else if (VA.getLocInfo() == CCValAssign::ZExt)
3613           Opcode = ISD::AssertZext;
3614         if (Opcode)
3615           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3616                                  DAG.getValueType(ValVT));
3617         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3618       }
3619
3620       // Handle floating point arguments passed in integer registers.
3621       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3622           (RegVT == MVT::i64 && ValVT == MVT::f64))
3623         ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3624       else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3625         unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3626                                   getNextIntArgReg(ArgReg), RC);
3627         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3628         if (!Subtarget->isLittle())
3629           std::swap(ArgValue, ArgValue2);
3630         ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3631                                ArgValue, ArgValue2);
3632       }
3633
3634       InVals.push_back(ArgValue);
3635     } else { // VA.isRegLoc()
3636
3637       // sanity check
3638       assert(VA.isMemLoc());
3639
3640       // The stack pointer offset is relative to the caller stack frame.
3641       int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3642                                       VA.getLocMemOffset(), true);
3643
3644       // Create load nodes to retrieve arguments from the stack
3645       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3646       InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3647                                    MachinePointerInfo::getFixedStack(FI),
3648                                    false, false, false, 0));
3649     }
3650   }
3651
3652   // The mips ABIs for returning structs by value requires that we copy
3653   // the sret argument into $v0 for the return. Save the argument into
3654   // a virtual register so that we can access it from the return points.
3655   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3656     unsigned Reg = MipsFI->getSRetReturnReg();
3657     if (!Reg) {
3658       Reg = MF.getRegInfo().
3659         createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3660       MipsFI->setSRetReturnReg(Reg);
3661     }
3662     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3663     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3664   }
3665
3666   if (isVarArg)
3667     writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3668
3669   // All stores are grouped in one node to allow the matching between
3670   // the size of Ins and InVals. This only happens when on varg functions
3671   if (!OutChains.empty()) {
3672     OutChains.push_back(Chain);
3673     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3674                         &OutChains[0], OutChains.size());
3675   }
3676
3677   return Chain;
3678 }
3679
3680 //===----------------------------------------------------------------------===//
3681 //               Return Value Calling Convention Implementation
3682 //===----------------------------------------------------------------------===//
3683
3684 bool
3685 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3686                                    MachineFunction &MF, bool isVarArg,
3687                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3688                                    LLVMContext &Context) const {
3689   SmallVector<CCValAssign, 16> RVLocs;
3690   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3691                  RVLocs, Context);
3692   return CCInfo.CheckReturn(Outs, RetCC_Mips);
3693 }
3694
3695 SDValue
3696 MipsTargetLowering::LowerReturn(SDValue Chain,
3697                                 CallingConv::ID CallConv, bool isVarArg,
3698                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
3699                                 const SmallVectorImpl<SDValue> &OutVals,
3700                                 DebugLoc dl, SelectionDAG &DAG) const {
3701
3702   // CCValAssign - represent the assignment of
3703   // the return value to a location
3704   SmallVector<CCValAssign, 16> RVLocs;
3705
3706   // CCState - Info about the registers and stack slot.
3707   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3708                  getTargetMachine(), RVLocs, *DAG.getContext());
3709
3710   // Analize return values.
3711   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3712
3713   SDValue Flag;
3714   SmallVector<SDValue, 4> RetOps(1, Chain);
3715
3716   // Copy the result values into the output registers.
3717   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3718     CCValAssign &VA = RVLocs[i];
3719     assert(VA.isRegLoc() && "Can only return in registers!");
3720
3721     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3722
3723     // Guarantee that all emitted copies are stuck together with flags.
3724     Flag = Chain.getValue(1);
3725     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3726   }
3727
3728   // The mips ABIs for returning structs by value requires that we copy
3729   // the sret argument into $v0 for the return. We saved the argument into
3730   // a virtual register in the entry block, so now we copy the value out
3731   // and into $v0.
3732   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3733     MachineFunction &MF      = DAG.getMachineFunction();
3734     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3735     unsigned Reg = MipsFI->getSRetReturnReg();
3736
3737     if (!Reg)
3738       llvm_unreachable("sret virtual register not created in the entry block");
3739     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3740     unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3741
3742     Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3743     Flag = Chain.getValue(1);
3744     RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3745   }
3746
3747   RetOps[0] = Chain;  // Update chain.
3748
3749   // Add the flag if we have it.
3750   if (Flag.getNode())
3751     RetOps.push_back(Flag);
3752
3753   // Return on Mips is always a "jr $ra"
3754   return DAG.getNode(MipsISD::Ret, dl, MVT::Other, &RetOps[0], RetOps.size());
3755 }
3756
3757 //===----------------------------------------------------------------------===//
3758 //                           Mips Inline Assembly Support
3759 //===----------------------------------------------------------------------===//
3760
3761 /// getConstraintType - Given a constraint letter, return the type of
3762 /// constraint it is for this target.
3763 MipsTargetLowering::ConstraintType MipsTargetLowering::
3764 getConstraintType(const std::string &Constraint) const
3765 {
3766   // Mips specific constrainy
3767   // GCC config/mips/constraints.md
3768   //
3769   // 'd' : An address register. Equivalent to r
3770   //       unless generating MIPS16 code.
3771   // 'y' : Equivalent to r; retained for
3772   //       backwards compatibility.
3773   // 'c' : A register suitable for use in an indirect
3774   //       jump. This will always be $25 for -mabicalls.
3775   // 'l' : The lo register. 1 word storage.
3776   // 'x' : The hilo register pair. Double word storage.
3777   if (Constraint.size() == 1) {
3778     switch (Constraint[0]) {
3779       default : break;
3780       case 'd':
3781       case 'y':
3782       case 'f':
3783       case 'c':
3784       case 'l':
3785       case 'x':
3786         return C_RegisterClass;
3787     }
3788   }
3789   return TargetLowering::getConstraintType(Constraint);
3790 }
3791
3792 /// Examine constraint type and operand type and determine a weight value.
3793 /// This object must already have been set up with the operand type
3794 /// and the current alternative constraint selected.
3795 TargetLowering::ConstraintWeight
3796 MipsTargetLowering::getSingleConstraintMatchWeight(
3797     AsmOperandInfo &info, const char *constraint) const {
3798   ConstraintWeight weight = CW_Invalid;
3799   Value *CallOperandVal = info.CallOperandVal;
3800     // If we don't have a value, we can't do a match,
3801     // but allow it at the lowest weight.
3802   if (CallOperandVal == NULL)
3803     return CW_Default;
3804   Type *type = CallOperandVal->getType();
3805   // Look at the constraint type.
3806   switch (*constraint) {
3807   default:
3808     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3809     break;
3810   case 'd':
3811   case 'y':
3812     if (type->isIntegerTy())
3813       weight = CW_Register;
3814     break;
3815   case 'f':
3816     if (type->isFloatTy())
3817       weight = CW_Register;
3818     break;
3819   case 'c': // $25 for indirect jumps
3820   case 'l': // lo register
3821   case 'x': // hilo register pair
3822       if (type->isIntegerTy())
3823       weight = CW_SpecificReg;
3824       break;
3825   case 'I': // signed 16 bit immediate
3826   case 'J': // integer zero
3827   case 'K': // unsigned 16 bit immediate
3828   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3829   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3830   case 'O': // signed 15 bit immediate (+- 16383)
3831   case 'P': // immediate in the range of 65535 to 1 (inclusive)
3832     if (isa<ConstantInt>(CallOperandVal))
3833       weight = CW_Constant;
3834     break;
3835   }
3836   return weight;
3837 }
3838
3839 /// Given a register class constraint, like 'r', if this corresponds directly
3840 /// to an LLVM register class, return a register of 0 and the register class
3841 /// pointer.
3842 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3843 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3844 {
3845   if (Constraint.size() == 1) {
3846     switch (Constraint[0]) {
3847     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3848     case 'y': // Same as 'r'. Exists for compatibility.
3849     case 'r':
3850       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3851         if (Subtarget->inMips16Mode())
3852           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3853         return std::make_pair(0U, &Mips::CPURegsRegClass);
3854       }
3855       if (VT == MVT::i64 && !HasMips64)
3856         return std::make_pair(0U, &Mips::CPURegsRegClass);
3857       if (VT == MVT::i64 && HasMips64)
3858         return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3859       // This will generate an error message
3860       return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3861     case 'f':
3862       if (VT == MVT::f32)
3863         return std::make_pair(0U, &Mips::FGR32RegClass);
3864       if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3865         if (Subtarget->isFP64bit())
3866           return std::make_pair(0U, &Mips::FGR64RegClass);
3867         return std::make_pair(0U, &Mips::AFGR64RegClass);
3868       }
3869       break;
3870     case 'c': // register suitable for indirect jump
3871       if (VT == MVT::i32)
3872         return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3873       assert(VT == MVT::i64 && "Unexpected type.");
3874       return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3875     case 'l': // register suitable for indirect jump
3876       if (VT == MVT::i32)
3877         return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3878       return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3879     case 'x': // register suitable for indirect jump
3880       // Fixme: Not triggering the use of both hi and low
3881       // This will generate an error message
3882       return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3883     }
3884   }
3885   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3886 }
3887
3888 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3889 /// vector.  If it is invalid, don't add anything to Ops.
3890 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3891                                                      std::string &Constraint,
3892                                                      std::vector<SDValue>&Ops,
3893                                                      SelectionDAG &DAG) const {
3894   SDValue Result(0, 0);
3895
3896   // Only support length 1 constraints for now.
3897   if (Constraint.length() > 1) return;
3898
3899   char ConstraintLetter = Constraint[0];
3900   switch (ConstraintLetter) {
3901   default: break; // This will fall through to the generic implementation
3902   case 'I': // Signed 16 bit constant
3903     // If this fails, the parent routine will give an error
3904     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3905       EVT Type = Op.getValueType();
3906       int64_t Val = C->getSExtValue();
3907       if (isInt<16>(Val)) {
3908         Result = DAG.getTargetConstant(Val, Type);
3909         break;
3910       }
3911     }
3912     return;
3913   case 'J': // integer zero
3914     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3915       EVT Type = Op.getValueType();
3916       int64_t Val = C->getZExtValue();
3917       if (Val == 0) {
3918         Result = DAG.getTargetConstant(0, Type);
3919         break;
3920       }
3921     }
3922     return;
3923   case 'K': // unsigned 16 bit immediate
3924     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3925       EVT Type = Op.getValueType();
3926       uint64_t Val = (uint64_t)C->getZExtValue();
3927       if (isUInt<16>(Val)) {
3928         Result = DAG.getTargetConstant(Val, Type);
3929         break;
3930       }
3931     }
3932     return;
3933   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3934     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3935       EVT Type = Op.getValueType();
3936       int64_t Val = C->getSExtValue();
3937       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3938         Result = DAG.getTargetConstant(Val, Type);
3939         break;
3940       }
3941     }
3942     return;
3943   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3944     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3945       EVT Type = Op.getValueType();
3946       int64_t Val = C->getSExtValue();
3947       if ((Val >= -65535) && (Val <= -1)) {
3948         Result = DAG.getTargetConstant(Val, Type);
3949         break;
3950       }
3951     }
3952     return;
3953   case 'O': // signed 15 bit immediate
3954     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3955       EVT Type = Op.getValueType();
3956       int64_t Val = C->getSExtValue();
3957       if ((isInt<15>(Val))) {
3958         Result = DAG.getTargetConstant(Val, Type);
3959         break;
3960       }
3961     }
3962     return;
3963   case 'P': // immediate in the range of 1 to 65535 (inclusive)
3964     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3965       EVT Type = Op.getValueType();
3966       int64_t Val = C->getSExtValue();
3967       if ((Val <= 65535) && (Val >= 1)) {
3968         Result = DAG.getTargetConstant(Val, Type);
3969         break;
3970       }
3971     }
3972     return;
3973   }
3974
3975   if (Result.getNode()) {
3976     Ops.push_back(Result);
3977     return;
3978   }
3979
3980   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3981 }
3982
3983 bool
3984 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3985   // No global is ever allowed as a base.
3986   if (AM.BaseGV)
3987     return false;
3988
3989   switch (AM.Scale) {
3990   case 0: // "r+i" or just "i", depending on HasBaseReg.
3991     break;
3992   case 1:
3993     if (!AM.HasBaseReg) // allow "r+i".
3994       break;
3995     return false; // disallow "r+r" or "r+r+i".
3996   default:
3997     return false;
3998   }
3999
4000   return true;
4001 }
4002
4003 bool
4004 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4005   // The Mips target isn't yet aware of offsets.
4006   return false;
4007 }
4008
4009 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
4010                                             unsigned SrcAlign,
4011                                             bool IsMemset, bool ZeroMemset,
4012                                             bool MemcpyStrSrc,
4013                                             MachineFunction &MF) const {
4014   if (Subtarget->hasMips64())
4015     return MVT::i64;
4016
4017   return MVT::i32;
4018 }
4019
4020 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4021   if (VT != MVT::f32 && VT != MVT::f64)
4022     return false;
4023   if (Imm.isNegZero())
4024     return false;
4025   return Imm.isZero();
4026 }
4027
4028 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4029   if (IsN64)
4030     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4031
4032   return TargetLowering::getJumpTableEncoding();
4033 }
4034
4035 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC, bool IsO32_,
4036                                    CCState &Info)
4037   : CCInfo(Info), CallConv(CC), IsO32(IsO32_) {
4038   // Pre-allocate reserved argument area.
4039   CCInfo.AllocateStack(reservedArgArea(), 1);
4040 }
4041
4042 void MipsTargetLowering::MipsCC::
4043 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
4044                     bool IsVarArg) {
4045   assert((CallConv != CallingConv::Fast || !IsVarArg) &&
4046          "CallingConv::Fast shouldn't be used for vararg functions.");
4047
4048   unsigned NumOpnds = Args.size();
4049   llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
4050
4051   for (unsigned I = 0; I != NumOpnds; ++I) {
4052     MVT ArgVT = Args[I].VT;
4053     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
4054     bool R;
4055
4056     if (ArgFlags.isByVal()) {
4057       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
4058       continue;
4059     }
4060
4061     if (IsVarArg && !Args[I].IsFixed)
4062       R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4063     else
4064       R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4065
4066     if (R) {
4067 #ifndef NDEBUG
4068       dbgs() << "Call operand #" << I << " has unhandled type "
4069              << EVT(ArgVT).getEVTString();
4070 #endif
4071       llvm_unreachable(0);
4072     }
4073   }
4074 }
4075
4076 void MipsTargetLowering::MipsCC::
4077 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
4078   unsigned NumArgs = Args.size();
4079   llvm::CCAssignFn *FixedFn = fixedArgFn();
4080
4081   for (unsigned I = 0; I != NumArgs; ++I) {
4082     MVT ArgVT = Args[I].VT;
4083     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
4084
4085     if (ArgFlags.isByVal()) {
4086       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
4087       continue;
4088     }
4089
4090     if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
4091       continue;
4092
4093 #ifndef NDEBUG
4094     dbgs() << "Formal Arg #" << I << " has unhandled type "
4095            << EVT(ArgVT).getEVTString();
4096 #endif
4097     llvm_unreachable(0);
4098   }
4099 }
4100
4101 void
4102 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
4103                                            MVT LocVT,
4104                                            CCValAssign::LocInfo LocInfo,
4105                                            ISD::ArgFlagsTy ArgFlags) {
4106   assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
4107
4108   struct ByValArgInfo ByVal;
4109   unsigned RegSize = regSize();
4110   unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
4111   unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
4112                             RegSize * 2);
4113
4114   if (useRegsForByval())
4115     allocateRegs(ByVal, ByValSize, Align);
4116
4117   // Allocate space on caller's stack.
4118   ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
4119                                        Align);
4120   CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
4121                                     LocInfo));
4122   ByValArgs.push_back(ByVal);
4123 }
4124
4125 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
4126   return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
4127 }
4128
4129 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
4130   return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
4131 }
4132
4133 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
4134   return IsO32 ? O32IntRegs : Mips64IntRegs;
4135 }
4136
4137 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
4138   if (CallConv == CallingConv::Fast)
4139     return CC_Mips_FastCC;
4140
4141   return IsO32 ? CC_MipsO32 : CC_MipsN;
4142 }
4143
4144 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
4145   return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
4146 }
4147
4148 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
4149   return IsO32 ? O32IntRegs : Mips64DPRegs;
4150 }
4151
4152 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
4153                                               unsigned ByValSize,
4154                                               unsigned Align) {
4155   unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
4156   const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
4157   assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
4158          "Byval argument's size and alignment should be a multiple of"
4159          "RegSize.");
4160
4161   ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
4162
4163   // If Align > RegSize, the first arg register must be even.
4164   if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
4165     CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
4166     ++ByVal.FirstIdx;
4167   }
4168
4169   // Mark the registers allocated.
4170   for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
4171        ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
4172     CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4173 }
4174
4175 void MipsTargetLowering::
4176 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
4177               SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4178               SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4179               const MipsCC &CC, const ByValArgInfo &ByVal) const {
4180   MachineFunction &MF = DAG.getMachineFunction();
4181   MachineFrameInfo *MFI = MF.getFrameInfo();
4182   unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
4183   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4184   int FrameObjOffset;
4185
4186   if (RegAreaSize)
4187     FrameObjOffset = (int)CC.reservedArgArea() -
4188       (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
4189   else
4190     FrameObjOffset = ByVal.Address;
4191
4192   // Create frame object.
4193   EVT PtrTy = getPointerTy();
4194   int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
4195   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4196   InVals.push_back(FIN);
4197
4198   if (!ByVal.NumRegs)
4199     return;
4200
4201   // Copy arg registers.
4202   MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
4203   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4204
4205   for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
4206     unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
4207     unsigned VReg = AddLiveIn(MF, ArgReg, RC);
4208     unsigned Offset = I * CC.regSize();
4209     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4210                                    DAG.getConstant(Offset, PtrTy));
4211     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4212                                  StorePtr, MachinePointerInfo(FuncArg, Offset),
4213                                  false, false, 0);
4214     OutChains.push_back(Store);
4215   }
4216 }
4217
4218 // Copy byVal arg to registers and stack.
4219 void MipsTargetLowering::
4220 passByValArg(SDValue Chain, DebugLoc DL,
4221              std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
4222              SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
4223              MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
4224              const MipsCC &CC, const ByValArgInfo &ByVal,
4225              const ISD::ArgFlagsTy &Flags, bool isLittle) const {
4226   unsigned ByValSize = Flags.getByValSize();
4227   unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
4228   unsigned RegSize = CC.regSize();
4229   unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
4230   EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
4231
4232   if (ByVal.NumRegs) {
4233     const uint16_t *ArgRegs = CC.intArgRegs();
4234     bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
4235     unsigned I = 0;
4236
4237     // Copy words to registers.
4238     for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
4239       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4240                                     DAG.getConstant(Offset, PtrTy));
4241       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4242                                     MachinePointerInfo(), false, false, false,
4243                                     Alignment);
4244       MemOpChains.push_back(LoadVal.getValue(1));
4245       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4246       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4247     }
4248
4249     // Return if the struct has been fully copied.
4250     if (ByValSize == Offset)
4251       return;
4252
4253     // Copy the remainder of the byval argument with sub-word loads and shifts.
4254     if (LeftoverBytes) {
4255       assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
4256              "Size of the remainder should be smaller than RegSize.");
4257       SDValue Val;
4258
4259       for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
4260            Offset < ByValSize; LoadSize /= 2) {
4261         unsigned RemSize = ByValSize - Offset;
4262
4263         if (RemSize < LoadSize)
4264           continue;
4265
4266         // Load subword.
4267         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4268                                       DAG.getConstant(Offset, PtrTy));
4269         SDValue LoadVal =
4270           DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
4271                          MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
4272                          false, false, Alignment);
4273         MemOpChains.push_back(LoadVal.getValue(1));
4274
4275         // Shift the loaded value.
4276         unsigned Shamt;
4277
4278         if (isLittle)
4279           Shamt = TotalSizeLoaded;
4280         else
4281           Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
4282
4283         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4284                                     DAG.getConstant(Shamt, MVT::i32));
4285
4286         if (Val.getNode())
4287           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4288         else
4289           Val = Shift;
4290
4291         Offset += LoadSize;
4292         TotalSizeLoaded += LoadSize;
4293         Alignment = std::min(Alignment, LoadSize);
4294       }
4295
4296       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4297       RegsToPass.push_back(std::make_pair(ArgReg, Val));
4298       return;
4299     }
4300   }
4301
4302   // Copy remainder of byval arg to it with memcpy.
4303   unsigned MemCpySize = ByValSize - Offset;
4304   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4305                             DAG.getConstant(Offset, PtrTy));
4306   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4307                             DAG.getIntPtrConstant(ByVal.Address));
4308   Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4309                         DAG.getConstant(MemCpySize, PtrTy), Alignment,
4310                         /*isVolatile=*/false, /*AlwaysInline=*/false,
4311                         MachinePointerInfo(0), MachinePointerInfo(0));
4312   MemOpChains.push_back(Chain);
4313 }
4314
4315 void
4316 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4317                                     const MipsCC &CC, SDValue Chain,
4318                                     DebugLoc DL, SelectionDAG &DAG) const {
4319   unsigned NumRegs = CC.numIntArgRegs();
4320   const uint16_t *ArgRegs = CC.intArgRegs();
4321   const CCState &CCInfo = CC.getCCInfo();
4322   unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
4323   unsigned RegSize = CC.regSize();
4324   MVT RegTy = MVT::getIntegerVT(RegSize * 8);
4325   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4326   MachineFunction &MF = DAG.getMachineFunction();
4327   MachineFrameInfo *MFI = MF.getFrameInfo();
4328   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4329
4330   // Offset of the first variable argument from stack pointer.
4331   int VaArgOffset;
4332
4333   if (NumRegs == Idx)
4334     VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
4335   else
4336     VaArgOffset =
4337       (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
4338
4339   // Record the frame index of the first variable argument
4340   // which is a value necessary to VASTART.
4341   int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4342   MipsFI->setVarArgsFrameIndex(FI);
4343
4344   // Copy the integer registers that have not been used for argument passing
4345   // to the argument register save area. For O32, the save area is allocated
4346   // in the caller's stack frame, while for N32/64, it is allocated in the
4347   // callee's stack frame.
4348   for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
4349     unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
4350     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4351     FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4352     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
4353     SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
4354                                  MachinePointerInfo(), false, false, 0);
4355     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
4356     OutChains.push_back(Store);
4357   }
4358 }