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