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