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