[mips][mips64r6] c.cond.fmt, mov[fntz], and mov[fntz].[ds] are not available on MIPS3...
[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/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23
24 using namespace llvm;
25
26 #define DEBUG_TYPE "mips-isel"
27
28 static cl::opt<bool>
29 EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
30                     cl::desc("MIPS: Enable tail calls."), cl::init(false));
31
32 static cl::opt<bool> NoDPLoadStore("mno-ldc1-sdc1", cl::init(false),
33                                    cl::desc("Expand double precision loads and "
34                                             "stores to their single precision "
35                                             "counterparts"));
36
37 MipsSETargetLowering::MipsSETargetLowering(MipsTargetMachine &TM)
38   : MipsTargetLowering(TM) {
39   // Set up the register classes
40   addRegisterClass(MVT::i32, &Mips::GPR32RegClass);
41
42   if (isGP64bit())
43     addRegisterClass(MVT::i64, &Mips::GPR64RegClass);
44
45   if (Subtarget->hasDSP() || Subtarget->hasMSA()) {
46     // Expand all truncating stores and extending loads.
47     unsigned FirstVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
48     unsigned LastVT = (unsigned)MVT::LAST_VECTOR_VALUETYPE;
49
50     for (unsigned VT0 = FirstVT; VT0 <= LastVT; ++VT0) {
51       for (unsigned VT1 = FirstVT; VT1 <= LastVT; ++VT1)
52         setTruncStoreAction((MVT::SimpleValueType)VT0,
53                             (MVT::SimpleValueType)VT1, Expand);
54
55       setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT0, Expand);
56       setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT0, Expand);
57       setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT0, Expand);
58     }
59   }
60
61   if (Subtarget->hasDSP()) {
62     MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
63
64     for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
65       addRegisterClass(VecTys[i], &Mips::DSPRRegClass);
66
67       // Expand all builtin opcodes.
68       for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
69         setOperationAction(Opc, VecTys[i], Expand);
70
71       setOperationAction(ISD::ADD, VecTys[i], Legal);
72       setOperationAction(ISD::SUB, VecTys[i], Legal);
73       setOperationAction(ISD::LOAD, VecTys[i], Legal);
74       setOperationAction(ISD::STORE, VecTys[i], Legal);
75       setOperationAction(ISD::BITCAST, VecTys[i], Legal);
76     }
77
78     setTargetDAGCombine(ISD::SHL);
79     setTargetDAGCombine(ISD::SRA);
80     setTargetDAGCombine(ISD::SRL);
81     setTargetDAGCombine(ISD::SETCC);
82     setTargetDAGCombine(ISD::VSELECT);
83   }
84
85   if (Subtarget->hasDSPR2())
86     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
87
88   if (Subtarget->hasMSA()) {
89     addMSAIntType(MVT::v16i8, &Mips::MSA128BRegClass);
90     addMSAIntType(MVT::v8i16, &Mips::MSA128HRegClass);
91     addMSAIntType(MVT::v4i32, &Mips::MSA128WRegClass);
92     addMSAIntType(MVT::v2i64, &Mips::MSA128DRegClass);
93     addMSAFloatType(MVT::v8f16, &Mips::MSA128HRegClass);
94     addMSAFloatType(MVT::v4f32, &Mips::MSA128WRegClass);
95     addMSAFloatType(MVT::v2f64, &Mips::MSA128DRegClass);
96
97     setTargetDAGCombine(ISD::AND);
98     setTargetDAGCombine(ISD::OR);
99     setTargetDAGCombine(ISD::SRA);
100     setTargetDAGCombine(ISD::VSELECT);
101     setTargetDAGCombine(ISD::XOR);
102   }
103
104   if (!Subtarget->mipsSEUsesSoftFloat()) {
105     addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
106
107     // When dealing with single precision only, use libcalls
108     if (!Subtarget->isSingleFloat()) {
109       if (Subtarget->isFP64bit())
110         addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
111       else
112         addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
113     }
114   }
115
116   setOperationAction(ISD::SMUL_LOHI,          MVT::i32, Custom);
117   setOperationAction(ISD::UMUL_LOHI,          MVT::i32, Custom);
118   setOperationAction(ISD::MULHS,              MVT::i32, Custom);
119   setOperationAction(ISD::MULHU,              MVT::i32, Custom);
120
121   if (Subtarget->hasCnMips())
122     setOperationAction(ISD::MUL,              MVT::i64, Legal);
123   else if (isGP64bit())
124     setOperationAction(ISD::MUL,              MVT::i64, Custom);
125
126   if (isGP64bit()) {
127     setOperationAction(ISD::MULHS,            MVT::i64, Custom);
128     setOperationAction(ISD::MULHU,            MVT::i64, Custom);
129   }
130
131   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
132   setOperationAction(ISD::INTRINSIC_W_CHAIN,  MVT::i64, Custom);
133
134   setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
135   setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
136   setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
137   setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
138   setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Custom);
139   setOperationAction(ISD::LOAD,               MVT::i32, Custom);
140   setOperationAction(ISD::STORE,              MVT::i32, Custom);
141
142   setTargetDAGCombine(ISD::ADDE);
143   setTargetDAGCombine(ISD::SUBE);
144   setTargetDAGCombine(ISD::MUL);
145
146   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
147   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
148   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
149
150   if (NoDPLoadStore) {
151     setOperationAction(ISD::LOAD, MVT::f64, Custom);
152     setOperationAction(ISD::STORE, MVT::f64, Custom);
153   }
154
155   if (Subtarget->hasMips32r6()) {
156     // MIPS32r6 replaces the accumulator-based multiplies with a three register
157     // instruction
158     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
159     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
160     setOperationAction(ISD::MUL, MVT::i32, Legal);
161     setOperationAction(ISD::MULHS, MVT::i32, Legal);
162     setOperationAction(ISD::MULHU, MVT::i32, Legal);
163
164     // MIPS32r6 replaces the accumulator-based division/remainder with separate
165     // three register division and remainder instructions.
166     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
167     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
168     setOperationAction(ISD::SDIV, MVT::i32, Legal);
169     setOperationAction(ISD::UDIV, MVT::i32, Legal);
170     setOperationAction(ISD::SREM, MVT::i32, Legal);
171     setOperationAction(ISD::UREM, MVT::i32, Legal);
172
173     // MIPS32r6 replaces conditional moves with an equivalent that removes the
174     // need for three GPR read ports.
175     setOperationAction(ISD::SETCC, MVT::i32, Legal);
176     setOperationAction(ISD::SELECT, MVT::i32, Legal);
177     setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
178
179     setOperationAction(ISD::SETCC, MVT::f32, Legal);
180     setOperationAction(ISD::SELECT, MVT::f32, Legal);
181     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
182
183     assert(Subtarget->isFP64bit() && "FR=1 is required for MIPS32r6");
184     setOperationAction(ISD::SETCC, MVT::f64, Legal);
185     setOperationAction(ISD::SELECT, MVT::f64, Legal);
186     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
187
188     // Floating point > and >= are supported via < and <=
189     setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
190     setCondCodeAction(ISD::SETOGT, MVT::f32, Expand);
191     setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
192     setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
193
194     setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
195     setCondCodeAction(ISD::SETOGT, MVT::f64, Expand);
196     setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
197     setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
198   }
199
200   if (Subtarget->hasMips64r6()) {
201     // MIPS64r6 replaces the accumulator-based multiplies with a three register
202     // instruction
203     setOperationAction(ISD::MUL, MVT::i64, Legal);
204     setOperationAction(ISD::MULHS, MVT::i64, Legal);
205     setOperationAction(ISD::MULHU, MVT::i64, Legal);
206
207     // MIPS32r6 replaces the accumulator-based division/remainder with separate
208     // three register division and remainder instructions.
209     setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
210     setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
211     setOperationAction(ISD::SDIV, MVT::i64, Legal);
212     setOperationAction(ISD::UDIV, MVT::i64, Legal);
213     setOperationAction(ISD::SREM, MVT::i64, Legal);
214     setOperationAction(ISD::UREM, MVT::i64, Legal);
215
216     // MIPS64r6 replaces conditional moves with an equivalent that removes the
217     // need for three GPR read ports.
218     setOperationAction(ISD::SETCC, MVT::i64, Legal);
219     setOperationAction(ISD::SELECT, MVT::i64, Legal);
220     setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
221   }
222
223   computeRegisterProperties();
224 }
225
226 const MipsTargetLowering *
227 llvm::createMipsSETargetLowering(MipsTargetMachine &TM) {
228   return new MipsSETargetLowering(TM);
229 }
230
231 // Enable MSA support for the given integer type and Register class.
232 void MipsSETargetLowering::
233 addMSAIntType(MVT::SimpleValueType Ty, const TargetRegisterClass *RC) {
234   addRegisterClass(Ty, RC);
235
236   // Expand all builtin opcodes.
237   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
238     setOperationAction(Opc, Ty, Expand);
239
240   setOperationAction(ISD::BITCAST, Ty, Legal);
241   setOperationAction(ISD::LOAD, Ty, Legal);
242   setOperationAction(ISD::STORE, Ty, Legal);
243   setOperationAction(ISD::EXTRACT_VECTOR_ELT, Ty, Custom);
244   setOperationAction(ISD::INSERT_VECTOR_ELT, Ty, Legal);
245   setOperationAction(ISD::BUILD_VECTOR, Ty, Custom);
246
247   setOperationAction(ISD::ADD, Ty, Legal);
248   setOperationAction(ISD::AND, Ty, Legal);
249   setOperationAction(ISD::CTLZ, Ty, Legal);
250   setOperationAction(ISD::CTPOP, Ty, Legal);
251   setOperationAction(ISD::MUL, Ty, Legal);
252   setOperationAction(ISD::OR, Ty, Legal);
253   setOperationAction(ISD::SDIV, Ty, Legal);
254   setOperationAction(ISD::SREM, Ty, Legal);
255   setOperationAction(ISD::SHL, Ty, Legal);
256   setOperationAction(ISD::SRA, Ty, Legal);
257   setOperationAction(ISD::SRL, Ty, Legal);
258   setOperationAction(ISD::SUB, Ty, Legal);
259   setOperationAction(ISD::UDIV, Ty, Legal);
260   setOperationAction(ISD::UREM, Ty, Legal);
261   setOperationAction(ISD::VECTOR_SHUFFLE, Ty, Custom);
262   setOperationAction(ISD::VSELECT, Ty, Legal);
263   setOperationAction(ISD::XOR, Ty, Legal);
264
265   if (Ty == MVT::v4i32 || Ty == MVT::v2i64) {
266     setOperationAction(ISD::FP_TO_SINT, Ty, Legal);
267     setOperationAction(ISD::FP_TO_UINT, Ty, Legal);
268     setOperationAction(ISD::SINT_TO_FP, Ty, Legal);
269     setOperationAction(ISD::UINT_TO_FP, Ty, Legal);
270   }
271
272   setOperationAction(ISD::SETCC, Ty, Legal);
273   setCondCodeAction(ISD::SETNE, Ty, Expand);
274   setCondCodeAction(ISD::SETGE, Ty, Expand);
275   setCondCodeAction(ISD::SETGT, Ty, Expand);
276   setCondCodeAction(ISD::SETUGE, Ty, Expand);
277   setCondCodeAction(ISD::SETUGT, Ty, Expand);
278 }
279
280 // Enable MSA support for the given floating-point type and Register class.
281 void MipsSETargetLowering::
282 addMSAFloatType(MVT::SimpleValueType Ty, const TargetRegisterClass *RC) {
283   addRegisterClass(Ty, RC);
284
285   // Expand all builtin opcodes.
286   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
287     setOperationAction(Opc, Ty, Expand);
288
289   setOperationAction(ISD::LOAD, Ty, Legal);
290   setOperationAction(ISD::STORE, Ty, Legal);
291   setOperationAction(ISD::BITCAST, Ty, Legal);
292   setOperationAction(ISD::EXTRACT_VECTOR_ELT, Ty, Legal);
293   setOperationAction(ISD::INSERT_VECTOR_ELT, Ty, Legal);
294   setOperationAction(ISD::BUILD_VECTOR, Ty, Custom);
295
296   if (Ty != MVT::v8f16) {
297     setOperationAction(ISD::FABS,  Ty, Legal);
298     setOperationAction(ISD::FADD,  Ty, Legal);
299     setOperationAction(ISD::FDIV,  Ty, Legal);
300     setOperationAction(ISD::FEXP2, Ty, Legal);
301     setOperationAction(ISD::FLOG2, Ty, Legal);
302     setOperationAction(ISD::FMA,   Ty, Legal);
303     setOperationAction(ISD::FMUL,  Ty, Legal);
304     setOperationAction(ISD::FRINT, Ty, Legal);
305     setOperationAction(ISD::FSQRT, Ty, Legal);
306     setOperationAction(ISD::FSUB,  Ty, Legal);
307     setOperationAction(ISD::VSELECT, Ty, Legal);
308
309     setOperationAction(ISD::SETCC, Ty, Legal);
310     setCondCodeAction(ISD::SETOGE, Ty, Expand);
311     setCondCodeAction(ISD::SETOGT, Ty, Expand);
312     setCondCodeAction(ISD::SETUGE, Ty, Expand);
313     setCondCodeAction(ISD::SETUGT, Ty, Expand);
314     setCondCodeAction(ISD::SETGE,  Ty, Expand);
315     setCondCodeAction(ISD::SETGT,  Ty, Expand);
316   }
317 }
318
319 bool
320 MipsSETargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
321                                                     unsigned,
322                                                     bool *Fast) const {
323   MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
324
325   if (Subtarget->systemSupportsUnalignedAccess()) {
326     // MIPS32r6/MIPS64r6 is required to support unaligned access. It's
327     // implementation defined whether this is handled by hardware, software, or
328     // a hybrid of the two but it's expected that most implementations will
329     // handle the majority of cases in hardware.
330     if (Fast)
331       *Fast = true;
332     return true;
333   }
334
335   switch (SVT) {
336   case MVT::i64:
337   case MVT::i32:
338     if (Fast)
339       *Fast = true;
340     return true;
341   default:
342     return false;
343   }
344 }
345
346 SDValue MipsSETargetLowering::LowerOperation(SDValue Op,
347                                              SelectionDAG &DAG) const {
348   switch(Op.getOpcode()) {
349   case ISD::LOAD:  return lowerLOAD(Op, DAG);
350   case ISD::STORE: return lowerSTORE(Op, DAG);
351   case ISD::SMUL_LOHI: return lowerMulDiv(Op, MipsISD::Mult, true, true, DAG);
352   case ISD::UMUL_LOHI: return lowerMulDiv(Op, MipsISD::Multu, true, true, DAG);
353   case ISD::MULHS:     return lowerMulDiv(Op, MipsISD::Mult, false, true, DAG);
354   case ISD::MULHU:     return lowerMulDiv(Op, MipsISD::Multu, false, true, DAG);
355   case ISD::MUL:       return lowerMulDiv(Op, MipsISD::Mult, true, false, DAG);
356   case ISD::SDIVREM:   return lowerMulDiv(Op, MipsISD::DivRem, true, true, DAG);
357   case ISD::UDIVREM:   return lowerMulDiv(Op, MipsISD::DivRemU, true, true,
358                                           DAG);
359   case ISD::INTRINSIC_WO_CHAIN: return lowerINTRINSIC_WO_CHAIN(Op, DAG);
360   case ISD::INTRINSIC_W_CHAIN:  return lowerINTRINSIC_W_CHAIN(Op, DAG);
361   case ISD::INTRINSIC_VOID:     return lowerINTRINSIC_VOID(Op, DAG);
362   case ISD::EXTRACT_VECTOR_ELT: return lowerEXTRACT_VECTOR_ELT(Op, DAG);
363   case ISD::BUILD_VECTOR:       return lowerBUILD_VECTOR(Op, DAG);
364   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, DAG);
365   }
366
367   return MipsTargetLowering::LowerOperation(Op, DAG);
368 }
369
370 // selectMADD -
371 // Transforms a subgraph in CurDAG if the following pattern is found:
372 //  (addc multLo, Lo0), (adde multHi, Hi0),
373 // where,
374 //  multHi/Lo: product of multiplication
375 //  Lo0: initial value of Lo register
376 //  Hi0: initial value of Hi register
377 // Return true if pattern matching was successful.
378 static bool selectMADD(SDNode *ADDENode, SelectionDAG *CurDAG) {
379   // ADDENode's second operand must be a flag output of an ADDC node in order
380   // for the matching to be successful.
381   SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
382
383   if (ADDCNode->getOpcode() != ISD::ADDC)
384     return false;
385
386   SDValue MultHi = ADDENode->getOperand(0);
387   SDValue MultLo = ADDCNode->getOperand(0);
388   SDNode *MultNode = MultHi.getNode();
389   unsigned MultOpc = MultHi.getOpcode();
390
391   // MultHi and MultLo must be generated by the same node,
392   if (MultLo.getNode() != MultNode)
393     return false;
394
395   // and it must be a multiplication.
396   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
397     return false;
398
399   // MultLo amd MultHi must be the first and second output of MultNode
400   // respectively.
401   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
402     return false;
403
404   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
405   // of the values of MultNode, in which case MultNode will be removed in later
406   // phases.
407   // If there exist users other than ADDENode or ADDCNode, this function returns
408   // here, which will result in MultNode being mapped to a single MULT
409   // instruction node rather than a pair of MULT and MADD instructions being
410   // produced.
411   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
412     return false;
413
414   SDLoc DL(ADDENode);
415
416   // Initialize accumulator.
417   SDValue ACCIn = CurDAG->getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
418                                   ADDCNode->getOperand(1),
419                                   ADDENode->getOperand(1));
420
421   // create MipsMAdd(u) node
422   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
423
424   SDValue MAdd = CurDAG->getNode(MultOpc, DL, MVT::Untyped,
425                                  MultNode->getOperand(0),// Factor 0
426                                  MultNode->getOperand(1),// Factor 1
427                                  ACCIn);
428
429   // replace uses of adde and addc here
430   if (!SDValue(ADDCNode, 0).use_empty()) {
431     SDValue LoOut = CurDAG->getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
432     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), LoOut);
433   }
434   if (!SDValue(ADDENode, 0).use_empty()) {
435     SDValue HiOut = CurDAG->getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
436     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), HiOut);
437   }
438
439   return true;
440 }
441
442 // selectMSUB -
443 // Transforms a subgraph in CurDAG if the following pattern is found:
444 //  (addc Lo0, multLo), (sube Hi0, multHi),
445 // where,
446 //  multHi/Lo: product of multiplication
447 //  Lo0: initial value of Lo register
448 //  Hi0: initial value of Hi register
449 // Return true if pattern matching was successful.
450 static bool selectMSUB(SDNode *SUBENode, SelectionDAG *CurDAG) {
451   // SUBENode's second operand must be a flag output of an SUBC node in order
452   // for the matching to be successful.
453   SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
454
455   if (SUBCNode->getOpcode() != ISD::SUBC)
456     return false;
457
458   SDValue MultHi = SUBENode->getOperand(1);
459   SDValue MultLo = SUBCNode->getOperand(1);
460   SDNode *MultNode = MultHi.getNode();
461   unsigned MultOpc = MultHi.getOpcode();
462
463   // MultHi and MultLo must be generated by the same node,
464   if (MultLo.getNode() != MultNode)
465     return false;
466
467   // and it must be a multiplication.
468   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
469     return false;
470
471   // MultLo amd MultHi must be the first and second output of MultNode
472   // respectively.
473   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
474     return false;
475
476   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
477   // of the values of MultNode, in which case MultNode will be removed in later
478   // phases.
479   // If there exist users other than SUBENode or SUBCNode, this function returns
480   // here, which will result in MultNode being mapped to a single MULT
481   // instruction node rather than a pair of MULT and MSUB instructions being
482   // produced.
483   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
484     return false;
485
486   SDLoc DL(SUBENode);
487
488   // Initialize accumulator.
489   SDValue ACCIn = CurDAG->getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
490                                   SUBCNode->getOperand(0),
491                                   SUBENode->getOperand(0));
492
493   // create MipsSub(u) node
494   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
495
496   SDValue MSub = CurDAG->getNode(MultOpc, DL, MVT::Glue,
497                                  MultNode->getOperand(0),// Factor 0
498                                  MultNode->getOperand(1),// Factor 1
499                                  ACCIn);
500
501   // replace uses of sube and subc here
502   if (!SDValue(SUBCNode, 0).use_empty()) {
503     SDValue LoOut = CurDAG->getNode(MipsISD::MFLO, DL, MVT::i32, MSub);
504     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), LoOut);
505   }
506   if (!SDValue(SUBENode, 0).use_empty()) {
507     SDValue HiOut = CurDAG->getNode(MipsISD::MFHI, DL, MVT::i32, MSub);
508     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), HiOut);
509   }
510
511   return true;
512 }
513
514 static SDValue performADDECombine(SDNode *N, SelectionDAG &DAG,
515                                   TargetLowering::DAGCombinerInfo &DCI,
516                                   const MipsSubtarget *Subtarget) {
517   if (DCI.isBeforeLegalize())
518     return SDValue();
519
520   if (Subtarget->hasMips32() && !Subtarget->hasMips32r6() &&
521       N->getValueType(0) == MVT::i32 && selectMADD(N, &DAG))
522     return SDValue(N, 0);
523
524   return SDValue();
525 }
526
527 // Fold zero extensions into MipsISD::VEXTRACT_[SZ]EXT_ELT
528 //
529 // Performs the following transformations:
530 // - Changes MipsISD::VEXTRACT_[SZ]EXT_ELT to zero extension if its
531 //   sign/zero-extension is completely overwritten by the new one performed by
532 //   the ISD::AND.
533 // - Removes redundant zero extensions performed by an ISD::AND.
534 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
535                                  TargetLowering::DAGCombinerInfo &DCI,
536                                  const MipsSubtarget *Subtarget) {
537   if (!Subtarget->hasMSA())
538     return SDValue();
539
540   SDValue Op0 = N->getOperand(0);
541   SDValue Op1 = N->getOperand(1);
542   unsigned Op0Opcode = Op0->getOpcode();
543
544   // (and (MipsVExtract[SZ]Ext $a, $b, $c), imm:$d)
545   // where $d + 1 == 2^n and n == 32
546   // or    $d + 1 == 2^n and n <= 32 and ZExt
547   // -> (MipsVExtractZExt $a, $b, $c)
548   if (Op0Opcode == MipsISD::VEXTRACT_SEXT_ELT ||
549       Op0Opcode == MipsISD::VEXTRACT_ZEXT_ELT) {
550     ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Op1);
551
552     if (!Mask)
553       return SDValue();
554
555     int32_t Log2IfPositive = (Mask->getAPIntValue() + 1).exactLogBase2();
556
557     if (Log2IfPositive <= 0)
558       return SDValue(); // Mask+1 is not a power of 2
559
560     SDValue Op0Op2 = Op0->getOperand(2);
561     EVT ExtendTy = cast<VTSDNode>(Op0Op2)->getVT();
562     unsigned ExtendTySize = ExtendTy.getSizeInBits();
563     unsigned Log2 = Log2IfPositive;
564
565     if ((Op0Opcode == MipsISD::VEXTRACT_ZEXT_ELT && Log2 >= ExtendTySize) ||
566         Log2 == ExtendTySize) {
567       SDValue Ops[] = { Op0->getOperand(0), Op0->getOperand(1), Op0Op2 };
568       DAG.MorphNodeTo(Op0.getNode(), MipsISD::VEXTRACT_ZEXT_ELT,
569                       Op0->getVTList(),
570                       makeArrayRef(Ops, Op0->getNumOperands()));
571       return Op0;
572     }
573   }
574
575   return SDValue();
576 }
577
578 // Determine if the specified node is a constant vector splat.
579 //
580 // Returns true and sets Imm if:
581 // * N is a ISD::BUILD_VECTOR representing a constant splat
582 //
583 // This function is quite similar to MipsSEDAGToDAGISel::selectVSplat. The
584 // differences are that it assumes the MSA has already been checked and the
585 // arbitrary requirement for a maximum of 32-bit integers isn't applied (and
586 // must not be in order for binsri.d to be selectable).
587 static bool isVSplat(SDValue N, APInt &Imm, bool IsLittleEndian) {
588   BuildVectorSDNode *Node = dyn_cast<BuildVectorSDNode>(N.getNode());
589
590   if (!Node)
591     return false;
592
593   APInt SplatValue, SplatUndef;
594   unsigned SplatBitSize;
595   bool HasAnyUndefs;
596
597   if (!Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
598                              8, !IsLittleEndian))
599     return false;
600
601   Imm = SplatValue;
602
603   return true;
604 }
605
606 // Test whether the given node is an all-ones build_vector.
607 static bool isVectorAllOnes(SDValue N) {
608   // Look through bitcasts. Endianness doesn't matter because we are looking
609   // for an all-ones value.
610   if (N->getOpcode() == ISD::BITCAST)
611     N = N->getOperand(0);
612
613   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
614
615   if (!BVN)
616     return false;
617
618   APInt SplatValue, SplatUndef;
619   unsigned SplatBitSize;
620   bool HasAnyUndefs;
621
622   // Endianness doesn't matter in this context because we are looking for
623   // an all-ones value.
624   if (BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs))
625     return SplatValue.isAllOnesValue();
626
627   return false;
628 }
629
630 // Test whether N is the bitwise inverse of OfNode.
631 static bool isBitwiseInverse(SDValue N, SDValue OfNode) {
632   if (N->getOpcode() != ISD::XOR)
633     return false;
634
635   if (isVectorAllOnes(N->getOperand(0)))
636     return N->getOperand(1) == OfNode;
637
638   if (isVectorAllOnes(N->getOperand(1)))
639     return N->getOperand(0) == OfNode;
640
641   return false;
642 }
643
644 // Perform combines where ISD::OR is the root node.
645 //
646 // Performs the following transformations:
647 // - (or (and $a, $mask), (and $b, $inv_mask)) => (vselect $mask, $a, $b)
648 //   where $inv_mask is the bitwise inverse of $mask and the 'or' has a 128-bit
649 //   vector type.
650 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
651                                 TargetLowering::DAGCombinerInfo &DCI,
652                                 const MipsSubtarget *Subtarget) {
653   if (!Subtarget->hasMSA())
654     return SDValue();
655
656   EVT Ty = N->getValueType(0);
657
658   if (!Ty.is128BitVector())
659     return SDValue();
660
661   SDValue Op0 = N->getOperand(0);
662   SDValue Op1 = N->getOperand(1);
663
664   if (Op0->getOpcode() == ISD::AND && Op1->getOpcode() == ISD::AND) {
665     SDValue Op0Op0 = Op0->getOperand(0);
666     SDValue Op0Op1 = Op0->getOperand(1);
667     SDValue Op1Op0 = Op1->getOperand(0);
668     SDValue Op1Op1 = Op1->getOperand(1);
669     bool IsLittleEndian = !Subtarget->isLittle();
670
671     SDValue IfSet, IfClr, Cond;
672     bool IsConstantMask = false;
673     APInt Mask, InvMask;
674
675     // If Op0Op0 is an appropriate mask, try to find it's inverse in either
676     // Op1Op0, or Op1Op1. Keep track of the Cond, IfSet, and IfClr nodes, while
677     // looking.
678     // IfClr will be set if we find a valid match.
679     if (isVSplat(Op0Op0, Mask, IsLittleEndian)) {
680       Cond = Op0Op0;
681       IfSet = Op0Op1;
682
683       if (isVSplat(Op1Op0, InvMask, IsLittleEndian) &&
684           Mask.getBitWidth() == InvMask.getBitWidth() && Mask == ~InvMask)
685         IfClr = Op1Op1;
686       else if (isVSplat(Op1Op1, InvMask, IsLittleEndian) &&
687                Mask.getBitWidth() == InvMask.getBitWidth() && Mask == ~InvMask)
688         IfClr = Op1Op0;
689
690       IsConstantMask = true;
691     }
692
693     // If IfClr is not yet set, and Op0Op1 is an appropriate mask, try the same
694     // thing again using this mask.
695     // IfClr will be set if we find a valid match.
696     if (!IfClr.getNode() && isVSplat(Op0Op1, Mask, IsLittleEndian)) {
697       Cond = Op0Op1;
698       IfSet = Op0Op0;
699
700       if (isVSplat(Op1Op0, InvMask, IsLittleEndian) &&
701           Mask.getBitWidth() == InvMask.getBitWidth() && Mask == ~InvMask)
702         IfClr = Op1Op1;
703       else if (isVSplat(Op1Op1, InvMask, IsLittleEndian) &&
704                Mask.getBitWidth() == InvMask.getBitWidth() && Mask == ~InvMask)
705         IfClr = Op1Op0;
706
707       IsConstantMask = true;
708     }
709
710     // If IfClr is not yet set, try looking for a non-constant match.
711     // IfClr will be set if we find a valid match amongst the eight
712     // possibilities.
713     if (!IfClr.getNode()) {
714       if (isBitwiseInverse(Op0Op0, Op1Op0)) {
715         Cond = Op1Op0;
716         IfSet = Op1Op1;
717         IfClr = Op0Op1;
718       } else if (isBitwiseInverse(Op0Op1, Op1Op0)) {
719         Cond = Op1Op0;
720         IfSet = Op1Op1;
721         IfClr = Op0Op0;
722       } else if (isBitwiseInverse(Op0Op0, Op1Op1)) {
723         Cond = Op1Op1;
724         IfSet = Op1Op0;
725         IfClr = Op0Op1;
726       } else if (isBitwiseInverse(Op0Op1, Op1Op1)) {
727         Cond = Op1Op1;
728         IfSet = Op1Op0;
729         IfClr = Op0Op0;
730       } else if (isBitwiseInverse(Op1Op0, Op0Op0)) {
731         Cond = Op0Op0;
732         IfSet = Op0Op1;
733         IfClr = Op1Op1;
734       } else if (isBitwiseInverse(Op1Op1, Op0Op0)) {
735         Cond = Op0Op0;
736         IfSet = Op0Op1;
737         IfClr = Op1Op0;
738       } else if (isBitwiseInverse(Op1Op0, Op0Op1)) {
739         Cond = Op0Op1;
740         IfSet = Op0Op0;
741         IfClr = Op1Op1;
742       } else if (isBitwiseInverse(Op1Op1, Op0Op1)) {
743         Cond = Op0Op1;
744         IfSet = Op0Op0;
745         IfClr = Op1Op0;
746       }
747     }
748
749     // At this point, IfClr will be set if we have a valid match.
750     if (!IfClr.getNode())
751       return SDValue();
752
753     assert(Cond.getNode() && IfSet.getNode());
754
755     // Fold degenerate cases.
756     if (IsConstantMask) {
757       if (Mask.isAllOnesValue())
758         return IfSet;
759       else if (Mask == 0)
760         return IfClr;
761     }
762
763     // Transform the DAG into an equivalent VSELECT.
764     return DAG.getNode(ISD::VSELECT, SDLoc(N), Ty, Cond, IfSet, IfClr);
765   }
766
767   return SDValue();
768 }
769
770 static SDValue performSUBECombine(SDNode *N, SelectionDAG &DAG,
771                                   TargetLowering::DAGCombinerInfo &DCI,
772                                   const MipsSubtarget *Subtarget) {
773   if (DCI.isBeforeLegalize())
774     return SDValue();
775
776   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
777       selectMSUB(N, &DAG))
778     return SDValue(N, 0);
779
780   return SDValue();
781 }
782
783 static SDValue genConstMult(SDValue X, uint64_t C, SDLoc DL, EVT VT,
784                             EVT ShiftTy, SelectionDAG &DAG) {
785   // Clear the upper (64 - VT.sizeInBits) bits.
786   C &= ((uint64_t)-1) >> (64 - VT.getSizeInBits());
787
788   // Return 0.
789   if (C == 0)
790     return DAG.getConstant(0, VT);
791
792   // Return x.
793   if (C == 1)
794     return X;
795
796   // If c is power of 2, return (shl x, log2(c)).
797   if (isPowerOf2_64(C))
798     return DAG.getNode(ISD::SHL, DL, VT, X,
799                        DAG.getConstant(Log2_64(C), ShiftTy));
800
801   unsigned Log2Ceil = Log2_64_Ceil(C);
802   uint64_t Floor = 1LL << Log2_64(C);
803   uint64_t Ceil = Log2Ceil == 64 ? 0LL : 1LL << Log2Ceil;
804
805   // If |c - floor_c| <= |c - ceil_c|,
806   // where floor_c = pow(2, floor(log2(c))) and ceil_c = pow(2, ceil(log2(c))),
807   // return (add constMult(x, floor_c), constMult(x, c - floor_c)).
808   if (C - Floor <= Ceil - C) {
809     SDValue Op0 = genConstMult(X, Floor, DL, VT, ShiftTy, DAG);
810     SDValue Op1 = genConstMult(X, C - Floor, DL, VT, ShiftTy, DAG);
811     return DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
812   }
813
814   // If |c - floor_c| > |c - ceil_c|,
815   // return (sub constMult(x, ceil_c), constMult(x, ceil_c - c)).
816   SDValue Op0 = genConstMult(X, Ceil, DL, VT, ShiftTy, DAG);
817   SDValue Op1 = genConstMult(X, Ceil - C, DL, VT, ShiftTy, DAG);
818   return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
819 }
820
821 static SDValue performMULCombine(SDNode *N, SelectionDAG &DAG,
822                                  const TargetLowering::DAGCombinerInfo &DCI,
823                                  const MipsSETargetLowering *TL) {
824   EVT VT = N->getValueType(0);
825
826   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
827     if (!VT.isVector())
828       return genConstMult(N->getOperand(0), C->getZExtValue(), SDLoc(N),
829                           VT, TL->getScalarShiftAmountTy(VT), DAG);
830
831   return SDValue(N, 0);
832 }
833
834 static SDValue performDSPShiftCombine(unsigned Opc, SDNode *N, EVT Ty,
835                                       SelectionDAG &DAG,
836                                       const MipsSubtarget *Subtarget) {
837   // See if this is a vector splat immediate node.
838   APInt SplatValue, SplatUndef;
839   unsigned SplatBitSize;
840   bool HasAnyUndefs;
841   unsigned EltSize = Ty.getVectorElementType().getSizeInBits();
842   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
843
844   if (!Subtarget->hasDSP())
845     return SDValue();
846
847   if (!BV ||
848       !BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
849                            EltSize, !Subtarget->isLittle()) ||
850       (SplatBitSize != EltSize) ||
851       (SplatValue.getZExtValue() >= EltSize))
852     return SDValue();
853
854   return DAG.getNode(Opc, SDLoc(N), Ty, N->getOperand(0),
855                      DAG.getConstant(SplatValue.getZExtValue(), MVT::i32));
856 }
857
858 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
859                                  TargetLowering::DAGCombinerInfo &DCI,
860                                  const MipsSubtarget *Subtarget) {
861   EVT Ty = N->getValueType(0);
862
863   if ((Ty != MVT::v2i16) && (Ty != MVT::v4i8))
864     return SDValue();
865
866   return performDSPShiftCombine(MipsISD::SHLL_DSP, N, Ty, DAG, Subtarget);
867 }
868
869 // Fold sign-extensions into MipsISD::VEXTRACT_[SZ]EXT_ELT for MSA and fold
870 // constant splats into MipsISD::SHRA_DSP for DSPr2.
871 //
872 // Performs the following transformations:
873 // - Changes MipsISD::VEXTRACT_[SZ]EXT_ELT to sign extension if its
874 //   sign/zero-extension is completely overwritten by the new one performed by
875 //   the ISD::SRA and ISD::SHL nodes.
876 // - Removes redundant sign extensions performed by an ISD::SRA and ISD::SHL
877 //   sequence.
878 //
879 // See performDSPShiftCombine for more information about the transformation
880 // used for DSPr2.
881 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG,
882                                  TargetLowering::DAGCombinerInfo &DCI,
883                                  const MipsSubtarget *Subtarget) {
884   EVT Ty = N->getValueType(0);
885
886   if (Subtarget->hasMSA()) {
887     SDValue Op0 = N->getOperand(0);
888     SDValue Op1 = N->getOperand(1);
889
890     // (sra (shl (MipsVExtract[SZ]Ext $a, $b, $c), imm:$d), imm:$d)
891     // where $d + sizeof($c) == 32
892     // or    $d + sizeof($c) <= 32 and SExt
893     // -> (MipsVExtractSExt $a, $b, $c)
894     if (Op0->getOpcode() == ISD::SHL && Op1 == Op0->getOperand(1)) {
895       SDValue Op0Op0 = Op0->getOperand(0);
896       ConstantSDNode *ShAmount = dyn_cast<ConstantSDNode>(Op1);
897
898       if (!ShAmount)
899         return SDValue();
900
901       if (Op0Op0->getOpcode() != MipsISD::VEXTRACT_SEXT_ELT &&
902           Op0Op0->getOpcode() != MipsISD::VEXTRACT_ZEXT_ELT)
903         return SDValue();
904
905       EVT ExtendTy = cast<VTSDNode>(Op0Op0->getOperand(2))->getVT();
906       unsigned TotalBits = ShAmount->getZExtValue() + ExtendTy.getSizeInBits();
907
908       if (TotalBits == 32 ||
909           (Op0Op0->getOpcode() == MipsISD::VEXTRACT_SEXT_ELT &&
910            TotalBits <= 32)) {
911         SDValue Ops[] = { Op0Op0->getOperand(0), Op0Op0->getOperand(1),
912                           Op0Op0->getOperand(2) };
913         DAG.MorphNodeTo(Op0Op0.getNode(), MipsISD::VEXTRACT_SEXT_ELT,
914                         Op0Op0->getVTList(),
915                         makeArrayRef(Ops, Op0Op0->getNumOperands()));
916         return Op0Op0;
917       }
918     }
919   }
920
921   if ((Ty != MVT::v2i16) && ((Ty != MVT::v4i8) || !Subtarget->hasDSPR2()))
922     return SDValue();
923
924   return performDSPShiftCombine(MipsISD::SHRA_DSP, N, Ty, DAG, Subtarget);
925 }
926
927
928 static SDValue performSRLCombine(SDNode *N, SelectionDAG &DAG,
929                                  TargetLowering::DAGCombinerInfo &DCI,
930                                  const MipsSubtarget *Subtarget) {
931   EVT Ty = N->getValueType(0);
932
933   if (((Ty != MVT::v2i16) || !Subtarget->hasDSPR2()) && (Ty != MVT::v4i8))
934     return SDValue();
935
936   return performDSPShiftCombine(MipsISD::SHRL_DSP, N, Ty, DAG, Subtarget);
937 }
938
939 static bool isLegalDSPCondCode(EVT Ty, ISD::CondCode CC) {
940   bool IsV216 = (Ty == MVT::v2i16);
941
942   switch (CC) {
943   case ISD::SETEQ:
944   case ISD::SETNE:  return true;
945   case ISD::SETLT:
946   case ISD::SETLE:
947   case ISD::SETGT:
948   case ISD::SETGE:  return IsV216;
949   case ISD::SETULT:
950   case ISD::SETULE:
951   case ISD::SETUGT:
952   case ISD::SETUGE: return !IsV216;
953   default:          return false;
954   }
955 }
956
957 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG) {
958   EVT Ty = N->getValueType(0);
959
960   if ((Ty != MVT::v2i16) && (Ty != MVT::v4i8))
961     return SDValue();
962
963   if (!isLegalDSPCondCode(Ty, cast<CondCodeSDNode>(N->getOperand(2))->get()))
964     return SDValue();
965
966   return DAG.getNode(MipsISD::SETCC_DSP, SDLoc(N), Ty, N->getOperand(0),
967                      N->getOperand(1), N->getOperand(2));
968 }
969
970 static SDValue performVSELECTCombine(SDNode *N, SelectionDAG &DAG) {
971   EVT Ty = N->getValueType(0);
972
973   if (Ty.is128BitVector() && Ty.isInteger()) {
974     // Try the following combines:
975     //   (vselect (setcc $a, $b, SETLT), $b, $a)) -> (vsmax $a, $b)
976     //   (vselect (setcc $a, $b, SETLE), $b, $a)) -> (vsmax $a, $b)
977     //   (vselect (setcc $a, $b, SETLT), $a, $b)) -> (vsmin $a, $b)
978     //   (vselect (setcc $a, $b, SETLE), $a, $b)) -> (vsmin $a, $b)
979     //   (vselect (setcc $a, $b, SETULT), $b, $a)) -> (vumax $a, $b)
980     //   (vselect (setcc $a, $b, SETULE), $b, $a)) -> (vumax $a, $b)
981     //   (vselect (setcc $a, $b, SETULT), $a, $b)) -> (vumin $a, $b)
982     //   (vselect (setcc $a, $b, SETULE), $a, $b)) -> (vumin $a, $b)
983     // SETGT/SETGE/SETUGT/SETUGE variants of these will show up initially but
984     // will be expanded to equivalent SETLT/SETLE/SETULT/SETULE versions by the
985     // legalizer.
986     SDValue Op0 = N->getOperand(0);
987
988     if (Op0->getOpcode() != ISD::SETCC)
989       return SDValue();
990
991     ISD::CondCode CondCode = cast<CondCodeSDNode>(Op0->getOperand(2))->get();
992     bool Signed;
993
994     if (CondCode == ISD::SETLT  || CondCode == ISD::SETLE)
995       Signed = true;
996     else if (CondCode == ISD::SETULT || CondCode == ISD::SETULE)
997       Signed = false;
998     else
999       return SDValue();
1000
1001     SDValue Op1 = N->getOperand(1);
1002     SDValue Op2 = N->getOperand(2);
1003     SDValue Op0Op0 = Op0->getOperand(0);
1004     SDValue Op0Op1 = Op0->getOperand(1);
1005
1006     if (Op1 == Op0Op0 && Op2 == Op0Op1)
1007       return DAG.getNode(Signed ? MipsISD::VSMIN : MipsISD::VUMIN, SDLoc(N),
1008                          Ty, Op1, Op2);
1009     else if (Op1 == Op0Op1 && Op2 == Op0Op0)
1010       return DAG.getNode(Signed ? MipsISD::VSMAX : MipsISD::VUMAX, SDLoc(N),
1011                          Ty, Op1, Op2);
1012   } else if ((Ty == MVT::v2i16) || (Ty == MVT::v4i8)) {
1013     SDValue SetCC = N->getOperand(0);
1014
1015     if (SetCC.getOpcode() != MipsISD::SETCC_DSP)
1016       return SDValue();
1017
1018     return DAG.getNode(MipsISD::SELECT_CC_DSP, SDLoc(N), Ty,
1019                        SetCC.getOperand(0), SetCC.getOperand(1),
1020                        N->getOperand(1), N->getOperand(2), SetCC.getOperand(2));
1021   }
1022
1023   return SDValue();
1024 }
1025
1026 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG,
1027                                  const MipsSubtarget *Subtarget) {
1028   EVT Ty = N->getValueType(0);
1029
1030   if (Subtarget->hasMSA() && Ty.is128BitVector() && Ty.isInteger()) {
1031     // Try the following combines:
1032     //   (xor (or $a, $b), (build_vector allones))
1033     //   (xor (or $a, $b), (bitcast (build_vector allones)))
1034     SDValue Op0 = N->getOperand(0);
1035     SDValue Op1 = N->getOperand(1);
1036     SDValue NotOp;
1037
1038     if (ISD::isBuildVectorAllOnes(Op0.getNode()))
1039       NotOp = Op1;
1040     else if (ISD::isBuildVectorAllOnes(Op1.getNode()))
1041       NotOp = Op0;
1042     else
1043       return SDValue();
1044
1045     if (NotOp->getOpcode() == ISD::OR)
1046       return DAG.getNode(MipsISD::VNOR, SDLoc(N), Ty, NotOp->getOperand(0),
1047                          NotOp->getOperand(1));
1048   }
1049
1050   return SDValue();
1051 }
1052
1053 SDValue
1054 MipsSETargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1055   SelectionDAG &DAG = DCI.DAG;
1056   SDValue Val;
1057
1058   switch (N->getOpcode()) {
1059   case ISD::ADDE:
1060     return performADDECombine(N, DAG, DCI, Subtarget);
1061   case ISD::AND:
1062     Val = performANDCombine(N, DAG, DCI, Subtarget);
1063     break;
1064   case ISD::OR:
1065     Val = performORCombine(N, DAG, DCI, Subtarget);
1066     break;
1067   case ISD::SUBE:
1068     return performSUBECombine(N, DAG, DCI, Subtarget);
1069   case ISD::MUL:
1070     return performMULCombine(N, DAG, DCI, this);
1071   case ISD::SHL:
1072     return performSHLCombine(N, DAG, DCI, Subtarget);
1073   case ISD::SRA:
1074     return performSRACombine(N, DAG, DCI, Subtarget);
1075   case ISD::SRL:
1076     return performSRLCombine(N, DAG, DCI, Subtarget);
1077   case ISD::VSELECT:
1078     return performVSELECTCombine(N, DAG);
1079   case ISD::XOR:
1080     Val = performXORCombine(N, DAG, Subtarget);
1081     break;
1082   case ISD::SETCC:
1083     Val = performSETCCCombine(N, DAG);
1084     break;
1085   }
1086
1087   if (Val.getNode()) {
1088     DEBUG(dbgs() << "\nMipsSE DAG Combine:\n";
1089           N->printrWithDepth(dbgs(), &DAG);
1090           dbgs() << "\n=> \n";
1091           Val.getNode()->printrWithDepth(dbgs(), &DAG);
1092           dbgs() << "\n");
1093     return Val;
1094   }
1095
1096   return MipsTargetLowering::PerformDAGCombine(N, DCI);
1097 }
1098
1099 MachineBasicBlock *
1100 MipsSETargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1101                                                   MachineBasicBlock *BB) const {
1102   switch (MI->getOpcode()) {
1103   default:
1104     return MipsTargetLowering::EmitInstrWithCustomInserter(MI, BB);
1105   case Mips::BPOSGE32_PSEUDO:
1106     return emitBPOSGE32(MI, BB);
1107   case Mips::SNZ_B_PSEUDO:
1108     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_B);
1109   case Mips::SNZ_H_PSEUDO:
1110     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_H);
1111   case Mips::SNZ_W_PSEUDO:
1112     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_W);
1113   case Mips::SNZ_D_PSEUDO:
1114     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_D);
1115   case Mips::SNZ_V_PSEUDO:
1116     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_V);
1117   case Mips::SZ_B_PSEUDO:
1118     return emitMSACBranchPseudo(MI, BB, Mips::BZ_B);
1119   case Mips::SZ_H_PSEUDO:
1120     return emitMSACBranchPseudo(MI, BB, Mips::BZ_H);
1121   case Mips::SZ_W_PSEUDO:
1122     return emitMSACBranchPseudo(MI, BB, Mips::BZ_W);
1123   case Mips::SZ_D_PSEUDO:
1124     return emitMSACBranchPseudo(MI, BB, Mips::BZ_D);
1125   case Mips::SZ_V_PSEUDO:
1126     return emitMSACBranchPseudo(MI, BB, Mips::BZ_V);
1127   case Mips::COPY_FW_PSEUDO:
1128     return emitCOPY_FW(MI, BB);
1129   case Mips::COPY_FD_PSEUDO:
1130     return emitCOPY_FD(MI, BB);
1131   case Mips::INSERT_FW_PSEUDO:
1132     return emitINSERT_FW(MI, BB);
1133   case Mips::INSERT_FD_PSEUDO:
1134     return emitINSERT_FD(MI, BB);
1135   case Mips::INSERT_B_VIDX_PSEUDO:
1136     return emitINSERT_DF_VIDX(MI, BB, 1, false);
1137   case Mips::INSERT_H_VIDX_PSEUDO:
1138     return emitINSERT_DF_VIDX(MI, BB, 2, false);
1139   case Mips::INSERT_W_VIDX_PSEUDO:
1140     return emitINSERT_DF_VIDX(MI, BB, 4, false);
1141   case Mips::INSERT_D_VIDX_PSEUDO:
1142     return emitINSERT_DF_VIDX(MI, BB, 8, false);
1143   case Mips::INSERT_FW_VIDX_PSEUDO:
1144     return emitINSERT_DF_VIDX(MI, BB, 4, true);
1145   case Mips::INSERT_FD_VIDX_PSEUDO:
1146     return emitINSERT_DF_VIDX(MI, BB, 8, true);
1147   case Mips::FILL_FW_PSEUDO:
1148     return emitFILL_FW(MI, BB);
1149   case Mips::FILL_FD_PSEUDO:
1150     return emitFILL_FD(MI, BB);
1151   case Mips::FEXP2_W_1_PSEUDO:
1152     return emitFEXP2_W_1(MI, BB);
1153   case Mips::FEXP2_D_1_PSEUDO:
1154     return emitFEXP2_D_1(MI, BB);
1155   }
1156 }
1157
1158 bool MipsSETargetLowering::
1159 isEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
1160                                   unsigned NextStackOffset,
1161                                   const MipsFunctionInfo& FI) const {
1162   if (!EnableMipsTailCalls)
1163     return false;
1164
1165   // Return false if either the callee or caller has a byval argument.
1166   if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
1167     return false;
1168
1169   // Return true if the callee's argument area is no larger than the
1170   // caller's.
1171   return NextStackOffset <= FI.getIncomingArgSize();
1172 }
1173
1174 void MipsSETargetLowering::
1175 getOpndList(SmallVectorImpl<SDValue> &Ops,
1176             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
1177             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
1178             CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
1179   Ops.push_back(Callee);
1180   MipsTargetLowering::getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal,
1181                                   InternalLinkage, CLI, Callee, Chain);
1182 }
1183
1184 SDValue MipsSETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1185   LoadSDNode &Nd = *cast<LoadSDNode>(Op);
1186
1187   if (Nd.getMemoryVT() != MVT::f64 || !NoDPLoadStore)
1188     return MipsTargetLowering::lowerLOAD(Op, DAG);
1189
1190   // Replace a double precision load with two i32 loads and a buildpair64.
1191   SDLoc DL(Op);
1192   SDValue Ptr = Nd.getBasePtr(), Chain = Nd.getChain();
1193   EVT PtrVT = Ptr.getValueType();
1194
1195   // i32 load from lower address.
1196   SDValue Lo = DAG.getLoad(MVT::i32, DL, Chain, Ptr,
1197                            MachinePointerInfo(), Nd.isVolatile(),
1198                            Nd.isNonTemporal(), Nd.isInvariant(),
1199                            Nd.getAlignment());
1200
1201   // i32 load from higher address.
1202   Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr, DAG.getConstant(4, PtrVT));
1203   SDValue Hi = DAG.getLoad(MVT::i32, DL, Lo.getValue(1), Ptr,
1204                            MachinePointerInfo(), Nd.isVolatile(),
1205                            Nd.isNonTemporal(), Nd.isInvariant(),
1206                            std::min(Nd.getAlignment(), 4U));
1207
1208   if (!Subtarget->isLittle())
1209     std::swap(Lo, Hi);
1210
1211   SDValue BP = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
1212   SDValue Ops[2] = {BP, Hi.getValue(1)};
1213   return DAG.getMergeValues(Ops, DL);
1214 }
1215
1216 SDValue MipsSETargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1217   StoreSDNode &Nd = *cast<StoreSDNode>(Op);
1218
1219   if (Nd.getMemoryVT() != MVT::f64 || !NoDPLoadStore)
1220     return MipsTargetLowering::lowerSTORE(Op, DAG);
1221
1222   // Replace a double precision store with two extractelement64s and i32 stores.
1223   SDLoc DL(Op);
1224   SDValue Val = Nd.getValue(), Ptr = Nd.getBasePtr(), Chain = Nd.getChain();
1225   EVT PtrVT = Ptr.getValueType();
1226   SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1227                            Val, DAG.getConstant(0, MVT::i32));
1228   SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1229                            Val, DAG.getConstant(1, MVT::i32));
1230
1231   if (!Subtarget->isLittle())
1232     std::swap(Lo, Hi);
1233
1234   // i32 store to lower address.
1235   Chain = DAG.getStore(Chain, DL, Lo, Ptr, MachinePointerInfo(),
1236                        Nd.isVolatile(), Nd.isNonTemporal(), Nd.getAlignment(),
1237                        Nd.getTBAAInfo());
1238
1239   // i32 store to higher address.
1240   Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr, DAG.getConstant(4, PtrVT));
1241   return DAG.getStore(Chain, DL, Hi, Ptr, MachinePointerInfo(),
1242                       Nd.isVolatile(), Nd.isNonTemporal(),
1243                       std::min(Nd.getAlignment(), 4U), Nd.getTBAAInfo());
1244 }
1245
1246 SDValue MipsSETargetLowering::lowerMulDiv(SDValue Op, unsigned NewOpc,
1247                                           bool HasLo, bool HasHi,
1248                                           SelectionDAG &DAG) const {
1249   // MIPS32r6/MIPS64r6 removed accumulator based multiplies.
1250   assert(!Subtarget->hasMips32r6());
1251
1252   EVT Ty = Op.getOperand(0).getValueType();
1253   SDLoc DL(Op);
1254   SDValue Mult = DAG.getNode(NewOpc, DL, MVT::Untyped,
1255                              Op.getOperand(0), Op.getOperand(1));
1256   SDValue Lo, Hi;
1257
1258   if (HasLo)
1259     Lo = DAG.getNode(MipsISD::MFLO, DL, Ty, Mult);
1260   if (HasHi)
1261     Hi = DAG.getNode(MipsISD::MFHI, DL, Ty, Mult);
1262
1263   if (!HasLo || !HasHi)
1264     return HasLo ? Lo : Hi;
1265
1266   SDValue Vals[] = { Lo, Hi };
1267   return DAG.getMergeValues(Vals, DL);
1268 }
1269
1270
1271 static SDValue initAccumulator(SDValue In, SDLoc DL, SelectionDAG &DAG) {
1272   SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, In,
1273                              DAG.getConstant(0, MVT::i32));
1274   SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, In,
1275                              DAG.getConstant(1, MVT::i32));
1276   return DAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped, InLo, InHi);
1277 }
1278
1279 static SDValue extractLOHI(SDValue Op, SDLoc DL, SelectionDAG &DAG) {
1280   SDValue Lo = DAG.getNode(MipsISD::MFLO, DL, MVT::i32, Op);
1281   SDValue Hi = DAG.getNode(MipsISD::MFHI, DL, MVT::i32, Op);
1282   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
1283 }
1284
1285 // This function expands mips intrinsic nodes which have 64-bit input operands
1286 // or output values.
1287 //
1288 // out64 = intrinsic-node in64
1289 // =>
1290 // lo = copy (extract-element (in64, 0))
1291 // hi = copy (extract-element (in64, 1))
1292 // mips-specific-node
1293 // v0 = copy lo
1294 // v1 = copy hi
1295 // out64 = merge-values (v0, v1)
1296 //
1297 static SDValue lowerDSPIntr(SDValue Op, SelectionDAG &DAG, unsigned Opc) {
1298   SDLoc DL(Op);
1299   bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
1300   SmallVector<SDValue, 3> Ops;
1301   unsigned OpNo = 0;
1302
1303   // See if Op has a chain input.
1304   if (HasChainIn)
1305     Ops.push_back(Op->getOperand(OpNo++));
1306
1307   // The next operand is the intrinsic opcode.
1308   assert(Op->getOperand(OpNo).getOpcode() == ISD::TargetConstant);
1309
1310   // See if the next operand has type i64.
1311   SDValue Opnd = Op->getOperand(++OpNo), In64;
1312
1313   if (Opnd.getValueType() == MVT::i64)
1314     In64 = initAccumulator(Opnd, DL, DAG);
1315   else
1316     Ops.push_back(Opnd);
1317
1318   // Push the remaining operands.
1319   for (++OpNo ; OpNo < Op->getNumOperands(); ++OpNo)
1320     Ops.push_back(Op->getOperand(OpNo));
1321
1322   // Add In64 to the end of the list.
1323   if (In64.getNode())
1324     Ops.push_back(In64);
1325
1326   // Scan output.
1327   SmallVector<EVT, 2> ResTys;
1328
1329   for (SDNode::value_iterator I = Op->value_begin(), E = Op->value_end();
1330        I != E; ++I)
1331     ResTys.push_back((*I == MVT::i64) ? MVT::Untyped : *I);
1332
1333   // Create node.
1334   SDValue Val = DAG.getNode(Opc, DL, ResTys, Ops);
1335   SDValue Out = (ResTys[0] == MVT::Untyped) ? extractLOHI(Val, DL, DAG) : Val;
1336
1337   if (!HasChainIn)
1338     return Out;
1339
1340   assert(Val->getValueType(1) == MVT::Other);
1341   SDValue Vals[] = { Out, SDValue(Val.getNode(), 1) };
1342   return DAG.getMergeValues(Vals, DL);
1343 }
1344
1345 // Lower an MSA copy intrinsic into the specified SelectionDAG node
1346 static SDValue lowerMSACopyIntr(SDValue Op, SelectionDAG &DAG, unsigned Opc) {
1347   SDLoc DL(Op);
1348   SDValue Vec = Op->getOperand(1);
1349   SDValue Idx = Op->getOperand(2);
1350   EVT ResTy = Op->getValueType(0);
1351   EVT EltTy = Vec->getValueType(0).getVectorElementType();
1352
1353   SDValue Result = DAG.getNode(Opc, DL, ResTy, Vec, Idx,
1354                                DAG.getValueType(EltTy));
1355
1356   return Result;
1357 }
1358
1359 static SDValue lowerMSASplatZExt(SDValue Op, unsigned OpNr, SelectionDAG &DAG) {
1360   EVT ResVecTy = Op->getValueType(0);
1361   EVT ViaVecTy = ResVecTy;
1362   SDLoc DL(Op);
1363
1364   // When ResVecTy == MVT::v2i64, LaneA is the upper 32 bits of the lane and
1365   // LaneB is the lower 32-bits. Otherwise LaneA and LaneB are alternating
1366   // lanes.
1367   SDValue LaneA;
1368   SDValue LaneB = Op->getOperand(2);
1369
1370   if (ResVecTy == MVT::v2i64) {
1371     LaneA = DAG.getConstant(0, MVT::i32);
1372     ViaVecTy = MVT::v4i32;
1373   } else
1374     LaneA = LaneB;
1375
1376   SDValue Ops[16] = { LaneA, LaneB, LaneA, LaneB, LaneA, LaneB, LaneA, LaneB,
1377                       LaneA, LaneB, LaneA, LaneB, LaneA, LaneB, LaneA, LaneB };
1378
1379   SDValue Result = DAG.getNode(ISD::BUILD_VECTOR, DL, ViaVecTy,
1380                        makeArrayRef(Ops, ViaVecTy.getVectorNumElements()));
1381
1382   if (ViaVecTy != ResVecTy)
1383     Result = DAG.getNode(ISD::BITCAST, DL, ResVecTy, Result);
1384
1385   return Result;
1386 }
1387
1388 static SDValue lowerMSASplatImm(SDValue Op, unsigned ImmOp, SelectionDAG &DAG) {
1389   return DAG.getConstant(Op->getConstantOperandVal(ImmOp), Op->getValueType(0));
1390 }
1391
1392 static SDValue getBuildVectorSplat(EVT VecTy, SDValue SplatValue,
1393                                    bool BigEndian, SelectionDAG &DAG) {
1394   EVT ViaVecTy = VecTy;
1395   SDValue SplatValueA = SplatValue;
1396   SDValue SplatValueB = SplatValue;
1397   SDLoc DL(SplatValue);
1398
1399   if (VecTy == MVT::v2i64) {
1400     // v2i64 BUILD_VECTOR must be performed via v4i32 so split into i32's.
1401     ViaVecTy = MVT::v4i32;
1402
1403     SplatValueA = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, SplatValue);
1404     SplatValueB = DAG.getNode(ISD::SRL, DL, MVT::i64, SplatValue,
1405                               DAG.getConstant(32, MVT::i32));
1406     SplatValueB = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, SplatValueB);
1407   }
1408
1409   // We currently hold the parts in little endian order. Swap them if
1410   // necessary.
1411   if (BigEndian)
1412     std::swap(SplatValueA, SplatValueB);
1413
1414   SDValue Ops[16] = { SplatValueA, SplatValueB, SplatValueA, SplatValueB,
1415                       SplatValueA, SplatValueB, SplatValueA, SplatValueB,
1416                       SplatValueA, SplatValueB, SplatValueA, SplatValueB,
1417                       SplatValueA, SplatValueB, SplatValueA, SplatValueB };
1418
1419   SDValue Result = DAG.getNode(ISD::BUILD_VECTOR, DL, ViaVecTy,
1420                        makeArrayRef(Ops, ViaVecTy.getVectorNumElements()));
1421
1422   if (VecTy != ViaVecTy)
1423     Result = DAG.getNode(ISD::BITCAST, DL, VecTy, Result);
1424
1425   return Result;
1426 }
1427
1428 static SDValue lowerMSABinaryBitImmIntr(SDValue Op, SelectionDAG &DAG,
1429                                         unsigned Opc, SDValue Imm,
1430                                         bool BigEndian) {
1431   EVT VecTy = Op->getValueType(0);
1432   SDValue Exp2Imm;
1433   SDLoc DL(Op);
1434
1435   // The DAG Combiner can't constant fold bitcasted vectors yet so we must do it
1436   // here for now.
1437   if (VecTy == MVT::v2i64) {
1438     if (ConstantSDNode *CImm = dyn_cast<ConstantSDNode>(Imm)) {
1439       APInt BitImm = APInt(64, 1) << CImm->getAPIntValue();
1440
1441       SDValue BitImmHiOp = DAG.getConstant(BitImm.lshr(32).trunc(32), MVT::i32);
1442       SDValue BitImmLoOp = DAG.getConstant(BitImm.trunc(32), MVT::i32);
1443
1444       if (BigEndian)
1445         std::swap(BitImmLoOp, BitImmHiOp);
1446
1447       Exp2Imm =
1448           DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
1449                       DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, BitImmLoOp,
1450                                   BitImmHiOp, BitImmLoOp, BitImmHiOp));
1451     }
1452   }
1453
1454   if (!Exp2Imm.getNode()) {
1455     // We couldnt constant fold, do a vector shift instead
1456
1457     // Extend i32 to i64 if necessary. Sign or zero extend doesn't matter since
1458     // only values 0-63 are valid.
1459     if (VecTy == MVT::v2i64)
1460       Imm = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Imm);
1461
1462     Exp2Imm = getBuildVectorSplat(VecTy, Imm, BigEndian, DAG);
1463
1464     Exp2Imm =
1465         DAG.getNode(ISD::SHL, DL, VecTy, DAG.getConstant(1, VecTy), Exp2Imm);
1466   }
1467
1468   return DAG.getNode(Opc, DL, VecTy, Op->getOperand(1), Exp2Imm);
1469 }
1470
1471 static SDValue lowerMSABitClear(SDValue Op, SelectionDAG &DAG) {
1472   EVT ResTy = Op->getValueType(0);
1473   SDLoc DL(Op);
1474   SDValue One = DAG.getConstant(1, ResTy);
1475   SDValue Bit = DAG.getNode(ISD::SHL, DL, ResTy, One, Op->getOperand(2));
1476
1477   return DAG.getNode(ISD::AND, DL, ResTy, Op->getOperand(1),
1478                      DAG.getNOT(DL, Bit, ResTy));
1479 }
1480
1481 static SDValue lowerMSABitClearImm(SDValue Op, SelectionDAG &DAG) {
1482   SDLoc DL(Op);
1483   EVT ResTy = Op->getValueType(0);
1484   APInt BitImm = APInt(ResTy.getVectorElementType().getSizeInBits(), 1)
1485                  << cast<ConstantSDNode>(Op->getOperand(2))->getAPIntValue();
1486   SDValue BitMask = DAG.getConstant(~BitImm, ResTy);
1487
1488   return DAG.getNode(ISD::AND, DL, ResTy, Op->getOperand(1), BitMask);
1489 }
1490
1491 SDValue MipsSETargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
1492                                                       SelectionDAG &DAG) const {
1493   SDLoc DL(Op);
1494
1495   switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
1496   default:
1497     return SDValue();
1498   case Intrinsic::mips_shilo:
1499     return lowerDSPIntr(Op, DAG, MipsISD::SHILO);
1500   case Intrinsic::mips_dpau_h_qbl:
1501     return lowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL);
1502   case Intrinsic::mips_dpau_h_qbr:
1503     return lowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR);
1504   case Intrinsic::mips_dpsu_h_qbl:
1505     return lowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL);
1506   case Intrinsic::mips_dpsu_h_qbr:
1507     return lowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR);
1508   case Intrinsic::mips_dpa_w_ph:
1509     return lowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH);
1510   case Intrinsic::mips_dps_w_ph:
1511     return lowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH);
1512   case Intrinsic::mips_dpax_w_ph:
1513     return lowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH);
1514   case Intrinsic::mips_dpsx_w_ph:
1515     return lowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH);
1516   case Intrinsic::mips_mulsa_w_ph:
1517     return lowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH);
1518   case Intrinsic::mips_mult:
1519     return lowerDSPIntr(Op, DAG, MipsISD::Mult);
1520   case Intrinsic::mips_multu:
1521     return lowerDSPIntr(Op, DAG, MipsISD::Multu);
1522   case Intrinsic::mips_madd:
1523     return lowerDSPIntr(Op, DAG, MipsISD::MAdd);
1524   case Intrinsic::mips_maddu:
1525     return lowerDSPIntr(Op, DAG, MipsISD::MAddu);
1526   case Intrinsic::mips_msub:
1527     return lowerDSPIntr(Op, DAG, MipsISD::MSub);
1528   case Intrinsic::mips_msubu:
1529     return lowerDSPIntr(Op, DAG, MipsISD::MSubu);
1530   case Intrinsic::mips_addv_b:
1531   case Intrinsic::mips_addv_h:
1532   case Intrinsic::mips_addv_w:
1533   case Intrinsic::mips_addv_d:
1534     return DAG.getNode(ISD::ADD, DL, Op->getValueType(0), Op->getOperand(1),
1535                        Op->getOperand(2));
1536   case Intrinsic::mips_addvi_b:
1537   case Intrinsic::mips_addvi_h:
1538   case Intrinsic::mips_addvi_w:
1539   case Intrinsic::mips_addvi_d:
1540     return DAG.getNode(ISD::ADD, DL, Op->getValueType(0), Op->getOperand(1),
1541                        lowerMSASplatImm(Op, 2, DAG));
1542   case Intrinsic::mips_and_v:
1543     return DAG.getNode(ISD::AND, DL, Op->getValueType(0), Op->getOperand(1),
1544                        Op->getOperand(2));
1545   case Intrinsic::mips_andi_b:
1546     return DAG.getNode(ISD::AND, DL, Op->getValueType(0), Op->getOperand(1),
1547                        lowerMSASplatImm(Op, 2, DAG));
1548   case Intrinsic::mips_bclr_b:
1549   case Intrinsic::mips_bclr_h:
1550   case Intrinsic::mips_bclr_w:
1551   case Intrinsic::mips_bclr_d:
1552     return lowerMSABitClear(Op, DAG);
1553   case Intrinsic::mips_bclri_b:
1554   case Intrinsic::mips_bclri_h:
1555   case Intrinsic::mips_bclri_w:
1556   case Intrinsic::mips_bclri_d:
1557     return lowerMSABitClearImm(Op, DAG);
1558   case Intrinsic::mips_binsli_b:
1559   case Intrinsic::mips_binsli_h:
1560   case Intrinsic::mips_binsli_w:
1561   case Intrinsic::mips_binsli_d: {
1562     // binsli_x(IfClear, IfSet, nbits) -> (vselect LBitsMask, IfSet, IfClear)
1563     EVT VecTy = Op->getValueType(0);
1564     EVT EltTy = VecTy.getVectorElementType();
1565     APInt Mask = APInt::getHighBitsSet(EltTy.getSizeInBits(),
1566                                        Op->getConstantOperandVal(3));
1567     return DAG.getNode(ISD::VSELECT, DL, VecTy,
1568                        DAG.getConstant(Mask, VecTy, true), Op->getOperand(2),
1569                        Op->getOperand(1));
1570   }
1571   case Intrinsic::mips_binsri_b:
1572   case Intrinsic::mips_binsri_h:
1573   case Intrinsic::mips_binsri_w:
1574   case Intrinsic::mips_binsri_d: {
1575     // binsri_x(IfClear, IfSet, nbits) -> (vselect RBitsMask, IfSet, IfClear)
1576     EVT VecTy = Op->getValueType(0);
1577     EVT EltTy = VecTy.getVectorElementType();
1578     APInt Mask = APInt::getLowBitsSet(EltTy.getSizeInBits(),
1579                                       Op->getConstantOperandVal(3));
1580     return DAG.getNode(ISD::VSELECT, DL, VecTy,
1581                        DAG.getConstant(Mask, VecTy, true), Op->getOperand(2),
1582                        Op->getOperand(1));
1583   }
1584   case Intrinsic::mips_bmnz_v:
1585     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0), Op->getOperand(3),
1586                        Op->getOperand(2), Op->getOperand(1));
1587   case Intrinsic::mips_bmnzi_b:
1588     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1589                        lowerMSASplatImm(Op, 3, DAG), Op->getOperand(2),
1590                        Op->getOperand(1));
1591   case Intrinsic::mips_bmz_v:
1592     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0), Op->getOperand(3),
1593                        Op->getOperand(1), Op->getOperand(2));
1594   case Intrinsic::mips_bmzi_b:
1595     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1596                        lowerMSASplatImm(Op, 3, DAG), Op->getOperand(1),
1597                        Op->getOperand(2));
1598   case Intrinsic::mips_bneg_b:
1599   case Intrinsic::mips_bneg_h:
1600   case Intrinsic::mips_bneg_w:
1601   case Intrinsic::mips_bneg_d: {
1602     EVT VecTy = Op->getValueType(0);
1603     SDValue One = DAG.getConstant(1, VecTy);
1604
1605     return DAG.getNode(ISD::XOR, DL, VecTy, Op->getOperand(1),
1606                        DAG.getNode(ISD::SHL, DL, VecTy, One,
1607                                    Op->getOperand(2)));
1608   }
1609   case Intrinsic::mips_bnegi_b:
1610   case Intrinsic::mips_bnegi_h:
1611   case Intrinsic::mips_bnegi_w:
1612   case Intrinsic::mips_bnegi_d:
1613     return lowerMSABinaryBitImmIntr(Op, DAG, ISD::XOR, Op->getOperand(2),
1614                                     !Subtarget->isLittle());
1615   case Intrinsic::mips_bnz_b:
1616   case Intrinsic::mips_bnz_h:
1617   case Intrinsic::mips_bnz_w:
1618   case Intrinsic::mips_bnz_d:
1619     return DAG.getNode(MipsISD::VALL_NONZERO, DL, Op->getValueType(0),
1620                        Op->getOperand(1));
1621   case Intrinsic::mips_bnz_v:
1622     return DAG.getNode(MipsISD::VANY_NONZERO, DL, Op->getValueType(0),
1623                        Op->getOperand(1));
1624   case Intrinsic::mips_bsel_v:
1625     // bsel_v(Mask, IfClear, IfSet) -> (vselect Mask, IfSet, IfClear)
1626     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1627                        Op->getOperand(1), Op->getOperand(3),
1628                        Op->getOperand(2));
1629   case Intrinsic::mips_bseli_b:
1630     // bseli_v(Mask, IfClear, IfSet) -> (vselect Mask, IfSet, IfClear)
1631     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1632                        Op->getOperand(1), lowerMSASplatImm(Op, 3, DAG),
1633                        Op->getOperand(2));
1634   case Intrinsic::mips_bset_b:
1635   case Intrinsic::mips_bset_h:
1636   case Intrinsic::mips_bset_w:
1637   case Intrinsic::mips_bset_d: {
1638     EVT VecTy = Op->getValueType(0);
1639     SDValue One = DAG.getConstant(1, VecTy);
1640
1641     return DAG.getNode(ISD::OR, DL, VecTy, Op->getOperand(1),
1642                        DAG.getNode(ISD::SHL, DL, VecTy, One,
1643                                    Op->getOperand(2)));
1644   }
1645   case Intrinsic::mips_bseti_b:
1646   case Intrinsic::mips_bseti_h:
1647   case Intrinsic::mips_bseti_w:
1648   case Intrinsic::mips_bseti_d:
1649     return lowerMSABinaryBitImmIntr(Op, DAG, ISD::OR, Op->getOperand(2),
1650                                     !Subtarget->isLittle());
1651   case Intrinsic::mips_bz_b:
1652   case Intrinsic::mips_bz_h:
1653   case Intrinsic::mips_bz_w:
1654   case Intrinsic::mips_bz_d:
1655     return DAG.getNode(MipsISD::VALL_ZERO, DL, Op->getValueType(0),
1656                        Op->getOperand(1));
1657   case Intrinsic::mips_bz_v:
1658     return DAG.getNode(MipsISD::VANY_ZERO, DL, Op->getValueType(0),
1659                        Op->getOperand(1));
1660   case Intrinsic::mips_ceq_b:
1661   case Intrinsic::mips_ceq_h:
1662   case Intrinsic::mips_ceq_w:
1663   case Intrinsic::mips_ceq_d:
1664     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1665                         Op->getOperand(2), ISD::SETEQ);
1666   case Intrinsic::mips_ceqi_b:
1667   case Intrinsic::mips_ceqi_h:
1668   case Intrinsic::mips_ceqi_w:
1669   case Intrinsic::mips_ceqi_d:
1670     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1671                         lowerMSASplatImm(Op, 2, DAG), ISD::SETEQ);
1672   case Intrinsic::mips_cle_s_b:
1673   case Intrinsic::mips_cle_s_h:
1674   case Intrinsic::mips_cle_s_w:
1675   case Intrinsic::mips_cle_s_d:
1676     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1677                         Op->getOperand(2), ISD::SETLE);
1678   case Intrinsic::mips_clei_s_b:
1679   case Intrinsic::mips_clei_s_h:
1680   case Intrinsic::mips_clei_s_w:
1681   case Intrinsic::mips_clei_s_d:
1682     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1683                         lowerMSASplatImm(Op, 2, DAG), ISD::SETLE);
1684   case Intrinsic::mips_cle_u_b:
1685   case Intrinsic::mips_cle_u_h:
1686   case Intrinsic::mips_cle_u_w:
1687   case Intrinsic::mips_cle_u_d:
1688     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1689                         Op->getOperand(2), ISD::SETULE);
1690   case Intrinsic::mips_clei_u_b:
1691   case Intrinsic::mips_clei_u_h:
1692   case Intrinsic::mips_clei_u_w:
1693   case Intrinsic::mips_clei_u_d:
1694     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1695                         lowerMSASplatImm(Op, 2, DAG), ISD::SETULE);
1696   case Intrinsic::mips_clt_s_b:
1697   case Intrinsic::mips_clt_s_h:
1698   case Intrinsic::mips_clt_s_w:
1699   case Intrinsic::mips_clt_s_d:
1700     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1701                         Op->getOperand(2), ISD::SETLT);
1702   case Intrinsic::mips_clti_s_b:
1703   case Intrinsic::mips_clti_s_h:
1704   case Intrinsic::mips_clti_s_w:
1705   case Intrinsic::mips_clti_s_d:
1706     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1707                         lowerMSASplatImm(Op, 2, DAG), ISD::SETLT);
1708   case Intrinsic::mips_clt_u_b:
1709   case Intrinsic::mips_clt_u_h:
1710   case Intrinsic::mips_clt_u_w:
1711   case Intrinsic::mips_clt_u_d:
1712     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1713                         Op->getOperand(2), ISD::SETULT);
1714   case Intrinsic::mips_clti_u_b:
1715   case Intrinsic::mips_clti_u_h:
1716   case Intrinsic::mips_clti_u_w:
1717   case Intrinsic::mips_clti_u_d:
1718     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1719                         lowerMSASplatImm(Op, 2, DAG), ISD::SETULT);
1720   case Intrinsic::mips_copy_s_b:
1721   case Intrinsic::mips_copy_s_h:
1722   case Intrinsic::mips_copy_s_w:
1723     return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_SEXT_ELT);
1724   case Intrinsic::mips_copy_s_d:
1725     if (hasMips64())
1726       // Lower directly into VEXTRACT_SEXT_ELT since i64 is legal on Mips64.
1727       return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_SEXT_ELT);
1728     else {
1729       // Lower into the generic EXTRACT_VECTOR_ELT node and let the type
1730       // legalizer and EXTRACT_VECTOR_ELT lowering sort it out.
1731       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op),
1732                          Op->getValueType(0), Op->getOperand(1),
1733                          Op->getOperand(2));
1734     }
1735   case Intrinsic::mips_copy_u_b:
1736   case Intrinsic::mips_copy_u_h:
1737   case Intrinsic::mips_copy_u_w:
1738     return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_ZEXT_ELT);
1739   case Intrinsic::mips_copy_u_d:
1740     if (hasMips64())
1741       // Lower directly into VEXTRACT_ZEXT_ELT since i64 is legal on Mips64.
1742       return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_ZEXT_ELT);
1743     else {
1744       // Lower into the generic EXTRACT_VECTOR_ELT node and let the type
1745       // legalizer and EXTRACT_VECTOR_ELT lowering sort it out.
1746       // Note: When i64 is illegal, this results in copy_s.w instructions
1747       // instead of copy_u.w instructions. This makes no difference to the
1748       // behaviour since i64 is only illegal when the register file is 32-bit.
1749       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op),
1750                          Op->getValueType(0), Op->getOperand(1),
1751                          Op->getOperand(2));
1752     }
1753   case Intrinsic::mips_div_s_b:
1754   case Intrinsic::mips_div_s_h:
1755   case Intrinsic::mips_div_s_w:
1756   case Intrinsic::mips_div_s_d:
1757     return DAG.getNode(ISD::SDIV, DL, Op->getValueType(0), Op->getOperand(1),
1758                        Op->getOperand(2));
1759   case Intrinsic::mips_div_u_b:
1760   case Intrinsic::mips_div_u_h:
1761   case Intrinsic::mips_div_u_w:
1762   case Intrinsic::mips_div_u_d:
1763     return DAG.getNode(ISD::UDIV, DL, Op->getValueType(0), Op->getOperand(1),
1764                        Op->getOperand(2));
1765   case Intrinsic::mips_fadd_w:
1766   case Intrinsic::mips_fadd_d:
1767     return DAG.getNode(ISD::FADD, DL, Op->getValueType(0), Op->getOperand(1),
1768                        Op->getOperand(2));
1769   // Don't lower mips_fcaf_[wd] since LLVM folds SETFALSE condcodes away
1770   case Intrinsic::mips_fceq_w:
1771   case Intrinsic::mips_fceq_d:
1772     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1773                         Op->getOperand(2), ISD::SETOEQ);
1774   case Intrinsic::mips_fcle_w:
1775   case Intrinsic::mips_fcle_d:
1776     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1777                         Op->getOperand(2), ISD::SETOLE);
1778   case Intrinsic::mips_fclt_w:
1779   case Intrinsic::mips_fclt_d:
1780     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1781                         Op->getOperand(2), ISD::SETOLT);
1782   case Intrinsic::mips_fcne_w:
1783   case Intrinsic::mips_fcne_d:
1784     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1785                         Op->getOperand(2), ISD::SETONE);
1786   case Intrinsic::mips_fcor_w:
1787   case Intrinsic::mips_fcor_d:
1788     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1789                         Op->getOperand(2), ISD::SETO);
1790   case Intrinsic::mips_fcueq_w:
1791   case Intrinsic::mips_fcueq_d:
1792     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1793                         Op->getOperand(2), ISD::SETUEQ);
1794   case Intrinsic::mips_fcule_w:
1795   case Intrinsic::mips_fcule_d:
1796     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1797                         Op->getOperand(2), ISD::SETULE);
1798   case Intrinsic::mips_fcult_w:
1799   case Intrinsic::mips_fcult_d:
1800     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1801                         Op->getOperand(2), ISD::SETULT);
1802   case Intrinsic::mips_fcun_w:
1803   case Intrinsic::mips_fcun_d:
1804     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1805                         Op->getOperand(2), ISD::SETUO);
1806   case Intrinsic::mips_fcune_w:
1807   case Intrinsic::mips_fcune_d:
1808     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1809                         Op->getOperand(2), ISD::SETUNE);
1810   case Intrinsic::mips_fdiv_w:
1811   case Intrinsic::mips_fdiv_d:
1812     return DAG.getNode(ISD::FDIV, DL, Op->getValueType(0), Op->getOperand(1),
1813                        Op->getOperand(2));
1814   case Intrinsic::mips_ffint_u_w:
1815   case Intrinsic::mips_ffint_u_d:
1816     return DAG.getNode(ISD::UINT_TO_FP, DL, Op->getValueType(0),
1817                        Op->getOperand(1));
1818   case Intrinsic::mips_ffint_s_w:
1819   case Intrinsic::mips_ffint_s_d:
1820     return DAG.getNode(ISD::SINT_TO_FP, DL, Op->getValueType(0),
1821                        Op->getOperand(1));
1822   case Intrinsic::mips_fill_b:
1823   case Intrinsic::mips_fill_h:
1824   case Intrinsic::mips_fill_w:
1825   case Intrinsic::mips_fill_d: {
1826     SmallVector<SDValue, 16> Ops;
1827     EVT ResTy = Op->getValueType(0);
1828
1829     for (unsigned i = 0; i < ResTy.getVectorNumElements(); ++i)
1830       Ops.push_back(Op->getOperand(1));
1831
1832     // If ResTy is v2i64 then the type legalizer will break this node down into
1833     // an equivalent v4i32.
1834     return DAG.getNode(ISD::BUILD_VECTOR, DL, ResTy, Ops);
1835   }
1836   case Intrinsic::mips_fexp2_w:
1837   case Intrinsic::mips_fexp2_d: {
1838     EVT ResTy = Op->getValueType(0);
1839     return DAG.getNode(
1840         ISD::FMUL, SDLoc(Op), ResTy, Op->getOperand(1),
1841         DAG.getNode(ISD::FEXP2, SDLoc(Op), ResTy, Op->getOperand(2)));
1842   }
1843   case Intrinsic::mips_flog2_w:
1844   case Intrinsic::mips_flog2_d:
1845     return DAG.getNode(ISD::FLOG2, DL, Op->getValueType(0), Op->getOperand(1));
1846   case Intrinsic::mips_fmadd_w:
1847   case Intrinsic::mips_fmadd_d:
1848     return DAG.getNode(ISD::FMA, SDLoc(Op), Op->getValueType(0),
1849                        Op->getOperand(1), Op->getOperand(2), Op->getOperand(3));
1850   case Intrinsic::mips_fmul_w:
1851   case Intrinsic::mips_fmul_d:
1852     return DAG.getNode(ISD::FMUL, DL, Op->getValueType(0), Op->getOperand(1),
1853                        Op->getOperand(2));
1854   case Intrinsic::mips_fmsub_w:
1855   case Intrinsic::mips_fmsub_d: {
1856     EVT ResTy = Op->getValueType(0);
1857     return DAG.getNode(ISD::FSUB, SDLoc(Op), ResTy, Op->getOperand(1),
1858                        DAG.getNode(ISD::FMUL, SDLoc(Op), ResTy,
1859                                    Op->getOperand(2), Op->getOperand(3)));
1860   }
1861   case Intrinsic::mips_frint_w:
1862   case Intrinsic::mips_frint_d:
1863     return DAG.getNode(ISD::FRINT, DL, Op->getValueType(0), Op->getOperand(1));
1864   case Intrinsic::mips_fsqrt_w:
1865   case Intrinsic::mips_fsqrt_d:
1866     return DAG.getNode(ISD::FSQRT, DL, Op->getValueType(0), Op->getOperand(1));
1867   case Intrinsic::mips_fsub_w:
1868   case Intrinsic::mips_fsub_d:
1869     return DAG.getNode(ISD::FSUB, DL, Op->getValueType(0), Op->getOperand(1),
1870                        Op->getOperand(2));
1871   case Intrinsic::mips_ftrunc_u_w:
1872   case Intrinsic::mips_ftrunc_u_d:
1873     return DAG.getNode(ISD::FP_TO_UINT, DL, Op->getValueType(0),
1874                        Op->getOperand(1));
1875   case Intrinsic::mips_ftrunc_s_w:
1876   case Intrinsic::mips_ftrunc_s_d:
1877     return DAG.getNode(ISD::FP_TO_SINT, DL, Op->getValueType(0),
1878                        Op->getOperand(1));
1879   case Intrinsic::mips_ilvev_b:
1880   case Intrinsic::mips_ilvev_h:
1881   case Intrinsic::mips_ilvev_w:
1882   case Intrinsic::mips_ilvev_d:
1883     return DAG.getNode(MipsISD::ILVEV, DL, Op->getValueType(0),
1884                        Op->getOperand(1), Op->getOperand(2));
1885   case Intrinsic::mips_ilvl_b:
1886   case Intrinsic::mips_ilvl_h:
1887   case Intrinsic::mips_ilvl_w:
1888   case Intrinsic::mips_ilvl_d:
1889     return DAG.getNode(MipsISD::ILVL, DL, Op->getValueType(0),
1890                        Op->getOperand(1), Op->getOperand(2));
1891   case Intrinsic::mips_ilvod_b:
1892   case Intrinsic::mips_ilvod_h:
1893   case Intrinsic::mips_ilvod_w:
1894   case Intrinsic::mips_ilvod_d:
1895     return DAG.getNode(MipsISD::ILVOD, DL, Op->getValueType(0),
1896                        Op->getOperand(1), Op->getOperand(2));
1897   case Intrinsic::mips_ilvr_b:
1898   case Intrinsic::mips_ilvr_h:
1899   case Intrinsic::mips_ilvr_w:
1900   case Intrinsic::mips_ilvr_d:
1901     return DAG.getNode(MipsISD::ILVR, DL, Op->getValueType(0),
1902                        Op->getOperand(1), Op->getOperand(2));
1903   case Intrinsic::mips_insert_b:
1904   case Intrinsic::mips_insert_h:
1905   case Intrinsic::mips_insert_w:
1906   case Intrinsic::mips_insert_d:
1907     return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), Op->getValueType(0),
1908                        Op->getOperand(1), Op->getOperand(3), Op->getOperand(2));
1909   case Intrinsic::mips_insve_b:
1910   case Intrinsic::mips_insve_h:
1911   case Intrinsic::mips_insve_w:
1912   case Intrinsic::mips_insve_d:
1913     return DAG.getNode(MipsISD::INSVE, DL, Op->getValueType(0),
1914                        Op->getOperand(1), Op->getOperand(2), Op->getOperand(3),
1915                        DAG.getConstant(0, MVT::i32));
1916   case Intrinsic::mips_ldi_b:
1917   case Intrinsic::mips_ldi_h:
1918   case Intrinsic::mips_ldi_w:
1919   case Intrinsic::mips_ldi_d:
1920     return lowerMSASplatImm(Op, 1, DAG);
1921   case Intrinsic::mips_lsa:
1922   case Intrinsic::mips_dlsa: {
1923     EVT ResTy = Op->getValueType(0);
1924     return DAG.getNode(ISD::ADD, SDLoc(Op), ResTy, Op->getOperand(1),
1925                        DAG.getNode(ISD::SHL, SDLoc(Op), ResTy,
1926                                    Op->getOperand(2), Op->getOperand(3)));
1927   }
1928   case Intrinsic::mips_maddv_b:
1929   case Intrinsic::mips_maddv_h:
1930   case Intrinsic::mips_maddv_w:
1931   case Intrinsic::mips_maddv_d: {
1932     EVT ResTy = Op->getValueType(0);
1933     return DAG.getNode(ISD::ADD, SDLoc(Op), ResTy, Op->getOperand(1),
1934                        DAG.getNode(ISD::MUL, SDLoc(Op), ResTy,
1935                                    Op->getOperand(2), Op->getOperand(3)));
1936   }
1937   case Intrinsic::mips_max_s_b:
1938   case Intrinsic::mips_max_s_h:
1939   case Intrinsic::mips_max_s_w:
1940   case Intrinsic::mips_max_s_d:
1941     return DAG.getNode(MipsISD::VSMAX, DL, Op->getValueType(0),
1942                        Op->getOperand(1), Op->getOperand(2));
1943   case Intrinsic::mips_max_u_b:
1944   case Intrinsic::mips_max_u_h:
1945   case Intrinsic::mips_max_u_w:
1946   case Intrinsic::mips_max_u_d:
1947     return DAG.getNode(MipsISD::VUMAX, DL, Op->getValueType(0),
1948                        Op->getOperand(1), Op->getOperand(2));
1949   case Intrinsic::mips_maxi_s_b:
1950   case Intrinsic::mips_maxi_s_h:
1951   case Intrinsic::mips_maxi_s_w:
1952   case Intrinsic::mips_maxi_s_d:
1953     return DAG.getNode(MipsISD::VSMAX, DL, Op->getValueType(0),
1954                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1955   case Intrinsic::mips_maxi_u_b:
1956   case Intrinsic::mips_maxi_u_h:
1957   case Intrinsic::mips_maxi_u_w:
1958   case Intrinsic::mips_maxi_u_d:
1959     return DAG.getNode(MipsISD::VUMAX, DL, Op->getValueType(0),
1960                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1961   case Intrinsic::mips_min_s_b:
1962   case Intrinsic::mips_min_s_h:
1963   case Intrinsic::mips_min_s_w:
1964   case Intrinsic::mips_min_s_d:
1965     return DAG.getNode(MipsISD::VSMIN, DL, Op->getValueType(0),
1966                        Op->getOperand(1), Op->getOperand(2));
1967   case Intrinsic::mips_min_u_b:
1968   case Intrinsic::mips_min_u_h:
1969   case Intrinsic::mips_min_u_w:
1970   case Intrinsic::mips_min_u_d:
1971     return DAG.getNode(MipsISD::VUMIN, DL, Op->getValueType(0),
1972                        Op->getOperand(1), Op->getOperand(2));
1973   case Intrinsic::mips_mini_s_b:
1974   case Intrinsic::mips_mini_s_h:
1975   case Intrinsic::mips_mini_s_w:
1976   case Intrinsic::mips_mini_s_d:
1977     return DAG.getNode(MipsISD::VSMIN, DL, Op->getValueType(0),
1978                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1979   case Intrinsic::mips_mini_u_b:
1980   case Intrinsic::mips_mini_u_h:
1981   case Intrinsic::mips_mini_u_w:
1982   case Intrinsic::mips_mini_u_d:
1983     return DAG.getNode(MipsISD::VUMIN, DL, Op->getValueType(0),
1984                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1985   case Intrinsic::mips_mod_s_b:
1986   case Intrinsic::mips_mod_s_h:
1987   case Intrinsic::mips_mod_s_w:
1988   case Intrinsic::mips_mod_s_d:
1989     return DAG.getNode(ISD::SREM, DL, Op->getValueType(0), Op->getOperand(1),
1990                        Op->getOperand(2));
1991   case Intrinsic::mips_mod_u_b:
1992   case Intrinsic::mips_mod_u_h:
1993   case Intrinsic::mips_mod_u_w:
1994   case Intrinsic::mips_mod_u_d:
1995     return DAG.getNode(ISD::UREM, DL, Op->getValueType(0), Op->getOperand(1),
1996                        Op->getOperand(2));
1997   case Intrinsic::mips_mulv_b:
1998   case Intrinsic::mips_mulv_h:
1999   case Intrinsic::mips_mulv_w:
2000   case Intrinsic::mips_mulv_d:
2001     return DAG.getNode(ISD::MUL, DL, Op->getValueType(0), Op->getOperand(1),
2002                        Op->getOperand(2));
2003   case Intrinsic::mips_msubv_b:
2004   case Intrinsic::mips_msubv_h:
2005   case Intrinsic::mips_msubv_w:
2006   case Intrinsic::mips_msubv_d: {
2007     EVT ResTy = Op->getValueType(0);
2008     return DAG.getNode(ISD::SUB, SDLoc(Op), ResTy, Op->getOperand(1),
2009                        DAG.getNode(ISD::MUL, SDLoc(Op), ResTy,
2010                                    Op->getOperand(2), Op->getOperand(3)));
2011   }
2012   case Intrinsic::mips_nlzc_b:
2013   case Intrinsic::mips_nlzc_h:
2014   case Intrinsic::mips_nlzc_w:
2015   case Intrinsic::mips_nlzc_d:
2016     return DAG.getNode(ISD::CTLZ, DL, Op->getValueType(0), Op->getOperand(1));
2017   case Intrinsic::mips_nor_v: {
2018     SDValue Res = DAG.getNode(ISD::OR, DL, Op->getValueType(0),
2019                               Op->getOperand(1), Op->getOperand(2));
2020     return DAG.getNOT(DL, Res, Res->getValueType(0));
2021   }
2022   case Intrinsic::mips_nori_b: {
2023     SDValue Res =  DAG.getNode(ISD::OR, DL, Op->getValueType(0),
2024                                Op->getOperand(1),
2025                                lowerMSASplatImm(Op, 2, DAG));
2026     return DAG.getNOT(DL, Res, Res->getValueType(0));
2027   }
2028   case Intrinsic::mips_or_v:
2029     return DAG.getNode(ISD::OR, DL, Op->getValueType(0), Op->getOperand(1),
2030                        Op->getOperand(2));
2031   case Intrinsic::mips_ori_b:
2032     return DAG.getNode(ISD::OR, DL, Op->getValueType(0),
2033                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2034   case Intrinsic::mips_pckev_b:
2035   case Intrinsic::mips_pckev_h:
2036   case Intrinsic::mips_pckev_w:
2037   case Intrinsic::mips_pckev_d:
2038     return DAG.getNode(MipsISD::PCKEV, DL, Op->getValueType(0),
2039                        Op->getOperand(1), Op->getOperand(2));
2040   case Intrinsic::mips_pckod_b:
2041   case Intrinsic::mips_pckod_h:
2042   case Intrinsic::mips_pckod_w:
2043   case Intrinsic::mips_pckod_d:
2044     return DAG.getNode(MipsISD::PCKOD, DL, Op->getValueType(0),
2045                        Op->getOperand(1), Op->getOperand(2));
2046   case Intrinsic::mips_pcnt_b:
2047   case Intrinsic::mips_pcnt_h:
2048   case Intrinsic::mips_pcnt_w:
2049   case Intrinsic::mips_pcnt_d:
2050     return DAG.getNode(ISD::CTPOP, DL, Op->getValueType(0), Op->getOperand(1));
2051   case Intrinsic::mips_shf_b:
2052   case Intrinsic::mips_shf_h:
2053   case Intrinsic::mips_shf_w:
2054     return DAG.getNode(MipsISD::SHF, DL, Op->getValueType(0),
2055                        Op->getOperand(2), Op->getOperand(1));
2056   case Intrinsic::mips_sll_b:
2057   case Intrinsic::mips_sll_h:
2058   case Intrinsic::mips_sll_w:
2059   case Intrinsic::mips_sll_d:
2060     return DAG.getNode(ISD::SHL, DL, Op->getValueType(0), Op->getOperand(1),
2061                        Op->getOperand(2));
2062   case Intrinsic::mips_slli_b:
2063   case Intrinsic::mips_slli_h:
2064   case Intrinsic::mips_slli_w:
2065   case Intrinsic::mips_slli_d:
2066     return DAG.getNode(ISD::SHL, DL, Op->getValueType(0),
2067                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2068   case Intrinsic::mips_splat_b:
2069   case Intrinsic::mips_splat_h:
2070   case Intrinsic::mips_splat_w:
2071   case Intrinsic::mips_splat_d:
2072     // We can't lower via VECTOR_SHUFFLE because it requires constant shuffle
2073     // masks, nor can we lower via BUILD_VECTOR & EXTRACT_VECTOR_ELT because
2074     // EXTRACT_VECTOR_ELT can't extract i64's on MIPS32.
2075     // Instead we lower to MipsISD::VSHF and match from there.
2076     return DAG.getNode(MipsISD::VSHF, DL, Op->getValueType(0),
2077                        lowerMSASplatZExt(Op, 2, DAG), Op->getOperand(1),
2078                        Op->getOperand(1));
2079   case Intrinsic::mips_splati_b:
2080   case Intrinsic::mips_splati_h:
2081   case Intrinsic::mips_splati_w:
2082   case Intrinsic::mips_splati_d:
2083     return DAG.getNode(MipsISD::VSHF, DL, Op->getValueType(0),
2084                        lowerMSASplatImm(Op, 2, DAG), Op->getOperand(1),
2085                        Op->getOperand(1));
2086   case Intrinsic::mips_sra_b:
2087   case Intrinsic::mips_sra_h:
2088   case Intrinsic::mips_sra_w:
2089   case Intrinsic::mips_sra_d:
2090     return DAG.getNode(ISD::SRA, DL, Op->getValueType(0), Op->getOperand(1),
2091                        Op->getOperand(2));
2092   case Intrinsic::mips_srai_b:
2093   case Intrinsic::mips_srai_h:
2094   case Intrinsic::mips_srai_w:
2095   case Intrinsic::mips_srai_d:
2096     return DAG.getNode(ISD::SRA, DL, Op->getValueType(0),
2097                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2098   case Intrinsic::mips_srl_b:
2099   case Intrinsic::mips_srl_h:
2100   case Intrinsic::mips_srl_w:
2101   case Intrinsic::mips_srl_d:
2102     return DAG.getNode(ISD::SRL, DL, Op->getValueType(0), Op->getOperand(1),
2103                        Op->getOperand(2));
2104   case Intrinsic::mips_srli_b:
2105   case Intrinsic::mips_srli_h:
2106   case Intrinsic::mips_srli_w:
2107   case Intrinsic::mips_srli_d:
2108     return DAG.getNode(ISD::SRL, DL, Op->getValueType(0),
2109                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2110   case Intrinsic::mips_subv_b:
2111   case Intrinsic::mips_subv_h:
2112   case Intrinsic::mips_subv_w:
2113   case Intrinsic::mips_subv_d:
2114     return DAG.getNode(ISD::SUB, DL, Op->getValueType(0), Op->getOperand(1),
2115                        Op->getOperand(2));
2116   case Intrinsic::mips_subvi_b:
2117   case Intrinsic::mips_subvi_h:
2118   case Intrinsic::mips_subvi_w:
2119   case Intrinsic::mips_subvi_d:
2120     return DAG.getNode(ISD::SUB, DL, Op->getValueType(0),
2121                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2122   case Intrinsic::mips_vshf_b:
2123   case Intrinsic::mips_vshf_h:
2124   case Intrinsic::mips_vshf_w:
2125   case Intrinsic::mips_vshf_d:
2126     return DAG.getNode(MipsISD::VSHF, DL, Op->getValueType(0),
2127                        Op->getOperand(1), Op->getOperand(2), Op->getOperand(3));
2128   case Intrinsic::mips_xor_v:
2129     return DAG.getNode(ISD::XOR, DL, Op->getValueType(0), Op->getOperand(1),
2130                        Op->getOperand(2));
2131   case Intrinsic::mips_xori_b:
2132     return DAG.getNode(ISD::XOR, DL, Op->getValueType(0),
2133                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2134   }
2135 }
2136
2137 static SDValue lowerMSALoadIntr(SDValue Op, SelectionDAG &DAG, unsigned Intr) {
2138   SDLoc DL(Op);
2139   SDValue ChainIn = Op->getOperand(0);
2140   SDValue Address = Op->getOperand(2);
2141   SDValue Offset  = Op->getOperand(3);
2142   EVT ResTy = Op->getValueType(0);
2143   EVT PtrTy = Address->getValueType(0);
2144
2145   Address = DAG.getNode(ISD::ADD, DL, PtrTy, Address, Offset);
2146
2147   return DAG.getLoad(ResTy, DL, ChainIn, Address, MachinePointerInfo(), false,
2148                      false, false, 16);
2149 }
2150
2151 SDValue MipsSETargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
2152                                                      SelectionDAG &DAG) const {
2153   unsigned Intr = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
2154   switch (Intr) {
2155   default:
2156     return SDValue();
2157   case Intrinsic::mips_extp:
2158     return lowerDSPIntr(Op, DAG, MipsISD::EXTP);
2159   case Intrinsic::mips_extpdp:
2160     return lowerDSPIntr(Op, DAG, MipsISD::EXTPDP);
2161   case Intrinsic::mips_extr_w:
2162     return lowerDSPIntr(Op, DAG, MipsISD::EXTR_W);
2163   case Intrinsic::mips_extr_r_w:
2164     return lowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W);
2165   case Intrinsic::mips_extr_rs_w:
2166     return lowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W);
2167   case Intrinsic::mips_extr_s_h:
2168     return lowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H);
2169   case Intrinsic::mips_mthlip:
2170     return lowerDSPIntr(Op, DAG, MipsISD::MTHLIP);
2171   case Intrinsic::mips_mulsaq_s_w_ph:
2172     return lowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH);
2173   case Intrinsic::mips_maq_s_w_phl:
2174     return lowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL);
2175   case Intrinsic::mips_maq_s_w_phr:
2176     return lowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR);
2177   case Intrinsic::mips_maq_sa_w_phl:
2178     return lowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL);
2179   case Intrinsic::mips_maq_sa_w_phr:
2180     return lowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR);
2181   case Intrinsic::mips_dpaq_s_w_ph:
2182     return lowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH);
2183   case Intrinsic::mips_dpsq_s_w_ph:
2184     return lowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH);
2185   case Intrinsic::mips_dpaq_sa_l_w:
2186     return lowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W);
2187   case Intrinsic::mips_dpsq_sa_l_w:
2188     return lowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W);
2189   case Intrinsic::mips_dpaqx_s_w_ph:
2190     return lowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH);
2191   case Intrinsic::mips_dpaqx_sa_w_ph:
2192     return lowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH);
2193   case Intrinsic::mips_dpsqx_s_w_ph:
2194     return lowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH);
2195   case Intrinsic::mips_dpsqx_sa_w_ph:
2196     return lowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH);
2197   case Intrinsic::mips_ld_b:
2198   case Intrinsic::mips_ld_h:
2199   case Intrinsic::mips_ld_w:
2200   case Intrinsic::mips_ld_d:
2201    return lowerMSALoadIntr(Op, DAG, Intr);
2202   }
2203 }
2204
2205 static SDValue lowerMSAStoreIntr(SDValue Op, SelectionDAG &DAG, unsigned Intr) {
2206   SDLoc DL(Op);
2207   SDValue ChainIn = Op->getOperand(0);
2208   SDValue Value   = Op->getOperand(2);
2209   SDValue Address = Op->getOperand(3);
2210   SDValue Offset  = Op->getOperand(4);
2211   EVT PtrTy = Address->getValueType(0);
2212
2213   Address = DAG.getNode(ISD::ADD, DL, PtrTy, Address, Offset);
2214
2215   return DAG.getStore(ChainIn, DL, Value, Address, MachinePointerInfo(), false,
2216                       false, 16);
2217 }
2218
2219 SDValue MipsSETargetLowering::lowerINTRINSIC_VOID(SDValue Op,
2220                                                   SelectionDAG &DAG) const {
2221   unsigned Intr = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
2222   switch (Intr) {
2223   default:
2224     return SDValue();
2225   case Intrinsic::mips_st_b:
2226   case Intrinsic::mips_st_h:
2227   case Intrinsic::mips_st_w:
2228   case Intrinsic::mips_st_d:
2229     return lowerMSAStoreIntr(Op, DAG, Intr);
2230   }
2231 }
2232
2233 /// \brief Check if the given BuildVectorSDNode is a splat.
2234 /// This method currently relies on DAG nodes being reused when equivalent,
2235 /// so it's possible for this to return false even when isConstantSplat returns
2236 /// true.
2237 static bool isSplatVector(const BuildVectorSDNode *N) {
2238   unsigned int nOps = N->getNumOperands();
2239   assert(nOps > 1 && "isSplatVector has 0 or 1 sized build vector");
2240
2241   SDValue Operand0 = N->getOperand(0);
2242
2243   for (unsigned int i = 1; i < nOps; ++i) {
2244     if (N->getOperand(i) != Operand0)
2245       return false;
2246   }
2247
2248   return true;
2249 }
2250
2251 // Lower ISD::EXTRACT_VECTOR_ELT into MipsISD::VEXTRACT_SEXT_ELT.
2252 //
2253 // The non-value bits resulting from ISD::EXTRACT_VECTOR_ELT are undefined. We
2254 // choose to sign-extend but we could have equally chosen zero-extend. The
2255 // DAGCombiner will fold any sign/zero extension of the ISD::EXTRACT_VECTOR_ELT
2256 // result into this node later (possibly changing it to a zero-extend in the
2257 // process).
2258 SDValue MipsSETargetLowering::
2259 lowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
2260   SDLoc DL(Op);
2261   EVT ResTy = Op->getValueType(0);
2262   SDValue Op0 = Op->getOperand(0);
2263   EVT VecTy = Op0->getValueType(0);
2264
2265   if (!VecTy.is128BitVector())
2266     return SDValue();
2267
2268   if (ResTy.isInteger()) {
2269     SDValue Op1 = Op->getOperand(1);
2270     EVT EltTy = VecTy.getVectorElementType();
2271     return DAG.getNode(MipsISD::VEXTRACT_SEXT_ELT, DL, ResTy, Op0, Op1,
2272                        DAG.getValueType(EltTy));
2273   }
2274
2275   return Op;
2276 }
2277
2278 static bool isConstantOrUndef(const SDValue Op) {
2279   if (Op->getOpcode() == ISD::UNDEF)
2280     return true;
2281   if (dyn_cast<ConstantSDNode>(Op))
2282     return true;
2283   if (dyn_cast<ConstantFPSDNode>(Op))
2284     return true;
2285   return false;
2286 }
2287
2288 static bool isConstantOrUndefBUILD_VECTOR(const BuildVectorSDNode *Op) {
2289   for (unsigned i = 0; i < Op->getNumOperands(); ++i)
2290     if (isConstantOrUndef(Op->getOperand(i)))
2291       return true;
2292   return false;
2293 }
2294
2295 // Lowers ISD::BUILD_VECTOR into appropriate SelectionDAG nodes for the
2296 // backend.
2297 //
2298 // Lowers according to the following rules:
2299 // - Constant splats are legal as-is as long as the SplatBitSize is a power of
2300 //   2 less than or equal to 64 and the value fits into a signed 10-bit
2301 //   immediate
2302 // - Constant splats are lowered to bitconverted BUILD_VECTORs if SplatBitSize
2303 //   is a power of 2 less than or equal to 64 and the value does not fit into a
2304 //   signed 10-bit immediate
2305 // - Non-constant splats are legal as-is.
2306 // - Non-constant non-splats are lowered to sequences of INSERT_VECTOR_ELT.
2307 // - All others are illegal and must be expanded.
2308 SDValue MipsSETargetLowering::lowerBUILD_VECTOR(SDValue Op,
2309                                                 SelectionDAG &DAG) const {
2310   BuildVectorSDNode *Node = cast<BuildVectorSDNode>(Op);
2311   EVT ResTy = Op->getValueType(0);
2312   SDLoc DL(Op);
2313   APInt SplatValue, SplatUndef;
2314   unsigned SplatBitSize;
2315   bool HasAnyUndefs;
2316
2317   if (!Subtarget->hasMSA() || !ResTy.is128BitVector())
2318     return SDValue();
2319
2320   if (Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
2321                             HasAnyUndefs, 8,
2322                             !Subtarget->isLittle()) && SplatBitSize <= 64) {
2323     // We can only cope with 8, 16, 32, or 64-bit elements
2324     if (SplatBitSize != 8 && SplatBitSize != 16 && SplatBitSize != 32 &&
2325         SplatBitSize != 64)
2326       return SDValue();
2327
2328     // If the value fits into a simm10 then we can use ldi.[bhwd]
2329     // However, if it isn't an integer type we will have to bitcast from an
2330     // integer type first. Also, if there are any undefs, we must lower them
2331     // to defined values first.
2332     if (ResTy.isInteger() && !HasAnyUndefs && SplatValue.isSignedIntN(10))
2333       return Op;
2334
2335     EVT ViaVecTy;
2336
2337     switch (SplatBitSize) {
2338     default:
2339       return SDValue();
2340     case 8:
2341       ViaVecTy = MVT::v16i8;
2342       break;
2343     case 16:
2344       ViaVecTy = MVT::v8i16;
2345       break;
2346     case 32:
2347       ViaVecTy = MVT::v4i32;
2348       break;
2349     case 64:
2350       // There's no fill.d to fall back on for 64-bit values
2351       return SDValue();
2352     }
2353
2354     // SelectionDAG::getConstant will promote SplatValue appropriately.
2355     SDValue Result = DAG.getConstant(SplatValue, ViaVecTy);
2356
2357     // Bitcast to the type we originally wanted
2358     if (ViaVecTy != ResTy)
2359       Result = DAG.getNode(ISD::BITCAST, SDLoc(Node), ResTy, Result);
2360
2361     return Result;
2362   } else if (isSplatVector(Node))
2363     return Op;
2364   else if (!isConstantOrUndefBUILD_VECTOR(Node)) {
2365     // Use INSERT_VECTOR_ELT operations rather than expand to stores.
2366     // The resulting code is the same length as the expansion, but it doesn't
2367     // use memory operations
2368     EVT ResTy = Node->getValueType(0);
2369
2370     assert(ResTy.isVector());
2371
2372     unsigned NumElts = ResTy.getVectorNumElements();
2373     SDValue Vector = DAG.getUNDEF(ResTy);
2374     for (unsigned i = 0; i < NumElts; ++i) {
2375       Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ResTy, Vector,
2376                            Node->getOperand(i),
2377                            DAG.getConstant(i, MVT::i32));
2378     }
2379     return Vector;
2380   }
2381
2382   return SDValue();
2383 }
2384
2385 // Lower VECTOR_SHUFFLE into SHF (if possible).
2386 //
2387 // SHF splits the vector into blocks of four elements, then shuffles these
2388 // elements according to a <4 x i2> constant (encoded as an integer immediate).
2389 //
2390 // It is therefore possible to lower into SHF when the mask takes the form:
2391 //   <a, b, c, d, a+4, b+4, c+4, d+4, a+8, b+8, c+8, d+8, ...>
2392 // When undef's appear they are treated as if they were whatever value is
2393 // necessary in order to fit the above form.
2394 //
2395 // For example:
2396 //   %2 = shufflevector <8 x i16> %0, <8 x i16> undef,
2397 //                      <8 x i32> <i32 3, i32 2, i32 1, i32 0,
2398 //                                 i32 7, i32 6, i32 5, i32 4>
2399 // is lowered to:
2400 //   (SHF_H $w0, $w1, 27)
2401 // where the 27 comes from:
2402 //   3 + (2 << 2) + (1 << 4) + (0 << 6)
2403 static SDValue lowerVECTOR_SHUFFLE_SHF(SDValue Op, EVT ResTy,
2404                                        SmallVector<int, 16> Indices,
2405                                        SelectionDAG &DAG) {
2406   int SHFIndices[4] = { -1, -1, -1, -1 };
2407
2408   if (Indices.size() < 4)
2409     return SDValue();
2410
2411   for (unsigned i = 0; i < 4; ++i) {
2412     for (unsigned j = i; j < Indices.size(); j += 4) {
2413       int Idx = Indices[j];
2414
2415       // Convert from vector index to 4-element subvector index
2416       // If an index refers to an element outside of the subvector then give up
2417       if (Idx != -1) {
2418         Idx -= 4 * (j / 4);
2419         if (Idx < 0 || Idx >= 4)
2420           return SDValue();
2421       }
2422
2423       // If the mask has an undef, replace it with the current index.
2424       // Note that it might still be undef if the current index is also undef
2425       if (SHFIndices[i] == -1)
2426         SHFIndices[i] = Idx;
2427
2428       // Check that non-undef values are the same as in the mask. If they
2429       // aren't then give up
2430       if (!(Idx == -1 || Idx == SHFIndices[i]))
2431         return SDValue();
2432     }
2433   }
2434
2435   // Calculate the immediate. Replace any remaining undefs with zero
2436   APInt Imm(32, 0);
2437   for (int i = 3; i >= 0; --i) {
2438     int Idx = SHFIndices[i];
2439
2440     if (Idx == -1)
2441       Idx = 0;
2442
2443     Imm <<= 2;
2444     Imm |= Idx & 0x3;
2445   }
2446
2447   return DAG.getNode(MipsISD::SHF, SDLoc(Op), ResTy,
2448                      DAG.getConstant(Imm, MVT::i32), Op->getOperand(0));
2449 }
2450
2451 // Lower VECTOR_SHUFFLE into ILVEV (if possible).
2452 //
2453 // ILVEV interleaves the even elements from each vector.
2454 //
2455 // It is possible to lower into ILVEV when the mask takes the form:
2456 //   <0, n, 2, n+2, 4, n+4, ...>
2457 // where n is the number of elements in the vector.
2458 //
2459 // When undef's appear in the mask they are treated as if they were whatever
2460 // value is necessary in order to fit the above form.
2461 static SDValue lowerVECTOR_SHUFFLE_ILVEV(SDValue Op, EVT ResTy,
2462                                          SmallVector<int, 16> Indices,
2463                                          SelectionDAG &DAG) {
2464   assert ((Indices.size() % 2) == 0);
2465   int WsIdx = 0;
2466   int WtIdx = ResTy.getVectorNumElements();
2467
2468   for (unsigned i = 0; i < Indices.size(); i += 2) {
2469     if (Indices[i] != -1 && Indices[i] != WsIdx)
2470       return SDValue();
2471     if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2472       return SDValue();
2473     WsIdx += 2;
2474     WtIdx += 2;
2475   }
2476
2477   return DAG.getNode(MipsISD::ILVEV, SDLoc(Op), ResTy, Op->getOperand(0),
2478                      Op->getOperand(1));
2479 }
2480
2481 // Lower VECTOR_SHUFFLE into ILVOD (if possible).
2482 //
2483 // ILVOD interleaves the odd elements from each vector.
2484 //
2485 // It is possible to lower into ILVOD when the mask takes the form:
2486 //   <1, n+1, 3, n+3, 5, n+5, ...>
2487 // where n is the number of elements in the vector.
2488 //
2489 // When undef's appear in the mask they are treated as if they were whatever
2490 // value is necessary in order to fit the above form.
2491 static SDValue lowerVECTOR_SHUFFLE_ILVOD(SDValue Op, EVT ResTy,
2492                                          SmallVector<int, 16> Indices,
2493                                          SelectionDAG &DAG) {
2494   assert ((Indices.size() % 2) == 0);
2495   int WsIdx = 1;
2496   int WtIdx = ResTy.getVectorNumElements() + 1;
2497
2498   for (unsigned i = 0; i < Indices.size(); i += 2) {
2499     if (Indices[i] != -1 && Indices[i] != WsIdx)
2500       return SDValue();
2501     if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2502       return SDValue();
2503     WsIdx += 2;
2504     WtIdx += 2;
2505   }
2506
2507   return DAG.getNode(MipsISD::ILVOD, SDLoc(Op), ResTy, Op->getOperand(0),
2508                      Op->getOperand(1));
2509 }
2510
2511 // Lower VECTOR_SHUFFLE into ILVL (if possible).
2512 //
2513 // ILVL interleaves consecutive elements from the left half of each vector.
2514 //
2515 // It is possible to lower into ILVL when the mask takes the form:
2516 //   <0, n, 1, n+1, 2, n+2, ...>
2517 // where n is the number of elements in the vector.
2518 //
2519 // When undef's appear in the mask they are treated as if they were whatever
2520 // value is necessary in order to fit the above form.
2521 static SDValue lowerVECTOR_SHUFFLE_ILVL(SDValue Op, EVT ResTy,
2522                                         SmallVector<int, 16> Indices,
2523                                         SelectionDAG &DAG) {
2524   assert ((Indices.size() % 2) == 0);
2525   int WsIdx = 0;
2526   int WtIdx = ResTy.getVectorNumElements();
2527
2528   for (unsigned i = 0; i < Indices.size(); i += 2) {
2529     if (Indices[i] != -1 && Indices[i] != WsIdx)
2530       return SDValue();
2531     if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2532       return SDValue();
2533     WsIdx ++;
2534     WtIdx ++;
2535   }
2536
2537   return DAG.getNode(MipsISD::ILVL, SDLoc(Op), ResTy, Op->getOperand(0),
2538                      Op->getOperand(1));
2539 }
2540
2541 // Lower VECTOR_SHUFFLE into ILVR (if possible).
2542 //
2543 // ILVR interleaves consecutive elements from the right half of each vector.
2544 //
2545 // It is possible to lower into ILVR when the mask takes the form:
2546 //   <x, n+x, x+1, n+x+1, x+2, n+x+2, ...>
2547 // where n is the number of elements in the vector and x is half n.
2548 //
2549 // When undef's appear in the mask they are treated as if they were whatever
2550 // value is necessary in order to fit the above form.
2551 static SDValue lowerVECTOR_SHUFFLE_ILVR(SDValue Op, EVT ResTy,
2552                                         SmallVector<int, 16> Indices,
2553                                         SelectionDAG &DAG) {
2554   assert ((Indices.size() % 2) == 0);
2555   unsigned NumElts = ResTy.getVectorNumElements();
2556   int WsIdx = NumElts / 2;
2557   int WtIdx = NumElts + NumElts / 2;
2558
2559   for (unsigned i = 0; i < Indices.size(); i += 2) {
2560     if (Indices[i] != -1 && Indices[i] != WsIdx)
2561       return SDValue();
2562     if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2563       return SDValue();
2564     WsIdx ++;
2565     WtIdx ++;
2566   }
2567
2568   return DAG.getNode(MipsISD::ILVR, SDLoc(Op), ResTy, Op->getOperand(0),
2569                      Op->getOperand(1));
2570 }
2571
2572 // Lower VECTOR_SHUFFLE into PCKEV (if possible).
2573 //
2574 // PCKEV copies the even elements of each vector into the result vector.
2575 //
2576 // It is possible to lower into PCKEV when the mask takes the form:
2577 //   <0, 2, 4, ..., n, n+2, n+4, ...>
2578 // where n is the number of elements in the vector.
2579 //
2580 // When undef's appear in the mask they are treated as if they were whatever
2581 // value is necessary in order to fit the above form.
2582 static SDValue lowerVECTOR_SHUFFLE_PCKEV(SDValue Op, EVT ResTy,
2583                                          SmallVector<int, 16> Indices,
2584                                          SelectionDAG &DAG) {
2585   assert ((Indices.size() % 2) == 0);
2586   int Idx = 0;
2587
2588   for (unsigned i = 0; i < Indices.size(); ++i) {
2589     if (Indices[i] != -1 && Indices[i] != Idx)
2590       return SDValue();
2591     Idx += 2;
2592   }
2593
2594   return DAG.getNode(MipsISD::PCKEV, SDLoc(Op), ResTy, Op->getOperand(0),
2595                      Op->getOperand(1));
2596 }
2597
2598 // Lower VECTOR_SHUFFLE into PCKOD (if possible).
2599 //
2600 // PCKOD copies the odd elements of each vector into the result vector.
2601 //
2602 // It is possible to lower into PCKOD when the mask takes the form:
2603 //   <1, 3, 5, ..., n+1, n+3, n+5, ...>
2604 // where n is the number of elements in the vector.
2605 //
2606 // When undef's appear in the mask they are treated as if they were whatever
2607 // value is necessary in order to fit the above form.
2608 static SDValue lowerVECTOR_SHUFFLE_PCKOD(SDValue Op, EVT ResTy,
2609                                          SmallVector<int, 16> Indices,
2610                                          SelectionDAG &DAG) {
2611   assert ((Indices.size() % 2) == 0);
2612   int Idx = 1;
2613
2614   for (unsigned i = 0; i < Indices.size(); ++i) {
2615     if (Indices[i] != -1 && Indices[i] != Idx)
2616       return SDValue();
2617     Idx += 2;
2618   }
2619
2620   return DAG.getNode(MipsISD::PCKOD, SDLoc(Op), ResTy, Op->getOperand(0),
2621                      Op->getOperand(1));
2622 }
2623
2624 // Lower VECTOR_SHUFFLE into VSHF.
2625 //
2626 // This mostly consists of converting the shuffle indices in Indices into a
2627 // BUILD_VECTOR and adding it as an operand to the resulting VSHF. There is
2628 // also code to eliminate unused operands of the VECTOR_SHUFFLE. For example,
2629 // if the type is v8i16 and all the indices are less than 8 then the second
2630 // operand is unused and can be replaced with anything. We choose to replace it
2631 // with the used operand since this reduces the number of instructions overall.
2632 static SDValue lowerVECTOR_SHUFFLE_VSHF(SDValue Op, EVT ResTy,
2633                                         SmallVector<int, 16> Indices,
2634                                         SelectionDAG &DAG) {
2635   SmallVector<SDValue, 16> Ops;
2636   SDValue Op0;
2637   SDValue Op1;
2638   EVT MaskVecTy = ResTy.changeVectorElementTypeToInteger();
2639   EVT MaskEltTy = MaskVecTy.getVectorElementType();
2640   bool Using1stVec = false;
2641   bool Using2ndVec = false;
2642   SDLoc DL(Op);
2643   int ResTyNumElts = ResTy.getVectorNumElements();
2644
2645   for (int i = 0; i < ResTyNumElts; ++i) {
2646     // Idx == -1 means UNDEF
2647     int Idx = Indices[i];
2648
2649     if (0 <= Idx && Idx < ResTyNumElts)
2650       Using1stVec = true;
2651     if (ResTyNumElts <= Idx && Idx < ResTyNumElts * 2)
2652       Using2ndVec = true;
2653   }
2654
2655   for (SmallVector<int, 16>::iterator I = Indices.begin(); I != Indices.end();
2656        ++I)
2657     Ops.push_back(DAG.getTargetConstant(*I, MaskEltTy));
2658
2659   SDValue MaskVec = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecTy, Ops);
2660
2661   if (Using1stVec && Using2ndVec) {
2662     Op0 = Op->getOperand(0);
2663     Op1 = Op->getOperand(1);
2664   } else if (Using1stVec)
2665     Op0 = Op1 = Op->getOperand(0);
2666   else if (Using2ndVec)
2667     Op0 = Op1 = Op->getOperand(1);
2668   else
2669     llvm_unreachable("shuffle vector mask references neither vector operand?");
2670
2671   // VECTOR_SHUFFLE concatenates the vectors in an vectorwise fashion.
2672   // <0b00, 0b01> + <0b10, 0b11> -> <0b00, 0b01, 0b10, 0b11>
2673   // VSHF concatenates the vectors in a bitwise fashion:
2674   // <0b00, 0b01> + <0b10, 0b11> ->
2675   // 0b0100       + 0b1110       -> 0b01001110
2676   //                                <0b10, 0b11, 0b00, 0b01>
2677   // We must therefore swap the operands to get the correct result.
2678   return DAG.getNode(MipsISD::VSHF, DL, ResTy, MaskVec, Op1, Op0);
2679 }
2680
2681 // Lower VECTOR_SHUFFLE into one of a number of instructions depending on the
2682 // indices in the shuffle.
2683 SDValue MipsSETargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
2684                                                   SelectionDAG &DAG) const {
2685   ShuffleVectorSDNode *Node = cast<ShuffleVectorSDNode>(Op);
2686   EVT ResTy = Op->getValueType(0);
2687
2688   if (!ResTy.is128BitVector())
2689     return SDValue();
2690
2691   int ResTyNumElts = ResTy.getVectorNumElements();
2692   SmallVector<int, 16> Indices;
2693
2694   for (int i = 0; i < ResTyNumElts; ++i)
2695     Indices.push_back(Node->getMaskElt(i));
2696
2697   SDValue Result = lowerVECTOR_SHUFFLE_SHF(Op, ResTy, Indices, DAG);
2698   if (Result.getNode())
2699     return Result;
2700   Result = lowerVECTOR_SHUFFLE_ILVEV(Op, ResTy, Indices, DAG);
2701   if (Result.getNode())
2702     return Result;
2703   Result = lowerVECTOR_SHUFFLE_ILVOD(Op, ResTy, Indices, DAG);
2704   if (Result.getNode())
2705     return Result;
2706   Result = lowerVECTOR_SHUFFLE_ILVL(Op, ResTy, Indices, DAG);
2707   if (Result.getNode())
2708     return Result;
2709   Result = lowerVECTOR_SHUFFLE_ILVR(Op, ResTy, Indices, DAG);
2710   if (Result.getNode())
2711     return Result;
2712   Result = lowerVECTOR_SHUFFLE_PCKEV(Op, ResTy, Indices, DAG);
2713   if (Result.getNode())
2714     return Result;
2715   Result = lowerVECTOR_SHUFFLE_PCKOD(Op, ResTy, Indices, DAG);
2716   if (Result.getNode())
2717     return Result;
2718   return lowerVECTOR_SHUFFLE_VSHF(Op, ResTy, Indices, DAG);
2719 }
2720
2721 MachineBasicBlock * MipsSETargetLowering::
2722 emitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
2723   // $bb:
2724   //  bposge32_pseudo $vr0
2725   //  =>
2726   // $bb:
2727   //  bposge32 $tbb
2728   // $fbb:
2729   //  li $vr2, 0
2730   //  b $sink
2731   // $tbb:
2732   //  li $vr1, 1
2733   // $sink:
2734   //  $vr0 = phi($vr2, $fbb, $vr1, $tbb)
2735
2736   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2737   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2738   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
2739   DebugLoc DL = MI->getDebugLoc();
2740   const BasicBlock *LLVM_BB = BB->getBasicBlock();
2741   MachineFunction::iterator It = std::next(MachineFunction::iterator(BB));
2742   MachineFunction *F = BB->getParent();
2743   MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
2744   MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
2745   MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
2746   F->insert(It, FBB);
2747   F->insert(It, TBB);
2748   F->insert(It, Sink);
2749
2750   // Transfer the remainder of BB and its successor edges to Sink.
2751   Sink->splice(Sink->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
2752                BB->end());
2753   Sink->transferSuccessorsAndUpdatePHIs(BB);
2754
2755   // Add successors.
2756   BB->addSuccessor(FBB);
2757   BB->addSuccessor(TBB);
2758   FBB->addSuccessor(Sink);
2759   TBB->addSuccessor(Sink);
2760
2761   // Insert the real bposge32 instruction to $BB.
2762   BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
2763
2764   // Fill $FBB.
2765   unsigned VR2 = RegInfo.createVirtualRegister(RC);
2766   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
2767     .addReg(Mips::ZERO).addImm(0);
2768   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
2769
2770   // Fill $TBB.
2771   unsigned VR1 = RegInfo.createVirtualRegister(RC);
2772   BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
2773     .addReg(Mips::ZERO).addImm(1);
2774
2775   // Insert phi function to $Sink.
2776   BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
2777           MI->getOperand(0).getReg())
2778     .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
2779
2780   MI->eraseFromParent();   // The pseudo instruction is gone now.
2781   return Sink;
2782 }
2783
2784 MachineBasicBlock * MipsSETargetLowering::
2785 emitMSACBranchPseudo(MachineInstr *MI, MachineBasicBlock *BB,
2786                      unsigned BranchOp) const{
2787   // $bb:
2788   //  vany_nonzero $rd, $ws
2789   //  =>
2790   // $bb:
2791   //  bnz.b $ws, $tbb
2792   //  b $fbb
2793   // $fbb:
2794   //  li $rd1, 0
2795   //  b $sink
2796   // $tbb:
2797   //  li $rd2, 1
2798   // $sink:
2799   //  $rd = phi($rd1, $fbb, $rd2, $tbb)
2800
2801   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2802   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2803   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
2804   DebugLoc DL = MI->getDebugLoc();
2805   const BasicBlock *LLVM_BB = BB->getBasicBlock();
2806   MachineFunction::iterator It = std::next(MachineFunction::iterator(BB));
2807   MachineFunction *F = BB->getParent();
2808   MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
2809   MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
2810   MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
2811   F->insert(It, FBB);
2812   F->insert(It, TBB);
2813   F->insert(It, Sink);
2814
2815   // Transfer the remainder of BB and its successor edges to Sink.
2816   Sink->splice(Sink->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
2817                BB->end());
2818   Sink->transferSuccessorsAndUpdatePHIs(BB);
2819
2820   // Add successors.
2821   BB->addSuccessor(FBB);
2822   BB->addSuccessor(TBB);
2823   FBB->addSuccessor(Sink);
2824   TBB->addSuccessor(Sink);
2825
2826   // Insert the real bnz.b instruction to $BB.
2827   BuildMI(BB, DL, TII->get(BranchOp))
2828     .addReg(MI->getOperand(1).getReg())
2829     .addMBB(TBB);
2830
2831   // Fill $FBB.
2832   unsigned RD1 = RegInfo.createVirtualRegister(RC);
2833   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), RD1)
2834     .addReg(Mips::ZERO).addImm(0);
2835   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
2836
2837   // Fill $TBB.
2838   unsigned RD2 = RegInfo.createVirtualRegister(RC);
2839   BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), RD2)
2840     .addReg(Mips::ZERO).addImm(1);
2841
2842   // Insert phi function to $Sink.
2843   BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
2844           MI->getOperand(0).getReg())
2845     .addReg(RD1).addMBB(FBB).addReg(RD2).addMBB(TBB);
2846
2847   MI->eraseFromParent();   // The pseudo instruction is gone now.
2848   return Sink;
2849 }
2850
2851 // Emit the COPY_FW pseudo instruction.
2852 //
2853 // copy_fw_pseudo $fd, $ws, n
2854 // =>
2855 // copy_u_w $rt, $ws, $n
2856 // mtc1     $rt, $fd
2857 //
2858 // When n is zero, the equivalent operation can be performed with (potentially)
2859 // zero instructions due to register overlaps. This optimization is never valid
2860 // for lane 1 because it would require FR=0 mode which isn't supported by MSA.
2861 MachineBasicBlock * MipsSETargetLowering::
2862 emitCOPY_FW(MachineInstr *MI, MachineBasicBlock *BB) const{
2863   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2864   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2865   DebugLoc DL = MI->getDebugLoc();
2866   unsigned Fd = MI->getOperand(0).getReg();
2867   unsigned Ws = MI->getOperand(1).getReg();
2868   unsigned Lane = MI->getOperand(2).getImm();
2869
2870   if (Lane == 0)
2871     BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Ws, 0, Mips::sub_lo);
2872   else {
2873     unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
2874
2875     BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_W), Wt).addReg(Ws).addImm(Lane);
2876     BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Wt, 0, Mips::sub_lo);
2877   }
2878
2879   MI->eraseFromParent();   // The pseudo instruction is gone now.
2880   return BB;
2881 }
2882
2883 // Emit the COPY_FD pseudo instruction.
2884 //
2885 // copy_fd_pseudo $fd, $ws, n
2886 // =>
2887 // splati.d $wt, $ws, $n
2888 // copy $fd, $wt:sub_64
2889 //
2890 // When n is zero, the equivalent operation can be performed with (potentially)
2891 // zero instructions due to register overlaps. This optimization is always
2892 // valid because FR=1 mode which is the only supported mode in MSA.
2893 MachineBasicBlock * MipsSETargetLowering::
2894 emitCOPY_FD(MachineInstr *MI, MachineBasicBlock *BB) const{
2895   assert(Subtarget->isFP64bit());
2896
2897   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2898   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2899   unsigned Fd  = MI->getOperand(0).getReg();
2900   unsigned Ws  = MI->getOperand(1).getReg();
2901   unsigned Lane = MI->getOperand(2).getImm() * 2;
2902   DebugLoc DL = MI->getDebugLoc();
2903
2904   if (Lane == 0)
2905     BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Ws, 0, Mips::sub_64);
2906   else {
2907     unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
2908
2909     BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_D), Wt).addReg(Ws).addImm(1);
2910     BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Wt, 0, Mips::sub_64);
2911   }
2912
2913   MI->eraseFromParent();   // The pseudo instruction is gone now.
2914   return BB;
2915 }
2916
2917 // Emit the INSERT_FW pseudo instruction.
2918 //
2919 // insert_fw_pseudo $wd, $wd_in, $n, $fs
2920 // =>
2921 // subreg_to_reg $wt:sub_lo, $fs
2922 // insve_w $wd[$n], $wd_in, $wt[0]
2923 MachineBasicBlock *
2924 MipsSETargetLowering::emitINSERT_FW(MachineInstr *MI,
2925                                     MachineBasicBlock *BB) const {
2926   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2927   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2928   DebugLoc DL = MI->getDebugLoc();
2929   unsigned Wd = MI->getOperand(0).getReg();
2930   unsigned Wd_in = MI->getOperand(1).getReg();
2931   unsigned Lane = MI->getOperand(2).getImm();
2932   unsigned Fs = MI->getOperand(3).getReg();
2933   unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
2934
2935   BuildMI(*BB, MI, DL, TII->get(Mips::SUBREG_TO_REG), Wt)
2936       .addImm(0)
2937       .addReg(Fs)
2938       .addImm(Mips::sub_lo);
2939   BuildMI(*BB, MI, DL, TII->get(Mips::INSVE_W), Wd)
2940       .addReg(Wd_in)
2941       .addImm(Lane)
2942       .addReg(Wt)
2943       .addImm(0);
2944
2945   MI->eraseFromParent(); // The pseudo instruction is gone now.
2946   return BB;
2947 }
2948
2949 // Emit the INSERT_FD pseudo instruction.
2950 //
2951 // insert_fd_pseudo $wd, $fs, n
2952 // =>
2953 // subreg_to_reg $wt:sub_64, $fs
2954 // insve_d $wd[$n], $wd_in, $wt[0]
2955 MachineBasicBlock *
2956 MipsSETargetLowering::emitINSERT_FD(MachineInstr *MI,
2957                                     MachineBasicBlock *BB) const {
2958   assert(Subtarget->isFP64bit());
2959
2960   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2961   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2962   DebugLoc DL = MI->getDebugLoc();
2963   unsigned Wd = MI->getOperand(0).getReg();
2964   unsigned Wd_in = MI->getOperand(1).getReg();
2965   unsigned Lane = MI->getOperand(2).getImm();
2966   unsigned Fs = MI->getOperand(3).getReg();
2967   unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
2968
2969   BuildMI(*BB, MI, DL, TII->get(Mips::SUBREG_TO_REG), Wt)
2970       .addImm(0)
2971       .addReg(Fs)
2972       .addImm(Mips::sub_64);
2973   BuildMI(*BB, MI, DL, TII->get(Mips::INSVE_D), Wd)
2974       .addReg(Wd_in)
2975       .addImm(Lane)
2976       .addReg(Wt)
2977       .addImm(0);
2978
2979   MI->eraseFromParent(); // The pseudo instruction is gone now.
2980   return BB;
2981 }
2982
2983 // Emit the INSERT_([BHWD]|F[WD])_VIDX pseudo instruction.
2984 //
2985 // For integer:
2986 // (INSERT_([BHWD]|F[WD])_PSEUDO $wd, $wd_in, $n, $rs)
2987 // =>
2988 // (SLL $lanetmp1, $lane, <log2size)
2989 // (SLD_B $wdtmp1, $wd_in, $wd_in, $lanetmp1)
2990 // (INSERT_[BHWD], $wdtmp2, $wdtmp1, 0, $rs)
2991 // (NEG $lanetmp2, $lanetmp1)
2992 // (SLD_B $wd, $wdtmp2, $wdtmp2,  $lanetmp2)
2993 //
2994 // For floating point:
2995 // (INSERT_([BHWD]|F[WD])_PSEUDO $wd, $wd_in, $n, $fs)
2996 // =>
2997 // (SUBREG_TO_REG $wt, $fs, <subreg>)
2998 // (SLL $lanetmp1, $lane, <log2size)
2999 // (SLD_B $wdtmp1, $wd_in, $wd_in, $lanetmp1)
3000 // (INSVE_[WD], $wdtmp2, 0, $wdtmp1, 0)
3001 // (NEG $lanetmp2, $lanetmp1)
3002 // (SLD_B $wd, $wdtmp2, $wdtmp2,  $lanetmp2)
3003 MachineBasicBlock *
3004 MipsSETargetLowering::emitINSERT_DF_VIDX(MachineInstr *MI,
3005                                          MachineBasicBlock *BB,
3006                                          unsigned EltSizeInBytes,
3007                                          bool IsFP) const {
3008   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3009   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3010   DebugLoc DL = MI->getDebugLoc();
3011   unsigned Wd = MI->getOperand(0).getReg();
3012   unsigned SrcVecReg = MI->getOperand(1).getReg();
3013   unsigned LaneReg = MI->getOperand(2).getReg();
3014   unsigned SrcValReg = MI->getOperand(3).getReg();
3015
3016   const TargetRegisterClass *VecRC = nullptr;
3017   const TargetRegisterClass *GPRRC = isGP64bit() ? &Mips::GPR64RegClass
3018                                                  : &Mips::GPR32RegClass;
3019   unsigned EltLog2Size;
3020   unsigned InsertOp = 0;
3021   unsigned InsveOp = 0;
3022   switch (EltSizeInBytes) {
3023   default:
3024     llvm_unreachable("Unexpected size");
3025   case 1:
3026     EltLog2Size = 0;
3027     InsertOp = Mips::INSERT_B;
3028     InsveOp = Mips::INSVE_B;
3029     VecRC = &Mips::MSA128BRegClass;
3030     break;
3031   case 2:
3032     EltLog2Size = 1;
3033     InsertOp = Mips::INSERT_H;
3034     InsveOp = Mips::INSVE_H;
3035     VecRC = &Mips::MSA128HRegClass;
3036     break;
3037   case 4:
3038     EltLog2Size = 2;
3039     InsertOp = Mips::INSERT_W;
3040     InsveOp = Mips::INSVE_W;
3041     VecRC = &Mips::MSA128WRegClass;
3042     break;
3043   case 8:
3044     EltLog2Size = 3;
3045     InsertOp = Mips::INSERT_D;
3046     InsveOp = Mips::INSVE_D;
3047     VecRC = &Mips::MSA128DRegClass;
3048     break;
3049   }
3050
3051   if (IsFP) {
3052     unsigned Wt = RegInfo.createVirtualRegister(VecRC);
3053     BuildMI(*BB, MI, DL, TII->get(Mips::SUBREG_TO_REG), Wt)
3054         .addImm(0)
3055         .addReg(SrcValReg)
3056         .addImm(EltSizeInBytes == 8 ? Mips::sub_64 : Mips::sub_lo);
3057     SrcValReg = Wt;
3058   }
3059
3060   // Convert the lane index into a byte index
3061   if (EltSizeInBytes != 1) {
3062     unsigned LaneTmp1 = RegInfo.createVirtualRegister(GPRRC);
3063     BuildMI(*BB, MI, DL, TII->get(Mips::SLL), LaneTmp1)
3064         .addReg(LaneReg)
3065         .addImm(EltLog2Size);
3066     LaneReg = LaneTmp1;
3067   }
3068
3069   // Rotate bytes around so that the desired lane is element zero
3070   unsigned WdTmp1 = RegInfo.createVirtualRegister(VecRC);
3071   BuildMI(*BB, MI, DL, TII->get(Mips::SLD_B), WdTmp1)
3072       .addReg(SrcVecReg)
3073       .addReg(SrcVecReg)
3074       .addReg(LaneReg);
3075
3076   unsigned WdTmp2 = RegInfo.createVirtualRegister(VecRC);
3077   if (IsFP) {
3078     // Use insve.df to insert to element zero
3079     BuildMI(*BB, MI, DL, TII->get(InsveOp), WdTmp2)
3080         .addReg(WdTmp1)
3081         .addImm(0)
3082         .addReg(SrcValReg)
3083         .addImm(0);
3084   } else {
3085     // Use insert.df to insert to element zero
3086     BuildMI(*BB, MI, DL, TII->get(InsertOp), WdTmp2)
3087         .addReg(WdTmp1)
3088         .addReg(SrcValReg)
3089         .addImm(0);
3090   }
3091
3092   // Rotate elements the rest of the way for a full rotation.
3093   // sld.df inteprets $rt modulo the number of columns so we only need to negate
3094   // the lane index to do this.
3095   unsigned LaneTmp2 = RegInfo.createVirtualRegister(GPRRC);
3096   BuildMI(*BB, MI, DL, TII->get(Mips::SUB), LaneTmp2)
3097       .addReg(Mips::ZERO)
3098       .addReg(LaneReg);
3099   BuildMI(*BB, MI, DL, TII->get(Mips::SLD_B), Wd)
3100       .addReg(WdTmp2)
3101       .addReg(WdTmp2)
3102       .addReg(LaneTmp2);
3103
3104   MI->eraseFromParent(); // The pseudo instruction is gone now.
3105   return BB;
3106 }
3107
3108 // Emit the FILL_FW pseudo instruction.
3109 //
3110 // fill_fw_pseudo $wd, $fs
3111 // =>
3112 // implicit_def $wt1
3113 // insert_subreg $wt2:subreg_lo, $wt1, $fs
3114 // splati.w $wd, $wt2[0]
3115 MachineBasicBlock *
3116 MipsSETargetLowering::emitFILL_FW(MachineInstr *MI,
3117                                   MachineBasicBlock *BB) const {
3118   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3119   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3120   DebugLoc DL = MI->getDebugLoc();
3121   unsigned Wd = MI->getOperand(0).getReg();
3122   unsigned Fs = MI->getOperand(1).getReg();
3123   unsigned Wt1 = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
3124   unsigned Wt2 = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
3125
3126   BuildMI(*BB, MI, DL, TII->get(Mips::IMPLICIT_DEF), Wt1);
3127   BuildMI(*BB, MI, DL, TII->get(Mips::INSERT_SUBREG), Wt2)
3128       .addReg(Wt1)
3129       .addReg(Fs)
3130       .addImm(Mips::sub_lo);
3131   BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_W), Wd).addReg(Wt2).addImm(0);
3132
3133   MI->eraseFromParent(); // The pseudo instruction is gone now.
3134   return BB;
3135 }
3136
3137 // Emit the FILL_FD pseudo instruction.
3138 //
3139 // fill_fd_pseudo $wd, $fs
3140 // =>
3141 // implicit_def $wt1
3142 // insert_subreg $wt2:subreg_64, $wt1, $fs
3143 // splati.d $wd, $wt2[0]
3144 MachineBasicBlock *
3145 MipsSETargetLowering::emitFILL_FD(MachineInstr *MI,
3146                                   MachineBasicBlock *BB) const {
3147   assert(Subtarget->isFP64bit());
3148
3149   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3150   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3151   DebugLoc DL = MI->getDebugLoc();
3152   unsigned Wd = MI->getOperand(0).getReg();
3153   unsigned Fs = MI->getOperand(1).getReg();
3154   unsigned Wt1 = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
3155   unsigned Wt2 = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
3156
3157   BuildMI(*BB, MI, DL, TII->get(Mips::IMPLICIT_DEF), Wt1);
3158   BuildMI(*BB, MI, DL, TII->get(Mips::INSERT_SUBREG), Wt2)
3159       .addReg(Wt1)
3160       .addReg(Fs)
3161       .addImm(Mips::sub_64);
3162   BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_D), Wd).addReg(Wt2).addImm(0);
3163
3164   MI->eraseFromParent();   // The pseudo instruction is gone now.
3165   return BB;
3166 }
3167
3168 // Emit the FEXP2_W_1 pseudo instructions.
3169 //
3170 // fexp2_w_1_pseudo $wd, $wt
3171 // =>
3172 // ldi.w $ws, 1
3173 // fexp2.w $wd, $ws, $wt
3174 MachineBasicBlock *
3175 MipsSETargetLowering::emitFEXP2_W_1(MachineInstr *MI,
3176                                     MachineBasicBlock *BB) const {
3177   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3178   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3179   const TargetRegisterClass *RC = &Mips::MSA128WRegClass;
3180   unsigned Ws1 = RegInfo.createVirtualRegister(RC);
3181   unsigned Ws2 = RegInfo.createVirtualRegister(RC);
3182   DebugLoc DL = MI->getDebugLoc();
3183
3184   // Splat 1.0 into a vector
3185   BuildMI(*BB, MI, DL, TII->get(Mips::LDI_W), Ws1).addImm(1);
3186   BuildMI(*BB, MI, DL, TII->get(Mips::FFINT_U_W), Ws2).addReg(Ws1);
3187
3188   // Emit 1.0 * fexp2(Wt)
3189   BuildMI(*BB, MI, DL, TII->get(Mips::FEXP2_W), MI->getOperand(0).getReg())
3190       .addReg(Ws2)
3191       .addReg(MI->getOperand(1).getReg());
3192
3193   MI->eraseFromParent(); // The pseudo instruction is gone now.
3194   return BB;
3195 }
3196
3197 // Emit the FEXP2_D_1 pseudo instructions.
3198 //
3199 // fexp2_d_1_pseudo $wd, $wt
3200 // =>
3201 // ldi.d $ws, 1
3202 // fexp2.d $wd, $ws, $wt
3203 MachineBasicBlock *
3204 MipsSETargetLowering::emitFEXP2_D_1(MachineInstr *MI,
3205                                     MachineBasicBlock *BB) const {
3206   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3207   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3208   const TargetRegisterClass *RC = &Mips::MSA128DRegClass;
3209   unsigned Ws1 = RegInfo.createVirtualRegister(RC);
3210   unsigned Ws2 = RegInfo.createVirtualRegister(RC);
3211   DebugLoc DL = MI->getDebugLoc();
3212
3213   // Splat 1.0 into a vector
3214   BuildMI(*BB, MI, DL, TII->get(Mips::LDI_D), Ws1).addImm(1);
3215   BuildMI(*BB, MI, DL, TII->get(Mips::FFINT_U_D), Ws2).addReg(Ws1);
3216
3217   // Emit 1.0 * fexp2(Wt)
3218   BuildMI(*BB, MI, DL, TII->get(Mips::FEXP2_D), MI->getOperand(0).getReg())
3219       .addReg(Ws2)
3220       .addReg(MI->getOperand(1).getReg());
3221
3222   MI->eraseFromParent(); // The pseudo instruction is gone now.
3223   return BB;
3224 }