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