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