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