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