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