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