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