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