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