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