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