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