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