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