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