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