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