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