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