1 //===- LegalizeVectorOps.cpp - Implement SelectionDAG::LegalizeVectors ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the SelectionDAG::LegalizeVectors method.
10 //
11 // The vector legalizer looks for vector operations which might need to be
12 // scalarized and legalizes them. This is a separate step from Legalize because
13 // scalarizing can introduce illegal types.  For example, suppose we have an
14 // ISD::SDIV of type v2i64 on x86-32.  The type is legal (for example, addition
15 // on a v2i64 is legal), but ISD::SDIV isn't legal, so we have to unroll the
16 // operation, which introduces nodes with the illegal type i64 which must be
17 // expanded.  Similarly, suppose we have an ISD::SRA of type v16i8 on PowerPC;
18 // the operation must be unrolled, which introduces nodes with the illegal
19 // type i8 which must be promoted.
20 //
21 // This does not legalize vector manipulations like ISD::BUILD_VECTOR,
22 // or operations that happen to take a vector which are custom-lowered;
23 // the legalization for such operations never produces nodes
24 // with illegal types, so it's okay to put off legalizing them until
25 // SelectionDAG::Legalize runs.
26 //
27 //===----------------------------------------------------------------------===//
28 
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/SelectionDAGNodes.h"
36 #include "llvm/CodeGen/TargetLowering.h"
37 #include "llvm/CodeGen/ValueTypes.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/MachineValueType.h"
44 #include "llvm/Support/MathExtras.h"
45 #include <cassert>
46 #include <cstdint>
47 #include <iterator>
48 #include <utility>
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "legalizevectorops"
53 
54 namespace {
55 
56 class VectorLegalizer {
57   SelectionDAG& DAG;
58   const TargetLowering &TLI;
59   bool Changed = false; // Keep track of whether anything changed
60 
61   /// For nodes that are of legal width, and that have more than one use, this
62   /// map indicates what regularized operand to use.  This allows us to avoid
63   /// legalizing the same thing more than once.
64   SmallDenseMap<SDValue, SDValue, 64> LegalizedNodes;
65 
66   /// Adds a node to the translation cache.
67   void AddLegalizedOperand(SDValue From, SDValue To) {
68     LegalizedNodes.insert(std::make_pair(From, To));
69     // If someone requests legalization of the new node, return itself.
70     if (From != To)
71       LegalizedNodes.insert(std::make_pair(To, To));
72   }
73 
74   /// Legalizes the given node.
75   SDValue LegalizeOp(SDValue Op);
76 
77   /// Assuming the node is legal, "legalize" the results.
78   SDValue TranslateLegalizeResults(SDValue Op, SDValue Result);
79 
80   /// Implements unrolling a VSETCC.
81   SDValue UnrollVSETCC(SDValue Op);
82 
83   /// Implement expand-based legalization of vector operations.
84   ///
85   /// This is just a high-level routine to dispatch to specific code paths for
86   /// operations to legalize them.
87   SDValue Expand(SDValue Op);
88 
89   /// Implements expansion for FP_TO_UINT; falls back to UnrollVectorOp if
90   /// FP_TO_SINT isn't legal.
91   SDValue ExpandFP_TO_UINT(SDValue Op);
92 
93   /// Implements expansion for UINT_TO_FLOAT; falls back to UnrollVectorOp if
94   /// SINT_TO_FLOAT and SHR on vectors isn't legal.
95   SDValue ExpandUINT_TO_FLOAT(SDValue Op);
96 
97   /// Implement expansion for SIGN_EXTEND_INREG using SRL and SRA.
98   SDValue ExpandSEXTINREG(SDValue Op);
99 
100   /// Implement expansion for ANY_EXTEND_VECTOR_INREG.
101   ///
102   /// Shuffles the low lanes of the operand into place and bitcasts to the proper
103   /// type. The contents of the bits in the extended part of each element are
104   /// undef.
105   SDValue ExpandANY_EXTEND_VECTOR_INREG(SDValue Op);
106 
107   /// Implement expansion for SIGN_EXTEND_VECTOR_INREG.
108   ///
109   /// Shuffles the low lanes of the operand into place, bitcasts to the proper
110   /// type, then shifts left and arithmetic shifts right to introduce a sign
111   /// extension.
112   SDValue ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op);
113 
114   /// Implement expansion for ZERO_EXTEND_VECTOR_INREG.
115   ///
116   /// Shuffles the low lanes of the operand into place and blends zeros into
117   /// the remaining lanes, finally bitcasting to the proper type.
118   SDValue ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op);
119 
120   /// Implement expand-based legalization of ABS vector operations.
121   /// If following expanding is legal/custom then do it:
122   /// (ABS x) --> (XOR (ADD x, (SRA x, sizeof(x)-1)), (SRA x, sizeof(x)-1))
123   /// else unroll the operation.
124   SDValue ExpandABS(SDValue Op);
125 
126   /// Expand bswap of vectors into a shuffle if legal.
127   SDValue ExpandBSWAP(SDValue Op);
128 
129   /// Implement vselect in terms of XOR, AND, OR when blend is not
130   /// supported by the target.
131   SDValue ExpandVSELECT(SDValue Op);
132   SDValue ExpandSELECT(SDValue Op);
133   SDValue ExpandLoad(SDValue Op);
134   SDValue ExpandStore(SDValue Op);
135   SDValue ExpandFNEG(SDValue Op);
136   SDValue ExpandFSUB(SDValue Op);
137   SDValue ExpandBITREVERSE(SDValue Op);
138   SDValue ExpandCTPOP(SDValue Op);
139   SDValue ExpandCTLZ(SDValue Op);
140   SDValue ExpandCTTZ(SDValue Op);
141   SDValue ExpandFunnelShift(SDValue Op);
142   SDValue ExpandROT(SDValue Op);
143   SDValue ExpandFMINNUM_FMAXNUM(SDValue Op);
144   SDValue ExpandUADDSUBO(SDValue Op);
145   SDValue ExpandSADDSUBO(SDValue Op);
146   SDValue ExpandMULO(SDValue Op);
147   SDValue ExpandAddSubSat(SDValue Op);
148   SDValue ExpandFixedPointMul(SDValue Op);
149   SDValue ExpandStrictFPOp(SDValue Op);
150 
151   /// Implements vector promotion.
152   ///
153   /// This is essentially just bitcasting the operands to a different type and
154   /// bitcasting the result back to the original type.
155   SDValue Promote(SDValue Op);
156 
157   /// Implements [SU]INT_TO_FP vector promotion.
158   ///
159   /// This is a [zs]ext of the input operand to a larger integer type.
160   SDValue PromoteINT_TO_FP(SDValue Op);
161 
162   /// Implements FP_TO_[SU]INT vector promotion of the result type.
163   ///
164   /// It is promoted to a larger integer type.  The result is then
165   /// truncated back to the original type.
166   SDValue PromoteFP_TO_INT(SDValue Op);
167 
168 public:
169   VectorLegalizer(SelectionDAG& dag) :
170       DAG(dag), TLI(dag.getTargetLoweringInfo()) {}
171 
172   /// Begin legalizer the vector operations in the DAG.
173   bool Run();
174 };
175 
176 } // end anonymous namespace
177 
178 bool VectorLegalizer::Run() {
179   // Before we start legalizing vector nodes, check if there are any vectors.
180   bool HasVectors = false;
181   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
182        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I) {
183     // Check if the values of the nodes contain vectors. We don't need to check
184     // the operands because we are going to check their values at some point.
185     for (SDNode::value_iterator J = I->value_begin(), E = I->value_end();
186          J != E; ++J)
187       HasVectors |= J->isVector();
188 
189     // If we found a vector node we can start the legalization.
190     if (HasVectors)
191       break;
192   }
193 
194   // If this basic block has no vectors then no need to legalize vectors.
195   if (!HasVectors)
196     return false;
197 
198   // The legalize process is inherently a bottom-up recursive process (users
199   // legalize their uses before themselves).  Given infinite stack space, we
200   // could just start legalizing on the root and traverse the whole graph.  In
201   // practice however, this causes us to run out of stack space on large basic
202   // blocks.  To avoid this problem, compute an ordering of the nodes where each
203   // node is only legalized after all of its operands are legalized.
204   DAG.AssignTopologicalOrder();
205   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
206        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
207     LegalizeOp(SDValue(&*I, 0));
208 
209   // Finally, it's possible the root changed.  Get the new root.
210   SDValue OldRoot = DAG.getRoot();
211   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
212   DAG.setRoot(LegalizedNodes[OldRoot]);
213 
214   LegalizedNodes.clear();
215 
216   // Remove dead nodes now.
217   DAG.RemoveDeadNodes();
218 
219   return Changed;
220 }
221 
222 SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDValue Result) {
223   // Generic legalization: just pass the operand through.
224   for (unsigned i = 0, e = Op.getNode()->getNumValues(); i != e; ++i)
225     AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
226   return Result.getValue(Op.getResNo());
227 }
228 
229 SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
230   // Note that LegalizeOp may be reentered even from single-use nodes, which
231   // means that we always must cache transformed nodes.
232   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
233   if (I != LegalizedNodes.end()) return I->second;
234 
235   SDNode* Node = Op.getNode();
236 
237   // Legalize the operands
238   SmallVector<SDValue, 8> Ops;
239   for (const SDValue &Op : Node->op_values())
240     Ops.push_back(LegalizeOp(Op));
241 
242   SDValue Result = SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops),
243                            Op.getResNo());
244 
245   if (Op.getOpcode() == ISD::LOAD) {
246     LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
247     ISD::LoadExtType ExtType = LD->getExtensionType();
248     if (LD->getMemoryVT().isVector() && ExtType != ISD::NON_EXTLOAD) {
249       LLVM_DEBUG(dbgs() << "\nLegalizing extending vector load: ";
250                  Node->dump(&DAG));
251       switch (TLI.getLoadExtAction(LD->getExtensionType(), LD->getValueType(0),
252                                    LD->getMemoryVT())) {
253       default: llvm_unreachable("This action is not supported yet!");
254       case TargetLowering::Legal:
255         return TranslateLegalizeResults(Op, Result);
256       case TargetLowering::Custom:
257         if (SDValue Lowered = TLI.LowerOperation(Result, DAG)) {
258           assert(Lowered->getNumValues() == Op->getNumValues() &&
259                  "Unexpected number of results");
260           if (Lowered != Result) {
261             // Make sure the new code is also legal.
262             Lowered = LegalizeOp(Lowered);
263             Changed = true;
264           }
265           return TranslateLegalizeResults(Op, Lowered);
266         }
267         LLVM_FALLTHROUGH;
268       case TargetLowering::Expand:
269         Changed = true;
270         return ExpandLoad(Op);
271       }
272     }
273   } else if (Op.getOpcode() == ISD::STORE) {
274     StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
275     EVT StVT = ST->getMemoryVT();
276     MVT ValVT = ST->getValue().getSimpleValueType();
277     if (StVT.isVector() && ST->isTruncatingStore()) {
278       LLVM_DEBUG(dbgs() << "\nLegalizing truncating vector store: ";
279                  Node->dump(&DAG));
280       switch (TLI.getTruncStoreAction(ValVT, StVT)) {
281       default: llvm_unreachable("This action is not supported yet!");
282       case TargetLowering::Legal:
283         return TranslateLegalizeResults(Op, Result);
284       case TargetLowering::Custom: {
285         SDValue Lowered = TLI.LowerOperation(Result, DAG);
286         if (Lowered != Result) {
287           // Make sure the new code is also legal.
288           Lowered = LegalizeOp(Lowered);
289           Changed = true;
290         }
291         return TranslateLegalizeResults(Op, Lowered);
292       }
293       case TargetLowering::Expand:
294         Changed = true;
295         return ExpandStore(Op);
296       }
297     }
298   }
299 
300   bool HasVectorValueOrOp = false;
301   for (auto J = Node->value_begin(), E = Node->value_end(); J != E; ++J)
302     HasVectorValueOrOp |= J->isVector();
303   for (const SDValue &Op : Node->op_values())
304     HasVectorValueOrOp |= Op.getValueType().isVector();
305 
306   if (!HasVectorValueOrOp)
307     return TranslateLegalizeResults(Op, Result);
308 
309   TargetLowering::LegalizeAction Action = TargetLowering::Legal;
310   switch (Op.getOpcode()) {
311   default:
312     return TranslateLegalizeResults(Op, Result);
313 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
314   case ISD::STRICT_##DAGN:
315 #include "llvm/IR/ConstrainedOps.def"
316     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
317     // If we're asked to expand a strict vector floating-point operation,
318     // by default we're going to simply unroll it.  That is usually the
319     // best approach, except in the case where the resulting strict (scalar)
320     // operations would themselves use the fallback mutation to non-strict.
321     // In that specific case, just do the fallback on the vector op.
322     if (Action == TargetLowering::Expand &&
323         TLI.getStrictFPOperationAction(Node->getOpcode(),
324                                        Node->getValueType(0))
325         == TargetLowering::Legal) {
326       EVT EltVT = Node->getValueType(0).getVectorElementType();
327       if (TLI.getOperationAction(Node->getOpcode(), EltVT)
328           == TargetLowering::Expand &&
329           TLI.getStrictFPOperationAction(Node->getOpcode(), EltVT)
330           == TargetLowering::Legal)
331         Action = TargetLowering::Legal;
332     }
333     break;
334   case ISD::ADD:
335   case ISD::SUB:
336   case ISD::MUL:
337   case ISD::MULHS:
338   case ISD::MULHU:
339   case ISD::SDIV:
340   case ISD::UDIV:
341   case ISD::SREM:
342   case ISD::UREM:
343   case ISD::SDIVREM:
344   case ISD::UDIVREM:
345   case ISD::FADD:
346   case ISD::FSUB:
347   case ISD::FMUL:
348   case ISD::FDIV:
349   case ISD::FREM:
350   case ISD::AND:
351   case ISD::OR:
352   case ISD::XOR:
353   case ISD::SHL:
354   case ISD::SRA:
355   case ISD::SRL:
356   case ISD::FSHL:
357   case ISD::FSHR:
358   case ISD::ROTL:
359   case ISD::ROTR:
360   case ISD::ABS:
361   case ISD::BSWAP:
362   case ISD::BITREVERSE:
363   case ISD::CTLZ:
364   case ISD::CTTZ:
365   case ISD::CTLZ_ZERO_UNDEF:
366   case ISD::CTTZ_ZERO_UNDEF:
367   case ISD::CTPOP:
368   case ISD::SELECT:
369   case ISD::VSELECT:
370   case ISD::SELECT_CC:
371   case ISD::SETCC:
372   case ISD::ZERO_EXTEND:
373   case ISD::ANY_EXTEND:
374   case ISD::TRUNCATE:
375   case ISD::SIGN_EXTEND:
376   case ISD::FP_TO_SINT:
377   case ISD::FP_TO_UINT:
378   case ISD::FNEG:
379   case ISD::FABS:
380   case ISD::FMINNUM:
381   case ISD::FMAXNUM:
382   case ISD::FMINNUM_IEEE:
383   case ISD::FMAXNUM_IEEE:
384   case ISD::FMINIMUM:
385   case ISD::FMAXIMUM:
386   case ISD::FCOPYSIGN:
387   case ISD::FSQRT:
388   case ISD::FSIN:
389   case ISD::FCOS:
390   case ISD::FPOWI:
391   case ISD::FPOW:
392   case ISD::FLOG:
393   case ISD::FLOG2:
394   case ISD::FLOG10:
395   case ISD::FEXP:
396   case ISD::FEXP2:
397   case ISD::FCEIL:
398   case ISD::FTRUNC:
399   case ISD::FRINT:
400   case ISD::FNEARBYINT:
401   case ISD::FROUND:
402   case ISD::FFLOOR:
403   case ISD::FP_ROUND:
404   case ISD::FP_EXTEND:
405   case ISD::FMA:
406   case ISD::SIGN_EXTEND_INREG:
407   case ISD::ANY_EXTEND_VECTOR_INREG:
408   case ISD::SIGN_EXTEND_VECTOR_INREG:
409   case ISD::ZERO_EXTEND_VECTOR_INREG:
410   case ISD::SMIN:
411   case ISD::SMAX:
412   case ISD::UMIN:
413   case ISD::UMAX:
414   case ISD::SMUL_LOHI:
415   case ISD::UMUL_LOHI:
416   case ISD::SADDO:
417   case ISD::UADDO:
418   case ISD::SSUBO:
419   case ISD::USUBO:
420   case ISD::SMULO:
421   case ISD::UMULO:
422   case ISD::FCANONICALIZE:
423   case ISD::SADDSAT:
424   case ISD::UADDSAT:
425   case ISD::SSUBSAT:
426   case ISD::USUBSAT:
427     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
428     break;
429   case ISD::SMULFIX:
430   case ISD::SMULFIXSAT:
431   case ISD::UMULFIX:
432   case ISD::UMULFIXSAT: {
433     unsigned Scale = Node->getConstantOperandVal(2);
434     Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
435                                               Node->getValueType(0), Scale);
436     break;
437   }
438   case ISD::SINT_TO_FP:
439   case ISD::UINT_TO_FP:
440   case ISD::VECREDUCE_ADD:
441   case ISD::VECREDUCE_MUL:
442   case ISD::VECREDUCE_AND:
443   case ISD::VECREDUCE_OR:
444   case ISD::VECREDUCE_XOR:
445   case ISD::VECREDUCE_SMAX:
446   case ISD::VECREDUCE_SMIN:
447   case ISD::VECREDUCE_UMAX:
448   case ISD::VECREDUCE_UMIN:
449   case ISD::VECREDUCE_FADD:
450   case ISD::VECREDUCE_FMUL:
451   case ISD::VECREDUCE_FMAX:
452   case ISD::VECREDUCE_FMIN:
453     Action = TLI.getOperationAction(Node->getOpcode(),
454                                     Node->getOperand(0).getValueType());
455     break;
456   }
457 
458   LLVM_DEBUG(dbgs() << "\nLegalizing vector op: "; Node->dump(&DAG));
459 
460   switch (Action) {
461   default: llvm_unreachable("This action is not supported yet!");
462   case TargetLowering::Promote:
463     Result = Promote(Op);
464     Changed = true;
465     break;
466   case TargetLowering::Legal:
467     LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
468     break;
469   case TargetLowering::Custom: {
470     LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
471     if (SDValue Tmp1 = TLI.LowerOperation(Op, DAG)) {
472       LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
473       Result = Tmp1;
474       break;
475     }
476     LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
477     LLVM_FALLTHROUGH;
478   }
479   case TargetLowering::Expand:
480     Result = Expand(Op);
481   }
482 
483   // Make sure that the generated code is itself legal.
484   if (Result != Op) {
485     Result = LegalizeOp(Result);
486     Changed = true;
487   }
488 
489   // Note that LegalizeOp may be reentered even from single-use nodes, which
490   // means that we always must cache transformed nodes.
491   AddLegalizedOperand(Op, Result);
492   return Result;
493 }
494 
495 SDValue VectorLegalizer::Promote(SDValue Op) {
496   // For a few operations there is a specific concept for promotion based on
497   // the operand's type.
498   switch (Op.getOpcode()) {
499   case ISD::SINT_TO_FP:
500   case ISD::UINT_TO_FP:
501     // "Promote" the operation by extending the operand.
502     return PromoteINT_TO_FP(Op);
503   case ISD::FP_TO_UINT:
504   case ISD::FP_TO_SINT:
505     // Promote the operation by extending the operand.
506     return PromoteFP_TO_INT(Op);
507   }
508 
509   // There are currently two cases of vector promotion:
510   // 1) Bitcasting a vector of integers to a different type to a vector of the
511   //    same overall length. For example, x86 promotes ISD::AND v2i32 to v1i64.
512   // 2) Extending a vector of floats to a vector of the same number of larger
513   //    floats. For example, AArch64 promotes ISD::FADD on v4f16 to v4f32.
514   MVT VT = Op.getSimpleValueType();
515   assert(Op.getNode()->getNumValues() == 1 &&
516          "Can't promote a vector with multiple results!");
517   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
518   SDLoc dl(Op);
519   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
520 
521   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
522     if (Op.getOperand(j).getValueType().isVector())
523       if (Op.getOperand(j)
524               .getValueType()
525               .getVectorElementType()
526               .isFloatingPoint() &&
527           NVT.isVector() && NVT.getVectorElementType().isFloatingPoint())
528         Operands[j] = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Op.getOperand(j));
529       else
530         Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
531     else
532       Operands[j] = Op.getOperand(j);
533   }
534 
535   Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands, Op.getNode()->getFlags());
536   if ((VT.isFloatingPoint() && NVT.isFloatingPoint()) ||
537       (VT.isVector() && VT.getVectorElementType().isFloatingPoint() &&
538        NVT.isVector() && NVT.getVectorElementType().isFloatingPoint()))
539     return DAG.getNode(ISD::FP_ROUND, dl, VT, Op, DAG.getIntPtrConstant(0, dl));
540   else
541     return DAG.getNode(ISD::BITCAST, dl, VT, Op);
542 }
543 
544 SDValue VectorLegalizer::PromoteINT_TO_FP(SDValue Op) {
545   // INT_TO_FP operations may require the input operand be promoted even
546   // when the type is otherwise legal.
547   MVT VT = Op.getOperand(0).getSimpleValueType();
548   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
549   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
550          "Vectors have different number of elements!");
551 
552   SDLoc dl(Op);
553   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
554 
555   unsigned Opc = Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND :
556     ISD::SIGN_EXTEND;
557   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
558     if (Op.getOperand(j).getValueType().isVector())
559       Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
560     else
561       Operands[j] = Op.getOperand(j);
562   }
563 
564   return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
565 }
566 
567 // For FP_TO_INT we promote the result type to a vector type with wider
568 // elements and then truncate the result.  This is different from the default
569 // PromoteVector which uses bitcast to promote thus assumning that the
570 // promoted vector type has the same overall size.
571 SDValue VectorLegalizer::PromoteFP_TO_INT(SDValue Op) {
572   MVT VT = Op.getSimpleValueType();
573   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
574   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
575          "Vectors have different number of elements!");
576 
577   unsigned NewOpc = Op->getOpcode();
578   // Change FP_TO_UINT to FP_TO_SINT if possible.
579   // TODO: Should we only do this if FP_TO_UINT itself isn't legal?
580   if (NewOpc == ISD::FP_TO_UINT &&
581       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
582     NewOpc = ISD::FP_TO_SINT;
583 
584   SDLoc dl(Op);
585   SDValue Promoted  = DAG.getNode(NewOpc, dl, NVT, Op.getOperand(0));
586 
587   // Assert that the converted value fits in the original type.  If it doesn't
588   // (eg: because the value being converted is too big), then the result of the
589   // original operation was undefined anyway, so the assert is still correct.
590   Promoted = DAG.getNode(Op->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
591                                                             : ISD::AssertSext,
592                          dl, NVT, Promoted,
593                          DAG.getValueType(VT.getScalarType()));
594   return DAG.getNode(ISD::TRUNCATE, dl, VT, Promoted);
595 }
596 
597 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
598   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
599 
600   EVT SrcVT = LD->getMemoryVT();
601   EVT SrcEltVT = SrcVT.getScalarType();
602   unsigned NumElem = SrcVT.getVectorNumElements();
603 
604   SDValue NewChain;
605   SDValue Value;
606   if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
607     SDLoc dl(Op);
608 
609     SmallVector<SDValue, 8> Vals;
610     SmallVector<SDValue, 8> LoadChains;
611 
612     EVT DstEltVT = LD->getValueType(0).getScalarType();
613     SDValue Chain = LD->getChain();
614     SDValue BasePTR = LD->getBasePtr();
615     ISD::LoadExtType ExtType = LD->getExtensionType();
616 
617     // When elements in a vector is not byte-addressable, we cannot directly
618     // load each element by advancing pointer, which could only address bytes.
619     // Instead, we load all significant words, mask bits off, and concatenate
620     // them to form each element. Finally, they are extended to destination
621     // scalar type to build the destination vector.
622     EVT WideVT = TLI.getPointerTy(DAG.getDataLayout());
623 
624     assert(WideVT.isRound() &&
625            "Could not handle the sophisticated case when the widest integer is"
626            " not power of 2.");
627     assert(WideVT.bitsGE(SrcEltVT) &&
628            "Type is not legalized?");
629 
630     unsigned WideBytes = WideVT.getStoreSize();
631     unsigned Offset = 0;
632     unsigned RemainingBytes = SrcVT.getStoreSize();
633     SmallVector<SDValue, 8> LoadVals;
634     while (RemainingBytes > 0) {
635       SDValue ScalarLoad;
636       unsigned LoadBytes = WideBytes;
637 
638       if (RemainingBytes >= LoadBytes) {
639         ScalarLoad =
640             DAG.getLoad(WideVT, dl, Chain, BasePTR,
641                         LD->getPointerInfo().getWithOffset(Offset),
642                         MinAlign(LD->getAlignment(), Offset),
643                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
644       } else {
645         EVT LoadVT = WideVT;
646         while (RemainingBytes < LoadBytes) {
647           LoadBytes >>= 1; // Reduce the load size by half.
648           LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
649         }
650         ScalarLoad =
651             DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
652                            LD->getPointerInfo().getWithOffset(Offset), LoadVT,
653                            MinAlign(LD->getAlignment(), Offset),
654                            LD->getMemOperand()->getFlags(), LD->getAAInfo());
655       }
656 
657       RemainingBytes -= LoadBytes;
658       Offset += LoadBytes;
659 
660       BasePTR = DAG.getObjectPtrOffset(dl, BasePTR, LoadBytes);
661 
662       LoadVals.push_back(ScalarLoad.getValue(0));
663       LoadChains.push_back(ScalarLoad.getValue(1));
664     }
665 
666     unsigned BitOffset = 0;
667     unsigned WideIdx = 0;
668     unsigned WideBits = WideVT.getSizeInBits();
669 
670     // Extract bits, pack and extend/trunc them into destination type.
671     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
672     SDValue SrcEltBitMask = DAG.getConstant(
673         APInt::getLowBitsSet(WideBits, SrcEltBits), dl, WideVT);
674 
675     for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
676       assert(BitOffset < WideBits && "Unexpected offset!");
677 
678       SDValue ShAmt = DAG.getConstant(
679           BitOffset, dl, TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
680       SDValue Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
681 
682       BitOffset += SrcEltBits;
683       if (BitOffset >= WideBits) {
684         WideIdx++;
685         BitOffset -= WideBits;
686         if (BitOffset > 0) {
687           ShAmt = DAG.getConstant(
688               SrcEltBits - BitOffset, dl,
689               TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
690           SDValue Hi =
691               DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
692           Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
693         }
694       }
695 
696       Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
697 
698       switch (ExtType) {
699       default: llvm_unreachable("Unknown extended-load op!");
700       case ISD::EXTLOAD:
701         Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
702         break;
703       case ISD::ZEXTLOAD:
704         Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
705         break;
706       case ISD::SEXTLOAD:
707         ShAmt =
708             DAG.getConstant(WideBits - SrcEltBits, dl,
709                             TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
710         Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
711         Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
712         Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
713         break;
714       }
715       Vals.push_back(Lo);
716     }
717 
718     NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
719     Value = DAG.getBuildVector(Op.getNode()->getValueType(0), dl, Vals);
720   } else {
721     SDValue Scalarized = TLI.scalarizeVectorLoad(LD, DAG);
722     // Skip past MERGE_VALUE node if known.
723     if (Scalarized->getOpcode() == ISD::MERGE_VALUES) {
724       NewChain = Scalarized.getOperand(1);
725       Value = Scalarized.getOperand(0);
726     } else {
727       NewChain = Scalarized.getValue(1);
728       Value = Scalarized.getValue(0);
729     }
730   }
731 
732   AddLegalizedOperand(Op.getValue(0), Value);
733   AddLegalizedOperand(Op.getValue(1), NewChain);
734 
735   return (Op.getResNo() ? NewChain : Value);
736 }
737 
738 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
739   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
740   SDValue TF = TLI.scalarizeVectorStore(ST, DAG);
741   AddLegalizedOperand(Op, TF);
742   return TF;
743 }
744 
745 SDValue VectorLegalizer::Expand(SDValue Op) {
746   switch (Op->getOpcode()) {
747   case ISD::SIGN_EXTEND_INREG:
748     return ExpandSEXTINREG(Op);
749   case ISD::ANY_EXTEND_VECTOR_INREG:
750     return ExpandANY_EXTEND_VECTOR_INREG(Op);
751   case ISD::SIGN_EXTEND_VECTOR_INREG:
752     return ExpandSIGN_EXTEND_VECTOR_INREG(Op);
753   case ISD::ZERO_EXTEND_VECTOR_INREG:
754     return ExpandZERO_EXTEND_VECTOR_INREG(Op);
755   case ISD::BSWAP:
756     return ExpandBSWAP(Op);
757   case ISD::VSELECT:
758     return ExpandVSELECT(Op);
759   case ISD::SELECT:
760     return ExpandSELECT(Op);
761   case ISD::FP_TO_UINT:
762     return ExpandFP_TO_UINT(Op);
763   case ISD::UINT_TO_FP:
764     return ExpandUINT_TO_FLOAT(Op);
765   case ISD::FNEG:
766     return ExpandFNEG(Op);
767   case ISD::FSUB:
768     return ExpandFSUB(Op);
769   case ISD::SETCC:
770     return UnrollVSETCC(Op);
771   case ISD::ABS:
772     return ExpandABS(Op);
773   case ISD::BITREVERSE:
774     return ExpandBITREVERSE(Op);
775   case ISD::CTPOP:
776     return ExpandCTPOP(Op);
777   case ISD::CTLZ:
778   case ISD::CTLZ_ZERO_UNDEF:
779     return ExpandCTLZ(Op);
780   case ISD::CTTZ:
781   case ISD::CTTZ_ZERO_UNDEF:
782     return ExpandCTTZ(Op);
783   case ISD::FSHL:
784   case ISD::FSHR:
785     return ExpandFunnelShift(Op);
786   case ISD::ROTL:
787   case ISD::ROTR:
788     return ExpandROT(Op);
789   case ISD::FMINNUM:
790   case ISD::FMAXNUM:
791     return ExpandFMINNUM_FMAXNUM(Op);
792   case ISD::UADDO:
793   case ISD::USUBO:
794     return ExpandUADDSUBO(Op);
795   case ISD::SADDO:
796   case ISD::SSUBO:
797     return ExpandSADDSUBO(Op);
798   case ISD::UMULO:
799   case ISD::SMULO:
800     return ExpandMULO(Op);
801   case ISD::USUBSAT:
802   case ISD::SSUBSAT:
803   case ISD::UADDSAT:
804   case ISD::SADDSAT:
805     return ExpandAddSubSat(Op);
806   case ISD::SMULFIX:
807   case ISD::UMULFIX:
808     return ExpandFixedPointMul(Op);
809   case ISD::SMULFIXSAT:
810   case ISD::UMULFIXSAT:
811     // FIXME: We do not expand SMULFIXSAT/UMULFIXSAT here yet, not sure exactly
812     // why. Maybe it results in worse codegen compared to the unroll for some
813     // targets? This should probably be investigated. And if we still prefer to
814     // unroll an explanation could be helpful.
815     return DAG.UnrollVectorOp(Op.getNode());
816 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
817   case ISD::STRICT_##DAGN:
818 #include "llvm/IR/ConstrainedOps.def"
819     return ExpandStrictFPOp(Op);
820   case ISD::VECREDUCE_ADD:
821   case ISD::VECREDUCE_MUL:
822   case ISD::VECREDUCE_AND:
823   case ISD::VECREDUCE_OR:
824   case ISD::VECREDUCE_XOR:
825   case ISD::VECREDUCE_SMAX:
826   case ISD::VECREDUCE_SMIN:
827   case ISD::VECREDUCE_UMAX:
828   case ISD::VECREDUCE_UMIN:
829   case ISD::VECREDUCE_FADD:
830   case ISD::VECREDUCE_FMUL:
831   case ISD::VECREDUCE_FMAX:
832   case ISD::VECREDUCE_FMIN:
833     return TLI.expandVecReduce(Op.getNode(), DAG);
834   default:
835     return DAG.UnrollVectorOp(Op.getNode());
836   }
837 }
838 
839 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
840   // Lower a select instruction where the condition is a scalar and the
841   // operands are vectors. Lower this select to VSELECT and implement it
842   // using XOR AND OR. The selector bit is broadcasted.
843   EVT VT = Op.getValueType();
844   SDLoc DL(Op);
845 
846   SDValue Mask = Op.getOperand(0);
847   SDValue Op1 = Op.getOperand(1);
848   SDValue Op2 = Op.getOperand(2);
849 
850   assert(VT.isVector() && !Mask.getValueType().isVector()
851          && Op1.getValueType() == Op2.getValueType() && "Invalid type");
852 
853   // If we can't even use the basic vector operations of
854   // AND,OR,XOR, we will have to scalarize the op.
855   // Notice that the operation may be 'promoted' which means that it is
856   // 'bitcasted' to another type which is handled.
857   // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
858   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
859       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
860       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
861       TLI.getOperationAction(ISD::BUILD_VECTOR,  VT) == TargetLowering::Expand)
862     return DAG.UnrollVectorOp(Op.getNode());
863 
864   // Generate a mask operand.
865   EVT MaskTy = VT.changeVectorElementTypeToInteger();
866 
867   // What is the size of each element in the vector mask.
868   EVT BitTy = MaskTy.getScalarType();
869 
870   Mask = DAG.getSelect(DL, BitTy, Mask,
871           DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), DL,
872                           BitTy),
873           DAG.getConstant(0, DL, BitTy));
874 
875   // Broadcast the mask so that the entire vector is all-one or all zero.
876   Mask = DAG.getSplatBuildVector(MaskTy, DL, Mask);
877 
878   // Bitcast the operands to be the same type as the mask.
879   // This is needed when we select between FP types because
880   // the mask is a vector of integers.
881   Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
882   Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
883 
884   SDValue AllOnes = DAG.getConstant(
885             APInt::getAllOnesValue(BitTy.getSizeInBits()), DL, MaskTy);
886   SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
887 
888   Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
889   Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
890   SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
891   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
892 }
893 
894 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
895   EVT VT = Op.getValueType();
896 
897   // Make sure that the SRA and SHL instructions are available.
898   if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
899       TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
900     return DAG.UnrollVectorOp(Op.getNode());
901 
902   SDLoc DL(Op);
903   EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
904 
905   unsigned BW = VT.getScalarSizeInBits();
906   unsigned OrigBW = OrigTy.getScalarSizeInBits();
907   SDValue ShiftSz = DAG.getConstant(BW - OrigBW, DL, VT);
908 
909   Op = Op.getOperand(0);
910   Op =   DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
911   return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
912 }
913 
914 // Generically expand a vector anyext in register to a shuffle of the relevant
915 // lanes into the appropriate locations, with other lanes left undef.
916 SDValue VectorLegalizer::ExpandANY_EXTEND_VECTOR_INREG(SDValue Op) {
917   SDLoc DL(Op);
918   EVT VT = Op.getValueType();
919   int NumElements = VT.getVectorNumElements();
920   SDValue Src = Op.getOperand(0);
921   EVT SrcVT = Src.getValueType();
922   int NumSrcElements = SrcVT.getVectorNumElements();
923 
924   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
925   // into a larger vector type.
926   if (SrcVT.bitsLE(VT)) {
927     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
928            "ANY_EXTEND_VECTOR_INREG vector size mismatch");
929     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
930     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
931                              NumSrcElements);
932     Src = DAG.getNode(
933         ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT), Src,
934         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
935   }
936 
937   // Build a base mask of undef shuffles.
938   SmallVector<int, 16> ShuffleMask;
939   ShuffleMask.resize(NumSrcElements, -1);
940 
941   // Place the extended lanes into the correct locations.
942   int ExtLaneScale = NumSrcElements / NumElements;
943   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
944   for (int i = 0; i < NumElements; ++i)
945     ShuffleMask[i * ExtLaneScale + EndianOffset] = i;
946 
947   return DAG.getNode(
948       ISD::BITCAST, DL, VT,
949       DAG.getVectorShuffle(SrcVT, DL, Src, DAG.getUNDEF(SrcVT), ShuffleMask));
950 }
951 
952 SDValue VectorLegalizer::ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op) {
953   SDLoc DL(Op);
954   EVT VT = Op.getValueType();
955   SDValue Src = Op.getOperand(0);
956   EVT SrcVT = Src.getValueType();
957 
958   // First build an any-extend node which can be legalized above when we
959   // recurse through it.
960   Op = DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Src);
961 
962   // Now we need sign extend. Do this by shifting the elements. Even if these
963   // aren't legal operations, they have a better chance of being legalized
964   // without full scalarization than the sign extension does.
965   unsigned EltWidth = VT.getScalarSizeInBits();
966   unsigned SrcEltWidth = SrcVT.getScalarSizeInBits();
967   SDValue ShiftAmount = DAG.getConstant(EltWidth - SrcEltWidth, DL, VT);
968   return DAG.getNode(ISD::SRA, DL, VT,
969                      DAG.getNode(ISD::SHL, DL, VT, Op, ShiftAmount),
970                      ShiftAmount);
971 }
972 
973 // Generically expand a vector zext in register to a shuffle of the relevant
974 // lanes into the appropriate locations, a blend of zero into the high bits,
975 // and a bitcast to the wider element type.
976 SDValue VectorLegalizer::ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op) {
977   SDLoc DL(Op);
978   EVT VT = Op.getValueType();
979   int NumElements = VT.getVectorNumElements();
980   SDValue Src = Op.getOperand(0);
981   EVT SrcVT = Src.getValueType();
982   int NumSrcElements = SrcVT.getVectorNumElements();
983 
984   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
985   // into a larger vector type.
986   if (SrcVT.bitsLE(VT)) {
987     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
988            "ZERO_EXTEND_VECTOR_INREG vector size mismatch");
989     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
990     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
991                              NumSrcElements);
992     Src = DAG.getNode(
993         ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT), Src,
994         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
995   }
996 
997   // Build up a zero vector to blend into this one.
998   SDValue Zero = DAG.getConstant(0, DL, SrcVT);
999 
1000   // Shuffle the incoming lanes into the correct position, and pull all other
1001   // lanes from the zero vector.
1002   SmallVector<int, 16> ShuffleMask;
1003   ShuffleMask.reserve(NumSrcElements);
1004   for (int i = 0; i < NumSrcElements; ++i)
1005     ShuffleMask.push_back(i);
1006 
1007   int ExtLaneScale = NumSrcElements / NumElements;
1008   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
1009   for (int i = 0; i < NumElements; ++i)
1010     ShuffleMask[i * ExtLaneScale + EndianOffset] = NumSrcElements + i;
1011 
1012   return DAG.getNode(ISD::BITCAST, DL, VT,
1013                      DAG.getVectorShuffle(SrcVT, DL, Zero, Src, ShuffleMask));
1014 }
1015 
1016 static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
1017   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
1018   for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
1019     for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
1020       ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
1021 }
1022 
1023 SDValue VectorLegalizer::ExpandBSWAP(SDValue Op) {
1024   EVT VT = Op.getValueType();
1025 
1026   // Generate a byte wise shuffle mask for the BSWAP.
1027   SmallVector<int, 16> ShuffleMask;
1028   createBSWAPShuffleMask(VT, ShuffleMask);
1029   EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
1030 
1031   // Only emit a shuffle if the mask is legal.
1032   if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
1033     return DAG.UnrollVectorOp(Op.getNode());
1034 
1035   SDLoc DL(Op);
1036   Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1037   Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT), ShuffleMask);
1038   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1039 }
1040 
1041 SDValue VectorLegalizer::ExpandBITREVERSE(SDValue Op) {
1042   EVT VT = Op.getValueType();
1043 
1044   // If we have the scalar operation, it's probably cheaper to unroll it.
1045   if (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, VT.getScalarType()))
1046     return DAG.UnrollVectorOp(Op.getNode());
1047 
1048   // If the vector element width is a whole number of bytes, test if its legal
1049   // to BSWAP shuffle the bytes and then perform the BITREVERSE on the byte
1050   // vector. This greatly reduces the number of bit shifts necessary.
1051   unsigned ScalarSizeInBits = VT.getScalarSizeInBits();
1052   if (ScalarSizeInBits > 8 && (ScalarSizeInBits % 8) == 0) {
1053     SmallVector<int, 16> BSWAPMask;
1054     createBSWAPShuffleMask(VT, BSWAPMask);
1055 
1056     EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, BSWAPMask.size());
1057     if (TLI.isShuffleMaskLegal(BSWAPMask, ByteVT) &&
1058         (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, ByteVT) ||
1059          (TLI.isOperationLegalOrCustom(ISD::SHL, ByteVT) &&
1060           TLI.isOperationLegalOrCustom(ISD::SRL, ByteVT) &&
1061           TLI.isOperationLegalOrCustomOrPromote(ISD::AND, ByteVT) &&
1062           TLI.isOperationLegalOrCustomOrPromote(ISD::OR, ByteVT)))) {
1063       SDLoc DL(Op);
1064       Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1065       Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
1066                                 BSWAPMask);
1067       Op = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Op);
1068       return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1069     }
1070   }
1071 
1072   // If we have the appropriate vector bit operations, it is better to use them
1073   // than unrolling and expanding each component.
1074   if (!TLI.isOperationLegalOrCustom(ISD::SHL, VT) ||
1075       !TLI.isOperationLegalOrCustom(ISD::SRL, VT) ||
1076       !TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
1077       !TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT))
1078     return DAG.UnrollVectorOp(Op.getNode());
1079 
1080   // Let LegalizeDAG handle this later.
1081   return Op;
1082 }
1083 
1084 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
1085   // Implement VSELECT in terms of XOR, AND, OR
1086   // on platforms which do not support blend natively.
1087   SDLoc DL(Op);
1088 
1089   SDValue Mask = Op.getOperand(0);
1090   SDValue Op1 = Op.getOperand(1);
1091   SDValue Op2 = Op.getOperand(2);
1092 
1093   EVT VT = Mask.getValueType();
1094 
1095   // If we can't even use the basic vector operations of
1096   // AND,OR,XOR, we will have to scalarize the op.
1097   // Notice that the operation may be 'promoted' which means that it is
1098   // 'bitcasted' to another type which is handled.
1099   // This operation also isn't safe with AND, OR, XOR when the boolean
1100   // type is 0/1 as we need an all ones vector constant to mask with.
1101   // FIXME: Sign extend 1 to all ones if thats legal on the target.
1102   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
1103       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
1104       TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
1105       TLI.getBooleanContents(Op1.getValueType()) !=
1106           TargetLowering::ZeroOrNegativeOneBooleanContent)
1107     return DAG.UnrollVectorOp(Op.getNode());
1108 
1109   // If the mask and the type are different sizes, unroll the vector op. This
1110   // can occur when getSetCCResultType returns something that is different in
1111   // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
1112   if (VT.getSizeInBits() != Op1.getValueSizeInBits())
1113     return DAG.UnrollVectorOp(Op.getNode());
1114 
1115   // Bitcast the operands to be the same type as the mask.
1116   // This is needed when we select between FP types because
1117   // the mask is a vector of integers.
1118   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
1119   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
1120 
1121   SDValue AllOnes = DAG.getConstant(
1122     APInt::getAllOnesValue(VT.getScalarSizeInBits()), DL, VT);
1123   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
1124 
1125   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
1126   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
1127   SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
1128   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
1129 }
1130 
1131 SDValue VectorLegalizer::ExpandABS(SDValue Op) {
1132   // Attempt to expand using TargetLowering.
1133   SDValue Result;
1134   if (TLI.expandABS(Op.getNode(), Result, DAG))
1135     return Result;
1136 
1137   // Otherwise go ahead and unroll.
1138   return DAG.UnrollVectorOp(Op.getNode());
1139 }
1140 
1141 SDValue VectorLegalizer::ExpandFP_TO_UINT(SDValue Op) {
1142   // Attempt to expand using TargetLowering.
1143   SDValue Result, Chain;
1144   if (TLI.expandFP_TO_UINT(Op.getNode(), Result, Chain, DAG)) {
1145     if (Op.getNode()->isStrictFPOpcode())
1146       // Relink the chain
1147       DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Chain);
1148     return Result;
1149   }
1150 
1151   // Otherwise go ahead and unroll.
1152   return DAG.UnrollVectorOp(Op.getNode());
1153 }
1154 
1155 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
1156   EVT VT = Op.getOperand(0).getValueType();
1157   SDLoc DL(Op);
1158 
1159   // Attempt to expand using TargetLowering.
1160   SDValue Result;
1161   if (TLI.expandUINT_TO_FP(Op.getNode(), Result, DAG))
1162     return Result;
1163 
1164   // Make sure that the SINT_TO_FP and SRL instructions are available.
1165   if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) == TargetLowering::Expand ||
1166       TLI.getOperationAction(ISD::SRL,        VT) == TargetLowering::Expand)
1167     return DAG.UnrollVectorOp(Op.getNode());
1168 
1169   unsigned BW = VT.getScalarSizeInBits();
1170   assert((BW == 64 || BW == 32) &&
1171          "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
1172 
1173   SDValue HalfWord = DAG.getConstant(BW / 2, DL, VT);
1174 
1175   // Constants to clear the upper part of the word.
1176   // Notice that we can also use SHL+SHR, but using a constant is slightly
1177   // faster on x86.
1178   uint64_t HWMask = (BW == 64) ? 0x00000000FFFFFFFF : 0x0000FFFF;
1179   SDValue HalfWordMask = DAG.getConstant(HWMask, DL, VT);
1180 
1181   // Two to the power of half-word-size.
1182   SDValue TWOHW = DAG.getConstantFP(1ULL << (BW / 2), DL, Op.getValueType());
1183 
1184   // Clear upper part of LO, lower HI
1185   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
1186   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
1187 
1188   // Convert hi and lo to floats
1189   // Convert the hi part back to the upper values
1190   // TODO: Can any fast-math-flags be set on these nodes?
1191   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
1192           fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
1193   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
1194 
1195   // Add the two halves
1196   return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
1197 }
1198 
1199 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
1200   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
1201     SDLoc DL(Op);
1202     SDValue Zero = DAG.getConstantFP(-0.0, DL, Op.getValueType());
1203     // TODO: If FNEG had fast-math-flags, they'd get propagated to this FSUB.
1204     return DAG.getNode(ISD::FSUB, DL, Op.getValueType(),
1205                        Zero, Op.getOperand(0));
1206   }
1207   return DAG.UnrollVectorOp(Op.getNode());
1208 }
1209 
1210 SDValue VectorLegalizer::ExpandFSUB(SDValue Op) {
1211   // For floating-point values, (a-b) is the same as a+(-b). If FNEG is legal,
1212   // we can defer this to operation legalization where it will be lowered as
1213   // a+(-b).
1214   EVT VT = Op.getValueType();
1215   if (TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
1216       TLI.isOperationLegalOrCustom(ISD::FADD, VT))
1217     return Op; // Defer to LegalizeDAG
1218 
1219   return DAG.UnrollVectorOp(Op.getNode());
1220 }
1221 
1222 SDValue VectorLegalizer::ExpandCTPOP(SDValue Op) {
1223   SDValue Result;
1224   if (TLI.expandCTPOP(Op.getNode(), Result, DAG))
1225     return Result;
1226 
1227   return DAG.UnrollVectorOp(Op.getNode());
1228 }
1229 
1230 SDValue VectorLegalizer::ExpandCTLZ(SDValue Op) {
1231   SDValue Result;
1232   if (TLI.expandCTLZ(Op.getNode(), Result, DAG))
1233     return Result;
1234 
1235   return DAG.UnrollVectorOp(Op.getNode());
1236 }
1237 
1238 SDValue VectorLegalizer::ExpandCTTZ(SDValue Op) {
1239   SDValue Result;
1240   if (TLI.expandCTTZ(Op.getNode(), Result, DAG))
1241     return Result;
1242 
1243   return DAG.UnrollVectorOp(Op.getNode());
1244 }
1245 
1246 SDValue VectorLegalizer::ExpandFunnelShift(SDValue Op) {
1247   SDValue Result;
1248   if (TLI.expandFunnelShift(Op.getNode(), Result, DAG))
1249     return Result;
1250 
1251   return DAG.UnrollVectorOp(Op.getNode());
1252 }
1253 
1254 SDValue VectorLegalizer::ExpandROT(SDValue Op) {
1255   SDValue Result;
1256   if (TLI.expandROT(Op.getNode(), Result, DAG))
1257     return Result;
1258 
1259   return DAG.UnrollVectorOp(Op.getNode());
1260 }
1261 
1262 SDValue VectorLegalizer::ExpandFMINNUM_FMAXNUM(SDValue Op) {
1263   if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Op.getNode(), DAG))
1264     return Expanded;
1265   return DAG.UnrollVectorOp(Op.getNode());
1266 }
1267 
1268 SDValue VectorLegalizer::ExpandUADDSUBO(SDValue Op) {
1269   SDValue Result, Overflow;
1270   TLI.expandUADDSUBO(Op.getNode(), Result, Overflow, DAG);
1271 
1272   if (Op.getResNo() == 0) {
1273     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1274     return Result;
1275   } else {
1276     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1277     return Overflow;
1278   }
1279 }
1280 
1281 SDValue VectorLegalizer::ExpandSADDSUBO(SDValue Op) {
1282   SDValue Result, Overflow;
1283   TLI.expandSADDSUBO(Op.getNode(), Result, Overflow, DAG);
1284 
1285   if (Op.getResNo() == 0) {
1286     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1287     return Result;
1288   } else {
1289     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1290     return Overflow;
1291   }
1292 }
1293 
1294 SDValue VectorLegalizer::ExpandMULO(SDValue Op) {
1295   SDValue Result, Overflow;
1296   if (!TLI.expandMULO(Op.getNode(), Result, Overflow, DAG))
1297     std::tie(Result, Overflow) = DAG.UnrollVectorOverflowOp(Op.getNode());
1298 
1299   if (Op.getResNo() == 0) {
1300     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1301     return Result;
1302   } else {
1303     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1304     return Overflow;
1305   }
1306 }
1307 
1308 SDValue VectorLegalizer::ExpandAddSubSat(SDValue Op) {
1309   if (SDValue Expanded = TLI.expandAddSubSat(Op.getNode(), DAG))
1310     return Expanded;
1311   return DAG.UnrollVectorOp(Op.getNode());
1312 }
1313 
1314 SDValue VectorLegalizer::ExpandFixedPointMul(SDValue Op) {
1315   if (SDValue Expanded = TLI.expandFixedPointMul(Op.getNode(), DAG))
1316     return Expanded;
1317   return DAG.UnrollVectorOp(Op.getNode());
1318 }
1319 
1320 SDValue VectorLegalizer::ExpandStrictFPOp(SDValue Op) {
1321   EVT VT = Op.getValueType();
1322   EVT EltVT = VT.getVectorElementType();
1323   unsigned NumElems = VT.getVectorNumElements();
1324   unsigned NumOpers = Op.getNumOperands();
1325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1326   EVT ValueVTs[] = {EltVT, MVT::Other};
1327   SDValue Chain = Op.getOperand(0);
1328   SDLoc dl(Op);
1329 
1330   SmallVector<SDValue, 32> OpValues;
1331   SmallVector<SDValue, 32> OpChains;
1332   for (unsigned i = 0; i < NumElems; ++i) {
1333     SmallVector<SDValue, 4> Opers;
1334     SDValue Idx = DAG.getConstant(i, dl,
1335                                   TLI.getVectorIdxTy(DAG.getDataLayout()));
1336 
1337     // The Chain is the first operand.
1338     Opers.push_back(Chain);
1339 
1340     // Now process the remaining operands.
1341     for (unsigned j = 1; j < NumOpers; ++j) {
1342       SDValue Oper = Op.getOperand(j);
1343       EVT OperVT = Oper.getValueType();
1344 
1345       if (OperVT.isVector())
1346         Oper = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1347                            OperVT.getVectorElementType(), Oper, Idx);
1348 
1349       Opers.push_back(Oper);
1350     }
1351 
1352     SDValue ScalarOp = DAG.getNode(Op->getOpcode(), dl, ValueVTs, Opers);
1353 
1354     OpValues.push_back(ScalarOp.getValue(0));
1355     OpChains.push_back(ScalarOp.getValue(1));
1356   }
1357 
1358   SDValue Result = DAG.getBuildVector(VT, dl, OpValues);
1359   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OpChains);
1360 
1361   AddLegalizedOperand(Op.getValue(0), Result);
1362   AddLegalizedOperand(Op.getValue(1), NewChain);
1363 
1364   return Op.getResNo() ? NewChain : Result;
1365 }
1366 
1367 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
1368   EVT VT = Op.getValueType();
1369   unsigned NumElems = VT.getVectorNumElements();
1370   EVT EltVT = VT.getVectorElementType();
1371   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
1372   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
1373   SDLoc dl(Op);
1374   SmallVector<SDValue, 8> Ops(NumElems);
1375   for (unsigned i = 0; i < NumElems; ++i) {
1376     SDValue LHSElem = DAG.getNode(
1377         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
1378         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1379     SDValue RHSElem = DAG.getNode(
1380         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
1381         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1382     Ops[i] = DAG.getNode(ISD::SETCC, dl,
1383                          TLI.getSetCCResultType(DAG.getDataLayout(),
1384                                                 *DAG.getContext(), TmpEltVT),
1385                          LHSElem, RHSElem, CC);
1386     Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
1387                            DAG.getConstant(APInt::getAllOnesValue
1388                                            (EltVT.getSizeInBits()), dl, EltVT),
1389                            DAG.getConstant(0, dl, EltVT));
1390   }
1391   return DAG.getBuildVector(VT, dl, Ops);
1392 }
1393 
1394 bool SelectionDAG::LegalizeVectors() {
1395   return VectorLegalizer(*this).Run();
1396 }
1397