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