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