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