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