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   EVT ValVT;
311   switch (Op.getOpcode()) {
312   default:
313     return TranslateLegalizeResults(Op, Result);
314 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
315   case ISD::STRICT_##DAGN:
316 #include "llvm/IR/ConstrainedOps.def"
317     ValVT = Node->getValueType(0);
318     if (Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
319         Op.getOpcode() == ISD::STRICT_UINT_TO_FP)
320       ValVT = Node->getOperand(1).getValueType();
321     Action = TLI.getOperationAction(Node->getOpcode(), ValVT);
322     // If we're asked to expand a strict vector floating-point operation,
323     // by default we're going to simply unroll it.  That is usually the
324     // best approach, except in the case where the resulting strict (scalar)
325     // operations would themselves use the fallback mutation to non-strict.
326     // In that specific case, just do the fallback on the vector op.
327     if (Action == TargetLowering::Expand && !TLI.isStrictFPEnabled() &&
328         TLI.getStrictFPOperationAction(Node->getOpcode(), ValVT) ==
329             TargetLowering::Legal) {
330       EVT EltVT = ValVT.getVectorElementType();
331       if (TLI.getOperationAction(Node->getOpcode(), EltVT)
332           == TargetLowering::Expand &&
333           TLI.getStrictFPOperationAction(Node->getOpcode(), EltVT)
334           == TargetLowering::Legal)
335         Action = TargetLowering::Legal;
336     }
337     break;
338   case ISD::ADD:
339   case ISD::SUB:
340   case ISD::MUL:
341   case ISD::MULHS:
342   case ISD::MULHU:
343   case ISD::SDIV:
344   case ISD::UDIV:
345   case ISD::SREM:
346   case ISD::UREM:
347   case ISD::SDIVREM:
348   case ISD::UDIVREM:
349   case ISD::FADD:
350   case ISD::FSUB:
351   case ISD::FMUL:
352   case ISD::FDIV:
353   case ISD::FREM:
354   case ISD::AND:
355   case ISD::OR:
356   case ISD::XOR:
357   case ISD::SHL:
358   case ISD::SRA:
359   case ISD::SRL:
360   case ISD::FSHL:
361   case ISD::FSHR:
362   case ISD::ROTL:
363   case ISD::ROTR:
364   case ISD::ABS:
365   case ISD::BSWAP:
366   case ISD::BITREVERSE:
367   case ISD::CTLZ:
368   case ISD::CTTZ:
369   case ISD::CTLZ_ZERO_UNDEF:
370   case ISD::CTTZ_ZERO_UNDEF:
371   case ISD::CTPOP:
372   case ISD::SELECT:
373   case ISD::VSELECT:
374   case ISD::SELECT_CC:
375   case ISD::SETCC:
376   case ISD::ZERO_EXTEND:
377   case ISD::ANY_EXTEND:
378   case ISD::TRUNCATE:
379   case ISD::SIGN_EXTEND:
380   case ISD::FP_TO_SINT:
381   case ISD::FP_TO_UINT:
382   case ISD::FNEG:
383   case ISD::FABS:
384   case ISD::FMINNUM:
385   case ISD::FMAXNUM:
386   case ISD::FMINNUM_IEEE:
387   case ISD::FMAXNUM_IEEE:
388   case ISD::FMINIMUM:
389   case ISD::FMAXIMUM:
390   case ISD::FCOPYSIGN:
391   case ISD::FSQRT:
392   case ISD::FSIN:
393   case ISD::FCOS:
394   case ISD::FPOWI:
395   case ISD::FPOW:
396   case ISD::FLOG:
397   case ISD::FLOG2:
398   case ISD::FLOG10:
399   case ISD::FEXP:
400   case ISD::FEXP2:
401   case ISD::FCEIL:
402   case ISD::FTRUNC:
403   case ISD::FRINT:
404   case ISD::FNEARBYINT:
405   case ISD::FROUND:
406   case ISD::FFLOOR:
407   case ISD::FP_ROUND:
408   case ISD::FP_EXTEND:
409   case ISD::FMA:
410   case ISD::SIGN_EXTEND_INREG:
411   case ISD::ANY_EXTEND_VECTOR_INREG:
412   case ISD::SIGN_EXTEND_VECTOR_INREG:
413   case ISD::ZERO_EXTEND_VECTOR_INREG:
414   case ISD::SMIN:
415   case ISD::SMAX:
416   case ISD::UMIN:
417   case ISD::UMAX:
418   case ISD::SMUL_LOHI:
419   case ISD::UMUL_LOHI:
420   case ISD::SADDO:
421   case ISD::UADDO:
422   case ISD::SSUBO:
423   case ISD::USUBO:
424   case ISD::SMULO:
425   case ISD::UMULO:
426   case ISD::FCANONICALIZE:
427   case ISD::SADDSAT:
428   case ISD::UADDSAT:
429   case ISD::SSUBSAT:
430   case ISD::USUBSAT:
431     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
432     break;
433   case ISD::SMULFIX:
434   case ISD::SMULFIXSAT:
435   case ISD::UMULFIX:
436   case ISD::UMULFIXSAT: {
437     unsigned Scale = Node->getConstantOperandVal(2);
438     Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
439                                               Node->getValueType(0), Scale);
440     break;
441   }
442   case ISD::SINT_TO_FP:
443   case ISD::UINT_TO_FP:
444   case ISD::VECREDUCE_ADD:
445   case ISD::VECREDUCE_MUL:
446   case ISD::VECREDUCE_AND:
447   case ISD::VECREDUCE_OR:
448   case ISD::VECREDUCE_XOR:
449   case ISD::VECREDUCE_SMAX:
450   case ISD::VECREDUCE_SMIN:
451   case ISD::VECREDUCE_UMAX:
452   case ISD::VECREDUCE_UMIN:
453   case ISD::VECREDUCE_FADD:
454   case ISD::VECREDUCE_FMUL:
455   case ISD::VECREDUCE_FMAX:
456   case ISD::VECREDUCE_FMIN:
457     Action = TLI.getOperationAction(Node->getOpcode(),
458                                     Node->getOperand(0).getValueType());
459     break;
460   }
461 
462   LLVM_DEBUG(dbgs() << "\nLegalizing vector op: "; Node->dump(&DAG));
463 
464   switch (Action) {
465   default: llvm_unreachable("This action is not supported yet!");
466   case TargetLowering::Promote:
467     Result = Promote(Op);
468     Changed = true;
469     break;
470   case TargetLowering::Legal:
471     LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
472     break;
473   case TargetLowering::Custom: {
474     LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
475     if (SDValue Tmp1 = TLI.LowerOperation(Op, DAG)) {
476       LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
477       Result = Tmp1;
478       break;
479     }
480     LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
481     LLVM_FALLTHROUGH;
482   }
483   case TargetLowering::Expand:
484     Result = Expand(Op);
485   }
486 
487   // Make sure that the generated code is itself legal.
488   if (Result != Op) {
489     Result = LegalizeOp(Result);
490     Changed = true;
491   }
492 
493   // Note that LegalizeOp may be reentered even from single-use nodes, which
494   // means that we always must cache transformed nodes.
495   AddLegalizedOperand(Op, Result);
496   return Result;
497 }
498 
499 SDValue VectorLegalizer::Promote(SDValue Op) {
500   // For a few operations there is a specific concept for promotion based on
501   // the operand's type.
502   switch (Op.getOpcode()) {
503   case ISD::SINT_TO_FP:
504   case ISD::UINT_TO_FP:
505     // "Promote" the operation by extending the operand.
506     return PromoteINT_TO_FP(Op);
507   case ISD::FP_TO_UINT:
508   case ISD::FP_TO_SINT:
509     // Promote the operation by extending the operand.
510     return PromoteFP_TO_INT(Op);
511   }
512 
513   // There are currently two cases of vector promotion:
514   // 1) Bitcasting a vector of integers to a different type to a vector of the
515   //    same overall length. For example, x86 promotes ISD::AND v2i32 to v1i64.
516   // 2) Extending a vector of floats to a vector of the same number of larger
517   //    floats. For example, AArch64 promotes ISD::FADD on v4f16 to v4f32.
518   MVT VT = Op.getSimpleValueType();
519   assert(Op.getNode()->getNumValues() == 1 &&
520          "Can't promote a vector with multiple results!");
521   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
522   SDLoc dl(Op);
523   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
524 
525   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
526     if (Op.getOperand(j).getValueType().isVector())
527       if (Op.getOperand(j)
528               .getValueType()
529               .getVectorElementType()
530               .isFloatingPoint() &&
531           NVT.isVector() && NVT.getVectorElementType().isFloatingPoint())
532         Operands[j] = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Op.getOperand(j));
533       else
534         Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
535     else
536       Operands[j] = Op.getOperand(j);
537   }
538 
539   Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands, Op.getNode()->getFlags());
540   if ((VT.isFloatingPoint() && NVT.isFloatingPoint()) ||
541       (VT.isVector() && VT.getVectorElementType().isFloatingPoint() &&
542        NVT.isVector() && NVT.getVectorElementType().isFloatingPoint()))
543     return DAG.getNode(ISD::FP_ROUND, dl, VT, Op, DAG.getIntPtrConstant(0, dl));
544   else
545     return DAG.getNode(ISD::BITCAST, dl, VT, Op);
546 }
547 
548 SDValue VectorLegalizer::PromoteINT_TO_FP(SDValue Op) {
549   // INT_TO_FP operations may require the input operand be promoted even
550   // when the type is otherwise legal.
551   MVT VT = Op.getOperand(0).getSimpleValueType();
552   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
553   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
554          "Vectors have different number of elements!");
555 
556   SDLoc dl(Op);
557   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
558 
559   unsigned Opc = Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND :
560     ISD::SIGN_EXTEND;
561   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
562     if (Op.getOperand(j).getValueType().isVector())
563       Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
564     else
565       Operands[j] = Op.getOperand(j);
566   }
567 
568   return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
569 }
570 
571 // For FP_TO_INT we promote the result type to a vector type with wider
572 // elements and then truncate the result.  This is different from the default
573 // PromoteVector which uses bitcast to promote thus assumning that the
574 // promoted vector type has the same overall size.
575 SDValue VectorLegalizer::PromoteFP_TO_INT(SDValue Op) {
576   MVT VT = Op.getSimpleValueType();
577   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
578   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
579          "Vectors have different number of elements!");
580 
581   unsigned NewOpc = Op->getOpcode();
582   // Change FP_TO_UINT to FP_TO_SINT if possible.
583   // TODO: Should we only do this if FP_TO_UINT itself isn't legal?
584   if (NewOpc == ISD::FP_TO_UINT &&
585       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
586     NewOpc = ISD::FP_TO_SINT;
587 
588   SDLoc dl(Op);
589   SDValue Promoted  = DAG.getNode(NewOpc, dl, NVT, Op.getOperand(0));
590 
591   // Assert that the converted value fits in the original type.  If it doesn't
592   // (eg: because the value being converted is too big), then the result of the
593   // original operation was undefined anyway, so the assert is still correct.
594   Promoted = DAG.getNode(Op->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
595                                                             : ISD::AssertSext,
596                          dl, NVT, Promoted,
597                          DAG.getValueType(VT.getScalarType()));
598   return DAG.getNode(ISD::TRUNCATE, dl, VT, Promoted);
599 }
600 
601 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
602   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
603 
604   EVT SrcVT = LD->getMemoryVT();
605   EVT SrcEltVT = SrcVT.getScalarType();
606   unsigned NumElem = SrcVT.getVectorNumElements();
607 
608   SDValue NewChain;
609   SDValue Value;
610   if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
611     SDLoc dl(Op);
612 
613     SmallVector<SDValue, 8> Vals;
614     SmallVector<SDValue, 8> LoadChains;
615 
616     EVT DstEltVT = LD->getValueType(0).getScalarType();
617     SDValue Chain = LD->getChain();
618     SDValue BasePTR = LD->getBasePtr();
619     ISD::LoadExtType ExtType = LD->getExtensionType();
620 
621     // When elements in a vector is not byte-addressable, we cannot directly
622     // load each element by advancing pointer, which could only address bytes.
623     // Instead, we load all significant words, mask bits off, and concatenate
624     // them to form each element. Finally, they are extended to destination
625     // scalar type to build the destination vector.
626     EVT WideVT = TLI.getPointerTy(DAG.getDataLayout());
627 
628     assert(WideVT.isRound() &&
629            "Could not handle the sophisticated case when the widest integer is"
630            " not power of 2.");
631     assert(WideVT.bitsGE(SrcEltVT) &&
632            "Type is not legalized?");
633 
634     unsigned WideBytes = WideVT.getStoreSize();
635     unsigned Offset = 0;
636     unsigned RemainingBytes = SrcVT.getStoreSize();
637     SmallVector<SDValue, 8> LoadVals;
638     while (RemainingBytes > 0) {
639       SDValue ScalarLoad;
640       unsigned LoadBytes = WideBytes;
641 
642       if (RemainingBytes >= LoadBytes) {
643         ScalarLoad =
644             DAG.getLoad(WideVT, dl, Chain, BasePTR,
645                         LD->getPointerInfo().getWithOffset(Offset),
646                         MinAlign(LD->getAlignment(), Offset),
647                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
648       } else {
649         EVT LoadVT = WideVT;
650         while (RemainingBytes < LoadBytes) {
651           LoadBytes >>= 1; // Reduce the load size by half.
652           LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
653         }
654         ScalarLoad =
655             DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
656                            LD->getPointerInfo().getWithOffset(Offset), LoadVT,
657                            MinAlign(LD->getAlignment(), Offset),
658                            LD->getMemOperand()->getFlags(), LD->getAAInfo());
659       }
660 
661       RemainingBytes -= LoadBytes;
662       Offset += LoadBytes;
663 
664       BasePTR = DAG.getObjectPtrOffset(dl, BasePTR, LoadBytes);
665 
666       LoadVals.push_back(ScalarLoad.getValue(0));
667       LoadChains.push_back(ScalarLoad.getValue(1));
668     }
669 
670     unsigned BitOffset = 0;
671     unsigned WideIdx = 0;
672     unsigned WideBits = WideVT.getSizeInBits();
673 
674     // Extract bits, pack and extend/trunc them into destination type.
675     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
676     SDValue SrcEltBitMask = DAG.getConstant(
677         APInt::getLowBitsSet(WideBits, SrcEltBits), dl, WideVT);
678 
679     for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
680       assert(BitOffset < WideBits && "Unexpected offset!");
681 
682       SDValue ShAmt = DAG.getConstant(
683           BitOffset, dl, TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
684       SDValue Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
685 
686       BitOffset += SrcEltBits;
687       if (BitOffset >= WideBits) {
688         WideIdx++;
689         BitOffset -= WideBits;
690         if (BitOffset > 0) {
691           ShAmt = DAG.getConstant(
692               SrcEltBits - BitOffset, dl,
693               TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
694           SDValue Hi =
695               DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
696           Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
697         }
698       }
699 
700       Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
701 
702       switch (ExtType) {
703       default: llvm_unreachable("Unknown extended-load op!");
704       case ISD::EXTLOAD:
705         Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
706         break;
707       case ISD::ZEXTLOAD:
708         Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
709         break;
710       case ISD::SEXTLOAD:
711         ShAmt =
712             DAG.getConstant(WideBits - SrcEltBits, dl,
713                             TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
714         Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
715         Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
716         Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
717         break;
718       }
719       Vals.push_back(Lo);
720     }
721 
722     NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
723     Value = DAG.getBuildVector(Op.getNode()->getValueType(0), dl, Vals);
724   } else {
725     SDValue Scalarized = TLI.scalarizeVectorLoad(LD, DAG);
726     // Skip past MERGE_VALUE node if known.
727     if (Scalarized->getOpcode() == ISD::MERGE_VALUES) {
728       NewChain = Scalarized.getOperand(1);
729       Value = Scalarized.getOperand(0);
730     } else {
731       NewChain = Scalarized.getValue(1);
732       Value = Scalarized.getValue(0);
733     }
734   }
735 
736   AddLegalizedOperand(Op.getValue(0), Value);
737   AddLegalizedOperand(Op.getValue(1), NewChain);
738 
739   return (Op.getResNo() ? NewChain : Value);
740 }
741 
742 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
743   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
744   SDValue TF = TLI.scalarizeVectorStore(ST, DAG);
745   AddLegalizedOperand(Op, TF);
746   return TF;
747 }
748 
749 SDValue VectorLegalizer::Expand(SDValue Op) {
750   switch (Op->getOpcode()) {
751   case ISD::SIGN_EXTEND_INREG:
752     return ExpandSEXTINREG(Op);
753   case ISD::ANY_EXTEND_VECTOR_INREG:
754     return ExpandANY_EXTEND_VECTOR_INREG(Op);
755   case ISD::SIGN_EXTEND_VECTOR_INREG:
756     return ExpandSIGN_EXTEND_VECTOR_INREG(Op);
757   case ISD::ZERO_EXTEND_VECTOR_INREG:
758     return ExpandZERO_EXTEND_VECTOR_INREG(Op);
759   case ISD::BSWAP:
760     return ExpandBSWAP(Op);
761   case ISD::VSELECT:
762     return ExpandVSELECT(Op);
763   case ISD::SELECT:
764     return ExpandSELECT(Op);
765   case ISD::FP_TO_UINT:
766     return ExpandFP_TO_UINT(Op);
767   case ISD::UINT_TO_FP:
768     return ExpandUINT_TO_FLOAT(Op);
769   case ISD::FNEG:
770     return ExpandFNEG(Op);
771   case ISD::FSUB:
772     return ExpandFSUB(Op);
773   case ISD::SETCC:
774     return UnrollVSETCC(Op);
775   case ISD::ABS:
776     return ExpandABS(Op);
777   case ISD::BITREVERSE:
778     return ExpandBITREVERSE(Op);
779   case ISD::CTPOP:
780     return ExpandCTPOP(Op);
781   case ISD::CTLZ:
782   case ISD::CTLZ_ZERO_UNDEF:
783     return ExpandCTLZ(Op);
784   case ISD::CTTZ:
785   case ISD::CTTZ_ZERO_UNDEF:
786     return ExpandCTTZ(Op);
787   case ISD::FSHL:
788   case ISD::FSHR:
789     return ExpandFunnelShift(Op);
790   case ISD::ROTL:
791   case ISD::ROTR:
792     return ExpandROT(Op);
793   case ISD::FMINNUM:
794   case ISD::FMAXNUM:
795     return ExpandFMINNUM_FMAXNUM(Op);
796   case ISD::UADDO:
797   case ISD::USUBO:
798     return ExpandUADDSUBO(Op);
799   case ISD::SADDO:
800   case ISD::SSUBO:
801     return ExpandSADDSUBO(Op);
802   case ISD::UMULO:
803   case ISD::SMULO:
804     return ExpandMULO(Op);
805   case ISD::USUBSAT:
806   case ISD::SSUBSAT:
807   case ISD::UADDSAT:
808   case ISD::SADDSAT:
809     return ExpandAddSubSat(Op);
810   case ISD::SMULFIX:
811   case ISD::UMULFIX:
812     return ExpandFixedPointMul(Op);
813   case ISD::SMULFIXSAT:
814   case ISD::UMULFIXSAT:
815     // FIXME: We do not expand SMULFIXSAT/UMULFIXSAT here yet, not sure exactly
816     // why. Maybe it results in worse codegen compared to the unroll for some
817     // targets? This should probably be investigated. And if we still prefer to
818     // unroll an explanation could be helpful.
819     return DAG.UnrollVectorOp(Op.getNode());
820 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
821   case ISD::STRICT_##DAGN:
822 #include "llvm/IR/ConstrainedOps.def"
823     return ExpandStrictFPOp(Op);
824   case ISD::VECREDUCE_ADD:
825   case ISD::VECREDUCE_MUL:
826   case ISD::VECREDUCE_AND:
827   case ISD::VECREDUCE_OR:
828   case ISD::VECREDUCE_XOR:
829   case ISD::VECREDUCE_SMAX:
830   case ISD::VECREDUCE_SMIN:
831   case ISD::VECREDUCE_UMAX:
832   case ISD::VECREDUCE_UMIN:
833   case ISD::VECREDUCE_FADD:
834   case ISD::VECREDUCE_FMUL:
835   case ISD::VECREDUCE_FMAX:
836   case ISD::VECREDUCE_FMIN:
837     return TLI.expandVecReduce(Op.getNode(), DAG);
838   default:
839     return DAG.UnrollVectorOp(Op.getNode());
840   }
841 }
842 
843 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
844   // Lower a select instruction where the condition is a scalar and the
845   // operands are vectors. Lower this select to VSELECT and implement it
846   // using XOR AND OR. The selector bit is broadcasted.
847   EVT VT = Op.getValueType();
848   SDLoc DL(Op);
849 
850   SDValue Mask = Op.getOperand(0);
851   SDValue Op1 = Op.getOperand(1);
852   SDValue Op2 = Op.getOperand(2);
853 
854   assert(VT.isVector() && !Mask.getValueType().isVector()
855          && Op1.getValueType() == Op2.getValueType() && "Invalid type");
856 
857   // If we can't even use the basic vector operations of
858   // AND,OR,XOR, we will have to scalarize the op.
859   // Notice that the operation may be 'promoted' which means that it is
860   // 'bitcasted' to another type which is handled.
861   // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
862   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
863       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
864       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
865       TLI.getOperationAction(ISD::BUILD_VECTOR,  VT) == TargetLowering::Expand)
866     return DAG.UnrollVectorOp(Op.getNode());
867 
868   // Generate a mask operand.
869   EVT MaskTy = VT.changeVectorElementTypeToInteger();
870 
871   // What is the size of each element in the vector mask.
872   EVT BitTy = MaskTy.getScalarType();
873 
874   Mask = DAG.getSelect(DL, BitTy, Mask,
875           DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), DL,
876                           BitTy),
877           DAG.getConstant(0, DL, BitTy));
878 
879   // Broadcast the mask so that the entire vector is all-one or all zero.
880   Mask = DAG.getSplatBuildVector(MaskTy, DL, Mask);
881 
882   // Bitcast the operands to be the same type as the mask.
883   // This is needed when we select between FP types because
884   // the mask is a vector of integers.
885   Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
886   Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
887 
888   SDValue AllOnes = DAG.getConstant(
889             APInt::getAllOnesValue(BitTy.getSizeInBits()), DL, MaskTy);
890   SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
891 
892   Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
893   Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
894   SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
895   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
896 }
897 
898 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
899   EVT VT = Op.getValueType();
900 
901   // Make sure that the SRA and SHL instructions are available.
902   if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
903       TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
904     return DAG.UnrollVectorOp(Op.getNode());
905 
906   SDLoc DL(Op);
907   EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
908 
909   unsigned BW = VT.getScalarSizeInBits();
910   unsigned OrigBW = OrigTy.getScalarSizeInBits();
911   SDValue ShiftSz = DAG.getConstant(BW - OrigBW, DL, VT);
912 
913   Op = Op.getOperand(0);
914   Op =   DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
915   return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
916 }
917 
918 // Generically expand a vector anyext in register to a shuffle of the relevant
919 // lanes into the appropriate locations, with other lanes left undef.
920 SDValue VectorLegalizer::ExpandANY_EXTEND_VECTOR_INREG(SDValue Op) {
921   SDLoc DL(Op);
922   EVT VT = Op.getValueType();
923   int NumElements = VT.getVectorNumElements();
924   SDValue Src = Op.getOperand(0);
925   EVT SrcVT = Src.getValueType();
926   int NumSrcElements = SrcVT.getVectorNumElements();
927 
928   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
929   // into a larger vector type.
930   if (SrcVT.bitsLE(VT)) {
931     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
932            "ANY_EXTEND_VECTOR_INREG vector size mismatch");
933     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
934     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
935                              NumSrcElements);
936     Src = DAG.getNode(
937         ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT), Src,
938         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
939   }
940 
941   // Build a base mask of undef shuffles.
942   SmallVector<int, 16> ShuffleMask;
943   ShuffleMask.resize(NumSrcElements, -1);
944 
945   // Place the extended lanes into the correct locations.
946   int ExtLaneScale = NumSrcElements / NumElements;
947   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
948   for (int i = 0; i < NumElements; ++i)
949     ShuffleMask[i * ExtLaneScale + EndianOffset] = i;
950 
951   return DAG.getNode(
952       ISD::BITCAST, DL, VT,
953       DAG.getVectorShuffle(SrcVT, DL, Src, DAG.getUNDEF(SrcVT), ShuffleMask));
954 }
955 
956 SDValue VectorLegalizer::ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op) {
957   SDLoc DL(Op);
958   EVT VT = Op.getValueType();
959   SDValue Src = Op.getOperand(0);
960   EVT SrcVT = Src.getValueType();
961 
962   // First build an any-extend node which can be legalized above when we
963   // recurse through it.
964   Op = DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Src);
965 
966   // Now we need sign extend. Do this by shifting the elements. Even if these
967   // aren't legal operations, they have a better chance of being legalized
968   // without full scalarization than the sign extension does.
969   unsigned EltWidth = VT.getScalarSizeInBits();
970   unsigned SrcEltWidth = SrcVT.getScalarSizeInBits();
971   SDValue ShiftAmount = DAG.getConstant(EltWidth - SrcEltWidth, DL, VT);
972   return DAG.getNode(ISD::SRA, DL, VT,
973                      DAG.getNode(ISD::SHL, DL, VT, Op, ShiftAmount),
974                      ShiftAmount);
975 }
976 
977 // Generically expand a vector zext in register to a shuffle of the relevant
978 // lanes into the appropriate locations, a blend of zero into the high bits,
979 // and a bitcast to the wider element type.
980 SDValue VectorLegalizer::ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op) {
981   SDLoc DL(Op);
982   EVT VT = Op.getValueType();
983   int NumElements = VT.getVectorNumElements();
984   SDValue Src = Op.getOperand(0);
985   EVT SrcVT = Src.getValueType();
986   int NumSrcElements = SrcVT.getVectorNumElements();
987 
988   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
989   // into a larger vector type.
990   if (SrcVT.bitsLE(VT)) {
991     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
992            "ZERO_EXTEND_VECTOR_INREG vector size mismatch");
993     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
994     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
995                              NumSrcElements);
996     Src = DAG.getNode(
997         ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT), Src,
998         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
999   }
1000 
1001   // Build up a zero vector to blend into this one.
1002   SDValue Zero = DAG.getConstant(0, DL, SrcVT);
1003 
1004   // Shuffle the incoming lanes into the correct position, and pull all other
1005   // lanes from the zero vector.
1006   SmallVector<int, 16> ShuffleMask;
1007   ShuffleMask.reserve(NumSrcElements);
1008   for (int i = 0; i < NumSrcElements; ++i)
1009     ShuffleMask.push_back(i);
1010 
1011   int ExtLaneScale = NumSrcElements / NumElements;
1012   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
1013   for (int i = 0; i < NumElements; ++i)
1014     ShuffleMask[i * ExtLaneScale + EndianOffset] = NumSrcElements + i;
1015 
1016   return DAG.getNode(ISD::BITCAST, DL, VT,
1017                      DAG.getVectorShuffle(SrcVT, DL, Zero, Src, ShuffleMask));
1018 }
1019 
1020 static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
1021   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
1022   for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
1023     for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
1024       ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
1025 }
1026 
1027 SDValue VectorLegalizer::ExpandBSWAP(SDValue Op) {
1028   EVT VT = Op.getValueType();
1029 
1030   // Generate a byte wise shuffle mask for the BSWAP.
1031   SmallVector<int, 16> ShuffleMask;
1032   createBSWAPShuffleMask(VT, ShuffleMask);
1033   EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
1034 
1035   // Only emit a shuffle if the mask is legal.
1036   if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
1037     return DAG.UnrollVectorOp(Op.getNode());
1038 
1039   SDLoc DL(Op);
1040   Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1041   Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT), ShuffleMask);
1042   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1043 }
1044 
1045 SDValue VectorLegalizer::ExpandBITREVERSE(SDValue Op) {
1046   EVT VT = Op.getValueType();
1047 
1048   // If we have the scalar operation, it's probably cheaper to unroll it.
1049   if (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, VT.getScalarType()))
1050     return DAG.UnrollVectorOp(Op.getNode());
1051 
1052   // If the vector element width is a whole number of bytes, test if its legal
1053   // to BSWAP shuffle the bytes and then perform the BITREVERSE on the byte
1054   // vector. This greatly reduces the number of bit shifts necessary.
1055   unsigned ScalarSizeInBits = VT.getScalarSizeInBits();
1056   if (ScalarSizeInBits > 8 && (ScalarSizeInBits % 8) == 0) {
1057     SmallVector<int, 16> BSWAPMask;
1058     createBSWAPShuffleMask(VT, BSWAPMask);
1059 
1060     EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, BSWAPMask.size());
1061     if (TLI.isShuffleMaskLegal(BSWAPMask, ByteVT) &&
1062         (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, ByteVT) ||
1063          (TLI.isOperationLegalOrCustom(ISD::SHL, ByteVT) &&
1064           TLI.isOperationLegalOrCustom(ISD::SRL, ByteVT) &&
1065           TLI.isOperationLegalOrCustomOrPromote(ISD::AND, ByteVT) &&
1066           TLI.isOperationLegalOrCustomOrPromote(ISD::OR, ByteVT)))) {
1067       SDLoc DL(Op);
1068       Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1069       Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
1070                                 BSWAPMask);
1071       Op = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Op);
1072       return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1073     }
1074   }
1075 
1076   // If we have the appropriate vector bit operations, it is better to use them
1077   // than unrolling and expanding each component.
1078   if (!TLI.isOperationLegalOrCustom(ISD::SHL, VT) ||
1079       !TLI.isOperationLegalOrCustom(ISD::SRL, VT) ||
1080       !TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
1081       !TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT))
1082     return DAG.UnrollVectorOp(Op.getNode());
1083 
1084   // Let LegalizeDAG handle this later.
1085   return Op;
1086 }
1087 
1088 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
1089   // Implement VSELECT in terms of XOR, AND, OR
1090   // on platforms which do not support blend natively.
1091   SDLoc DL(Op);
1092 
1093   SDValue Mask = Op.getOperand(0);
1094   SDValue Op1 = Op.getOperand(1);
1095   SDValue Op2 = Op.getOperand(2);
1096 
1097   EVT VT = Mask.getValueType();
1098 
1099   // If we can't even use the basic vector operations of
1100   // AND,OR,XOR, we will have to scalarize the op.
1101   // Notice that the operation may be 'promoted' which means that it is
1102   // 'bitcasted' to another type which is handled.
1103   // This operation also isn't safe with AND, OR, XOR when the boolean
1104   // type is 0/1 as we need an all ones vector constant to mask with.
1105   // FIXME: Sign extend 1 to all ones if thats legal on the target.
1106   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
1107       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
1108       TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
1109       TLI.getBooleanContents(Op1.getValueType()) !=
1110           TargetLowering::ZeroOrNegativeOneBooleanContent)
1111     return DAG.UnrollVectorOp(Op.getNode());
1112 
1113   // If the mask and the type are different sizes, unroll the vector op. This
1114   // can occur when getSetCCResultType returns something that is different in
1115   // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
1116   if (VT.getSizeInBits() != Op1.getValueSizeInBits())
1117     return DAG.UnrollVectorOp(Op.getNode());
1118 
1119   // Bitcast the operands to be the same type as the mask.
1120   // This is needed when we select between FP types because
1121   // the mask is a vector of integers.
1122   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
1123   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
1124 
1125   SDValue AllOnes = DAG.getConstant(
1126     APInt::getAllOnesValue(VT.getScalarSizeInBits()), DL, VT);
1127   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
1128 
1129   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
1130   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
1131   SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
1132   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
1133 }
1134 
1135 SDValue VectorLegalizer::ExpandABS(SDValue Op) {
1136   // Attempt to expand using TargetLowering.
1137   SDValue Result;
1138   if (TLI.expandABS(Op.getNode(), Result, DAG))
1139     return Result;
1140 
1141   // Otherwise go ahead and unroll.
1142   return DAG.UnrollVectorOp(Op.getNode());
1143 }
1144 
1145 SDValue VectorLegalizer::ExpandFP_TO_UINT(SDValue Op) {
1146   // Attempt to expand using TargetLowering.
1147   SDValue Result, Chain;
1148   if (TLI.expandFP_TO_UINT(Op.getNode(), Result, Chain, DAG)) {
1149     if (Op.getNode()->isStrictFPOpcode())
1150       // Relink the chain
1151       DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Chain);
1152     return Result;
1153   }
1154 
1155   // Otherwise go ahead and unroll.
1156   return DAG.UnrollVectorOp(Op.getNode());
1157 }
1158 
1159 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
1160   bool IsStrict = Op.getNode()->isStrictFPOpcode();
1161   unsigned OpNo = IsStrict ? 1 : 0;
1162   SDValue Src = Op.getOperand(OpNo);
1163   EVT VT = Src.getValueType();
1164   SDLoc DL(Op);
1165 
1166   // Attempt to expand using TargetLowering.
1167   SDValue Result;
1168   SDValue Chain;
1169   if (TLI.expandUINT_TO_FP(Op.getNode(), Result, Chain, DAG)) {
1170     if (IsStrict)
1171       // Relink the chain
1172       DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Chain);
1173     return Result;
1174   }
1175 
1176   // Make sure that the SINT_TO_FP and SRL instructions are available.
1177   if (((!IsStrict && TLI.getOperationAction(ISD::SINT_TO_FP, VT) ==
1178                          TargetLowering::Expand) ||
1179        (IsStrict && TLI.getOperationAction(ISD::STRICT_SINT_TO_FP, VT) ==
1180                         TargetLowering::Expand)) ||
1181       TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Expand)
1182     return IsStrict ? SDValue() : DAG.UnrollVectorOp(Op.getNode());
1183 
1184   unsigned BW = VT.getScalarSizeInBits();
1185   assert((BW == 64 || BW == 32) &&
1186          "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
1187 
1188   SDValue HalfWord = DAG.getConstant(BW / 2, DL, VT);
1189 
1190   // Constants to clear the upper part of the word.
1191   // Notice that we can also use SHL+SHR, but using a constant is slightly
1192   // faster on x86.
1193   uint64_t HWMask = (BW == 64) ? 0x00000000FFFFFFFF : 0x0000FFFF;
1194   SDValue HalfWordMask = DAG.getConstant(HWMask, DL, VT);
1195 
1196   // Two to the power of half-word-size.
1197   SDValue TWOHW = DAG.getConstantFP(1ULL << (BW / 2), DL, Op.getValueType());
1198 
1199   // Clear upper part of LO, lower HI
1200   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Src, HalfWord);
1201   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Src, HalfWordMask);
1202 
1203   if (IsStrict) {
1204     // Convert hi and lo to floats
1205     // Convert the hi part back to the upper values
1206     // TODO: Can any fast-math-flags be set on these nodes?
1207     SDValue fHI =
1208         DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {Op.getValueType(), MVT::Other},
1209                     {Op.getOperand(0), HI});
1210     fHI = DAG.getNode(ISD::STRICT_FMUL, DL, {Op.getValueType(), MVT::Other},
1211                       {SDValue(fHI.getNode(), 1), fHI, TWOHW});
1212     SDValue fLO =
1213         DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {Op.getValueType(), MVT::Other},
1214                     {SDValue(fHI.getNode(), 1), LO});
1215 
1216     // Add the two halves
1217     SDValue Result =
1218         DAG.getNode(ISD::STRICT_FADD, DL, {Op.getValueType(), MVT::Other},
1219                     {SDValue(fLO.getNode(), 1), fHI, fLO});
1220 
1221     // Relink the chain
1222     DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), SDValue(Result.getNode(), 1));
1223     return Result;
1224   }
1225 
1226   // Convert hi and lo to floats
1227   // Convert the hi part back to the upper values
1228   // TODO: Can any fast-math-flags be set on these nodes?
1229   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
1230           fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
1231   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
1232 
1233   // Add the two halves
1234   return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
1235 }
1236 
1237 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
1238   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
1239     SDLoc DL(Op);
1240     SDValue Zero = DAG.getConstantFP(-0.0, DL, Op.getValueType());
1241     // TODO: If FNEG had fast-math-flags, they'd get propagated to this FSUB.
1242     return DAG.getNode(ISD::FSUB, DL, Op.getValueType(),
1243                        Zero, Op.getOperand(0));
1244   }
1245   return DAG.UnrollVectorOp(Op.getNode());
1246 }
1247 
1248 SDValue VectorLegalizer::ExpandFSUB(SDValue Op) {
1249   // For floating-point values, (a-b) is the same as a+(-b). If FNEG is legal,
1250   // we can defer this to operation legalization where it will be lowered as
1251   // a+(-b).
1252   EVT VT = Op.getValueType();
1253   if (TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
1254       TLI.isOperationLegalOrCustom(ISD::FADD, VT))
1255     return Op; // Defer to LegalizeDAG
1256 
1257   return DAG.UnrollVectorOp(Op.getNode());
1258 }
1259 
1260 SDValue VectorLegalizer::ExpandCTPOP(SDValue Op) {
1261   SDValue Result;
1262   if (TLI.expandCTPOP(Op.getNode(), Result, DAG))
1263     return Result;
1264 
1265   return DAG.UnrollVectorOp(Op.getNode());
1266 }
1267 
1268 SDValue VectorLegalizer::ExpandCTLZ(SDValue Op) {
1269   SDValue Result;
1270   if (TLI.expandCTLZ(Op.getNode(), Result, DAG))
1271     return Result;
1272 
1273   return DAG.UnrollVectorOp(Op.getNode());
1274 }
1275 
1276 SDValue VectorLegalizer::ExpandCTTZ(SDValue Op) {
1277   SDValue Result;
1278   if (TLI.expandCTTZ(Op.getNode(), Result, DAG))
1279     return Result;
1280 
1281   return DAG.UnrollVectorOp(Op.getNode());
1282 }
1283 
1284 SDValue VectorLegalizer::ExpandFunnelShift(SDValue Op) {
1285   SDValue Result;
1286   if (TLI.expandFunnelShift(Op.getNode(), Result, DAG))
1287     return Result;
1288 
1289   return DAG.UnrollVectorOp(Op.getNode());
1290 }
1291 
1292 SDValue VectorLegalizer::ExpandROT(SDValue Op) {
1293   SDValue Result;
1294   if (TLI.expandROT(Op.getNode(), Result, DAG))
1295     return Result;
1296 
1297   return DAG.UnrollVectorOp(Op.getNode());
1298 }
1299 
1300 SDValue VectorLegalizer::ExpandFMINNUM_FMAXNUM(SDValue Op) {
1301   if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Op.getNode(), DAG))
1302     return Expanded;
1303   return DAG.UnrollVectorOp(Op.getNode());
1304 }
1305 
1306 SDValue VectorLegalizer::ExpandUADDSUBO(SDValue Op) {
1307   SDValue Result, Overflow;
1308   TLI.expandUADDSUBO(Op.getNode(), Result, Overflow, DAG);
1309 
1310   if (Op.getResNo() == 0) {
1311     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1312     return Result;
1313   } else {
1314     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1315     return Overflow;
1316   }
1317 }
1318 
1319 SDValue VectorLegalizer::ExpandSADDSUBO(SDValue Op) {
1320   SDValue Result, Overflow;
1321   TLI.expandSADDSUBO(Op.getNode(), Result, Overflow, DAG);
1322 
1323   if (Op.getResNo() == 0) {
1324     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1325     return Result;
1326   } else {
1327     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1328     return Overflow;
1329   }
1330 }
1331 
1332 SDValue VectorLegalizer::ExpandMULO(SDValue Op) {
1333   SDValue Result, Overflow;
1334   if (!TLI.expandMULO(Op.getNode(), Result, Overflow, DAG))
1335     std::tie(Result, Overflow) = DAG.UnrollVectorOverflowOp(Op.getNode());
1336 
1337   if (Op.getResNo() == 0) {
1338     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1339     return Result;
1340   } else {
1341     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1342     return Overflow;
1343   }
1344 }
1345 
1346 SDValue VectorLegalizer::ExpandAddSubSat(SDValue Op) {
1347   if (SDValue Expanded = TLI.expandAddSubSat(Op.getNode(), DAG))
1348     return Expanded;
1349   return DAG.UnrollVectorOp(Op.getNode());
1350 }
1351 
1352 SDValue VectorLegalizer::ExpandFixedPointMul(SDValue Op) {
1353   if (SDValue Expanded = TLI.expandFixedPointMul(Op.getNode(), DAG))
1354     return Expanded;
1355   return DAG.UnrollVectorOp(Op.getNode());
1356 }
1357 
1358 SDValue VectorLegalizer::ExpandStrictFPOp(SDValue Op) {
1359   if (Op.getOpcode() == ISD::STRICT_UINT_TO_FP) {
1360     if (SDValue Res = ExpandUINT_TO_FLOAT(Op))
1361       return Res;
1362   }
1363 
1364   EVT VT = Op.getValue(0).getValueType();
1365   EVT EltVT = VT.getVectorElementType();
1366   unsigned NumElems = VT.getVectorNumElements();
1367   unsigned NumOpers = Op.getNumOperands();
1368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1369 
1370   EVT TmpEltVT = EltVT;
1371   if (Op->getOpcode() == ISD::STRICT_FSETCC ||
1372       Op->getOpcode() == ISD::STRICT_FSETCCS)
1373     TmpEltVT = TLI.getSetCCResultType(DAG.getDataLayout(),
1374                                       *DAG.getContext(), TmpEltVT);
1375 
1376   EVT ValueVTs[] = {TmpEltVT, MVT::Other};
1377   SDValue Chain = Op.getOperand(0);
1378   SDLoc dl(Op);
1379 
1380   SmallVector<SDValue, 32> OpValues;
1381   SmallVector<SDValue, 32> OpChains;
1382   for (unsigned i = 0; i < NumElems; ++i) {
1383     SmallVector<SDValue, 4> Opers;
1384     SDValue Idx = DAG.getConstant(i, dl,
1385                                   TLI.getVectorIdxTy(DAG.getDataLayout()));
1386 
1387     // The Chain is the first operand.
1388     Opers.push_back(Chain);
1389 
1390     // Now process the remaining operands.
1391     for (unsigned j = 1; j < NumOpers; ++j) {
1392       SDValue Oper = Op.getOperand(j);
1393       EVT OperVT = Oper.getValueType();
1394 
1395       if (OperVT.isVector())
1396         Oper = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1397                            OperVT.getVectorElementType(), Oper, Idx);
1398 
1399       Opers.push_back(Oper);
1400     }
1401 
1402     SDValue ScalarOp = DAG.getNode(Op->getOpcode(), dl, ValueVTs, Opers);
1403     SDValue ScalarResult = ScalarOp.getValue(0);
1404     SDValue ScalarChain = ScalarOp.getValue(1);
1405 
1406     if (Op->getOpcode() == ISD::STRICT_FSETCC ||
1407         Op->getOpcode() == ISD::STRICT_FSETCCS)
1408       ScalarResult = DAG.getSelect(dl, EltVT, ScalarResult,
1409                            DAG.getConstant(APInt::getAllOnesValue
1410                                            (EltVT.getSizeInBits()), dl, EltVT),
1411                            DAG.getConstant(0, dl, EltVT));
1412 
1413     OpValues.push_back(ScalarResult);
1414     OpChains.push_back(ScalarChain);
1415   }
1416 
1417   SDValue Result = DAG.getBuildVector(VT, dl, OpValues);
1418   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OpChains);
1419 
1420   AddLegalizedOperand(Op.getValue(0), Result);
1421   AddLegalizedOperand(Op.getValue(1), NewChain);
1422 
1423   return Op.getResNo() ? NewChain : Result;
1424 }
1425 
1426 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
1427   EVT VT = Op.getValueType();
1428   unsigned NumElems = VT.getVectorNumElements();
1429   EVT EltVT = VT.getVectorElementType();
1430   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
1431   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
1432   SDLoc dl(Op);
1433   SmallVector<SDValue, 8> Ops(NumElems);
1434   for (unsigned i = 0; i < NumElems; ++i) {
1435     SDValue LHSElem = DAG.getNode(
1436         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
1437         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1438     SDValue RHSElem = DAG.getNode(
1439         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
1440         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1441     Ops[i] = DAG.getNode(ISD::SETCC, dl,
1442                          TLI.getSetCCResultType(DAG.getDataLayout(),
1443                                                 *DAG.getContext(), TmpEltVT),
1444                          LHSElem, RHSElem, CC);
1445     Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
1446                            DAG.getConstant(APInt::getAllOnesValue
1447                                            (EltVT.getSizeInBits()), dl, EltVT),
1448                            DAG.getConstant(0, dl, EltVT));
1449   }
1450   return DAG.getBuildVector(VT, dl, Ops);
1451 }
1452 
1453 bool SelectionDAG::LegalizeVectors() {
1454   return VectorLegalizer(*this).Run();
1455 }
1456