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