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