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