MipsSEISelLowering.cpp revision c879eabcc25c4099a50939ed0bca86471201b183
1//===-- MipsSEISelLowering.cpp - MipsSE DAG Lowering Interface --*- C++ -*-===//
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// Subclass of MipsTargetLowering specialized for mips32/64.
11//
12//===----------------------------------------------------------------------===//
13#include "MipsSEISelLowering.h"
14#include "MipsRegisterInfo.h"
15#include "MipsTargetMachine.h"
16#include "llvm/CodeGen/MachineInstrBuilder.h"
17#include "llvm/CodeGen/MachineRegisterInfo.h"
18#include "llvm/IR/Intrinsics.h"
19#include "llvm/Support/CommandLine.h"
20#include "llvm/Target/TargetInstrInfo.h"
21
22using namespace llvm;
23
24static cl::opt<bool>
25EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
26                    cl::desc("MIPS: Enable tail calls."), cl::init(false));
27
28static cl::opt<bool> NoDPLoadStore("mno-ldc1-sdc1", cl::init(false),
29                                   cl::desc("Expand double precision loads and "
30                                            "stores to their single precision "
31                                            "counterparts"));
32
33MipsSETargetLowering::MipsSETargetLowering(MipsTargetMachine &TM)
34  : MipsTargetLowering(TM) {
35  // Set up the register classes
36
37  clearRegisterClasses();
38
39  addRegisterClass(MVT::i32, &Mips::GPR32RegClass);
40
41  if (HasMips64)
42    addRegisterClass(MVT::i64, &Mips::GPR64RegClass);
43
44  if (Subtarget->hasDSP() || Subtarget->hasMSA()) {
45    // Expand all truncating stores and extending loads.
46    unsigned FirstVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
47    unsigned LastVT = (unsigned)MVT::LAST_VECTOR_VALUETYPE;
48
49    for (unsigned VT0 = FirstVT; VT0 <= LastVT; ++VT0) {
50      for (unsigned VT1 = FirstVT; VT1 <= LastVT; ++VT1)
51        setTruncStoreAction((MVT::SimpleValueType)VT0,
52                            (MVT::SimpleValueType)VT1, Expand);
53
54      setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT0, Expand);
55      setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT0, Expand);
56      setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT0, Expand);
57    }
58  }
59
60  if (Subtarget->hasDSP()) {
61    MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
62
63    for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
64      addRegisterClass(VecTys[i], &Mips::DSPRRegClass);
65
66      // Expand all builtin opcodes.
67      for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
68        setOperationAction(Opc, VecTys[i], Expand);
69
70      setOperationAction(ISD::ADD, VecTys[i], Legal);
71      setOperationAction(ISD::SUB, VecTys[i], Legal);
72      setOperationAction(ISD::LOAD, VecTys[i], Legal);
73      setOperationAction(ISD::STORE, VecTys[i], Legal);
74      setOperationAction(ISD::BITCAST, VecTys[i], Legal);
75    }
76
77    setTargetDAGCombine(ISD::SHL);
78    setTargetDAGCombine(ISD::SRA);
79    setTargetDAGCombine(ISD::SRL);
80    setTargetDAGCombine(ISD::SETCC);
81    setTargetDAGCombine(ISD::VSELECT);
82  }
83
84  if (Subtarget->hasDSPR2())
85    setOperationAction(ISD::MUL, MVT::v2i16, Legal);
86
87  if (Subtarget->hasMSA()) {
88    addMSAIntType(MVT::v16i8, &Mips::MSA128BRegClass);
89    addMSAIntType(MVT::v8i16, &Mips::MSA128HRegClass);
90    addMSAIntType(MVT::v4i32, &Mips::MSA128WRegClass);
91    addMSAIntType(MVT::v2i64, &Mips::MSA128DRegClass);
92    addMSAFloatType(MVT::v8f16, &Mips::MSA128HRegClass);
93    addMSAFloatType(MVT::v4f32, &Mips::MSA128WRegClass);
94    addMSAFloatType(MVT::v2f64, &Mips::MSA128DRegClass);
95
96    setTargetDAGCombine(ISD::AND);
97    setTargetDAGCombine(ISD::SRA);
98    setTargetDAGCombine(ISD::VSELECT);
99    setTargetDAGCombine(ISD::XOR);
100  }
101
102  if (!Subtarget->mipsSEUsesSoftFloat()) {
103    addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
104
105    // When dealing with single precision only, use libcalls
106    if (!Subtarget->isSingleFloat()) {
107      if (Subtarget->isFP64bit())
108        addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
109      else
110        addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
111    }
112  }
113
114  setOperationAction(ISD::SMUL_LOHI,          MVT::i32, Custom);
115  setOperationAction(ISD::UMUL_LOHI,          MVT::i32, Custom);
116  setOperationAction(ISD::MULHS,              MVT::i32, Custom);
117  setOperationAction(ISD::MULHU,              MVT::i32, Custom);
118
119  if (HasMips64) {
120    setOperationAction(ISD::MULHS,            MVT::i64, Custom);
121    setOperationAction(ISD::MULHU,            MVT::i64, Custom);
122    setOperationAction(ISD::MUL,              MVT::i64, Custom);
123  }
124
125  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
126  setOperationAction(ISD::INTRINSIC_W_CHAIN,  MVT::i64, Custom);
127
128  setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
129  setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
130  setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
131  setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
132  setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Custom);
133  setOperationAction(ISD::LOAD,               MVT::i32, Custom);
134  setOperationAction(ISD::STORE,              MVT::i32, Custom);
135
136  setTargetDAGCombine(ISD::ADDE);
137  setTargetDAGCombine(ISD::SUBE);
138  setTargetDAGCombine(ISD::MUL);
139
140  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
141  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
142  setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
143
144  if (NoDPLoadStore) {
145    setOperationAction(ISD::LOAD, MVT::f64, Custom);
146    setOperationAction(ISD::STORE, MVT::f64, Custom);
147  }
148
149  computeRegisterProperties();
150}
151
152const MipsTargetLowering *
153llvm::createMipsSETargetLowering(MipsTargetMachine &TM) {
154  return new MipsSETargetLowering(TM);
155}
156
157// Enable MSA support for the given integer type and Register class.
158void MipsSETargetLowering::
159addMSAIntType(MVT::SimpleValueType Ty, const TargetRegisterClass *RC) {
160  addRegisterClass(Ty, RC);
161
162  // Expand all builtin opcodes.
163  for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
164    setOperationAction(Opc, Ty, Expand);
165
166  setOperationAction(ISD::BITCAST, Ty, Legal);
167  setOperationAction(ISD::LOAD, Ty, Legal);
168  setOperationAction(ISD::STORE, Ty, Legal);
169  setOperationAction(ISD::EXTRACT_VECTOR_ELT, Ty, Custom);
170  setOperationAction(ISD::INSERT_VECTOR_ELT, Ty, Legal);
171  setOperationAction(ISD::BUILD_VECTOR, Ty, Custom);
172
173  setOperationAction(ISD::ADD, Ty, Legal);
174  setOperationAction(ISD::AND, Ty, Legal);
175  setOperationAction(ISD::CTLZ, Ty, Legal);
176  setOperationAction(ISD::CTPOP, Ty, Legal);
177  setOperationAction(ISD::MUL, Ty, Legal);
178  setOperationAction(ISD::OR, Ty, Legal);
179  setOperationAction(ISD::SDIV, Ty, Legal);
180  setOperationAction(ISD::SREM, Ty, Legal);
181  setOperationAction(ISD::SHL, Ty, Legal);
182  setOperationAction(ISD::SRA, Ty, Legal);
183  setOperationAction(ISD::SRL, Ty, Legal);
184  setOperationAction(ISD::SUB, Ty, Legal);
185  setOperationAction(ISD::UDIV, Ty, Legal);
186  setOperationAction(ISD::UREM, Ty, Legal);
187  setOperationAction(ISD::VECTOR_SHUFFLE, Ty, Custom);
188  setOperationAction(ISD::VSELECT, Ty, Legal);
189  setOperationAction(ISD::XOR, Ty, Legal);
190
191  if (Ty == MVT::v4i32 || Ty == MVT::v2i64) {
192    setOperationAction(ISD::FP_TO_SINT, Ty, Legal);
193    setOperationAction(ISD::FP_TO_UINT, Ty, Legal);
194    setOperationAction(ISD::SINT_TO_FP, Ty, Legal);
195    setOperationAction(ISD::UINT_TO_FP, Ty, Legal);
196  }
197
198  setOperationAction(ISD::SETCC, Ty, Legal);
199  setCondCodeAction(ISD::SETNE, Ty, Expand);
200  setCondCodeAction(ISD::SETGE, Ty, Expand);
201  setCondCodeAction(ISD::SETGT, Ty, Expand);
202  setCondCodeAction(ISD::SETUGE, Ty, Expand);
203  setCondCodeAction(ISD::SETUGT, Ty, Expand);
204}
205
206// Enable MSA support for the given floating-point type and Register class.
207void MipsSETargetLowering::
208addMSAFloatType(MVT::SimpleValueType Ty, const TargetRegisterClass *RC) {
209  addRegisterClass(Ty, RC);
210
211  // Expand all builtin opcodes.
212  for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
213    setOperationAction(Opc, Ty, Expand);
214
215  setOperationAction(ISD::LOAD, Ty, Legal);
216  setOperationAction(ISD::STORE, Ty, Legal);
217  setOperationAction(ISD::BITCAST, Ty, Legal);
218  setOperationAction(ISD::EXTRACT_VECTOR_ELT, Ty, Legal);
219  setOperationAction(ISD::INSERT_VECTOR_ELT, Ty, Legal);
220
221  if (Ty != MVT::v8f16) {
222    setOperationAction(ISD::FABS,  Ty, Legal);
223    setOperationAction(ISD::FADD,  Ty, Legal);
224    setOperationAction(ISD::FDIV,  Ty, Legal);
225    setOperationAction(ISD::FLOG2, Ty, Legal);
226    setOperationAction(ISD::FMA,   Ty, Legal);
227    setOperationAction(ISD::FMUL,  Ty, Legal);
228    setOperationAction(ISD::FRINT, Ty, Legal);
229    setOperationAction(ISD::FSQRT, Ty, Legal);
230    setOperationAction(ISD::FSUB,  Ty, Legal);
231    setOperationAction(ISD::VSELECT, Ty, Legal);
232
233    setOperationAction(ISD::SETCC, Ty, Legal);
234    setCondCodeAction(ISD::SETOGE, Ty, Expand);
235    setCondCodeAction(ISD::SETOGT, Ty, Expand);
236    setCondCodeAction(ISD::SETUGE, Ty, Expand);
237    setCondCodeAction(ISD::SETUGT, Ty, Expand);
238    setCondCodeAction(ISD::SETGE,  Ty, Expand);
239    setCondCodeAction(ISD::SETGT,  Ty, Expand);
240  }
241}
242
243bool
244MipsSETargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
245  MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
246
247  switch (SVT) {
248  case MVT::i64:
249  case MVT::i32:
250    if (Fast)
251      *Fast = true;
252    return true;
253  default:
254    return false;
255  }
256}
257
258SDValue MipsSETargetLowering::LowerOperation(SDValue Op,
259                                             SelectionDAG &DAG) const {
260  switch(Op.getOpcode()) {
261  case ISD::LOAD:  return lowerLOAD(Op, DAG);
262  case ISD::STORE: return lowerSTORE(Op, DAG);
263  case ISD::SMUL_LOHI: return lowerMulDiv(Op, MipsISD::Mult, true, true, DAG);
264  case ISD::UMUL_LOHI: return lowerMulDiv(Op, MipsISD::Multu, true, true, DAG);
265  case ISD::MULHS:     return lowerMulDiv(Op, MipsISD::Mult, false, true, DAG);
266  case ISD::MULHU:     return lowerMulDiv(Op, MipsISD::Multu, false, true, DAG);
267  case ISD::MUL:       return lowerMulDiv(Op, MipsISD::Mult, true, false, DAG);
268  case ISD::SDIVREM:   return lowerMulDiv(Op, MipsISD::DivRem, true, true, DAG);
269  case ISD::UDIVREM:   return lowerMulDiv(Op, MipsISD::DivRemU, true, true,
270                                          DAG);
271  case ISD::INTRINSIC_WO_CHAIN: return lowerINTRINSIC_WO_CHAIN(Op, DAG);
272  case ISD::INTRINSIC_W_CHAIN:  return lowerINTRINSIC_W_CHAIN(Op, DAG);
273  case ISD::INTRINSIC_VOID:     return lowerINTRINSIC_VOID(Op, DAG);
274  case ISD::EXTRACT_VECTOR_ELT: return lowerEXTRACT_VECTOR_ELT(Op, DAG);
275  case ISD::BUILD_VECTOR:       return lowerBUILD_VECTOR(Op, DAG);
276  case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, DAG);
277  }
278
279  return MipsTargetLowering::LowerOperation(Op, DAG);
280}
281
282// selectMADD -
283// Transforms a subgraph in CurDAG if the following pattern is found:
284//  (addc multLo, Lo0), (adde multHi, Hi0),
285// where,
286//  multHi/Lo: product of multiplication
287//  Lo0: initial value of Lo register
288//  Hi0: initial value of Hi register
289// Return true if pattern matching was successful.
290static bool selectMADD(SDNode *ADDENode, SelectionDAG *CurDAG) {
291  // ADDENode's second operand must be a flag output of an ADDC node in order
292  // for the matching to be successful.
293  SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
294
295  if (ADDCNode->getOpcode() != ISD::ADDC)
296    return false;
297
298  SDValue MultHi = ADDENode->getOperand(0);
299  SDValue MultLo = ADDCNode->getOperand(0);
300  SDNode *MultNode = MultHi.getNode();
301  unsigned MultOpc = MultHi.getOpcode();
302
303  // MultHi and MultLo must be generated by the same node,
304  if (MultLo.getNode() != MultNode)
305    return false;
306
307  // and it must be a multiplication.
308  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
309    return false;
310
311  // MultLo amd MultHi must be the first and second output of MultNode
312  // respectively.
313  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
314    return false;
315
316  // Transform this to a MADD only if ADDENode and ADDCNode are the only users
317  // of the values of MultNode, in which case MultNode will be removed in later
318  // phases.
319  // If there exist users other than ADDENode or ADDCNode, this function returns
320  // here, which will result in MultNode being mapped to a single MULT
321  // instruction node rather than a pair of MULT and MADD instructions being
322  // produced.
323  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
324    return false;
325
326  SDLoc DL(ADDENode);
327
328  // Initialize accumulator.
329  SDValue ACCIn = CurDAG->getNode(MipsISD::InsertLOHI, DL, MVT::Untyped,
330                                  ADDCNode->getOperand(1),
331                                  ADDENode->getOperand(1));
332
333  // create MipsMAdd(u) node
334  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
335
336  SDValue MAdd = CurDAG->getNode(MultOpc, DL, MVT::Untyped,
337                                 MultNode->getOperand(0),// Factor 0
338                                 MultNode->getOperand(1),// Factor 1
339                                 ACCIn);
340
341  // replace uses of adde and addc here
342  if (!SDValue(ADDCNode, 0).use_empty()) {
343    SDValue LoOut = CurDAG->getNode(MipsISD::ExtractLO, DL, MVT::i32, MAdd);
344    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), LoOut);
345  }
346  if (!SDValue(ADDENode, 0).use_empty()) {
347    SDValue HiOut = CurDAG->getNode(MipsISD::ExtractHI, DL, MVT::i32, MAdd);
348    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), HiOut);
349  }
350
351  return true;
352}
353
354// selectMSUB -
355// Transforms a subgraph in CurDAG if the following pattern is found:
356//  (addc Lo0, multLo), (sube Hi0, multHi),
357// where,
358//  multHi/Lo: product of multiplication
359//  Lo0: initial value of Lo register
360//  Hi0: initial value of Hi register
361// Return true if pattern matching was successful.
362static bool selectMSUB(SDNode *SUBENode, SelectionDAG *CurDAG) {
363  // SUBENode's second operand must be a flag output of an SUBC node in order
364  // for the matching to be successful.
365  SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
366
367  if (SUBCNode->getOpcode() != ISD::SUBC)
368    return false;
369
370  SDValue MultHi = SUBENode->getOperand(1);
371  SDValue MultLo = SUBCNode->getOperand(1);
372  SDNode *MultNode = MultHi.getNode();
373  unsigned MultOpc = MultHi.getOpcode();
374
375  // MultHi and MultLo must be generated by the same node,
376  if (MultLo.getNode() != MultNode)
377    return false;
378
379  // and it must be a multiplication.
380  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
381    return false;
382
383  // MultLo amd MultHi must be the first and second output of MultNode
384  // respectively.
385  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
386    return false;
387
388  // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
389  // of the values of MultNode, in which case MultNode will be removed in later
390  // phases.
391  // If there exist users other than SUBENode or SUBCNode, this function returns
392  // here, which will result in MultNode being mapped to a single MULT
393  // instruction node rather than a pair of MULT and MSUB instructions being
394  // produced.
395  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
396    return false;
397
398  SDLoc DL(SUBENode);
399
400  // Initialize accumulator.
401  SDValue ACCIn = CurDAG->getNode(MipsISD::InsertLOHI, DL, MVT::Untyped,
402                                  SUBCNode->getOperand(0),
403                                  SUBENode->getOperand(0));
404
405  // create MipsSub(u) node
406  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
407
408  SDValue MSub = CurDAG->getNode(MultOpc, DL, MVT::Glue,
409                                 MultNode->getOperand(0),// Factor 0
410                                 MultNode->getOperand(1),// Factor 1
411                                 ACCIn);
412
413  // replace uses of sube and subc here
414  if (!SDValue(SUBCNode, 0).use_empty()) {
415    SDValue LoOut = CurDAG->getNode(MipsISD::ExtractLO, DL, MVT::i32, MSub);
416    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), LoOut);
417  }
418  if (!SDValue(SUBENode, 0).use_empty()) {
419    SDValue HiOut = CurDAG->getNode(MipsISD::ExtractHI, DL, MVT::i32, MSub);
420    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), HiOut);
421  }
422
423  return true;
424}
425
426static SDValue performADDECombine(SDNode *N, SelectionDAG &DAG,
427                                  TargetLowering::DAGCombinerInfo &DCI,
428                                  const MipsSubtarget *Subtarget) {
429  if (DCI.isBeforeLegalize())
430    return SDValue();
431
432  if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
433      selectMADD(N, &DAG))
434    return SDValue(N, 0);
435
436  return SDValue();
437}
438
439// Fold zero extensions into MipsISD::VEXTRACT_[SZ]EXT_ELT
440//
441// Performs the following transformations:
442// - Changes MipsISD::VEXTRACT_[SZ]EXT_ELT to zero extension if its
443//   sign/zero-extension is completely overwritten by the new one performed by
444//   the ISD::AND.
445// - Removes redundant zero extensions performed by an ISD::AND.
446static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
447                                 TargetLowering::DAGCombinerInfo &DCI,
448                                 const MipsSubtarget *Subtarget) {
449  if (!Subtarget->hasMSA())
450    return SDValue();
451
452  SDValue Op0 = N->getOperand(0);
453  SDValue Op1 = N->getOperand(1);
454  unsigned Op0Opcode = Op0->getOpcode();
455
456  // (and (MipsVExtract[SZ]Ext $a, $b, $c), imm:$d)
457  // where $d + 1 == 2^n and n == 32
458  // or    $d + 1 == 2^n and n <= 32 and ZExt
459  // -> (MipsVExtractZExt $a, $b, $c)
460  if (Op0Opcode == MipsISD::VEXTRACT_SEXT_ELT ||
461      Op0Opcode == MipsISD::VEXTRACT_ZEXT_ELT) {
462    ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Op1);
463
464    if (!Mask)
465      return SDValue();
466
467    int32_t Log2IfPositive = (Mask->getAPIntValue() + 1).exactLogBase2();
468
469    if (Log2IfPositive <= 0)
470      return SDValue(); // Mask+1 is not a power of 2
471
472    SDValue Op0Op2 = Op0->getOperand(2);
473    EVT ExtendTy = cast<VTSDNode>(Op0Op2)->getVT();
474    unsigned ExtendTySize = ExtendTy.getSizeInBits();
475    unsigned Log2 = Log2IfPositive;
476
477    if ((Op0Opcode == MipsISD::VEXTRACT_ZEXT_ELT && Log2 >= ExtendTySize) ||
478        Log2 == ExtendTySize) {
479      SDValue Ops[] = { Op0->getOperand(0), Op0->getOperand(1), Op0Op2 };
480      DAG.MorphNodeTo(Op0.getNode(), MipsISD::VEXTRACT_ZEXT_ELT,
481                      Op0->getVTList(), Ops, Op0->getNumOperands());
482      return Op0;
483    }
484  }
485
486  return SDValue();
487}
488
489static SDValue performSUBECombine(SDNode *N, SelectionDAG &DAG,
490                                  TargetLowering::DAGCombinerInfo &DCI,
491                                  const MipsSubtarget *Subtarget) {
492  if (DCI.isBeforeLegalize())
493    return SDValue();
494
495  if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
496      selectMSUB(N, &DAG))
497    return SDValue(N, 0);
498
499  return SDValue();
500}
501
502static SDValue genConstMult(SDValue X, uint64_t C, SDLoc DL, EVT VT,
503                            EVT ShiftTy, SelectionDAG &DAG) {
504  // Clear the upper (64 - VT.sizeInBits) bits.
505  C &= ((uint64_t)-1) >> (64 - VT.getSizeInBits());
506
507  // Return 0.
508  if (C == 0)
509    return DAG.getConstant(0, VT);
510
511  // Return x.
512  if (C == 1)
513    return X;
514
515  // If c is power of 2, return (shl x, log2(c)).
516  if (isPowerOf2_64(C))
517    return DAG.getNode(ISD::SHL, DL, VT, X,
518                       DAG.getConstant(Log2_64(C), ShiftTy));
519
520  unsigned Log2Ceil = Log2_64_Ceil(C);
521  uint64_t Floor = 1LL << Log2_64(C);
522  uint64_t Ceil = Log2Ceil == 64 ? 0LL : 1LL << Log2Ceil;
523
524  // If |c - floor_c| <= |c - ceil_c|,
525  // where floor_c = pow(2, floor(log2(c))) and ceil_c = pow(2, ceil(log2(c))),
526  // return (add constMult(x, floor_c), constMult(x, c - floor_c)).
527  if (C - Floor <= Ceil - C) {
528    SDValue Op0 = genConstMult(X, Floor, DL, VT, ShiftTy, DAG);
529    SDValue Op1 = genConstMult(X, C - Floor, DL, VT, ShiftTy, DAG);
530    return DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
531  }
532
533  // If |c - floor_c| > |c - ceil_c|,
534  // return (sub constMult(x, ceil_c), constMult(x, ceil_c - c)).
535  SDValue Op0 = genConstMult(X, Ceil, DL, VT, ShiftTy, DAG);
536  SDValue Op1 = genConstMult(X, Ceil - C, DL, VT, ShiftTy, DAG);
537  return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
538}
539
540static SDValue performMULCombine(SDNode *N, SelectionDAG &DAG,
541                                 const TargetLowering::DAGCombinerInfo &DCI,
542                                 const MipsSETargetLowering *TL) {
543  EVT VT = N->getValueType(0);
544
545  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
546    if (!VT.isVector())
547      return genConstMult(N->getOperand(0), C->getZExtValue(), SDLoc(N),
548                          VT, TL->getScalarShiftAmountTy(VT), DAG);
549
550  return SDValue(N, 0);
551}
552
553static SDValue performDSPShiftCombine(unsigned Opc, SDNode *N, EVT Ty,
554                                      SelectionDAG &DAG,
555                                      const MipsSubtarget *Subtarget) {
556  // See if this is a vector splat immediate node.
557  APInt SplatValue, SplatUndef;
558  unsigned SplatBitSize;
559  bool HasAnyUndefs;
560  unsigned EltSize = Ty.getVectorElementType().getSizeInBits();
561  BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
562
563  if (!BV ||
564      !BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
565                           EltSize, !Subtarget->isLittle()) ||
566      (SplatBitSize != EltSize) ||
567      (SplatValue.getZExtValue() >= EltSize))
568    return SDValue();
569
570  return DAG.getNode(Opc, SDLoc(N), Ty, N->getOperand(0),
571                     DAG.getConstant(SplatValue.getZExtValue(), MVT::i32));
572}
573
574static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
575                                 TargetLowering::DAGCombinerInfo &DCI,
576                                 const MipsSubtarget *Subtarget) {
577  EVT Ty = N->getValueType(0);
578
579  if ((Ty != MVT::v2i16) && (Ty != MVT::v4i8))
580    return SDValue();
581
582  return performDSPShiftCombine(MipsISD::SHLL_DSP, N, Ty, DAG, Subtarget);
583}
584
585// Fold sign-extensions into MipsISD::VEXTRACT_[SZ]EXT_ELT for MSA and fold
586// constant splats into MipsISD::SHRA_DSP for DSPr2.
587//
588// Performs the following transformations:
589// - Changes MipsISD::VEXTRACT_[SZ]EXT_ELT to sign extension if its
590//   sign/zero-extension is completely overwritten by the new one performed by
591//   the ISD::SRA and ISD::SHL nodes.
592// - Removes redundant sign extensions performed by an ISD::SRA and ISD::SHL
593//   sequence.
594//
595// See performDSPShiftCombine for more information about the transformation
596// used for DSPr2.
597static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG,
598                                 TargetLowering::DAGCombinerInfo &DCI,
599                                 const MipsSubtarget *Subtarget) {
600  EVT Ty = N->getValueType(0);
601
602  if (Subtarget->hasMSA()) {
603    SDValue Op0 = N->getOperand(0);
604    SDValue Op1 = N->getOperand(1);
605
606    // (sra (shl (MipsVExtract[SZ]Ext $a, $b, $c), imm:$d), imm:$d)
607    // where $d + sizeof($c) == 32
608    // or    $d + sizeof($c) <= 32 and SExt
609    // -> (MipsVExtractSExt $a, $b, $c)
610    if (Op0->getOpcode() == ISD::SHL && Op1 == Op0->getOperand(1)) {
611      SDValue Op0Op0 = Op0->getOperand(0);
612      ConstantSDNode *ShAmount = dyn_cast<ConstantSDNode>(Op1);
613
614      if (!ShAmount)
615        return SDValue();
616
617      if (Op0Op0->getOpcode() != MipsISD::VEXTRACT_SEXT_ELT &&
618          Op0Op0->getOpcode() != MipsISD::VEXTRACT_ZEXT_ELT)
619        return SDValue();
620
621      EVT ExtendTy = cast<VTSDNode>(Op0Op0->getOperand(2))->getVT();
622      unsigned TotalBits = ShAmount->getZExtValue() + ExtendTy.getSizeInBits();
623
624      if (TotalBits == 32 ||
625          (Op0Op0->getOpcode() == MipsISD::VEXTRACT_SEXT_ELT &&
626           TotalBits <= 32)) {
627        SDValue Ops[] = { Op0Op0->getOperand(0), Op0Op0->getOperand(1),
628                          Op0Op0->getOperand(2) };
629        DAG.MorphNodeTo(Op0Op0.getNode(), MipsISD::VEXTRACT_SEXT_ELT,
630                        Op0Op0->getVTList(), Ops, Op0Op0->getNumOperands());
631        return Op0Op0;
632      }
633    }
634  }
635
636  if ((Ty != MVT::v2i16) && ((Ty != MVT::v4i8) || !Subtarget->hasDSPR2()))
637    return SDValue();
638
639  return performDSPShiftCombine(MipsISD::SHRA_DSP, N, Ty, DAG, Subtarget);
640}
641
642
643static SDValue performSRLCombine(SDNode *N, SelectionDAG &DAG,
644                                 TargetLowering::DAGCombinerInfo &DCI,
645                                 const MipsSubtarget *Subtarget) {
646  EVT Ty = N->getValueType(0);
647
648  if (((Ty != MVT::v2i16) || !Subtarget->hasDSPR2()) && (Ty != MVT::v4i8))
649    return SDValue();
650
651  return performDSPShiftCombine(MipsISD::SHRL_DSP, N, Ty, DAG, Subtarget);
652}
653
654static bool isLegalDSPCondCode(EVT Ty, ISD::CondCode CC) {
655  bool IsV216 = (Ty == MVT::v2i16);
656
657  switch (CC) {
658  case ISD::SETEQ:
659  case ISD::SETNE:  return true;
660  case ISD::SETLT:
661  case ISD::SETLE:
662  case ISD::SETGT:
663  case ISD::SETGE:  return IsV216;
664  case ISD::SETULT:
665  case ISD::SETULE:
666  case ISD::SETUGT:
667  case ISD::SETUGE: return !IsV216;
668  default:          return false;
669  }
670}
671
672static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG) {
673  EVT Ty = N->getValueType(0);
674
675  if ((Ty != MVT::v2i16) && (Ty != MVT::v4i8))
676    return SDValue();
677
678  if (!isLegalDSPCondCode(Ty, cast<CondCodeSDNode>(N->getOperand(2))->get()))
679    return SDValue();
680
681  return DAG.getNode(MipsISD::SETCC_DSP, SDLoc(N), Ty, N->getOperand(0),
682                     N->getOperand(1), N->getOperand(2));
683}
684
685static SDValue performVSELECTCombine(SDNode *N, SelectionDAG &DAG) {
686  EVT Ty = N->getValueType(0);
687
688  if (Ty.is128BitVector() && Ty.isInteger()) {
689    // Try the following combines:
690    //   (vselect (setcc $a, $b, SETLT), $b, $a)) -> (vsmax $a, $b)
691    //   (vselect (setcc $a, $b, SETLE), $b, $a)) -> (vsmax $a, $b)
692    //   (vselect (setcc $a, $b, SETLT), $a, $b)) -> (vsmin $a, $b)
693    //   (vselect (setcc $a, $b, SETLE), $a, $b)) -> (vsmin $a, $b)
694    //   (vselect (setcc $a, $b, SETULT), $b, $a)) -> (vumax $a, $b)
695    //   (vselect (setcc $a, $b, SETULE), $b, $a)) -> (vumax $a, $b)
696    //   (vselect (setcc $a, $b, SETULT), $a, $b)) -> (vumin $a, $b)
697    //   (vselect (setcc $a, $b, SETULE), $a, $b)) -> (vumin $a, $b)
698    // SETGT/SETGE/SETUGT/SETUGE variants of these will show up initially but
699    // will be expanded to equivalent SETLT/SETLE/SETULT/SETULE versions by the
700    // legalizer.
701    SDValue Op0 = N->getOperand(0);
702
703    if (Op0->getOpcode() != ISD::SETCC)
704      return SDValue();
705
706    ISD::CondCode CondCode = cast<CondCodeSDNode>(Op0->getOperand(2))->get();
707    bool Signed;
708
709    if (CondCode == ISD::SETLT  || CondCode == ISD::SETLE)
710      Signed = true;
711    else if (CondCode == ISD::SETULT || CondCode == ISD::SETULE)
712      Signed = false;
713    else
714      return SDValue();
715
716    SDValue Op1 = N->getOperand(1);
717    SDValue Op2 = N->getOperand(2);
718    SDValue Op0Op0 = Op0->getOperand(0);
719    SDValue Op0Op1 = Op0->getOperand(1);
720
721    if (Op1 == Op0Op0 && Op2 == Op0Op1)
722      return DAG.getNode(Signed ? MipsISD::VSMIN : MipsISD::VUMIN, SDLoc(N),
723                         Ty, Op1, Op2);
724    else if (Op1 == Op0Op1 && Op2 == Op0Op0)
725      return DAG.getNode(Signed ? MipsISD::VSMAX : MipsISD::VUMAX, SDLoc(N),
726                         Ty, Op1, Op2);
727  } else if ((Ty == MVT::v2i16) || (Ty == MVT::v4i8)) {
728    SDValue SetCC = N->getOperand(0);
729
730    if (SetCC.getOpcode() != MipsISD::SETCC_DSP)
731      return SDValue();
732
733    return DAG.getNode(MipsISD::SELECT_CC_DSP, SDLoc(N), Ty,
734                       SetCC.getOperand(0), SetCC.getOperand(1),
735                       N->getOperand(1), N->getOperand(2), SetCC.getOperand(2));
736  }
737
738  return SDValue();
739}
740
741static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG,
742                                 const MipsSubtarget *Subtarget) {
743  EVT Ty = N->getValueType(0);
744
745  if (Subtarget->hasMSA() && Ty.is128BitVector() && Ty.isInteger()) {
746    // Try the following combines:
747    //   (xor (or $a, $b), (build_vector allones))
748    //   (xor (or $a, $b), (bitcast (build_vector allones)))
749    SDValue Op0 = N->getOperand(0);
750    SDValue Op1 = N->getOperand(1);
751    SDValue NotOp;
752
753    if (ISD::isBuildVectorAllOnes(Op0.getNode()))
754      NotOp = Op1;
755    else if (ISD::isBuildVectorAllOnes(Op1.getNode()))
756      NotOp = Op0;
757    else
758      return SDValue();
759
760    if (NotOp->getOpcode() == ISD::OR)
761      return DAG.getNode(MipsISD::VNOR, SDLoc(N), Ty, NotOp->getOperand(0),
762                         NotOp->getOperand(1));
763  }
764
765  return SDValue();
766}
767
768SDValue
769MipsSETargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
770  SelectionDAG &DAG = DCI.DAG;
771  SDValue Val;
772
773  switch (N->getOpcode()) {
774  case ISD::ADDE:
775    return performADDECombine(N, DAG, DCI, Subtarget);
776  case ISD::AND:
777    Val = performANDCombine(N, DAG, DCI, Subtarget);
778    break;
779  case ISD::SUBE:
780    return performSUBECombine(N, DAG, DCI, Subtarget);
781  case ISD::MUL:
782    return performMULCombine(N, DAG, DCI, this);
783  case ISD::SHL:
784    return performSHLCombine(N, DAG, DCI, Subtarget);
785  case ISD::SRA:
786    return performSRACombine(N, DAG, DCI, Subtarget);
787  case ISD::SRL:
788    return performSRLCombine(N, DAG, DCI, Subtarget);
789  case ISD::VSELECT:
790    return performVSELECTCombine(N, DAG);
791  case ISD::XOR:
792    Val = performXORCombine(N, DAG, Subtarget);
793    break;
794  case ISD::SETCC:
795    Val = performSETCCCombine(N, DAG);
796    break;
797  }
798
799  if (Val.getNode())
800    return Val;
801
802  return MipsTargetLowering::PerformDAGCombine(N, DCI);
803}
804
805MachineBasicBlock *
806MipsSETargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
807                                                  MachineBasicBlock *BB) const {
808  switch (MI->getOpcode()) {
809  default:
810    return MipsTargetLowering::EmitInstrWithCustomInserter(MI, BB);
811  case Mips::BPOSGE32_PSEUDO:
812    return emitBPOSGE32(MI, BB);
813  case Mips::SNZ_B_PSEUDO:
814    return emitMSACBranchPseudo(MI, BB, Mips::BNZ_B);
815  case Mips::SNZ_H_PSEUDO:
816    return emitMSACBranchPseudo(MI, BB, Mips::BNZ_H);
817  case Mips::SNZ_W_PSEUDO:
818    return emitMSACBranchPseudo(MI, BB, Mips::BNZ_W);
819  case Mips::SNZ_D_PSEUDO:
820    return emitMSACBranchPseudo(MI, BB, Mips::BNZ_D);
821  case Mips::SNZ_V_PSEUDO:
822    return emitMSACBranchPseudo(MI, BB, Mips::BNZ_V);
823  case Mips::SZ_B_PSEUDO:
824    return emitMSACBranchPseudo(MI, BB, Mips::BZ_B);
825  case Mips::SZ_H_PSEUDO:
826    return emitMSACBranchPseudo(MI, BB, Mips::BZ_H);
827  case Mips::SZ_W_PSEUDO:
828    return emitMSACBranchPseudo(MI, BB, Mips::BZ_W);
829  case Mips::SZ_D_PSEUDO:
830    return emitMSACBranchPseudo(MI, BB, Mips::BZ_D);
831  case Mips::SZ_V_PSEUDO:
832    return emitMSACBranchPseudo(MI, BB, Mips::BZ_V);
833  case Mips::COPY_FW_PSEUDO:
834    return emitCOPY_FW(MI, BB);
835  case Mips::COPY_FD_PSEUDO:
836    return emitCOPY_FD(MI, BB);
837  case Mips::INSERT_FW_PSEUDO:
838    return emitINSERT_FW(MI, BB);
839  case Mips::INSERT_FD_PSEUDO:
840    return emitINSERT_FD(MI, BB);
841  }
842}
843
844bool MipsSETargetLowering::
845isEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
846                                  unsigned NextStackOffset,
847                                  const MipsFunctionInfo& FI) const {
848  if (!EnableMipsTailCalls)
849    return false;
850
851  // Return false if either the callee or caller has a byval argument.
852  if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
853    return false;
854
855  // Return true if the callee's argument area is no larger than the
856  // caller's.
857  return NextStackOffset <= FI.getIncomingArgSize();
858}
859
860void MipsSETargetLowering::
861getOpndList(SmallVectorImpl<SDValue> &Ops,
862            std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
863            bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
864            CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
865  // T9 should contain the address of the callee function if
866  // -reloction-model=pic or it is an indirect call.
867  if (IsPICCall || !GlobalOrExternal) {
868    unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
869    RegsToPass.push_front(std::make_pair(T9Reg, Callee));
870  } else
871    Ops.push_back(Callee);
872
873  MipsTargetLowering::getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal,
874                                  InternalLinkage, CLI, Callee, Chain);
875}
876
877SDValue MipsSETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
878  LoadSDNode &Nd = *cast<LoadSDNode>(Op);
879
880  if (Nd.getMemoryVT() != MVT::f64 || !NoDPLoadStore)
881    return MipsTargetLowering::lowerLOAD(Op, DAG);
882
883  // Replace a double precision load with two i32 loads and a buildpair64.
884  SDLoc DL(Op);
885  SDValue Ptr = Nd.getBasePtr(), Chain = Nd.getChain();
886  EVT PtrVT = Ptr.getValueType();
887
888  // i32 load from lower address.
889  SDValue Lo = DAG.getLoad(MVT::i32, DL, Chain, Ptr,
890                           MachinePointerInfo(), Nd.isVolatile(),
891                           Nd.isNonTemporal(), Nd.isInvariant(),
892                           Nd.getAlignment());
893
894  // i32 load from higher address.
895  Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr, DAG.getConstant(4, PtrVT));
896  SDValue Hi = DAG.getLoad(MVT::i32, DL, Lo.getValue(1), Ptr,
897                           MachinePointerInfo(), Nd.isVolatile(),
898                           Nd.isNonTemporal(), Nd.isInvariant(),
899                           std::min(Nd.getAlignment(), 4U));
900
901  if (!Subtarget->isLittle())
902    std::swap(Lo, Hi);
903
904  SDValue BP = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
905  SDValue Ops[2] = {BP, Hi.getValue(1)};
906  return DAG.getMergeValues(Ops, 2, DL);
907}
908
909SDValue MipsSETargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
910  StoreSDNode &Nd = *cast<StoreSDNode>(Op);
911
912  if (Nd.getMemoryVT() != MVT::f64 || !NoDPLoadStore)
913    return MipsTargetLowering::lowerSTORE(Op, DAG);
914
915  // Replace a double precision store with two extractelement64s and i32 stores.
916  SDLoc DL(Op);
917  SDValue Val = Nd.getValue(), Ptr = Nd.getBasePtr(), Chain = Nd.getChain();
918  EVT PtrVT = Ptr.getValueType();
919  SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
920                           Val, DAG.getConstant(0, MVT::i32));
921  SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
922                           Val, DAG.getConstant(1, MVT::i32));
923
924  if (!Subtarget->isLittle())
925    std::swap(Lo, Hi);
926
927  // i32 store to lower address.
928  Chain = DAG.getStore(Chain, DL, Lo, Ptr, MachinePointerInfo(),
929                       Nd.isVolatile(), Nd.isNonTemporal(), Nd.getAlignment(),
930                       Nd.getTBAAInfo());
931
932  // i32 store to higher address.
933  Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr, DAG.getConstant(4, PtrVT));
934  return DAG.getStore(Chain, DL, Hi, Ptr, MachinePointerInfo(),
935                      Nd.isVolatile(), Nd.isNonTemporal(),
936                      std::min(Nd.getAlignment(), 4U), Nd.getTBAAInfo());
937}
938
939SDValue MipsSETargetLowering::lowerMulDiv(SDValue Op, unsigned NewOpc,
940                                          bool HasLo, bool HasHi,
941                                          SelectionDAG &DAG) const {
942  EVT Ty = Op.getOperand(0).getValueType();
943  SDLoc DL(Op);
944  SDValue Mult = DAG.getNode(NewOpc, DL, MVT::Untyped,
945                             Op.getOperand(0), Op.getOperand(1));
946  SDValue Lo, Hi;
947
948  if (HasLo)
949    Lo = DAG.getNode(MipsISD::ExtractLO, DL, Ty, Mult);
950  if (HasHi)
951    Hi = DAG.getNode(MipsISD::ExtractHI, DL, Ty, Mult);
952
953  if (!HasLo || !HasHi)
954    return HasLo ? Lo : Hi;
955
956  SDValue Vals[] = { Lo, Hi };
957  return DAG.getMergeValues(Vals, 2, DL);
958}
959
960
961static SDValue initAccumulator(SDValue In, SDLoc DL, SelectionDAG &DAG) {
962  SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, In,
963                             DAG.getConstant(0, MVT::i32));
964  SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, In,
965                             DAG.getConstant(1, MVT::i32));
966  return DAG.getNode(MipsISD::InsertLOHI, DL, MVT::Untyped, InLo, InHi);
967}
968
969static SDValue extractLOHI(SDValue Op, SDLoc DL, SelectionDAG &DAG) {
970  SDValue Lo = DAG.getNode(MipsISD::ExtractLO, DL, MVT::i32, Op);
971  SDValue Hi = DAG.getNode(MipsISD::ExtractHI, DL, MVT::i32, Op);
972  return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
973}
974
975// This function expands mips intrinsic nodes which have 64-bit input operands
976// or output values.
977//
978// out64 = intrinsic-node in64
979// =>
980// lo = copy (extract-element (in64, 0))
981// hi = copy (extract-element (in64, 1))
982// mips-specific-node
983// v0 = copy lo
984// v1 = copy hi
985// out64 = merge-values (v0, v1)
986//
987static SDValue lowerDSPIntr(SDValue Op, SelectionDAG &DAG, unsigned Opc) {
988  SDLoc DL(Op);
989  bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
990  SmallVector<SDValue, 3> Ops;
991  unsigned OpNo = 0;
992
993  // See if Op has a chain input.
994  if (HasChainIn)
995    Ops.push_back(Op->getOperand(OpNo++));
996
997  // The next operand is the intrinsic opcode.
998  assert(Op->getOperand(OpNo).getOpcode() == ISD::TargetConstant);
999
1000  // See if the next operand has type i64.
1001  SDValue Opnd = Op->getOperand(++OpNo), In64;
1002
1003  if (Opnd.getValueType() == MVT::i64)
1004    In64 = initAccumulator(Opnd, DL, DAG);
1005  else
1006    Ops.push_back(Opnd);
1007
1008  // Push the remaining operands.
1009  for (++OpNo ; OpNo < Op->getNumOperands(); ++OpNo)
1010    Ops.push_back(Op->getOperand(OpNo));
1011
1012  // Add In64 to the end of the list.
1013  if (In64.getNode())
1014    Ops.push_back(In64);
1015
1016  // Scan output.
1017  SmallVector<EVT, 2> ResTys;
1018
1019  for (SDNode::value_iterator I = Op->value_begin(), E = Op->value_end();
1020       I != E; ++I)
1021    ResTys.push_back((*I == MVT::i64) ? MVT::Untyped : *I);
1022
1023  // Create node.
1024  SDValue Val = DAG.getNode(Opc, DL, ResTys, &Ops[0], Ops.size());
1025  SDValue Out = (ResTys[0] == MVT::Untyped) ? extractLOHI(Val, DL, DAG) : Val;
1026
1027  if (!HasChainIn)
1028    return Out;
1029
1030  assert(Val->getValueType(1) == MVT::Other);
1031  SDValue Vals[] = { Out, SDValue(Val.getNode(), 1) };
1032  return DAG.getMergeValues(Vals, 2, DL);
1033}
1034
1035// Lower an MSA copy intrinsic into the specified SelectionDAG node
1036static SDValue lowerMSACopyIntr(SDValue Op, SelectionDAG &DAG, unsigned Opc) {
1037  SDLoc DL(Op);
1038  SDValue Vec = Op->getOperand(1);
1039  SDValue Idx = Op->getOperand(2);
1040  EVT ResTy = Op->getValueType(0);
1041  EVT EltTy = Vec->getValueType(0).getVectorElementType();
1042
1043  SDValue Result = DAG.getNode(Opc, DL, ResTy, Vec, Idx,
1044                               DAG.getValueType(EltTy));
1045
1046  return Result;
1047}
1048
1049static SDValue
1050lowerMSASplatImm(SDLoc DL, EVT ResTy, SDValue ImmOp, SelectionDAG &DAG) {
1051  EVT ViaVecTy = ResTy;
1052  SmallVector<SDValue, 16> Ops;
1053  SDValue ImmHiOp;
1054
1055  if (ViaVecTy == MVT::v2i64) {
1056    ImmHiOp = DAG.getNode(ISD::SRA, DL, MVT::i32, ImmOp,
1057                          DAG.getConstant(31, MVT::i32));
1058    for (unsigned i = 0; i < ViaVecTy.getVectorNumElements(); ++i) {
1059      Ops.push_back(ImmHiOp);
1060      Ops.push_back(ImmOp);
1061    }
1062    ViaVecTy = MVT::v4i32;
1063  } else {
1064    for (unsigned i = 0; i < ResTy.getVectorNumElements(); ++i)
1065      Ops.push_back(ImmOp);
1066  }
1067
1068  SDValue Result = DAG.getNode(ISD::BUILD_VECTOR, DL, ViaVecTy, &Ops[0],
1069                               Ops.size());
1070
1071  if (ResTy != ViaVecTy)
1072    Result = DAG.getNode(ISD::BITCAST, DL, ResTy, Result);
1073
1074  return Result;
1075}
1076
1077static SDValue
1078lowerMSASplatImm(SDValue Op, unsigned ImmOp, SelectionDAG &DAG) {
1079  return lowerMSASplatImm(SDLoc(Op), Op->getValueType(0),
1080                          Op->getOperand(ImmOp), DAG);
1081}
1082
1083SDValue MipsSETargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
1084                                                      SelectionDAG &DAG) const {
1085  SDLoc DL(Op);
1086
1087  switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
1088  default:
1089    return SDValue();
1090  case Intrinsic::mips_shilo:
1091    return lowerDSPIntr(Op, DAG, MipsISD::SHILO);
1092  case Intrinsic::mips_dpau_h_qbl:
1093    return lowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL);
1094  case Intrinsic::mips_dpau_h_qbr:
1095    return lowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR);
1096  case Intrinsic::mips_dpsu_h_qbl:
1097    return lowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL);
1098  case Intrinsic::mips_dpsu_h_qbr:
1099    return lowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR);
1100  case Intrinsic::mips_dpa_w_ph:
1101    return lowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH);
1102  case Intrinsic::mips_dps_w_ph:
1103    return lowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH);
1104  case Intrinsic::mips_dpax_w_ph:
1105    return lowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH);
1106  case Intrinsic::mips_dpsx_w_ph:
1107    return lowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH);
1108  case Intrinsic::mips_mulsa_w_ph:
1109    return lowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH);
1110  case Intrinsic::mips_mult:
1111    return lowerDSPIntr(Op, DAG, MipsISD::Mult);
1112  case Intrinsic::mips_multu:
1113    return lowerDSPIntr(Op, DAG, MipsISD::Multu);
1114  case Intrinsic::mips_madd:
1115    return lowerDSPIntr(Op, DAG, MipsISD::MAdd);
1116  case Intrinsic::mips_maddu:
1117    return lowerDSPIntr(Op, DAG, MipsISD::MAddu);
1118  case Intrinsic::mips_msub:
1119    return lowerDSPIntr(Op, DAG, MipsISD::MSub);
1120  case Intrinsic::mips_msubu:
1121    return lowerDSPIntr(Op, DAG, MipsISD::MSubu);
1122  case Intrinsic::mips_addv_b:
1123  case Intrinsic::mips_addv_h:
1124  case Intrinsic::mips_addv_w:
1125  case Intrinsic::mips_addv_d:
1126    return DAG.getNode(ISD::ADD, DL, Op->getValueType(0), Op->getOperand(1),
1127                       Op->getOperand(2));
1128  case Intrinsic::mips_addvi_b:
1129  case Intrinsic::mips_addvi_h:
1130  case Intrinsic::mips_addvi_w:
1131  case Intrinsic::mips_addvi_d:
1132    return DAG.getNode(ISD::ADD, DL, Op->getValueType(0), Op->getOperand(1),
1133                       lowerMSASplatImm(Op, 2, DAG));
1134  case Intrinsic::mips_and_v:
1135    return DAG.getNode(ISD::AND, DL, Op->getValueType(0), Op->getOperand(1),
1136                       Op->getOperand(2));
1137  case Intrinsic::mips_andi_b:
1138    return DAG.getNode(ISD::AND, DL, Op->getValueType(0), Op->getOperand(1),
1139                       lowerMSASplatImm(Op, 2, DAG));
1140  case Intrinsic::mips_bnz_b:
1141  case Intrinsic::mips_bnz_h:
1142  case Intrinsic::mips_bnz_w:
1143  case Intrinsic::mips_bnz_d:
1144    return DAG.getNode(MipsISD::VALL_NONZERO, DL, Op->getValueType(0),
1145                       Op->getOperand(1));
1146  case Intrinsic::mips_bnz_v:
1147    return DAG.getNode(MipsISD::VANY_NONZERO, DL, Op->getValueType(0),
1148                       Op->getOperand(1));
1149  case Intrinsic::mips_bsel_v:
1150    return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1151                       Op->getOperand(1), Op->getOperand(2),
1152                       Op->getOperand(3));
1153  case Intrinsic::mips_bseli_b:
1154    return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1155                       Op->getOperand(1), Op->getOperand(2),
1156                       lowerMSASplatImm(Op, 3, DAG));
1157  case Intrinsic::mips_bz_b:
1158  case Intrinsic::mips_bz_h:
1159  case Intrinsic::mips_bz_w:
1160  case Intrinsic::mips_bz_d:
1161    return DAG.getNode(MipsISD::VALL_ZERO, DL, Op->getValueType(0),
1162                       Op->getOperand(1));
1163  case Intrinsic::mips_bz_v:
1164    return DAG.getNode(MipsISD::VANY_ZERO, DL, Op->getValueType(0),
1165                       Op->getOperand(1));
1166  case Intrinsic::mips_ceq_b:
1167  case Intrinsic::mips_ceq_h:
1168  case Intrinsic::mips_ceq_w:
1169  case Intrinsic::mips_ceq_d:
1170    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1171                        Op->getOperand(2), ISD::SETEQ);
1172  case Intrinsic::mips_ceqi_b:
1173  case Intrinsic::mips_ceqi_h:
1174  case Intrinsic::mips_ceqi_w:
1175  case Intrinsic::mips_ceqi_d:
1176    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1177                        lowerMSASplatImm(Op, 2, DAG), ISD::SETEQ);
1178  case Intrinsic::mips_cle_s_b:
1179  case Intrinsic::mips_cle_s_h:
1180  case Intrinsic::mips_cle_s_w:
1181  case Intrinsic::mips_cle_s_d:
1182    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1183                        Op->getOperand(2), ISD::SETLE);
1184  case Intrinsic::mips_clei_s_b:
1185  case Intrinsic::mips_clei_s_h:
1186  case Intrinsic::mips_clei_s_w:
1187  case Intrinsic::mips_clei_s_d:
1188    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1189                        lowerMSASplatImm(Op, 2, DAG), ISD::SETLE);
1190  case Intrinsic::mips_cle_u_b:
1191  case Intrinsic::mips_cle_u_h:
1192  case Intrinsic::mips_cle_u_w:
1193  case Intrinsic::mips_cle_u_d:
1194    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1195                        Op->getOperand(2), ISD::SETULE);
1196  case Intrinsic::mips_clei_u_b:
1197  case Intrinsic::mips_clei_u_h:
1198  case Intrinsic::mips_clei_u_w:
1199  case Intrinsic::mips_clei_u_d:
1200    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1201                        lowerMSASplatImm(Op, 2, DAG), ISD::SETULE);
1202  case Intrinsic::mips_clt_s_b:
1203  case Intrinsic::mips_clt_s_h:
1204  case Intrinsic::mips_clt_s_w:
1205  case Intrinsic::mips_clt_s_d:
1206    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1207                        Op->getOperand(2), ISD::SETLT);
1208  case Intrinsic::mips_clti_s_b:
1209  case Intrinsic::mips_clti_s_h:
1210  case Intrinsic::mips_clti_s_w:
1211  case Intrinsic::mips_clti_s_d:
1212    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1213                        lowerMSASplatImm(Op, 2, DAG), ISD::SETLT);
1214  case Intrinsic::mips_clt_u_b:
1215  case Intrinsic::mips_clt_u_h:
1216  case Intrinsic::mips_clt_u_w:
1217  case Intrinsic::mips_clt_u_d:
1218    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1219                        Op->getOperand(2), ISD::SETULT);
1220  case Intrinsic::mips_clti_u_b:
1221  case Intrinsic::mips_clti_u_h:
1222  case Intrinsic::mips_clti_u_w:
1223  case Intrinsic::mips_clti_u_d:
1224    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1225                        lowerMSASplatImm(Op, 2, DAG), ISD::SETULT);
1226  case Intrinsic::mips_copy_s_b:
1227  case Intrinsic::mips_copy_s_h:
1228  case Intrinsic::mips_copy_s_w:
1229    return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_SEXT_ELT);
1230  case Intrinsic::mips_copy_s_d:
1231    // Don't lower directly into VEXTRACT_SEXT_ELT since i64 might be illegal.
1232    // Instead lower to the generic EXTRACT_VECTOR_ELT node and let the type
1233    // legalizer and EXTRACT_VECTOR_ELT lowering sort it out.
1234    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op), Op->getValueType(0),
1235                       Op->getOperand(1), Op->getOperand(2));
1236  case Intrinsic::mips_copy_u_b:
1237  case Intrinsic::mips_copy_u_h:
1238  case Intrinsic::mips_copy_u_w:
1239    return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_ZEXT_ELT);
1240  case Intrinsic::mips_copy_u_d:
1241    // Don't lower directly into VEXTRACT_ZEXT_ELT since i64 might be illegal.
1242    // Instead lower to the generic EXTRACT_VECTOR_ELT node and let the type
1243    // legalizer and EXTRACT_VECTOR_ELT lowering sort it out.
1244    //
1245    // Note: When i64 is illegal, this results in copy_s.w instructions instead
1246    // of copy_u.w instructions. This makes no difference to the behaviour
1247    // since i64 is only illegal when the register file is 32-bit.
1248    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op), Op->getValueType(0),
1249                       Op->getOperand(1), Op->getOperand(2));
1250  case Intrinsic::mips_div_s_b:
1251  case Intrinsic::mips_div_s_h:
1252  case Intrinsic::mips_div_s_w:
1253  case Intrinsic::mips_div_s_d:
1254    return DAG.getNode(ISD::SDIV, DL, Op->getValueType(0), Op->getOperand(1),
1255                       Op->getOperand(2));
1256  case Intrinsic::mips_div_u_b:
1257  case Intrinsic::mips_div_u_h:
1258  case Intrinsic::mips_div_u_w:
1259  case Intrinsic::mips_div_u_d:
1260    return DAG.getNode(ISD::UDIV, DL, Op->getValueType(0), Op->getOperand(1),
1261                       Op->getOperand(2));
1262  case Intrinsic::mips_fadd_w:
1263  case Intrinsic::mips_fadd_d:
1264    return DAG.getNode(ISD::FADD, DL, Op->getValueType(0), Op->getOperand(1),
1265                       Op->getOperand(2));
1266  // Don't lower mips_fcaf_[wd] since LLVM folds SETFALSE condcodes away
1267  case Intrinsic::mips_fceq_w:
1268  case Intrinsic::mips_fceq_d:
1269    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1270                        Op->getOperand(2), ISD::SETOEQ);
1271  case Intrinsic::mips_fcle_w:
1272  case Intrinsic::mips_fcle_d:
1273    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1274                        Op->getOperand(2), ISD::SETOLE);
1275  case Intrinsic::mips_fclt_w:
1276  case Intrinsic::mips_fclt_d:
1277    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1278                        Op->getOperand(2), ISD::SETOLT);
1279  case Intrinsic::mips_fcne_w:
1280  case Intrinsic::mips_fcne_d:
1281    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1282                        Op->getOperand(2), ISD::SETONE);
1283  case Intrinsic::mips_fcor_w:
1284  case Intrinsic::mips_fcor_d:
1285    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1286                        Op->getOperand(2), ISD::SETO);
1287  case Intrinsic::mips_fcueq_w:
1288  case Intrinsic::mips_fcueq_d:
1289    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1290                        Op->getOperand(2), ISD::SETUEQ);
1291  case Intrinsic::mips_fcule_w:
1292  case Intrinsic::mips_fcule_d:
1293    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1294                        Op->getOperand(2), ISD::SETULE);
1295  case Intrinsic::mips_fcult_w:
1296  case Intrinsic::mips_fcult_d:
1297    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1298                        Op->getOperand(2), ISD::SETULT);
1299  case Intrinsic::mips_fcun_w:
1300  case Intrinsic::mips_fcun_d:
1301    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1302                        Op->getOperand(2), ISD::SETUO);
1303  case Intrinsic::mips_fcune_w:
1304  case Intrinsic::mips_fcune_d:
1305    return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1306                        Op->getOperand(2), ISD::SETUNE);
1307  case Intrinsic::mips_fdiv_w:
1308  case Intrinsic::mips_fdiv_d:
1309    return DAG.getNode(ISD::FDIV, DL, Op->getValueType(0), Op->getOperand(1),
1310                       Op->getOperand(2));
1311  case Intrinsic::mips_ffint_u_w:
1312  case Intrinsic::mips_ffint_u_d:
1313    return DAG.getNode(ISD::UINT_TO_FP, DL, Op->getValueType(0),
1314                       Op->getOperand(1));
1315  case Intrinsic::mips_ffint_s_w:
1316  case Intrinsic::mips_ffint_s_d:
1317    return DAG.getNode(ISD::SINT_TO_FP, DL, Op->getValueType(0),
1318                       Op->getOperand(1));
1319  case Intrinsic::mips_fill_b:
1320  case Intrinsic::mips_fill_h:
1321  case Intrinsic::mips_fill_w:
1322  case Intrinsic::mips_fill_d: {
1323    SmallVector<SDValue, 16> Ops;
1324    EVT ResTy = Op->getValueType(0);
1325
1326    for (unsigned i = 0; i < ResTy.getVectorNumElements(); ++i)
1327      Ops.push_back(Op->getOperand(1));
1328
1329    // If ResTy is v2i64 then the type legalizer will break this node down into
1330    // an equivalent v4i32.
1331    return DAG.getNode(ISD::BUILD_VECTOR, DL, ResTy, &Ops[0], Ops.size());
1332  }
1333  case Intrinsic::mips_flog2_w:
1334  case Intrinsic::mips_flog2_d:
1335    return DAG.getNode(ISD::FLOG2, DL, Op->getValueType(0), Op->getOperand(1));
1336  case Intrinsic::mips_fmadd_w:
1337  case Intrinsic::mips_fmadd_d:
1338    return DAG.getNode(ISD::FMA, SDLoc(Op), Op->getValueType(0),
1339                       Op->getOperand(1), Op->getOperand(2), Op->getOperand(3));
1340  case Intrinsic::mips_fmul_w:
1341  case Intrinsic::mips_fmul_d:
1342    return DAG.getNode(ISD::FMUL, DL, Op->getValueType(0), Op->getOperand(1),
1343                       Op->getOperand(2));
1344  case Intrinsic::mips_frint_w:
1345  case Intrinsic::mips_frint_d:
1346    return DAG.getNode(ISD::FRINT, DL, Op->getValueType(0), Op->getOperand(1));
1347  case Intrinsic::mips_fsqrt_w:
1348  case Intrinsic::mips_fsqrt_d:
1349    return DAG.getNode(ISD::FSQRT, DL, Op->getValueType(0), Op->getOperand(1));
1350  case Intrinsic::mips_fsub_w:
1351  case Intrinsic::mips_fsub_d:
1352    return DAG.getNode(ISD::FSUB, DL, Op->getValueType(0), Op->getOperand(1),
1353                       Op->getOperand(2));
1354  case Intrinsic::mips_ftrunc_u_w:
1355  case Intrinsic::mips_ftrunc_u_d:
1356    return DAG.getNode(ISD::FP_TO_UINT, DL, Op->getValueType(0),
1357                       Op->getOperand(1));
1358  case Intrinsic::mips_ftrunc_s_w:
1359  case Intrinsic::mips_ftrunc_s_d:
1360    return DAG.getNode(ISD::FP_TO_SINT, DL, Op->getValueType(0),
1361                       Op->getOperand(1));
1362  case Intrinsic::mips_ilvev_b:
1363  case Intrinsic::mips_ilvev_h:
1364  case Intrinsic::mips_ilvev_w:
1365  case Intrinsic::mips_ilvev_d:
1366    return DAG.getNode(MipsISD::ILVEV, DL, Op->getValueType(0),
1367                       Op->getOperand(1), Op->getOperand(2));
1368  case Intrinsic::mips_ilvl_b:
1369  case Intrinsic::mips_ilvl_h:
1370  case Intrinsic::mips_ilvl_w:
1371  case Intrinsic::mips_ilvl_d:
1372    return DAG.getNode(MipsISD::ILVL, DL, Op->getValueType(0),
1373                       Op->getOperand(1), Op->getOperand(2));
1374  case Intrinsic::mips_ilvod_b:
1375  case Intrinsic::mips_ilvod_h:
1376  case Intrinsic::mips_ilvod_w:
1377  case Intrinsic::mips_ilvod_d:
1378    return DAG.getNode(MipsISD::ILVOD, DL, Op->getValueType(0),
1379                       Op->getOperand(1), Op->getOperand(2));
1380  case Intrinsic::mips_ilvr_b:
1381  case Intrinsic::mips_ilvr_h:
1382  case Intrinsic::mips_ilvr_w:
1383  case Intrinsic::mips_ilvr_d:
1384    return DAG.getNode(MipsISD::ILVR, DL, Op->getValueType(0),
1385                       Op->getOperand(1), Op->getOperand(2));
1386  case Intrinsic::mips_insert_b:
1387  case Intrinsic::mips_insert_h:
1388  case Intrinsic::mips_insert_w:
1389  case Intrinsic::mips_insert_d:
1390    return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), Op->getValueType(0),
1391                       Op->getOperand(1), Op->getOperand(3), Op->getOperand(2));
1392  case Intrinsic::mips_ldi_b:
1393  case Intrinsic::mips_ldi_h:
1394  case Intrinsic::mips_ldi_w:
1395  case Intrinsic::mips_ldi_d:
1396    return lowerMSASplatImm(Op, 1, DAG);
1397  case Intrinsic::mips_max_s_b:
1398  case Intrinsic::mips_max_s_h:
1399  case Intrinsic::mips_max_s_w:
1400  case Intrinsic::mips_max_s_d:
1401    return DAG.getNode(MipsISD::VSMAX, DL, Op->getValueType(0),
1402                       Op->getOperand(1), Op->getOperand(2));
1403  case Intrinsic::mips_max_u_b:
1404  case Intrinsic::mips_max_u_h:
1405  case Intrinsic::mips_max_u_w:
1406  case Intrinsic::mips_max_u_d:
1407    return DAG.getNode(MipsISD::VUMAX, DL, Op->getValueType(0),
1408                       Op->getOperand(1), Op->getOperand(2));
1409  case Intrinsic::mips_maxi_s_b:
1410  case Intrinsic::mips_maxi_s_h:
1411  case Intrinsic::mips_maxi_s_w:
1412  case Intrinsic::mips_maxi_s_d:
1413    return DAG.getNode(MipsISD::VSMAX, DL, Op->getValueType(0),
1414                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1415  case Intrinsic::mips_maxi_u_b:
1416  case Intrinsic::mips_maxi_u_h:
1417  case Intrinsic::mips_maxi_u_w:
1418  case Intrinsic::mips_maxi_u_d:
1419    return DAG.getNode(MipsISD::VUMAX, DL, Op->getValueType(0),
1420                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1421  case Intrinsic::mips_min_s_b:
1422  case Intrinsic::mips_min_s_h:
1423  case Intrinsic::mips_min_s_w:
1424  case Intrinsic::mips_min_s_d:
1425    return DAG.getNode(MipsISD::VSMIN, DL, Op->getValueType(0),
1426                       Op->getOperand(1), Op->getOperand(2));
1427  case Intrinsic::mips_min_u_b:
1428  case Intrinsic::mips_min_u_h:
1429  case Intrinsic::mips_min_u_w:
1430  case Intrinsic::mips_min_u_d:
1431    return DAG.getNode(MipsISD::VUMIN, DL, Op->getValueType(0),
1432                       Op->getOperand(1), Op->getOperand(2));
1433  case Intrinsic::mips_mini_s_b:
1434  case Intrinsic::mips_mini_s_h:
1435  case Intrinsic::mips_mini_s_w:
1436  case Intrinsic::mips_mini_s_d:
1437    return DAG.getNode(MipsISD::VSMIN, DL, Op->getValueType(0),
1438                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1439  case Intrinsic::mips_mini_u_b:
1440  case Intrinsic::mips_mini_u_h:
1441  case Intrinsic::mips_mini_u_w:
1442  case Intrinsic::mips_mini_u_d:
1443    return DAG.getNode(MipsISD::VUMIN, DL, Op->getValueType(0),
1444                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1445  case Intrinsic::mips_mod_s_b:
1446  case Intrinsic::mips_mod_s_h:
1447  case Intrinsic::mips_mod_s_w:
1448  case Intrinsic::mips_mod_s_d:
1449    return DAG.getNode(ISD::SREM, DL, Op->getValueType(0), Op->getOperand(1),
1450                       Op->getOperand(2));
1451  case Intrinsic::mips_mod_u_b:
1452  case Intrinsic::mips_mod_u_h:
1453  case Intrinsic::mips_mod_u_w:
1454  case Intrinsic::mips_mod_u_d:
1455    return DAG.getNode(ISD::UREM, DL, Op->getValueType(0), Op->getOperand(1),
1456                       Op->getOperand(2));
1457  case Intrinsic::mips_mulv_b:
1458  case Intrinsic::mips_mulv_h:
1459  case Intrinsic::mips_mulv_w:
1460  case Intrinsic::mips_mulv_d:
1461    return DAG.getNode(ISD::MUL, DL, Op->getValueType(0), Op->getOperand(1),
1462                       Op->getOperand(2));
1463  case Intrinsic::mips_nlzc_b:
1464  case Intrinsic::mips_nlzc_h:
1465  case Intrinsic::mips_nlzc_w:
1466  case Intrinsic::mips_nlzc_d:
1467    return DAG.getNode(ISD::CTLZ, DL, Op->getValueType(0), Op->getOperand(1));
1468  case Intrinsic::mips_nor_v: {
1469    SDValue Res = DAG.getNode(ISD::OR, DL, Op->getValueType(0),
1470                              Op->getOperand(1), Op->getOperand(2));
1471    return DAG.getNOT(DL, Res, Res->getValueType(0));
1472  }
1473  case Intrinsic::mips_nori_b: {
1474    SDValue Res =  DAG.getNode(ISD::OR, DL, Op->getValueType(0),
1475                               Op->getOperand(1),
1476                               lowerMSASplatImm(Op, 2, DAG));
1477    return DAG.getNOT(DL, Res, Res->getValueType(0));
1478  }
1479  case Intrinsic::mips_or_v:
1480    return DAG.getNode(ISD::OR, DL, Op->getValueType(0), Op->getOperand(1),
1481                       Op->getOperand(2));
1482  case Intrinsic::mips_ori_b:
1483    return DAG.getNode(ISD::OR, DL, Op->getValueType(0),
1484                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1485  case Intrinsic::mips_pckev_b:
1486  case Intrinsic::mips_pckev_h:
1487  case Intrinsic::mips_pckev_w:
1488  case Intrinsic::mips_pckev_d:
1489    return DAG.getNode(MipsISD::PCKEV, DL, Op->getValueType(0),
1490                       Op->getOperand(1), Op->getOperand(2));
1491  case Intrinsic::mips_pckod_b:
1492  case Intrinsic::mips_pckod_h:
1493  case Intrinsic::mips_pckod_w:
1494  case Intrinsic::mips_pckod_d:
1495    return DAG.getNode(MipsISD::PCKOD, DL, Op->getValueType(0),
1496                       Op->getOperand(1), Op->getOperand(2));
1497  case Intrinsic::mips_pcnt_b:
1498  case Intrinsic::mips_pcnt_h:
1499  case Intrinsic::mips_pcnt_w:
1500  case Intrinsic::mips_pcnt_d:
1501    return DAG.getNode(ISD::CTPOP, DL, Op->getValueType(0), Op->getOperand(1));
1502  case Intrinsic::mips_shf_b:
1503  case Intrinsic::mips_shf_h:
1504  case Intrinsic::mips_shf_w:
1505    return DAG.getNode(MipsISD::SHF, DL, Op->getValueType(0),
1506                       Op->getOperand(2), Op->getOperand(1));
1507  case Intrinsic::mips_sll_b:
1508  case Intrinsic::mips_sll_h:
1509  case Intrinsic::mips_sll_w:
1510  case Intrinsic::mips_sll_d:
1511    return DAG.getNode(ISD::SHL, DL, Op->getValueType(0), Op->getOperand(1),
1512                       Op->getOperand(2));
1513  case Intrinsic::mips_slli_b:
1514  case Intrinsic::mips_slli_h:
1515  case Intrinsic::mips_slli_w:
1516  case Intrinsic::mips_slli_d:
1517    return DAG.getNode(ISD::SHL, DL, Op->getValueType(0),
1518                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1519  case Intrinsic::mips_splati_b:
1520  case Intrinsic::mips_splati_h:
1521  case Intrinsic::mips_splati_w:
1522  case Intrinsic::mips_splati_d:
1523    return DAG.getNode(MipsISD::VSHF, DL, Op->getValueType(0),
1524                       lowerMSASplatImm(Op, 2, DAG), Op->getOperand(1),
1525                       Op->getOperand(1));
1526  case Intrinsic::mips_sra_b:
1527  case Intrinsic::mips_sra_h:
1528  case Intrinsic::mips_sra_w:
1529  case Intrinsic::mips_sra_d:
1530    return DAG.getNode(ISD::SRA, DL, Op->getValueType(0), Op->getOperand(1),
1531                       Op->getOperand(2));
1532  case Intrinsic::mips_srai_b:
1533  case Intrinsic::mips_srai_h:
1534  case Intrinsic::mips_srai_w:
1535  case Intrinsic::mips_srai_d:
1536    return DAG.getNode(ISD::SRA, DL, Op->getValueType(0),
1537                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1538  case Intrinsic::mips_srl_b:
1539  case Intrinsic::mips_srl_h:
1540  case Intrinsic::mips_srl_w:
1541  case Intrinsic::mips_srl_d:
1542    return DAG.getNode(ISD::SRL, DL, Op->getValueType(0), Op->getOperand(1),
1543                       Op->getOperand(2));
1544  case Intrinsic::mips_srli_b:
1545  case Intrinsic::mips_srli_h:
1546  case Intrinsic::mips_srli_w:
1547  case Intrinsic::mips_srli_d:
1548    return DAG.getNode(ISD::SRL, DL, Op->getValueType(0),
1549                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1550  case Intrinsic::mips_subv_b:
1551  case Intrinsic::mips_subv_h:
1552  case Intrinsic::mips_subv_w:
1553  case Intrinsic::mips_subv_d:
1554    return DAG.getNode(ISD::SUB, DL, Op->getValueType(0), Op->getOperand(1),
1555                       Op->getOperand(2));
1556  case Intrinsic::mips_subvi_b:
1557  case Intrinsic::mips_subvi_h:
1558  case Intrinsic::mips_subvi_w:
1559  case Intrinsic::mips_subvi_d:
1560    return DAG.getNode(ISD::SUB, DL, Op->getValueType(0),
1561                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1562  case Intrinsic::mips_vshf_b:
1563  case Intrinsic::mips_vshf_h:
1564  case Intrinsic::mips_vshf_w:
1565  case Intrinsic::mips_vshf_d:
1566    return DAG.getNode(MipsISD::VSHF, DL, Op->getValueType(0),
1567                       Op->getOperand(1), Op->getOperand(2), Op->getOperand(3));
1568  case Intrinsic::mips_xor_v:
1569    return DAG.getNode(ISD::XOR, DL, Op->getValueType(0), Op->getOperand(1),
1570                       Op->getOperand(2));
1571  case Intrinsic::mips_xori_b:
1572    return DAG.getNode(ISD::XOR, DL, Op->getValueType(0),
1573                       Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1574  }
1575}
1576
1577static SDValue lowerMSALoadIntr(SDValue Op, SelectionDAG &DAG, unsigned Intr) {
1578  SDLoc DL(Op);
1579  SDValue ChainIn = Op->getOperand(0);
1580  SDValue Address = Op->getOperand(2);
1581  SDValue Offset  = Op->getOperand(3);
1582  EVT ResTy = Op->getValueType(0);
1583  EVT PtrTy = Address->getValueType(0);
1584
1585  Address = DAG.getNode(ISD::ADD, DL, PtrTy, Address, Offset);
1586
1587  return DAG.getLoad(ResTy, DL, ChainIn, Address, MachinePointerInfo(), false,
1588                     false, false, 16);
1589}
1590
1591SDValue MipsSETargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
1592                                                     SelectionDAG &DAG) const {
1593  unsigned Intr = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1594  switch (Intr) {
1595  default:
1596    return SDValue();
1597  case Intrinsic::mips_extp:
1598    return lowerDSPIntr(Op, DAG, MipsISD::EXTP);
1599  case Intrinsic::mips_extpdp:
1600    return lowerDSPIntr(Op, DAG, MipsISD::EXTPDP);
1601  case Intrinsic::mips_extr_w:
1602    return lowerDSPIntr(Op, DAG, MipsISD::EXTR_W);
1603  case Intrinsic::mips_extr_r_w:
1604    return lowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W);
1605  case Intrinsic::mips_extr_rs_w:
1606    return lowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W);
1607  case Intrinsic::mips_extr_s_h:
1608    return lowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H);
1609  case Intrinsic::mips_mthlip:
1610    return lowerDSPIntr(Op, DAG, MipsISD::MTHLIP);
1611  case Intrinsic::mips_mulsaq_s_w_ph:
1612    return lowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH);
1613  case Intrinsic::mips_maq_s_w_phl:
1614    return lowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL);
1615  case Intrinsic::mips_maq_s_w_phr:
1616    return lowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR);
1617  case Intrinsic::mips_maq_sa_w_phl:
1618    return lowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL);
1619  case Intrinsic::mips_maq_sa_w_phr:
1620    return lowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR);
1621  case Intrinsic::mips_dpaq_s_w_ph:
1622    return lowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH);
1623  case Intrinsic::mips_dpsq_s_w_ph:
1624    return lowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH);
1625  case Intrinsic::mips_dpaq_sa_l_w:
1626    return lowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W);
1627  case Intrinsic::mips_dpsq_sa_l_w:
1628    return lowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W);
1629  case Intrinsic::mips_dpaqx_s_w_ph:
1630    return lowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH);
1631  case Intrinsic::mips_dpaqx_sa_w_ph:
1632    return lowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH);
1633  case Intrinsic::mips_dpsqx_s_w_ph:
1634    return lowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH);
1635  case Intrinsic::mips_dpsqx_sa_w_ph:
1636    return lowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH);
1637  case Intrinsic::mips_ld_b:
1638  case Intrinsic::mips_ld_h:
1639  case Intrinsic::mips_ld_w:
1640  case Intrinsic::mips_ld_d:
1641  case Intrinsic::mips_ldx_b:
1642  case Intrinsic::mips_ldx_h:
1643  case Intrinsic::mips_ldx_w:
1644  case Intrinsic::mips_ldx_d:
1645   return lowerMSALoadIntr(Op, DAG, Intr);
1646  }
1647}
1648
1649static SDValue lowerMSAStoreIntr(SDValue Op, SelectionDAG &DAG, unsigned Intr) {
1650  SDLoc DL(Op);
1651  SDValue ChainIn = Op->getOperand(0);
1652  SDValue Value   = Op->getOperand(2);
1653  SDValue Address = Op->getOperand(3);
1654  SDValue Offset  = Op->getOperand(4);
1655  EVT PtrTy = Address->getValueType(0);
1656
1657  Address = DAG.getNode(ISD::ADD, DL, PtrTy, Address, Offset);
1658
1659  return DAG.getStore(ChainIn, DL, Value, Address, MachinePointerInfo(), false,
1660                      false, 16);
1661}
1662
1663SDValue MipsSETargetLowering::lowerINTRINSIC_VOID(SDValue Op,
1664                                                  SelectionDAG &DAG) const {
1665  unsigned Intr = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1666  switch (Intr) {
1667  default:
1668    return SDValue();
1669  case Intrinsic::mips_st_b:
1670  case Intrinsic::mips_st_h:
1671  case Intrinsic::mips_st_w:
1672  case Intrinsic::mips_st_d:
1673  case Intrinsic::mips_stx_b:
1674  case Intrinsic::mips_stx_h:
1675  case Intrinsic::mips_stx_w:
1676  case Intrinsic::mips_stx_d:
1677    return lowerMSAStoreIntr(Op, DAG, Intr);
1678  }
1679}
1680
1681/// \brief Check if the given BuildVectorSDNode is a splat.
1682/// This method currently relies on DAG nodes being reused when equivalent,
1683/// so it's possible for this to return false even when isConstantSplat returns
1684/// true.
1685static bool isSplatVector(const BuildVectorSDNode *N) {
1686  unsigned int nOps = N->getNumOperands();
1687  assert(nOps > 1 && "isSplat has 0 or 1 sized build vector");
1688
1689  SDValue Operand0 = N->getOperand(0);
1690
1691  for (unsigned int i = 1; i < nOps; ++i) {
1692    if (N->getOperand(i) != Operand0)
1693      return false;
1694  }
1695
1696  return true;
1697}
1698
1699// Lower ISD::EXTRACT_VECTOR_ELT into MipsISD::VEXTRACT_SEXT_ELT.
1700//
1701// The non-value bits resulting from ISD::EXTRACT_VECTOR_ELT are undefined. We
1702// choose to sign-extend but we could have equally chosen zero-extend. The
1703// DAGCombiner will fold any sign/zero extension of the ISD::EXTRACT_VECTOR_ELT
1704// result into this node later (possibly changing it to a zero-extend in the
1705// process).
1706SDValue MipsSETargetLowering::
1707lowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
1708  SDLoc DL(Op);
1709  EVT ResTy = Op->getValueType(0);
1710  SDValue Op0 = Op->getOperand(0);
1711  EVT VecTy = Op0->getValueType(0);
1712
1713  if (!VecTy.is128BitVector())
1714    return SDValue();
1715
1716  if (ResTy.isInteger()) {
1717    SDValue Op1 = Op->getOperand(1);
1718    EVT EltTy = VecTy.getVectorElementType();
1719    return DAG.getNode(MipsISD::VEXTRACT_SEXT_ELT, DL, ResTy, Op0, Op1,
1720                       DAG.getValueType(EltTy));
1721  }
1722
1723  return Op;
1724}
1725
1726static bool isConstantOrUndef(const SDValue Op) {
1727  if (Op->getOpcode() == ISD::UNDEF)
1728    return true;
1729  if (dyn_cast<ConstantSDNode>(Op))
1730    return true;
1731  if (dyn_cast<ConstantFPSDNode>(Op))
1732    return true;
1733  return false;
1734}
1735
1736static bool isConstantOrUndefBUILD_VECTOR(const BuildVectorSDNode *Op) {
1737  for (unsigned i = 0; i < Op->getNumOperands(); ++i)
1738    if (isConstantOrUndef(Op->getOperand(i)))
1739      return true;
1740  return false;
1741}
1742
1743// Lowers ISD::BUILD_VECTOR into appropriate SelectionDAG nodes for the
1744// backend.
1745//
1746// Lowers according to the following rules:
1747// - Constant splats are legal as-is as long as the SplatBitSize is a power of
1748//   2 less than or equal to 64 and the value fits into a signed 10-bit
1749//   immediate
1750// - Constant splats are lowered to bitconverted BUILD_VECTORs if SplatBitSize
1751//   is a power of 2 less than or equal to 64 and the value does not fit into a
1752//   signed 10-bit immediate
1753// - Non-constant splats are legal as-is.
1754// - Non-constant non-splats are lowered to sequences of INSERT_VECTOR_ELT.
1755// - All others are illegal and must be expanded.
1756SDValue MipsSETargetLowering::lowerBUILD_VECTOR(SDValue Op,
1757                                                SelectionDAG &DAG) const {
1758  BuildVectorSDNode *Node = cast<BuildVectorSDNode>(Op);
1759  EVT ResTy = Op->getValueType(0);
1760  SDLoc DL(Op);
1761  APInt SplatValue, SplatUndef;
1762  unsigned SplatBitSize;
1763  bool HasAnyUndefs;
1764
1765  if (!Subtarget->hasMSA() || !ResTy.is128BitVector())
1766    return SDValue();
1767
1768  if (Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1769                            HasAnyUndefs, 8,
1770                            !Subtarget->isLittle()) && SplatBitSize <= 64) {
1771    // We can only cope with 8, 16, 32, or 64-bit elements
1772    if (SplatBitSize != 8 && SplatBitSize != 16 && SplatBitSize != 32 &&
1773        SplatBitSize != 64)
1774      return SDValue();
1775
1776    // If the value fits into a simm10 then we can use ldi.[bhwd]
1777    if (SplatValue.isSignedIntN(10))
1778      return Op;
1779
1780    EVT ViaVecTy;
1781
1782    switch (SplatBitSize) {
1783    default:
1784      return SDValue();
1785    case 8:
1786      ViaVecTy = MVT::v16i8;
1787      break;
1788    case 16:
1789      ViaVecTy = MVT::v8i16;
1790      break;
1791    case 32:
1792      ViaVecTy = MVT::v4i32;
1793      break;
1794    case 64:
1795      // There's no fill.d to fall back on for 64-bit values
1796      return SDValue();
1797    }
1798
1799    SmallVector<SDValue, 16> Ops;
1800    SDValue Constant = DAG.getConstant(SplatValue.sextOrSelf(32), MVT::i32);
1801
1802    for (unsigned i = 0; i < ViaVecTy.getVectorNumElements(); ++i)
1803      Ops.push_back(Constant);
1804
1805    SDValue Result = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Node), ViaVecTy,
1806                                 &Ops[0], Ops.size());
1807
1808    if (ViaVecTy != ResTy)
1809      Result = DAG.getNode(ISD::BITCAST, SDLoc(Node), ResTy, Result);
1810
1811    return Result;
1812  } else if (isSplatVector(Node))
1813    return Op;
1814  else if (!isConstantOrUndefBUILD_VECTOR(Node)) {
1815    // Use INSERT_VECTOR_ELT operations rather than expand to stores.
1816    // The resulting code is the same length as the expansion, but it doesn't
1817    // use memory operations
1818    EVT ResTy = Node->getValueType(0);
1819
1820    assert(ResTy.isVector());
1821
1822    unsigned NumElts = ResTy.getVectorNumElements();
1823    SDValue Vector = DAG.getUNDEF(ResTy);
1824    for (unsigned i = 0; i < NumElts; ++i) {
1825      Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ResTy, Vector,
1826                           Node->getOperand(i),
1827                           DAG.getConstant(i, MVT::i32));
1828    }
1829    return Vector;
1830  }
1831
1832  return SDValue();
1833}
1834
1835// Lower VECTOR_SHUFFLE into SHF (if possible).
1836//
1837// SHF splits the vector into blocks of four elements, then shuffles these
1838// elements according to a <4 x i2> constant (encoded as an integer immediate).
1839//
1840// It is therefore possible to lower into SHF when the mask takes the form:
1841//   <a, b, c, d, a+4, b+4, c+4, d+4, a+8, b+8, c+8, d+8, ...>
1842// When undef's appear they are treated as if they were whatever value is
1843// necessary in order to fit the above form.
1844//
1845// For example:
1846//   %2 = shufflevector <8 x i16> %0, <8 x i16> undef,
1847//                      <8 x i32> <i32 3, i32 2, i32 1, i32 0,
1848//                                 i32 7, i32 6, i32 5, i32 4>
1849// is lowered to:
1850//   (SHF_H $w0, $w1, 27)
1851// where the 27 comes from:
1852//   3 + (2 << 2) + (1 << 4) + (0 << 6)
1853static SDValue lowerVECTOR_SHUFFLE_SHF(SDValue Op, EVT ResTy,
1854                                       SmallVector<int, 16> Indices,
1855                                       SelectionDAG &DAG) {
1856  int SHFIndices[4] = { -1, -1, -1, -1 };
1857
1858  if (Indices.size() < 4)
1859    return SDValue();
1860
1861  for (unsigned i = 0; i < 4; ++i) {
1862    for (unsigned j = i; j < Indices.size(); j += 4) {
1863      int Idx = Indices[j];
1864
1865      // Convert from vector index to 4-element subvector index
1866      // If an index refers to an element outside of the subvector then give up
1867      if (Idx != -1) {
1868        Idx -= 4 * (j / 4);
1869        if (Idx < 0 || Idx >= 4)
1870          return SDValue();
1871      }
1872
1873      // If the mask has an undef, replace it with the current index.
1874      // Note that it might still be undef if the current index is also undef
1875      if (SHFIndices[i] == -1)
1876        SHFIndices[i] = Idx;
1877
1878      // Check that non-undef values are the same as in the mask. If they
1879      // aren't then give up
1880      if (!(Idx == -1 || Idx == SHFIndices[i]))
1881        return SDValue();
1882    }
1883  }
1884
1885  // Calculate the immediate. Replace any remaining undefs with zero
1886  APInt Imm(32, 0);
1887  for (int i = 3; i >= 0; --i) {
1888    int Idx = SHFIndices[i];
1889
1890    if (Idx == -1)
1891      Idx = 0;
1892
1893    Imm <<= 2;
1894    Imm |= Idx & 0x3;
1895  }
1896
1897  return DAG.getNode(MipsISD::SHF, SDLoc(Op), ResTy,
1898                     DAG.getConstant(Imm, MVT::i32), Op->getOperand(0));
1899}
1900
1901// Lower VECTOR_SHUFFLE into ILVEV (if possible).
1902//
1903// ILVEV interleaves the even elements from each vector.
1904//
1905// It is possible to lower into ILVEV when the mask takes the form:
1906//   <0, n, 2, n+2, 4, n+4, ...>
1907// where n is the number of elements in the vector.
1908//
1909// When undef's appear in the mask they are treated as if they were whatever
1910// value is necessary in order to fit the above form.
1911static SDValue lowerVECTOR_SHUFFLE_ILVEV(SDValue Op, EVT ResTy,
1912                                         SmallVector<int, 16> Indices,
1913                                         SelectionDAG &DAG) {
1914  assert ((Indices.size() % 2) == 0);
1915  int WsIdx = 0;
1916  int WtIdx = ResTy.getVectorNumElements();
1917
1918  for (unsigned i = 0; i < Indices.size(); i += 2) {
1919    if (Indices[i] != -1 && Indices[i] != WsIdx)
1920      return SDValue();
1921    if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
1922      return SDValue();
1923    WsIdx += 2;
1924    WtIdx += 2;
1925  }
1926
1927  return DAG.getNode(MipsISD::ILVEV, SDLoc(Op), ResTy, Op->getOperand(0),
1928                     Op->getOperand(1));
1929}
1930
1931// Lower VECTOR_SHUFFLE into ILVOD (if possible).
1932//
1933// ILVOD interleaves the odd elements from each vector.
1934//
1935// It is possible to lower into ILVOD when the mask takes the form:
1936//   <1, n+1, 3, n+3, 5, n+5, ...>
1937// where n is the number of elements in the vector.
1938//
1939// When undef's appear in the mask they are treated as if they were whatever
1940// value is necessary in order to fit the above form.
1941static SDValue lowerVECTOR_SHUFFLE_ILVOD(SDValue Op, EVT ResTy,
1942                                         SmallVector<int, 16> Indices,
1943                                         SelectionDAG &DAG) {
1944  assert ((Indices.size() % 2) == 0);
1945  int WsIdx = 1;
1946  int WtIdx = ResTy.getVectorNumElements() + 1;
1947
1948  for (unsigned i = 0; i < Indices.size(); i += 2) {
1949    if (Indices[i] != -1 && Indices[i] != WsIdx)
1950      return SDValue();
1951    if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
1952      return SDValue();
1953    WsIdx += 2;
1954    WtIdx += 2;
1955  }
1956
1957  return DAG.getNode(MipsISD::ILVOD, SDLoc(Op), ResTy, Op->getOperand(0),
1958                     Op->getOperand(1));
1959}
1960
1961// Lower VECTOR_SHUFFLE into ILVL (if possible).
1962//
1963// ILVL interleaves consecutive elements from the left half of each vector.
1964//
1965// It is possible to lower into ILVL when the mask takes the form:
1966//   <0, n, 1, n+1, 2, n+2, ...>
1967// where n is the number of elements in the vector.
1968//
1969// When undef's appear in the mask they are treated as if they were whatever
1970// value is necessary in order to fit the above form.
1971static SDValue lowerVECTOR_SHUFFLE_ILVL(SDValue Op, EVT ResTy,
1972                                        SmallVector<int, 16> Indices,
1973                                        SelectionDAG &DAG) {
1974  assert ((Indices.size() % 2) == 0);
1975  int WsIdx = 0;
1976  int WtIdx = ResTy.getVectorNumElements();
1977
1978  for (unsigned i = 0; i < Indices.size(); i += 2) {
1979    if (Indices[i] != -1 && Indices[i] != WsIdx)
1980      return SDValue();
1981    if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
1982      return SDValue();
1983    WsIdx ++;
1984    WtIdx ++;
1985  }
1986
1987  return DAG.getNode(MipsISD::ILVL, SDLoc(Op), ResTy, Op->getOperand(0),
1988                     Op->getOperand(1));
1989}
1990
1991// Lower VECTOR_SHUFFLE into ILVR (if possible).
1992//
1993// ILVR interleaves consecutive elements from the right half of each vector.
1994//
1995// It is possible to lower into ILVR when the mask takes the form:
1996//   <x, n+x, x+1, n+x+1, x+2, n+x+2, ...>
1997// where n is the number of elements in the vector and x is half n.
1998//
1999// When undef's appear in the mask they are treated as if they were whatever
2000// value is necessary in order to fit the above form.
2001static SDValue lowerVECTOR_SHUFFLE_ILVR(SDValue Op, EVT ResTy,
2002                                        SmallVector<int, 16> Indices,
2003                                        SelectionDAG &DAG) {
2004  assert ((Indices.size() % 2) == 0);
2005  unsigned NumElts = ResTy.getVectorNumElements();
2006  int WsIdx = NumElts / 2;
2007  int WtIdx = NumElts + NumElts / 2;
2008
2009  for (unsigned i = 0; i < Indices.size(); i += 2) {
2010    if (Indices[i] != -1 && Indices[i] != WsIdx)
2011      return SDValue();
2012    if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2013      return SDValue();
2014    WsIdx ++;
2015    WtIdx ++;
2016  }
2017
2018  return DAG.getNode(MipsISD::ILVR, SDLoc(Op), ResTy, Op->getOperand(0),
2019                     Op->getOperand(1));
2020}
2021
2022// Lower VECTOR_SHUFFLE into PCKEV (if possible).
2023//
2024// PCKEV copies the even elements of each vector into the result vector.
2025//
2026// It is possible to lower into PCKEV when the mask takes the form:
2027//   <0, 2, 4, ..., n, n+2, n+4, ...>
2028// where n is the number of elements in the vector.
2029//
2030// When undef's appear in the mask they are treated as if they were whatever
2031// value is necessary in order to fit the above form.
2032static SDValue lowerVECTOR_SHUFFLE_PCKEV(SDValue Op, EVT ResTy,
2033                                         SmallVector<int, 16> Indices,
2034                                         SelectionDAG &DAG) {
2035  assert ((Indices.size() % 2) == 0);
2036  int Idx = 0;
2037
2038  for (unsigned i = 0; i < Indices.size(); ++i) {
2039    if (Indices[i] != -1 && Indices[i] != Idx)
2040      return SDValue();
2041    Idx += 2;
2042  }
2043
2044  return DAG.getNode(MipsISD::PCKEV, SDLoc(Op), ResTy, Op->getOperand(0),
2045                     Op->getOperand(1));
2046}
2047
2048// Lower VECTOR_SHUFFLE into PCKOD (if possible).
2049//
2050// PCKOD copies the odd elements of each vector into the result vector.
2051//
2052// It is possible to lower into PCKOD when the mask takes the form:
2053//   <1, 3, 5, ..., n+1, n+3, n+5, ...>
2054// where n is the number of elements in the vector.
2055//
2056// When undef's appear in the mask they are treated as if they were whatever
2057// value is necessary in order to fit the above form.
2058static SDValue lowerVECTOR_SHUFFLE_PCKOD(SDValue Op, EVT ResTy,
2059                                         SmallVector<int, 16> Indices,
2060                                         SelectionDAG &DAG) {
2061  assert ((Indices.size() % 2) == 0);
2062  int Idx = 1;
2063
2064  for (unsigned i = 0; i < Indices.size(); ++i) {
2065    if (Indices[i] != -1 && Indices[i] != Idx)
2066      return SDValue();
2067    Idx += 2;
2068  }
2069
2070  return DAG.getNode(MipsISD::PCKOD, SDLoc(Op), ResTy, Op->getOperand(0),
2071                     Op->getOperand(1));
2072}
2073
2074// Lower VECTOR_SHUFFLE into VSHF.
2075//
2076// This mostly consists of converting the shuffle indices in Indices into a
2077// BUILD_VECTOR and adding it as an operand to the resulting VSHF. There is
2078// also code to eliminate unused operands of the VECTOR_SHUFFLE. For example,
2079// if the type is v8i16 and all the indices are less than 8 then the second
2080// operand is unused and can be replaced with anything. We choose to replace it
2081// with the used operand since this reduces the number of instructions overall.
2082static SDValue lowerVECTOR_SHUFFLE_VSHF(SDValue Op, EVT ResTy,
2083                                        SmallVector<int, 16> Indices,
2084                                        SelectionDAG &DAG) {
2085  SmallVector<SDValue, 16> Ops;
2086  SDValue Op0;
2087  SDValue Op1;
2088  EVT MaskVecTy = ResTy.changeVectorElementTypeToInteger();
2089  EVT MaskEltTy = MaskVecTy.getVectorElementType();
2090  bool Using1stVec = false;
2091  bool Using2ndVec = false;
2092  SDLoc DL(Op);
2093  int ResTyNumElts = ResTy.getVectorNumElements();
2094
2095  for (int i = 0; i < ResTyNumElts; ++i) {
2096    // Idx == -1 means UNDEF
2097    int Idx = Indices[i];
2098
2099    if (0 <= Idx && Idx < ResTyNumElts)
2100      Using1stVec = true;
2101    if (ResTyNumElts <= Idx && Idx < ResTyNumElts * 2)
2102      Using2ndVec = true;
2103  }
2104
2105  for (SmallVector<int, 16>::iterator I = Indices.begin(); I != Indices.end();
2106       ++I)
2107    Ops.push_back(DAG.getTargetConstant(*I, MaskEltTy));
2108
2109  SDValue MaskVec = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecTy, &Ops[0],
2110                                Ops.size());
2111
2112  if (Using1stVec && Using2ndVec) {
2113    Op0 = Op->getOperand(0);
2114    Op1 = Op->getOperand(1);
2115  } else if (Using1stVec)
2116    Op0 = Op1 = Op->getOperand(0);
2117  else if (Using2ndVec)
2118    Op0 = Op1 = Op->getOperand(1);
2119  else
2120    llvm_unreachable("shuffle vector mask references neither vector operand?");
2121
2122  return DAG.getNode(MipsISD::VSHF, DL, ResTy, MaskVec, Op0, Op1);
2123}
2124
2125// Lower VECTOR_SHUFFLE into one of a number of instructions depending on the
2126// indices in the shuffle.
2127SDValue MipsSETargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
2128                                                  SelectionDAG &DAG) const {
2129  ShuffleVectorSDNode *Node = cast<ShuffleVectorSDNode>(Op);
2130  EVT ResTy = Op->getValueType(0);
2131
2132  if (!ResTy.is128BitVector())
2133    return SDValue();
2134
2135  int ResTyNumElts = ResTy.getVectorNumElements();
2136  SmallVector<int, 16> Indices;
2137
2138  for (int i = 0; i < ResTyNumElts; ++i)
2139    Indices.push_back(Node->getMaskElt(i));
2140
2141  SDValue Result = lowerVECTOR_SHUFFLE_SHF(Op, ResTy, Indices, DAG);
2142  if (Result.getNode())
2143    return Result;
2144  Result = lowerVECTOR_SHUFFLE_ILVEV(Op, ResTy, Indices, DAG);
2145  if (Result.getNode())
2146    return Result;
2147  Result = lowerVECTOR_SHUFFLE_ILVOD(Op, ResTy, Indices, DAG);
2148  if (Result.getNode())
2149    return Result;
2150  Result = lowerVECTOR_SHUFFLE_ILVL(Op, ResTy, Indices, DAG);
2151  if (Result.getNode())
2152    return Result;
2153  Result = lowerVECTOR_SHUFFLE_ILVR(Op, ResTy, Indices, DAG);
2154  if (Result.getNode())
2155    return Result;
2156  Result = lowerVECTOR_SHUFFLE_PCKEV(Op, ResTy, Indices, DAG);
2157  if (Result.getNode())
2158    return Result;
2159  Result = lowerVECTOR_SHUFFLE_PCKOD(Op, ResTy, Indices, DAG);
2160  if (Result.getNode())
2161    return Result;
2162  return lowerVECTOR_SHUFFLE_VSHF(Op, ResTy, Indices, DAG);
2163}
2164
2165MachineBasicBlock * MipsSETargetLowering::
2166emitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
2167  // $bb:
2168  //  bposge32_pseudo $vr0
2169  //  =>
2170  // $bb:
2171  //  bposge32 $tbb
2172  // $fbb:
2173  //  li $vr2, 0
2174  //  b $sink
2175  // $tbb:
2176  //  li $vr1, 1
2177  // $sink:
2178  //  $vr0 = phi($vr2, $fbb, $vr1, $tbb)
2179
2180  MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2181  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2182  const TargetRegisterClass *RC = &Mips::GPR32RegClass;
2183  DebugLoc DL = MI->getDebugLoc();
2184  const BasicBlock *LLVM_BB = BB->getBasicBlock();
2185  MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
2186  MachineFunction *F = BB->getParent();
2187  MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
2188  MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
2189  MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
2190  F->insert(It, FBB);
2191  F->insert(It, TBB);
2192  F->insert(It, Sink);
2193
2194  // Transfer the remainder of BB and its successor edges to Sink.
2195  Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
2196               BB->end());
2197  Sink->transferSuccessorsAndUpdatePHIs(BB);
2198
2199  // Add successors.
2200  BB->addSuccessor(FBB);
2201  BB->addSuccessor(TBB);
2202  FBB->addSuccessor(Sink);
2203  TBB->addSuccessor(Sink);
2204
2205  // Insert the real bposge32 instruction to $BB.
2206  BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
2207
2208  // Fill $FBB.
2209  unsigned VR2 = RegInfo.createVirtualRegister(RC);
2210  BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
2211    .addReg(Mips::ZERO).addImm(0);
2212  BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
2213
2214  // Fill $TBB.
2215  unsigned VR1 = RegInfo.createVirtualRegister(RC);
2216  BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
2217    .addReg(Mips::ZERO).addImm(1);
2218
2219  // Insert phi function to $Sink.
2220  BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
2221          MI->getOperand(0).getReg())
2222    .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
2223
2224  MI->eraseFromParent();   // The pseudo instruction is gone now.
2225  return Sink;
2226}
2227
2228MachineBasicBlock * MipsSETargetLowering::
2229emitMSACBranchPseudo(MachineInstr *MI, MachineBasicBlock *BB,
2230                     unsigned BranchOp) const{
2231  // $bb:
2232  //  vany_nonzero $rd, $ws
2233  //  =>
2234  // $bb:
2235  //  bnz.b $ws, $tbb
2236  //  b $fbb
2237  // $fbb:
2238  //  li $rd1, 0
2239  //  b $sink
2240  // $tbb:
2241  //  li $rd2, 1
2242  // $sink:
2243  //  $rd = phi($rd1, $fbb, $rd2, $tbb)
2244
2245  MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2246  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2247  const TargetRegisterClass *RC = &Mips::GPR32RegClass;
2248  DebugLoc DL = MI->getDebugLoc();
2249  const BasicBlock *LLVM_BB = BB->getBasicBlock();
2250  MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
2251  MachineFunction *F = BB->getParent();
2252  MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
2253  MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
2254  MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
2255  F->insert(It, FBB);
2256  F->insert(It, TBB);
2257  F->insert(It, Sink);
2258
2259  // Transfer the remainder of BB and its successor edges to Sink.
2260  Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
2261               BB->end());
2262  Sink->transferSuccessorsAndUpdatePHIs(BB);
2263
2264  // Add successors.
2265  BB->addSuccessor(FBB);
2266  BB->addSuccessor(TBB);
2267  FBB->addSuccessor(Sink);
2268  TBB->addSuccessor(Sink);
2269
2270  // Insert the real bnz.b instruction to $BB.
2271  BuildMI(BB, DL, TII->get(BranchOp))
2272    .addReg(MI->getOperand(1).getReg())
2273    .addMBB(TBB);
2274
2275  // Fill $FBB.
2276  unsigned RD1 = RegInfo.createVirtualRegister(RC);
2277  BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), RD1)
2278    .addReg(Mips::ZERO).addImm(0);
2279  BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
2280
2281  // Fill $TBB.
2282  unsigned RD2 = RegInfo.createVirtualRegister(RC);
2283  BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), RD2)
2284    .addReg(Mips::ZERO).addImm(1);
2285
2286  // Insert phi function to $Sink.
2287  BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
2288          MI->getOperand(0).getReg())
2289    .addReg(RD1).addMBB(FBB).addReg(RD2).addMBB(TBB);
2290
2291  MI->eraseFromParent();   // The pseudo instruction is gone now.
2292  return Sink;
2293}
2294
2295// Emit the COPY_FW pseudo instruction.
2296//
2297// copy_fw_pseudo $fd, $ws, n
2298// =>
2299// copy_u_w $rt, $ws, $n
2300// mtc1     $rt, $fd
2301//
2302// When n is zero, the equivalent operation can be performed with (potentially)
2303// zero instructions due to register overlaps. This optimization is never valid
2304// for lane 1 because it would require FR=0 mode which isn't supported by MSA.
2305MachineBasicBlock * MipsSETargetLowering::
2306emitCOPY_FW(MachineInstr *MI, MachineBasicBlock *BB) const{
2307  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2308  MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2309  DebugLoc DL = MI->getDebugLoc();
2310  unsigned Fd = MI->getOperand(0).getReg();
2311  unsigned Ws = MI->getOperand(1).getReg();
2312  unsigned Lane = MI->getOperand(2).getImm();
2313
2314  if (Lane == 0)
2315    BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Ws, 0, Mips::sub_lo);
2316  else {
2317    unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
2318
2319    BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_W), Wt).addReg(Ws).addImm(1);
2320    BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Wt, 0, Mips::sub_lo);
2321  }
2322
2323  MI->eraseFromParent();   // The pseudo instruction is gone now.
2324  return BB;
2325}
2326
2327// Emit the COPY_FD pseudo instruction.
2328//
2329// copy_fd_pseudo $fd, $ws, n
2330// =>
2331// splati.d $wt, $ws, $n
2332// copy $fd, $wt:sub_64
2333//
2334// When n is zero, the equivalent operation can be performed with (potentially)
2335// zero instructions due to register overlaps. This optimization is always
2336// valid because FR=1 mode which is the only supported mode in MSA.
2337MachineBasicBlock * MipsSETargetLowering::
2338emitCOPY_FD(MachineInstr *MI, MachineBasicBlock *BB) const{
2339  assert(Subtarget->isFP64bit());
2340
2341  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2342  MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2343  unsigned Fd  = MI->getOperand(0).getReg();
2344  unsigned Ws  = MI->getOperand(1).getReg();
2345  unsigned Lane = MI->getOperand(2).getImm() * 2;
2346  DebugLoc DL = MI->getDebugLoc();
2347
2348  if (Lane == 0)
2349    BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Ws, 0, Mips::sub_64);
2350  else {
2351    unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
2352
2353    BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_D), Wt).addReg(Ws).addImm(1);
2354    BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Wt, 0, Mips::sub_64);
2355  }
2356
2357  MI->eraseFromParent();   // The pseudo instruction is gone now.
2358  return BB;
2359}
2360
2361// Emit the INSERT_FW pseudo instruction.
2362//
2363// insert_fw_pseudo $wd, $wd_in, $n, $fs
2364// =>
2365// subreg_to_reg $wt:sub_lo, $fs
2366// insve_w $wd[$n], $wd_in, $wt[0]
2367MachineBasicBlock * MipsSETargetLowering::
2368emitINSERT_FW(MachineInstr *MI, MachineBasicBlock *BB) const{
2369  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2370  MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2371  DebugLoc DL = MI->getDebugLoc();
2372  unsigned Wd = MI->getOperand(0).getReg();
2373  unsigned Wd_in = MI->getOperand(1).getReg();
2374  unsigned Lane = MI->getOperand(2).getImm();
2375  unsigned Fs = MI->getOperand(3).getReg();
2376  unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
2377
2378  BuildMI(*BB, MI, DL, TII->get(Mips::SUBREG_TO_REG), Wt)
2379      .addImm(0).addReg(Fs).addImm(Mips::sub_lo);
2380  BuildMI(*BB, MI, DL, TII->get(Mips::INSVE_W), Wd)
2381      .addReg(Wd_in).addImm(Lane).addReg(Wt);
2382
2383  MI->eraseFromParent();   // The pseudo instruction is gone now.
2384  return BB;
2385}
2386
2387// Emit the INSERT_FD pseudo instruction.
2388//
2389// insert_fd_pseudo $wd, $fs, n
2390// =>
2391// subreg_to_reg $wt:sub_64, $fs
2392// insve_d $wd[$n], $wd_in, $wt[0]
2393MachineBasicBlock * MipsSETargetLowering::
2394emitINSERT_FD(MachineInstr *MI, MachineBasicBlock *BB) const{
2395  assert(Subtarget->isFP64bit());
2396
2397  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2398  MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2399  DebugLoc DL = MI->getDebugLoc();
2400  unsigned Wd = MI->getOperand(0).getReg();
2401  unsigned Wd_in = MI->getOperand(1).getReg();
2402  unsigned Lane = MI->getOperand(2).getImm();
2403  unsigned Fs = MI->getOperand(3).getReg();
2404  unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
2405
2406  BuildMI(*BB, MI, DL, TII->get(Mips::SUBREG_TO_REG), Wt)
2407      .addImm(0).addReg(Fs).addImm(Mips::sub_64);
2408  BuildMI(*BB, MI, DL, TII->get(Mips::INSVE_D), Wd)
2409      .addReg(Wd_in).addImm(Lane).addReg(Wt);
2410
2411  MI->eraseFromParent();   // The pseudo instruction is gone now.
2412  return BB;
2413}
2414