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