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