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