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