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