LLVM  16.0.0git
SLPVectorizer.cpp
Go to the documentation of this file.
1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
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 pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
42 #include "llvm/Analysis/LoopInfo.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/KnownBits.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <optional>
98 #include <set>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 #include <vector>
103 
104 using namespace llvm;
105 using namespace llvm::PatternMatch;
106 using namespace slpvectorizer;
107 
108 #define SV_NAME "slp-vectorizer"
109 #define DEBUG_TYPE "SLP"
110 
111 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
112 
113 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
114  cl::desc("Run the SLP vectorization passes"));
115 
116 static cl::opt<int>
117  SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
118  cl::desc("Only vectorize if you gain more than this "
119  "number "));
120 
121 static cl::opt<bool>
122 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
123  cl::desc("Attempt to vectorize horizontal reductions"));
124 
126  "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
127  cl::desc(
128  "Attempt to vectorize horizontal reductions feeding into a store"));
129 
130 static cl::opt<int>
131 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
132  cl::desc("Attempt to vectorize for this register size in bits"));
133 
134 static cl::opt<unsigned>
135 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
136  cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
137 
138 static cl::opt<int>
139 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
140  cl::desc("Maximum depth of the lookup for consecutive stores."));
141 
142 /// Limits the size of scheduling regions in a block.
143 /// It avoid long compile times for _very_ large blocks where vector
144 /// instructions are spread over a wide range.
145 /// This limit is way higher than needed by real-world functions.
146 static cl::opt<int>
147 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
148  cl::desc("Limit the size of the SLP scheduling region per block"));
149 
151  "slp-min-reg-size", cl::init(128), cl::Hidden,
152  cl::desc("Attempt to vectorize for this register size in bits"));
153 
155  "slp-recursion-max-depth", cl::init(12), cl::Hidden,
156  cl::desc("Limit the recursion depth when building a vectorizable tree"));
157 
159  "slp-min-tree-size", cl::init(3), cl::Hidden,
160  cl::desc("Only vectorize small trees if they are fully vectorizable"));
161 
162 // The maximum depth that the look-ahead score heuristic will explore.
163 // The higher this value, the higher the compilation time overhead.
165  "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
166  cl::desc("The maximum look-ahead depth for operand reordering scores"));
167 
168 // The maximum depth that the look-ahead score heuristic will explore
169 // when it probing among candidates for vectorization tree roots.
170 // The higher this value, the higher the compilation time overhead but unlike
171 // similar limit for operands ordering this is less frequently used, hence
172 // impact of higher value is less noticeable.
174  "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
175  cl::desc("The maximum look-ahead depth for searching best rooting option"));
176 
177 static cl::opt<bool>
178  ViewSLPTree("view-slp-tree", cl::Hidden,
179  cl::desc("Display the SLP trees with Graphviz"));
180 
181 // Limit the number of alias checks. The limit is chosen so that
182 // it has no negative effect on the llvm benchmarks.
183 static const unsigned AliasedCheckLimit = 10;
184 
185 // Another limit for the alias checks: The maximum distance between load/store
186 // instructions where alias checks are done.
187 // This limit is useful for very large basic blocks.
188 static const unsigned MaxMemDepDistance = 160;
189 
190 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
191 /// regions to be handled.
192 static const int MinScheduleRegionSize = 16;
193 
194 /// Predicate for the element types that the SLP vectorizer supports.
195 ///
196 /// The most important thing to filter here are types which are invalid in LLVM
197 /// vectors. We also filter target specific types which have absolutely no
198 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
199 /// avoids spending time checking the cost model and realizing that they will
200 /// be inevitably scalarized.
201 static bool isValidElementType(Type *Ty) {
202  return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
203  !Ty->isPPC_FP128Ty();
204 }
205 
206 /// \returns True if the value is a constant (but not globals/constant
207 /// expressions).
208 static bool isConstant(Value *V) {
209  return isa<Constant>(V) && !isa<ConstantExpr, GlobalValue>(V);
210 }
211 
212 /// Checks if \p V is one of vector-like instructions, i.e. undef,
213 /// insertelement/extractelement with constant indices for fixed vector type or
214 /// extractvalue instruction.
216  if (!isa<InsertElementInst, ExtractElementInst>(V) &&
217  !isa<ExtractValueInst, UndefValue>(V))
218  return false;
219  auto *I = dyn_cast<Instruction>(V);
220  if (!I || isa<ExtractValueInst>(I))
221  return true;
222  if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
223  return false;
224  if (isa<ExtractElementInst>(I))
225  return isConstant(I->getOperand(1));
226  assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
227  return isConstant(I->getOperand(2));
228 }
229 
230 /// \returns true if all of the instructions in \p VL are in the same block or
231 /// false otherwise.
233  Instruction *I0 = dyn_cast<Instruction>(VL[0]);
234  if (!I0)
235  return false;
237  return true;
238 
239  BasicBlock *BB = I0->getParent();
240  for (int I = 1, E = VL.size(); I < E; I++) {
241  auto *II = dyn_cast<Instruction>(VL[I]);
242  if (!II)
243  return false;
244 
245  if (BB != II->getParent())
246  return false;
247  }
248  return true;
249 }
250 
251 /// \returns True if all of the values in \p VL are constants (but not
252 /// globals/constant expressions).
254  // Constant expressions and globals can't be vectorized like normal integer/FP
255  // constants.
256  return all_of(VL, isConstant);
257 }
258 
259 /// \returns True if all of the values in \p VL are identical or some of them
260 /// are UndefValue.
261 static bool isSplat(ArrayRef<Value *> VL) {
262  Value *FirstNonUndef = nullptr;
263  for (Value *V : VL) {
264  if (isa<UndefValue>(V))
265  continue;
266  if (!FirstNonUndef) {
267  FirstNonUndef = V;
268  continue;
269  }
270  if (V != FirstNonUndef)
271  return false;
272  }
273  return FirstNonUndef != nullptr;
274 }
275 
276 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
277 static bool isCommutative(Instruction *I) {
278  if (auto *Cmp = dyn_cast<CmpInst>(I))
279  return Cmp->isCommutative();
280  if (auto *BO = dyn_cast<BinaryOperator>(I))
281  return BO->isCommutative();
282  // TODO: This should check for generic Instruction::isCommutative(), but
283  // we need to confirm that the caller code correctly handles Intrinsics
284  // for example (does not have 2 operands).
285  return false;
286 }
287 
288 /// \returns inserting index of InsertElement or InsertValue instruction,
289 /// using Offset as base offset for index.
290 static Optional<unsigned> getInsertIndex(const Value *InsertInst,
291  unsigned Offset = 0) {
292  int Index = Offset;
293  if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
294  const auto *VT = dyn_cast<FixedVectorType>(IE->getType());
295  if (!VT)
296  return None;
297  const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2));
298  if (!CI)
299  return None;
300  if (CI->getValue().uge(VT->getNumElements()))
301  return None;
302  Index *= VT->getNumElements();
303  Index += CI->getZExtValue();
304  return Index;
305  }
306 
307  const auto *IV = cast<InsertValueInst>(InsertInst);
308  Type *CurrentType = IV->getType();
309  for (unsigned I : IV->indices()) {
310  if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
311  Index *= ST->getNumElements();
312  CurrentType = ST->getElementType(I);
313  } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) {
314  Index *= AT->getNumElements();
315  CurrentType = AT->getElementType();
316  } else {
317  return None;
318  }
319  Index += I;
320  }
321  return Index;
322 }
323 
324 /// Checks if the given value is actually an undefined constant vector.
325 /// Also, if the\p ShuffleMask is not empty, tries to check if the non-masked
326 /// elements actually mask the insertelement buildvector, if any.
327 template <bool IsPoisonOnly = false>
329  ArrayRef<int> ShuffleMask = None) {
330  SmallBitVector Res(ShuffleMask.empty() ? 1 : ShuffleMask.size(), true);
331  using T = std::conditional_t<IsPoisonOnly, PoisonValue, UndefValue>;
332  if (isa<T>(V))
333  return Res;
334  auto *VecTy = dyn_cast<FixedVectorType>(V->getType());
335  if (!VecTy)
336  return Res.reset();
337  auto *C = dyn_cast<Constant>(V);
338  if (!C) {
339  if (!ShuffleMask.empty()) {
340  const Value *Base = V;
341  while (auto *II = dyn_cast<InsertElementInst>(Base)) {
342  if (isa<T>(II->getOperand(1)))
343  continue;
344  Base = II->getOperand(0);
346  if (!Idx)
347  continue;
348  if (*Idx < ShuffleMask.size() && ShuffleMask[*Idx] == UndefMaskElem)
349  Res.reset(*Idx);
350  }
351  // TODO: Add analysis for shuffles here too.
352  if (V == Base) {
353  Res.reset();
354  } else {
355  SmallVector<int> SubMask(ShuffleMask.size(), UndefMaskElem);
356  Res &= isUndefVector<IsPoisonOnly>(Base, SubMask);
357  }
358  } else {
359  Res.reset();
360  }
361  return Res;
362  }
363  for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
364  if (Constant *Elem = C->getAggregateElement(I))
365  if (!isa<T>(Elem) &&
366  (ShuffleMask.empty() ||
367  (I < ShuffleMask.size() && ShuffleMask[I] == UndefMaskElem)))
368  Res.reset(I);
369  }
370  return Res;
371 }
372 
373 /// Checks if the vector of instructions can be represented as a shuffle, like:
374 /// %x0 = extractelement <4 x i8> %x, i32 0
375 /// %x3 = extractelement <4 x i8> %x, i32 3
376 /// %y1 = extractelement <4 x i8> %y, i32 1
377 /// %y2 = extractelement <4 x i8> %y, i32 2
378 /// %x0x0 = mul i8 %x0, %x0
379 /// %x3x3 = mul i8 %x3, %x3
380 /// %y1y1 = mul i8 %y1, %y1
381 /// %y2y2 = mul i8 %y2, %y2
382 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
383 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
384 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
385 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
386 /// ret <4 x i8> %ins4
387 /// can be transformed into:
388 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
389 /// i32 6>
390 /// %2 = mul <4 x i8> %1, %1
391 /// ret <4 x i8> %2
392 /// We convert this initially to something like:
393 /// %x0 = extractelement <4 x i8> %x, i32 0
394 /// %x3 = extractelement <4 x i8> %x, i32 3
395 /// %y1 = extractelement <4 x i8> %y, i32 1
396 /// %y2 = extractelement <4 x i8> %y, i32 2
397 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
398 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
399 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
400 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
401 /// %5 = mul <4 x i8> %4, %4
402 /// %6 = extractelement <4 x i8> %5, i32 0
403 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
404 /// %7 = extractelement <4 x i8> %5, i32 1
405 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
406 /// %8 = extractelement <4 x i8> %5, i32 2
407 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
408 /// %9 = extractelement <4 x i8> %5, i32 3
409 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
410 /// ret <4 x i8> %ins4
411 /// InstCombiner transforms this into a shuffle and vector mul
412 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
413 /// TODO: Can we split off and reuse the shuffle mask detection from
414 /// ShuffleVectorInst/getShuffleCost?
417  const auto *It =
418  find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
419  if (It == VL.end())
420  return None;
421  auto *EI0 = cast<ExtractElementInst>(*It);
422  if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
423  return None;
424  unsigned Size =
425  cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
426  Value *Vec1 = nullptr;
427  Value *Vec2 = nullptr;
428  enum ShuffleMode { Unknown, Select, Permute };
429  ShuffleMode CommonShuffleMode = Unknown;
430  Mask.assign(VL.size(), UndefMaskElem);
431  for (unsigned I = 0, E = VL.size(); I < E; ++I) {
432  // Undef can be represented as an undef element in a vector.
433  if (isa<UndefValue>(VL[I]))
434  continue;
435  auto *EI = cast<ExtractElementInst>(VL[I]);
436  if (isa<ScalableVectorType>(EI->getVectorOperandType()))
437  return None;
438  auto *Vec = EI->getVectorOperand();
439  // We can extractelement from undef or poison vector.
440  if (isUndefVector(Vec).all())
441  continue;
442  // All vector operands must have the same number of vector elements.
443  if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
444  return None;
445  if (isa<UndefValue>(EI->getIndexOperand()))
446  continue;
447  auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
448  if (!Idx)
449  return None;
450  // Undefined behavior if Idx is negative or >= Size.
451  if (Idx->getValue().uge(Size))
452  continue;
453  unsigned IntIdx = Idx->getValue().getZExtValue();
454  Mask[I] = IntIdx;
455  // For correct shuffling we have to have at most 2 different vector operands
456  // in all extractelement instructions.
457  if (!Vec1 || Vec1 == Vec) {
458  Vec1 = Vec;
459  } else if (!Vec2 || Vec2 == Vec) {
460  Vec2 = Vec;
461  Mask[I] += Size;
462  } else {
463  return None;
464  }
465  if (CommonShuffleMode == Permute)
466  continue;
467  // If the extract index is not the same as the operation number, it is a
468  // permutation.
469  if (IntIdx != I) {
470  CommonShuffleMode = Permute;
471  continue;
472  }
473  CommonShuffleMode = Select;
474  }
475  // If we're not crossing lanes in different vectors, consider it as blending.
476  if (CommonShuffleMode == Select && Vec2)
478  // If Vec2 was never used, we have a permutation of a single vector, otherwise
479  // we have permutation of 2 vectors.
482 }
483 
484 namespace {
485 
486 /// Main data required for vectorization of instructions.
487 struct InstructionsState {
488  /// The very first instruction in the list with the main opcode.
489  Value *OpValue = nullptr;
490 
491  /// The main/alternate instruction.
492  Instruction *MainOp = nullptr;
493  Instruction *AltOp = nullptr;
494 
495  /// The main/alternate opcodes for the list of instructions.
496  unsigned getOpcode() const {
497  return MainOp ? MainOp->getOpcode() : 0;
498  }
499 
500  unsigned getAltOpcode() const {
501  return AltOp ? AltOp->getOpcode() : 0;
502  }
503 
504  /// Some of the instructions in the list have alternate opcodes.
505  bool isAltShuffle() const { return AltOp != MainOp; }
506 
507  bool isOpcodeOrAlt(Instruction *I) const {
508  unsigned CheckedOpcode = I->getOpcode();
509  return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
510  }
511 
512  InstructionsState() = delete;
513  InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
514  : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
515 };
516 
517 } // end anonymous namespace
518 
519 /// Chooses the correct key for scheduling data. If \p Op has the same (or
520 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
521 /// OpValue.
522 static Value *isOneOf(const InstructionsState &S, Value *Op) {
523  auto *I = dyn_cast<Instruction>(Op);
524  if (I && S.isOpcodeOrAlt(I))
525  return Op;
526  return S.OpValue;
527 }
528 
529 /// \returns true if \p Opcode is allowed as part of of the main/alternate
530 /// instruction for SLP vectorization.
531 ///
532 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
533 /// "shuffled out" lane would result in division by zero.
534 static bool isValidForAlternation(unsigned Opcode) {
535  if (Instruction::isIntDivRem(Opcode))
536  return false;
537 
538  return true;
539 }
540 
541 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
542  const TargetLibraryInfo &TLI,
543  unsigned BaseIndex = 0);
544 
545 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
546 /// compatible instructions or constants, or just some other regular values.
547 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
548  Value *Op1, const TargetLibraryInfo &TLI) {
549  return (isConstant(BaseOp0) && isConstant(Op0)) ||
550  (isConstant(BaseOp1) && isConstant(Op1)) ||
551  (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
552  !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
553  BaseOp0 == Op0 || BaseOp1 == Op1 ||
554  getSameOpcode({BaseOp0, Op0}, TLI).getOpcode() ||
555  getSameOpcode({BaseOp1, Op1}, TLI).getOpcode();
556 }
557 
558 /// \returns true if a compare instruction \p CI has similar "look" and
559 /// same predicate as \p BaseCI, "as is" or with its operands and predicate
560 /// swapped, false otherwise.
561 static bool isCmpSameOrSwapped(const CmpInst *BaseCI, const CmpInst *CI,
562  const TargetLibraryInfo &TLI) {
563  assert(BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() &&
564  "Assessing comparisons of different types?");
565  CmpInst::Predicate BasePred = BaseCI->getPredicate();
566  CmpInst::Predicate Pred = CI->getPredicate();
568 
569  Value *BaseOp0 = BaseCI->getOperand(0);
570  Value *BaseOp1 = BaseCI->getOperand(1);
571  Value *Op0 = CI->getOperand(0);
572  Value *Op1 = CI->getOperand(1);
573 
574  return (BasePred == Pred &&
575  areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1, TLI)) ||
576  (BasePred == SwappedPred &&
577  areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0, TLI));
578 }
579 
580 /// \returns analysis of the Instructions in \p VL described in
581 /// InstructionsState, the Opcode that we suppose the whole list
582 /// could be vectorized even if its structure is diverse.
583 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
584  const TargetLibraryInfo &TLI,
585  unsigned BaseIndex) {
586  // Make sure these are all Instructions.
587  if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
588  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
589 
590  bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
591  bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
592  bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
593  CmpInst::Predicate BasePred =
594  IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
596  unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
597  unsigned AltOpcode = Opcode;
598  unsigned AltIndex = BaseIndex;
599 
600  // Check for one alternate opcode from another BinaryOperator.
601  // TODO - generalize to support all operators (types, calls etc.).
602  auto *IBase = cast<Instruction>(VL[BaseIndex]);
603  Intrinsic::ID BaseID = 0;
604  SmallVector<VFInfo> BaseMappings;
605  if (auto *CallBase = dyn_cast<CallInst>(IBase)) {
606  BaseID = getVectorIntrinsicIDForCall(CallBase, &TLI);
607  BaseMappings = VFDatabase(*CallBase).getMappings(*CallBase);
608  if (!isTriviallyVectorizable(BaseID) && BaseMappings.empty())
609  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
610  }
611  for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
612  auto *I = cast<Instruction>(VL[Cnt]);
613  unsigned InstOpcode = I->getOpcode();
614  if (IsBinOp && isa<BinaryOperator>(I)) {
615  if (InstOpcode == Opcode || InstOpcode == AltOpcode)
616  continue;
617  if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
618  isValidForAlternation(Opcode)) {
619  AltOpcode = InstOpcode;
620  AltIndex = Cnt;
621  continue;
622  }
623  } else if (IsCastOp && isa<CastInst>(I)) {
624  Value *Op0 = IBase->getOperand(0);
625  Type *Ty0 = Op0->getType();
626  Value *Op1 = I->getOperand(0);
627  Type *Ty1 = Op1->getType();
628  if (Ty0 == Ty1) {
629  if (InstOpcode == Opcode || InstOpcode == AltOpcode)
630  continue;
631  if (Opcode == AltOpcode) {
632  assert(isValidForAlternation(Opcode) &&
633  isValidForAlternation(InstOpcode) &&
634  "Cast isn't safe for alternation, logic needs to be updated!");
635  AltOpcode = InstOpcode;
636  AltIndex = Cnt;
637  continue;
638  }
639  }
640  } else if (auto *Inst = dyn_cast<CmpInst>(VL[Cnt]); Inst && IsCmpOp) {
641  auto *BaseInst = cast<CmpInst>(VL[BaseIndex]);
642  Type *Ty0 = BaseInst->getOperand(0)->getType();
643  Type *Ty1 = Inst->getOperand(0)->getType();
644  if (Ty0 == Ty1) {
645  assert(InstOpcode == Opcode && "Expected same CmpInst opcode.");
646  // Check for compatible operands. If the corresponding operands are not
647  // compatible - need to perform alternate vectorization.
648  CmpInst::Predicate CurrentPred = Inst->getPredicate();
649  CmpInst::Predicate SwappedCurrentPred =
650  CmpInst::getSwappedPredicate(CurrentPred);
651 
652  if (E == 2 &&
653  (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
654  continue;
655 
656  if (isCmpSameOrSwapped(BaseInst, Inst, TLI))
657  continue;
658  auto *AltInst = cast<CmpInst>(VL[AltIndex]);
659  if (AltIndex != BaseIndex) {
660  if (isCmpSameOrSwapped(AltInst, Inst, TLI))
661  continue;
662  } else if (BasePred != CurrentPred) {
663  assert(
664  isValidForAlternation(InstOpcode) &&
665  "CmpInst isn't safe for alternation, logic needs to be updated!");
666  AltIndex = Cnt;
667  continue;
668  }
669  CmpInst::Predicate AltPred = AltInst->getPredicate();
670  if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
671  AltPred == CurrentPred || AltPred == SwappedCurrentPred)
672  continue;
673  }
674  } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) {
675  if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
676  if (Gep->getNumOperands() != 2 ||
677  Gep->getOperand(0)->getType() != IBase->getOperand(0)->getType())
678  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
679  } else if (auto *EI = dyn_cast<ExtractElementInst>(I)) {
681  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
682  } else if (auto *LI = dyn_cast<LoadInst>(I)) {
683  auto *BaseLI = cast<LoadInst>(IBase);
684  if (!LI->isSimple() || !BaseLI->isSimple())
685  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
686  } else if (auto *Call = dyn_cast<CallInst>(I)) {
687  auto *CallBase = cast<CallInst>(IBase);
688  if (Call->getCalledFunction() != CallBase->getCalledFunction())
689  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
690  if (Call->hasOperandBundles() &&
691  !std::equal(Call->op_begin() + Call->getBundleOperandsStartIndex(),
692  Call->op_begin() + Call->getBundleOperandsEndIndex(),
693  CallBase->op_begin() +
695  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
697  if (ID != BaseID)
698  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
699  if (!ID) {
701  if (Mappings.size() != BaseMappings.size() ||
702  Mappings.front().ISA != BaseMappings.front().ISA ||
703  Mappings.front().ScalarName != BaseMappings.front().ScalarName ||
704  Mappings.front().VectorName != BaseMappings.front().VectorName ||
705  Mappings.front().Shape.VF != BaseMappings.front().Shape.VF ||
706  Mappings.front().Shape.Parameters !=
707  BaseMappings.front().Shape.Parameters)
708  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
709  }
710  }
711  continue;
712  }
713  return InstructionsState(VL[BaseIndex], nullptr, nullptr);
714  }
715 
716  return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
717  cast<Instruction>(VL[AltIndex]));
718 }
719 
720 /// \returns true if all of the values in \p VL have the same type or false
721 /// otherwise.
723  Type *Ty = VL[0]->getType();
724  for (int i = 1, e = VL.size(); i < e; i++)
725  if (VL[i]->getType() != Ty)
726  return false;
727 
728  return true;
729 }
730 
731 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
733  unsigned Opcode = E->getOpcode();
734  assert((Opcode == Instruction::ExtractElement ||
735  Opcode == Instruction::ExtractValue) &&
736  "Expected extractelement or extractvalue instruction.");
737  if (Opcode == Instruction::ExtractElement) {
738  auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
739  if (!CI)
740  return None;
741  return CI->getZExtValue();
742  }
743  ExtractValueInst *EI = cast<ExtractValueInst>(E);
744  if (EI->getNumIndices() != 1)
745  return None;
746  return *EI->idx_begin();
747 }
748 
749 /// \returns True if in-tree use also needs extract. This refers to
750 /// possible scalar operand in vectorized instruction.
751 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
752  TargetLibraryInfo *TLI) {
753  unsigned Opcode = UserInst->getOpcode();
754  switch (Opcode) {
755  case Instruction::Load: {
756  LoadInst *LI = cast<LoadInst>(UserInst);
757  return (LI->getPointerOperand() == Scalar);
758  }
759  case Instruction::Store: {
760  StoreInst *SI = cast<StoreInst>(UserInst);
761  return (SI->getPointerOperand() == Scalar);
762  }
763  case Instruction::Call: {
764  CallInst *CI = cast<CallInst>(UserInst);
766  for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
768  return (CI->getArgOperand(i) == Scalar);
769  }
770  [[fallthrough]];
771  }
772  default:
773  return false;
774  }
775 }
776 
777 /// \returns the AA location that is being access by the instruction.
779  if (StoreInst *SI = dyn_cast<StoreInst>(I))
780  return MemoryLocation::get(SI);
781  if (LoadInst *LI = dyn_cast<LoadInst>(I))
782  return MemoryLocation::get(LI);
783  return MemoryLocation();
784 }
785 
786 /// \returns True if the instruction is not a volatile or atomic load/store.
787 static bool isSimple(Instruction *I) {
788  if (LoadInst *LI = dyn_cast<LoadInst>(I))
789  return LI->isSimple();
790  if (StoreInst *SI = dyn_cast<StoreInst>(I))
791  return SI->isSimple();
792  if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
793  return !MI->isVolatile();
794  return true;
795 }
796 
797 /// Shuffles \p Mask in accordance with the given \p SubMask.
799  if (SubMask.empty())
800  return;
801  if (Mask.empty()) {
802  Mask.append(SubMask.begin(), SubMask.end());
803  return;
804  }
805  SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
806  int TermValue = std::min(Mask.size(), SubMask.size());
807  for (int I = 0, E = SubMask.size(); I < E; ++I) {
808  if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
809  Mask[SubMask[I]] >= TermValue)
810  continue;
811  NewMask[I] = Mask[SubMask[I]];
812  }
813  Mask.swap(NewMask);
814 }
815 
816 /// Order may have elements assigned special value (size) which is out of
817 /// bounds. Such indices only appear on places which correspond to undef values
818 /// (see canReuseExtract for details) and used in order to avoid undef values
819 /// have effect on operands ordering.
820 /// The first loop below simply finds all unused indices and then the next loop
821 /// nest assigns these indices for undef values positions.
822 /// As an example below Order has two undef positions and they have assigned
823 /// values 3 and 7 respectively:
824 /// before: 6 9 5 4 9 2 1 0
825 /// after: 6 3 5 4 7 2 1 0
827  const unsigned Sz = Order.size();
828  SmallBitVector UnusedIndices(Sz, /*t=*/true);
829  SmallBitVector MaskedIndices(Sz);
830  for (unsigned I = 0; I < Sz; ++I) {
831  if (Order[I] < Sz)
832  UnusedIndices.reset(Order[I]);
833  else
834  MaskedIndices.set(I);
835  }
836  if (MaskedIndices.none())
837  return;
838  assert(UnusedIndices.count() == MaskedIndices.count() &&
839  "Non-synced masked/available indices.");
840  int Idx = UnusedIndices.find_first();
841  int MIdx = MaskedIndices.find_first();
842  while (MIdx >= 0) {
843  assert(Idx >= 0 && "Indices must be synced.");
844  Order[MIdx] = Idx;
845  Idx = UnusedIndices.find_next(Idx);
846  MIdx = MaskedIndices.find_next(MIdx);
847  }
848 }
849 
850 namespace llvm {
851 
854  Mask.clear();
855  const unsigned E = Indices.size();
856  Mask.resize(E, UndefMaskElem);
857  for (unsigned I = 0; I < E; ++I)
858  Mask[Indices[I]] = I;
859 }
860 
861 /// Reorders the list of scalars in accordance with the given \p Mask.
864  assert(!Mask.empty() && "Expected non-empty mask.");
865  SmallVector<Value *> Prev(Scalars.size(),
866  UndefValue::get(Scalars.front()->getType()));
867  Prev.swap(Scalars);
868  for (unsigned I = 0, E = Prev.size(); I < E; ++I)
869  if (Mask[I] != UndefMaskElem)
870  Scalars[Mask[I]] = Prev[I];
871 }
872 
873 /// Checks if the provided value does not require scheduling. It does not
874 /// require scheduling if this is not an instruction or it is an instruction
875 /// that does not read/write memory and all operands are either not instructions
876 /// or phi nodes or instructions from different blocks.
877 static bool areAllOperandsNonInsts(Value *V) {
878  auto *I = dyn_cast<Instruction>(V);
879  if (!I)
880  return true;
881  return !mayHaveNonDefUseDependency(*I) &&
882  all_of(I->operands(), [I](Value *V) {
883  auto *IO = dyn_cast<Instruction>(V);
884  if (!IO)
885  return true;
886  return isa<PHINode>(IO) || IO->getParent() != I->getParent();
887  });
888 }
889 
890 /// Checks if the provided value does not require scheduling. It does not
891 /// require scheduling if this is not an instruction or it is an instruction
892 /// that does not read/write memory and all users are phi nodes or instructions
893 /// from the different blocks.
894 static bool isUsedOutsideBlock(Value *V) {
895  auto *I = dyn_cast<Instruction>(V);
896  if (!I)
897  return true;
898  // Limits the number of uses to save compile time.
899  constexpr int UsesLimit = 8;
900  return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
901  all_of(I->users(), [I](User *U) {
902  auto *IU = dyn_cast<Instruction>(U);
903  if (!IU)
904  return true;
905  return IU->getParent() != I->getParent() || isa<PHINode>(IU);
906  });
907 }
908 
909 /// Checks if the specified value does not require scheduling. It does not
910 /// require scheduling if all operands and all users do not need to be scheduled
911 /// in the current basic block.
914 }
915 
916 /// Checks if the specified array of instructions does not require scheduling.
917 /// It is so if all either instructions have operands that do not require
918 /// scheduling or their users do not require scheduling since they are phis or
919 /// in other basic blocks.
921  return !VL.empty() &&
923 }
924 
925 namespace slpvectorizer {
926 
927 /// Bottom Up SLP Vectorizer.
928 class BoUpSLP {
929  struct TreeEntry;
930  struct ScheduleData;
931 
932 public:
940 
942  TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
945  : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
946  DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
947  CodeMetrics::collectEphemeralValues(F, AC, EphValues);
948  // Use the vector register size specified by the target unless overridden
949  // by a command-line option.
950  // TODO: It would be better to limit the vectorization factor based on
951  // data type rather than just register size. For example, x86 AVX has
952  // 256-bit registers, but it does not support integer operations
953  // at that width (that requires AVX2).
954  if (MaxVectorRegSizeOption.getNumOccurrences())
955  MaxVecRegSize = MaxVectorRegSizeOption;
956  else
957  MaxVecRegSize =
959  .getFixedSize();
960 
961  if (MinVectorRegSizeOption.getNumOccurrences())
962  MinVecRegSize = MinVectorRegSizeOption;
963  else
964  MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
965  }
966 
967  /// Vectorize the tree that starts with the elements in \p VL.
968  /// Returns the vectorized root.
969  Value *vectorizeTree();
970 
971  /// Vectorize the tree but with the list of externally used values \p
972  /// ExternallyUsedValues. Values in this MapVector can be replaced but the
973  /// generated extractvalue instructions.
974  Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues,
975  Instruction *ReductionRoot = nullptr);
976 
977  /// \returns the cost incurred by unwanted spills and fills, caused by
978  /// holding live values over call sites.
979  InstructionCost getSpillCost() const;
980 
981  /// \returns the vectorization cost of the subtree that starts at \p VL.
982  /// A negative number means that this is profitable.
983  InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
984 
985  /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
986  /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
987  void buildTree(ArrayRef<Value *> Roots,
988  const SmallDenseSet<Value *> &UserIgnoreLst);
989 
990  /// Construct a vectorizable tree that starts at \p Roots.
991  void buildTree(ArrayRef<Value *> Roots);
992 
993  /// Checks if the very first tree node is going to be vectorized.
994  bool isVectorizedFirstNode() const {
995  return !VectorizableTree.empty() &&
996  VectorizableTree.front()->State == TreeEntry::Vectorize;
997  }
998 
999  /// Returns the main instruction for the very first node.
1001  assert(!VectorizableTree.empty() && "No tree to get the first node from");
1002  return VectorizableTree.front()->getMainOp();
1003  }
1004 
1005  /// Builds external uses of the vectorized scalars, i.e. the list of
1006  /// vectorized scalars to be extracted, their lanes and their scalar users. \p
1007  /// ExternallyUsedValues contains additional list of external uses to handle
1008  /// vectorization of reductions.
1009  void
1010  buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
1011 
1012  /// Clear the internal data structures that are created by 'buildTree'.
1013  void deleteTree() {
1014  VectorizableTree.clear();
1015  ScalarToTreeEntry.clear();
1016  MustGather.clear();
1017  EntryToLastInstruction.clear();
1018  ExternalUses.clear();
1019  for (auto &Iter : BlocksSchedules) {
1020  BlockScheduling *BS = Iter.second.get();
1021  BS->clear();
1022  }
1023  MinBWs.clear();
1024  InstrElementSize.clear();
1025  UserIgnoreList = nullptr;
1026  }
1027 
1028  unsigned getTreeSize() const { return VectorizableTree.size(); }
1029 
1030  /// Perform LICM and CSE on the newly generated gather sequences.
1031  void optimizeGatherSequence();
1032 
1033  /// Checks if the specified gather tree entry \p TE can be represented as a
1034  /// shuffled vector entry + (possibly) permutation with other gathers. It
1035  /// implements the checks only for possibly ordered scalars (Loads,
1036  /// ExtractElement, ExtractValue), which can be part of the graph.
1037  Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
1038 
1039  /// Sort loads into increasing pointers offsets to allow greater clustering.
1040  Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
1041 
1042  /// Gets reordering data for the given tree entry. If the entry is vectorized
1043  /// - just return ReorderIndices, otherwise check if the scalars can be
1044  /// reordered and return the most optimal order.
1045  /// \param TopToBottom If true, include the order of vectorized stores and
1046  /// insertelement nodes, otherwise skip them.
1047  Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
1048 
1049  /// Reorders the current graph to the most profitable order starting from the
1050  /// root node to the leaf nodes. The best order is chosen only from the nodes
1051  /// of the same size (vectorization factor). Smaller nodes are considered
1052  /// parts of subgraph with smaller VF and they are reordered independently. We
1053  /// can make it because we still need to extend smaller nodes to the wider VF
1054  /// and we can merge reordering shuffles with the widening shuffles.
1055  void reorderTopToBottom();
1056 
1057  /// Reorders the current graph to the most profitable order starting from
1058  /// leaves to the root. It allows to rotate small subgraphs and reduce the
1059  /// number of reshuffles if the leaf nodes use the same order. In this case we
1060  /// can merge the orders and just shuffle user node instead of shuffling its
1061  /// operands. Plus, even the leaf nodes have different orders, it allows to
1062  /// sink reordering in the graph closer to the root node and merge it later
1063  /// during analysis.
1064  void reorderBottomToTop(bool IgnoreReorder = false);
1065 
1066  /// \return The vector element size in bits to use when vectorizing the
1067  /// expression tree ending at \p V. If V is a store, the size is the width of
1068  /// the stored value. Otherwise, the size is the width of the largest loaded
1069  /// value reaching V. This method is used by the vectorizer to calculate
1070  /// vectorization factors.
1071  unsigned getVectorElementSize(Value *V);
1072 
1073  /// Compute the minimum type sizes required to represent the entries in a
1074  /// vectorizable tree.
1075  void computeMinimumValueSizes();
1076 
1077  // \returns maximum vector register size as set by TTI or overridden by cl::opt.
1078  unsigned getMaxVecRegSize() const {
1079  return MaxVecRegSize;
1080  }
1081 
1082  // \returns minimum vector register size as set by cl::opt.
1083  unsigned getMinVecRegSize() const {
1084  return MinVecRegSize;
1085  }
1086 
1087  unsigned getMinVF(unsigned Sz) const {
1088  return std::max(2U, getMinVecRegSize() / Sz);
1089  }
1090 
1091  unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
1092  unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
1093  MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
1094  return MaxVF ? MaxVF : UINT_MAX;
1095  }
1096 
1097  /// Check if homogeneous aggregate is isomorphic to some VectorType.
1098  /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
1099  /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
1100  /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
1101  ///
1102  /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
1103  unsigned canMapToVector(Type *T, const DataLayout &DL) const;
1104 
1105  /// \returns True if the VectorizableTree is both tiny and not fully
1106  /// vectorizable. We do not vectorize such trees.
1107  bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1108 
1109  /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1110  /// can be load combined in the backend. Load combining may not be allowed in
1111  /// the IR optimizer, so we do not want to alter the pattern. For example,
1112  /// partially transforming a scalar bswap() pattern into vector code is
1113  /// effectively impossible for the backend to undo.
1114  /// TODO: If load combining is allowed in the IR optimizer, this analysis
1115  /// may not be necessary.
1116  bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1117 
1118  /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1119  /// can be load combined in the backend. Load combining may not be allowed in
1120  /// the IR optimizer, so we do not want to alter the pattern. For example,
1121  /// partially transforming a scalar bswap() pattern into vector code is
1122  /// effectively impossible for the backend to undo.
1123  /// TODO: If load combining is allowed in the IR optimizer, this analysis
1124  /// may not be necessary.
1125  bool isLoadCombineCandidate() const;
1126 
1128 
1129  /// This structure holds any data we need about the edges being traversed
1130  /// during buildTree_rec(). We keep track of:
1131  /// (i) the user TreeEntry index, and
1132  /// (ii) the index of the edge.
1133  struct EdgeInfo {
1134  EdgeInfo() = default;
1135  EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1136  : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1137  /// The user TreeEntry.
1138  TreeEntry *UserTE = nullptr;
1139  /// The operand index of the use.
1140  unsigned EdgeIdx = UINT_MAX;
1141 #ifndef NDEBUG
1142  friend inline raw_ostream &operator<<(raw_ostream &OS,
1143  const BoUpSLP::EdgeInfo &EI) {
1144  EI.dump(OS);
1145  return OS;
1146  }
1147  /// Debug print.
1148  void dump(raw_ostream &OS) const {
1149  OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1150  << " EdgeIdx:" << EdgeIdx << "}";
1151  }
1152  LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1153 #endif
1154  };
1155 
1156  /// A helper class used for scoring candidates for two consecutive lanes.
1158  const TargetLibraryInfo &TLI;
1159  const DataLayout &DL;
1160  ScalarEvolution &SE;
1161  const BoUpSLP &R;
1162  int NumLanes; // Total number of lanes (aka vectorization factor).
1163  int MaxLevel; // The maximum recursion depth for accumulating score.
1164 
1165  public:
1167  ScalarEvolution &SE, const BoUpSLP &R, int NumLanes,
1168  int MaxLevel)
1169  : TLI(TLI), DL(DL), SE(SE), R(R), NumLanes(NumLanes),
1170  MaxLevel(MaxLevel) {}
1171 
1172  // The hard-coded scores listed here are not very important, though it shall
1173  // be higher for better matches to improve the resulting cost. When
1174  // computing the scores of matching one sub-tree with another, we are
1175  // basically counting the number of values that are matching. So even if all
1176  // scores are set to 1, we would still get a decent matching result.
1177  // However, sometimes we have to break ties. For example we may have to
1178  // choose between matching loads vs matching opcodes. This is what these
1179  // scores are helping us with: they provide the order of preference. Also,
1180  // this is important if the scalar is externally used or used in another
1181  // tree entry node in the different lane.
1182 
1183  /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1184  static const int ScoreConsecutiveLoads = 4;
1185  /// The same load multiple times. This should have a better score than
1186  /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1187  /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1188  /// a vector load and 1.0 for a broadcast.
1189  static const int ScoreSplatLoads = 3;
1190  /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1191  static const int ScoreReversedLoads = 3;
1192  /// A load candidate for masked gather.
1193  static const int ScoreMaskedGatherCandidate = 1;
1194  /// ExtractElementInst from same vector and consecutive indexes.
1195  static const int ScoreConsecutiveExtracts = 4;
1196  /// ExtractElementInst from same vector and reversed indices.
1197  static const int ScoreReversedExtracts = 3;
1198  /// Constants.
1199  static const int ScoreConstants = 2;
1200  /// Instructions with the same opcode.
1201  static const int ScoreSameOpcode = 2;
1202  /// Instructions with alt opcodes (e.g, add + sub).
1203  static const int ScoreAltOpcodes = 1;
1204  /// Identical instructions (a.k.a. splat or broadcast).
1205  static const int ScoreSplat = 1;
1206  /// Matching with an undef is preferable to failing.
1207  static const int ScoreUndef = 1;
1208  /// Score for failing to find a decent match.
1209  static const int ScoreFail = 0;
1210  /// Score if all users are vectorized.
1211  static const int ScoreAllUserVectorized = 1;
1212 
1213  /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1214  /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1215  /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1216  /// MainAltOps.
1218  ArrayRef<Value *> MainAltOps) const {
1219  if (!isValidElementType(V1->getType()) ||
1220  !isValidElementType(V2->getType()))
1221  return LookAheadHeuristics::ScoreFail;
1222 
1223  if (V1 == V2) {
1224  if (isa<LoadInst>(V1)) {
1225  // Retruns true if the users of V1 and V2 won't need to be extracted.
1226  auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1227  // Bail out if we have too many uses to save compilation time.
1228  static constexpr unsigned Limit = 8;
1229  if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1230  return false;
1231 
1232  auto AllUsersVectorized = [U1, U2, this](Value *V) {
1233  return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1234  return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1235  });
1236  };
1237  return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1238  };
1239  // A broadcast of a load can be cheaper on some targets.
1240  if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1241  ElementCount::getFixed(NumLanes)) &&
1242  ((int)V1->getNumUses() == NumLanes ||
1243  AllUsersAreInternal(V1, V2)))
1244  return LookAheadHeuristics::ScoreSplatLoads;
1245  }
1246  return LookAheadHeuristics::ScoreSplat;
1247  }
1248 
1249  auto *LI1 = dyn_cast<LoadInst>(V1);
1250  auto *LI2 = dyn_cast<LoadInst>(V2);
1251  if (LI1 && LI2) {
1252  if (LI1->getParent() != LI2->getParent() || !LI1->isSimple() ||
1253  !LI2->isSimple())
1254  return LookAheadHeuristics::ScoreFail;
1255 
1257  LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1258  LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1259  if (!Dist || *Dist == 0) {
1260  if (getUnderlyingObject(LI1->getPointerOperand()) ==
1261  getUnderlyingObject(LI2->getPointerOperand()) &&
1262  R.TTI->isLegalMaskedGather(
1263  FixedVectorType::get(LI1->getType(), NumLanes),
1264  LI1->getAlign()))
1265  return LookAheadHeuristics::ScoreMaskedGatherCandidate;
1266  return LookAheadHeuristics::ScoreFail;
1267  }
1268  // The distance is too large - still may be profitable to use masked
1269  // loads/gathers.
1270  if (std::abs(*Dist) > NumLanes / 2)
1271  return LookAheadHeuristics::ScoreMaskedGatherCandidate;
1272  // This still will detect consecutive loads, but we might have "holes"
1273  // in some cases. It is ok for non-power-2 vectorization and may produce
1274  // better results. It should not affect current vectorization.
1275  return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1276  : LookAheadHeuristics::ScoreReversedLoads;
1277  }
1278 
1279  auto *C1 = dyn_cast<Constant>(V1);
1280  auto *C2 = dyn_cast<Constant>(V2);
1281  if (C1 && C2)
1282  return LookAheadHeuristics::ScoreConstants;
1283 
1284  // Extracts from consecutive indexes of the same vector better score as
1285  // the extracts could be optimized away.
1286  Value *EV1;
1287  ConstantInt *Ex1Idx;
1288  if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1289  // Undefs are always profitable for extractelements.
1290  if (isa<UndefValue>(V2))
1291  return LookAheadHeuristics::ScoreConsecutiveExtracts;
1292  Value *EV2 = nullptr;
1293  ConstantInt *Ex2Idx = nullptr;
1294  if (match(V2,
1296  m_Undef())))) {
1297  // Undefs are always profitable for extractelements.
1298  if (!Ex2Idx)
1299  return LookAheadHeuristics::ScoreConsecutiveExtracts;
1300  if (isUndefVector(EV2).all() && EV2->getType() == EV1->getType())
1301  return LookAheadHeuristics::ScoreConsecutiveExtracts;
1302  if (EV2 == EV1) {
1303  int Idx1 = Ex1Idx->getZExtValue();
1304  int Idx2 = Ex2Idx->getZExtValue();
1305  int Dist = Idx2 - Idx1;
1306  // The distance is too large - still may be profitable to use
1307  // shuffles.
1308  if (std::abs(Dist) == 0)
1309  return LookAheadHeuristics::ScoreSplat;
1310  if (std::abs(Dist) > NumLanes / 2)
1311  return LookAheadHeuristics::ScoreSameOpcode;
1312  return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1313  : LookAheadHeuristics::ScoreReversedExtracts;
1314  }
1315  return LookAheadHeuristics::ScoreAltOpcodes;
1316  }
1317  return LookAheadHeuristics::ScoreFail;
1318  }
1319 
1320  auto *I1 = dyn_cast<Instruction>(V1);
1321  auto *I2 = dyn_cast<Instruction>(V2);
1322  if (I1 && I2) {
1323  if (I1->getParent() != I2->getParent())
1324  return LookAheadHeuristics::ScoreFail;
1325  SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1326  Ops.push_back(I1);
1327  Ops.push_back(I2);
1328  InstructionsState S = getSameOpcode(Ops, TLI);
1329  // Note: Only consider instructions with <= 2 operands to avoid
1330  // complexity explosion.
1331  if (S.getOpcode() &&
1332  (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1333  !S.isAltShuffle()) &&
1334  all_of(Ops, [&S](Value *V) {
1335  return cast<Instruction>(V)->getNumOperands() ==
1336  S.MainOp->getNumOperands();
1337  }))
1338  return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1339  : LookAheadHeuristics::ScoreSameOpcode;
1340  }
1341 
1342  if (isa<UndefValue>(V2))
1343  return LookAheadHeuristics::ScoreUndef;
1344 
1345  return LookAheadHeuristics::ScoreFail;
1346  }
1347 
1348  /// Go through the operands of \p LHS and \p RHS recursively until
1349  /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1350  /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1351  /// of \p U1 and \p U2), except at the beginning of the recursion where
1352  /// these are set to nullptr.
1353  ///
1354  /// For example:
1355  /// \verbatim
1356  /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1]
1357  /// \ / \ / \ / \ /
1358  /// + + + +
1359  /// G1 G2 G3 G4
1360  /// \endverbatim
1361  /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1362  /// each level recursively, accumulating the score. It starts from matching
1363  /// the additions at level 0, then moves on to the loads (level 1). The
1364  /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1365  /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1366  /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1367  /// Please note that the order of the operands does not matter, as we
1368  /// evaluate the score of all profitable combinations of operands. In
1369  /// other words the score of G1 and G4 is the same as G1 and G2. This
1370  /// heuristic is based on ideas described in:
1371  /// Look-ahead SLP: Auto-vectorization in the presence of commutative
1372  /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1373  /// Luís F. W. Góes
1375  Instruction *U2, int CurrLevel,
1376  ArrayRef<Value *> MainAltOps) const {
1377 
1378  // Get the shallow score of V1 and V2.
1379  int ShallowScoreAtThisLevel =
1380  getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1381 
1382  // If reached MaxLevel,
1383  // or if V1 and V2 are not instructions,
1384  // or if they are SPLAT,
1385  // or if they are not consecutive,
1386  // or if profitable to vectorize loads or extractelements, early return
1387  // the current cost.
1388  auto *I1 = dyn_cast<Instruction>(LHS);
1389  auto *I2 = dyn_cast<Instruction>(RHS);
1390  if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1391  ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1392  (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1393  (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1394  (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1395  ShallowScoreAtThisLevel))
1396  return ShallowScoreAtThisLevel;
1397  assert(I1 && I2 && "Should have early exited.");
1398 
1399  // Contains the I2 operand indexes that got matched with I1 operands.
1400  SmallSet<unsigned, 4> Op2Used;
1401 
1402  // Recursion towards the operands of I1 and I2. We are trying all possible
1403  // operand pairs, and keeping track of the best score.
1404  for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1405  OpIdx1 != NumOperands1; ++OpIdx1) {
1406  // Try to pair op1I with the best operand of I2.
1407  int MaxTmpScore = 0;
1408  unsigned MaxOpIdx2 = 0;
1409  bool FoundBest = false;
1410  // If I2 is commutative try all combinations.
1411  unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1412  unsigned ToIdx = isCommutative(I2)
1413  ? I2->getNumOperands()
1414  : std::min(I2->getNumOperands(), OpIdx1 + 1);
1415  assert(FromIdx <= ToIdx && "Bad index");
1416  for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1417  // Skip operands already paired with OpIdx1.
1418  if (Op2Used.count(OpIdx2))
1419  continue;
1420  // Recursively calculate the cost at each level
1421  int TmpScore =
1422  getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1423  I1, I2, CurrLevel + 1, None);
1424  // Look for the best score.
1425  if (TmpScore > LookAheadHeuristics::ScoreFail &&
1426  TmpScore > MaxTmpScore) {
1427  MaxTmpScore = TmpScore;
1428  MaxOpIdx2 = OpIdx2;
1429  FoundBest = true;
1430  }
1431  }
1432  if (FoundBest) {
1433  // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1434  Op2Used.insert(MaxOpIdx2);
1435  ShallowScoreAtThisLevel += MaxTmpScore;
1436  }
1437  }
1438  return ShallowScoreAtThisLevel;
1439  }
1440  };
1441  /// A helper data structure to hold the operands of a vector of instructions.
1442  /// This supports a fixed vector length for all operand vectors.
1443  class VLOperands {
1444  /// For each operand we need (i) the value, and (ii) the opcode that it
1445  /// would be attached to if the expression was in a left-linearized form.
1446  /// This is required to avoid illegal operand reordering.
1447  /// For example:
1448  /// \verbatim
1449  /// 0 Op1
1450  /// |/
1451  /// Op1 Op2 Linearized + Op2
1452  /// \ / ----------> |/
1453  /// - -
1454  ///
1455  /// Op1 - Op2 (0 + Op1) - Op2
1456  /// \endverbatim
1457  ///
1458  /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1459  ///
1460  /// Another way to think of this is to track all the operations across the
1461  /// path from the operand all the way to the root of the tree and to
1462  /// calculate the operation that corresponds to this path. For example, the
1463  /// path from Op2 to the root crosses the RHS of the '-', therefore the
1464  /// corresponding operation is a '-' (which matches the one in the
1465  /// linearized tree, as shown above).
1466  ///
1467  /// For lack of a better term, we refer to this operation as Accumulated
1468  /// Path Operation (APO).
1469  struct OperandData {
1470  OperandData() = default;
1471  OperandData(Value *V, bool APO, bool IsUsed)
1472  : V(V), APO(APO), IsUsed(IsUsed) {}
1473  /// The operand value.
1474  Value *V = nullptr;
1475  /// TreeEntries only allow a single opcode, or an alternate sequence of
1476  /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1477  /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1478  /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1479  /// (e.g., Add/Mul)
1480  bool APO = false;
1481  /// Helper data for the reordering function.
1482  bool IsUsed = false;
1483  };
1484 
1485  /// During operand reordering, we are trying to select the operand at lane
1486  /// that matches best with the operand at the neighboring lane. Our
1487  /// selection is based on the type of value we are looking for. For example,
1488  /// if the neighboring lane has a load, we need to look for a load that is
1489  /// accessing a consecutive address. These strategies are summarized in the
1490  /// 'ReorderingMode' enumerator.
1491  enum class ReorderingMode {
1492  Load, ///< Matching loads to consecutive memory addresses
1493  Opcode, ///< Matching instructions based on opcode (same or alternate)
1494  Constant, ///< Matching constants
1495  Splat, ///< Matching the same instruction multiple times (broadcast)
1496  Failed, ///< We failed to create a vectorizable group
1497  };
1498 
1500 
1501  /// A vector of operand vectors.
1503 
1504  const TargetLibraryInfo &TLI;
1505  const DataLayout &DL;
1506  ScalarEvolution &SE;
1507  const BoUpSLP &R;
1508 
1509  /// \returns the operand data at \p OpIdx and \p Lane.
1510  OperandData &getData(unsigned OpIdx, unsigned Lane) {
1511  return OpsVec[OpIdx][Lane];
1512  }
1513 
1514  /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1515  const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1516  return OpsVec[OpIdx][Lane];
1517  }
1518 
1519  /// Clears the used flag for all entries.
1520  void clearUsed() {
1521  for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1522  OpIdx != NumOperands; ++OpIdx)
1523  for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1524  ++Lane)
1525  OpsVec[OpIdx][Lane].IsUsed = false;
1526  }
1527 
1528  /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1529  void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1530  std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1531  }
1532 
1533  /// \param Lane lane of the operands under analysis.
1534  /// \param OpIdx operand index in \p Lane lane we're looking the best
1535  /// candidate for.
1536  /// \param Idx operand index of the current candidate value.
1537  /// \returns The additional score due to possible broadcasting of the
1538  /// elements in the lane. It is more profitable to have power-of-2 unique
1539  /// elements in the lane, it will be vectorized with higher probability
1540  /// after removing duplicates. Currently the SLP vectorizer supports only
1541  /// vectorization of the power-of-2 number of unique scalars.
1542  int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1543  Value *IdxLaneV = getData(Idx, Lane).V;
1544  if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1545  return 0;
1546  SmallPtrSet<Value *, 4> Uniques;
1547  for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1548  if (Ln == Lane)
1549  continue;
1550  Value *OpIdxLnV = getData(OpIdx, Ln).V;
1551  if (!isa<Instruction>(OpIdxLnV))
1552  return 0;
1553  Uniques.insert(OpIdxLnV);
1554  }
1555  int UniquesCount = Uniques.size();
1556  int UniquesCntWithIdxLaneV =
1557  Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1558  Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1559  int UniquesCntWithOpIdxLaneV =
1560  Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1561  if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1562  return 0;
1563  return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1564  UniquesCntWithOpIdxLaneV) -
1565  (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1566  }
1567 
1568  /// \param Lane lane of the operands under analysis.
1569  /// \param OpIdx operand index in \p Lane lane we're looking the best
1570  /// candidate for.
1571  /// \param Idx operand index of the current candidate value.
1572  /// \returns The additional score for the scalar which users are all
1573  /// vectorized.
1574  int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1575  Value *IdxLaneV = getData(Idx, Lane).V;
1576  Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1577  // Do not care about number of uses for vector-like instructions
1578  // (extractelement/extractvalue with constant indices), they are extracts
1579  // themselves and already externally used. Vectorization of such
1580  // instructions does not add extra extractelement instruction, just may
1581  // remove it.
1582  if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1583  isVectorLikeInstWithConstOps(OpIdxLaneV))
1584  return LookAheadHeuristics::ScoreAllUserVectorized;
1585  auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1586  if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1587  return 0;
1588  return R.areAllUsersVectorized(IdxLaneI, None)
1589  ? LookAheadHeuristics::ScoreAllUserVectorized
1590  : 0;
1591  }
1592 
1593  /// Score scaling factor for fully compatible instructions but with
1594  /// different number of external uses. Allows better selection of the
1595  /// instructions with less external uses.
1596  static const int ScoreScaleFactor = 10;
1597 
1598  /// \Returns the look-ahead score, which tells us how much the sub-trees
1599  /// rooted at \p LHS and \p RHS match, the more they match the higher the
1600  /// score. This helps break ties in an informed way when we cannot decide on
1601  /// the order of the operands by just considering the immediate
1602  /// predecessors.
1603  int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1604  int Lane, unsigned OpIdx, unsigned Idx,
1605  bool &IsUsed) {
1606  LookAheadHeuristics LookAhead(TLI, DL, SE, R, getNumLanes(),
1608  // Keep track of the instruction stack as we recurse into the operands
1609  // during the look-ahead score exploration.
1610  int Score =
1611  LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1612  /*CurrLevel=*/1, MainAltOps);
1613  if (Score) {
1614  int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1615  if (Score <= -SplatScore) {
1616  // Set the minimum score for splat-like sequence to avoid setting
1617  // failed state.
1618  Score = 1;
1619  } else {
1620  Score += SplatScore;
1621  // Scale score to see the difference between different operands
1622  // and similar operands but all vectorized/not all vectorized
1623  // uses. It does not affect actual selection of the best
1624  // compatible operand in general, just allows to select the
1625  // operand with all vectorized uses.
1626  Score *= ScoreScaleFactor;
1627  Score += getExternalUseScore(Lane, OpIdx, Idx);
1628  IsUsed = true;
1629  }
1630  }
1631  return Score;
1632  }
1633 
1634  /// Best defined scores per lanes between the passes. Used to choose the
1635  /// best operand (with the highest score) between the passes.
1636  /// The key - {Operand Index, Lane}.
1637  /// The value - the best score between the passes for the lane and the
1638  /// operand.
1640  BestScoresPerLanes;
1641 
1642  // Search all operands in Ops[*][Lane] for the one that matches best
1643  // Ops[OpIdx][LastLane] and return its opreand index.
1644  // If no good match can be found, return None.
1645  Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1646  ArrayRef<ReorderingMode> ReorderingModes,
1647  ArrayRef<Value *> MainAltOps) {
1648  unsigned NumOperands = getNumOperands();
1649 
1650  // The operand of the previous lane at OpIdx.
1651  Value *OpLastLane = getData(OpIdx, LastLane).V;
1652 
1653  // Our strategy mode for OpIdx.
1654  ReorderingMode RMode = ReorderingModes[OpIdx];
1655  if (RMode == ReorderingMode::Failed)
1656  return None;
1657 
1658  // The linearized opcode of the operand at OpIdx, Lane.
1659  bool OpIdxAPO = getData(OpIdx, Lane).APO;
1660 
1661  // The best operand index and its score.
1662  // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1663  // are using the score to differentiate between the two.
1664  struct BestOpData {
1665  Optional<unsigned> Idx = None;
1666  unsigned Score = 0;
1667  } BestOp;
1668  BestOp.Score =
1669  BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1670  .first->second;
1671 
1672  // Track if the operand must be marked as used. If the operand is set to
1673  // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1674  // want to reestimate the operands again on the following iterations).
1675  bool IsUsed =
1676  RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1677  // Iterate through all unused operands and look for the best.
1678  for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1679  // Get the operand at Idx and Lane.
1680  OperandData &OpData = getData(Idx, Lane);
1681  Value *Op = OpData.V;
1682  bool OpAPO = OpData.APO;
1683 
1684  // Skip already selected operands.
1685  if (OpData.IsUsed)
1686  continue;
1687 
1688  // Skip if we are trying to move the operand to a position with a
1689  // different opcode in the linearized tree form. This would break the
1690  // semantics.
1691  if (OpAPO != OpIdxAPO)
1692  continue;
1693 
1694  // Look for an operand that matches the current mode.
1695  switch (RMode) {
1696  case ReorderingMode::Load:
1698  case ReorderingMode::Opcode: {
1699  bool LeftToRight = Lane > LastLane;
1700  Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1701  Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1702  int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1703  OpIdx, Idx, IsUsed);
1704  if (Score > static_cast<int>(BestOp.Score)) {
1705  BestOp.Idx = Idx;
1706  BestOp.Score = Score;
1707  BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1708  }
1709  break;
1710  }
1711  case ReorderingMode::Splat:
1712  if (Op == OpLastLane)
1713  BestOp.Idx = Idx;
1714  break;
1716  llvm_unreachable("Not expected Failed reordering mode.");
1717  }
1718  }
1719 
1720  if (BestOp.Idx) {
1721  getData(*BestOp.Idx, Lane).IsUsed = IsUsed;
1722  return BestOp.Idx;
1723  }
1724  // If we could not find a good match return None.
1725  return None;
1726  }
1727 
1728  /// Helper for reorderOperandVecs.
1729  /// \returns the lane that we should start reordering from. This is the one
1730  /// which has the least number of operands that can freely move about or
1731  /// less profitable because it already has the most optimal set of operands.
1732  unsigned getBestLaneToStartReordering() const {
1733  unsigned Min = UINT_MAX;
1734  unsigned SameOpNumber = 0;
1735  // std::pair<unsigned, unsigned> is used to implement a simple voting
1736  // algorithm and choose the lane with the least number of operands that
1737  // can freely move about or less profitable because it already has the
1738  // most optimal set of operands. The first unsigned is a counter for
1739  // voting, the second unsigned is the counter of lanes with instructions
1740  // with same/alternate opcodes and same parent basic block.
1742  // Try to be closer to the original results, if we have multiple lanes
1743  // with same cost. If 2 lanes have the same cost, use the one with the
1744  // lowest index.
1745  for (int I = getNumLanes(); I > 0; --I) {
1746  unsigned Lane = I - 1;
1747  OperandsOrderData NumFreeOpsHash =
1748  getMaxNumOperandsThatCanBeReordered(Lane);
1749  // Compare the number of operands that can move and choose the one with
1750  // the least number.
1751  if (NumFreeOpsHash.NumOfAPOs < Min) {
1752  Min = NumFreeOpsHash.NumOfAPOs;
1753  SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1754  HashMap.clear();
1755  HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1756  } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1757  NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1758  // Select the most optimal lane in terms of number of operands that
1759  // should be moved around.
1760  SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1761  HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1762  } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1763  NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1764  auto It = HashMap.find(NumFreeOpsHash.Hash);
1765  if (It == HashMap.end())
1766  HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1767  else
1768  ++It->second.first;
1769  }
1770  }
1771  // Select the lane with the minimum counter.
1772  unsigned BestLane = 0;
1773  unsigned CntMin = UINT_MAX;
1774  for (const auto &Data : reverse(HashMap)) {
1775  if (Data.second.first < CntMin) {
1776  CntMin = Data.second.first;
1777  BestLane = Data.second.second;
1778  }
1779  }
1780  return BestLane;
1781  }
1782 
1783  /// Data structure that helps to reorder operands.
1784  struct OperandsOrderData {
1785  /// The best number of operands with the same APOs, which can be
1786  /// reordered.
1787  unsigned NumOfAPOs = UINT_MAX;
1788  /// Number of operands with the same/alternate instruction opcode and
1789  /// parent.
1790  unsigned NumOpsWithSameOpcodeParent = 0;
1791  /// Hash for the actual operands ordering.
1792  /// Used to count operands, actually their position id and opcode
1793  /// value. It is used in the voting mechanism to find the lane with the
1794  /// least number of operands that can freely move about or less profitable
1795  /// because it already has the most optimal set of operands. Can be
1796  /// replaced with SmallVector<unsigned> instead but hash code is faster
1797  /// and requires less memory.
1798  unsigned Hash = 0;
1799  };
1800  /// \returns the maximum number of operands that are allowed to be reordered
1801  /// for \p Lane and the number of compatible instructions(with the same
1802  /// parent/opcode). This is used as a heuristic for selecting the first lane
1803  /// to start operand reordering.
1804  OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1805  unsigned CntTrue = 0;
1806  unsigned NumOperands = getNumOperands();
1807  // Operands with the same APO can be reordered. We therefore need to count
1808  // how many of them we have for each APO, like this: Cnt[APO] = x.
1809  // Since we only have two APOs, namely true and false, we can avoid using
1810  // a map. Instead we can simply count the number of operands that
1811  // correspond to one of them (in this case the 'true' APO), and calculate
1812  // the other by subtracting it from the total number of operands.
1813  // Operands with the same instruction opcode and parent are more
1814  // profitable since we don't need to move them in many cases, with a high
1815  // probability such lane already can be vectorized effectively.
1816  bool AllUndefs = true;
1817  unsigned NumOpsWithSameOpcodeParent = 0;
1818  Instruction *OpcodeI = nullptr;
1819  BasicBlock *Parent = nullptr;
1820  unsigned Hash = 0;
1821  for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1822  const OperandData &OpData = getData(OpIdx, Lane);
1823  if (OpData.APO)
1824  ++CntTrue;
1825  // Use Boyer-Moore majority voting for finding the majority opcode and
1826  // the number of times it occurs.
1827  if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1828  if (!OpcodeI || !getSameOpcode({OpcodeI, I}, TLI).getOpcode() ||
1829  I->getParent() != Parent) {
1830  if (NumOpsWithSameOpcodeParent == 0) {
1831  NumOpsWithSameOpcodeParent = 1;
1832  OpcodeI = I;
1833  Parent = I->getParent();
1834  } else {
1835  --NumOpsWithSameOpcodeParent;
1836  }
1837  } else {
1838  ++NumOpsWithSameOpcodeParent;
1839  }
1840  }
1841  Hash = hash_combine(
1842  Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1843  AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1844  }
1845  if (AllUndefs)
1846  return {};
1847  OperandsOrderData Data;
1848  Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1849  Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1850  Data.Hash = Hash;
1851  return Data;
1852  }
1853 
1854  /// Go through the instructions in VL and append their operands.
1855  void appendOperandsOfVL(ArrayRef<Value *> VL) {
1856  assert(!VL.empty() && "Bad VL");
1857  assert((empty() || VL.size() == getNumLanes()) &&
1858  "Expected same number of lanes");
1859  assert(isa<Instruction>(VL[0]) && "Expected instruction");
1860  unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1861  OpsVec.resize(NumOperands);
1862  unsigned NumLanes = VL.size();
1863  for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1864  OpsVec[OpIdx].resize(NumLanes);
1865  for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1866  assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1867  // Our tree has just 3 nodes: the root and two operands.
1868  // It is therefore trivial to get the APO. We only need to check the
1869  // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1870  // RHS operand. The LHS operand of both add and sub is never attached
1871  // to an inversese operation in the linearized form, therefore its APO
1872  // is false. The RHS is true only if VL[Lane] is an inverse operation.
1873 
1874  // Since operand reordering is performed on groups of commutative
1875  // operations or alternating sequences (e.g., +, -), we can safely
1876  // tell the inverse operations by checking commutativity.
1877  bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1878  bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1879  OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1880  APO, false};
1881  }
1882  }
1883  }
1884 
1885  /// \returns the number of operands.
1886  unsigned getNumOperands() const { return OpsVec.size(); }
1887 
1888  /// \returns the number of lanes.
1889  unsigned getNumLanes() const { return OpsVec[0].size(); }
1890 
1891  /// \returns the operand value at \p OpIdx and \p Lane.
1892  Value *getValue(unsigned OpIdx, unsigned Lane) const {
1893  return getData(OpIdx, Lane).V;
1894  }
1895 
1896  /// \returns true if the data structure is empty.
1897  bool empty() const { return OpsVec.empty(); }
1898 
1899  /// Clears the data.
1900  void clear() { OpsVec.clear(); }
1901 
1902  /// \Returns true if there are enough operands identical to \p Op to fill
1903  /// the whole vector.
1904  /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1905  bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1906  bool OpAPO = getData(OpIdx, Lane).APO;
1907  for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1908  if (Ln == Lane)
1909  continue;
1910  // This is set to true if we found a candidate for broadcast at Lane.
1911  bool FoundCandidate = false;
1912  for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1913  OperandData &Data = getData(OpI, Ln);
1914  if (Data.APO != OpAPO || Data.IsUsed)
1915  continue;
1916  if (Data.V == Op) {
1917  FoundCandidate = true;
1918  Data.IsUsed = true;
1919  break;
1920  }
1921  }
1922  if (!FoundCandidate)
1923  return false;
1924  }
1925  return true;
1926  }
1927 
1928  public:
1929  /// Initialize with all the operands of the instruction vector \p RootVL.
1931  const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R)
1932  : TLI(TLI), DL(DL), SE(SE), R(R) {
1933  // Append all the operands of RootVL.
1934  appendOperandsOfVL(RootVL);
1935  }
1936 
1937  /// \Returns a value vector with the operands across all lanes for the
1938  /// opearnd at \p OpIdx.
1939  ValueList getVL(unsigned OpIdx) const {
1940  ValueList OpVL(OpsVec[OpIdx].size());
1941  assert(OpsVec[OpIdx].size() == getNumLanes() &&
1942  "Expected same num of lanes across all operands");
1943  for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1944  OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1945  return OpVL;
1946  }
1947 
1948  // Performs operand reordering for 2 or more operands.
1949  // The original operands are in OrigOps[OpIdx][Lane].
1950  // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1951  void reorder() {
1952  unsigned NumOperands = getNumOperands();
1953  unsigned NumLanes = getNumLanes();
1954  // Each operand has its own mode. We are using this mode to help us select
1955  // the instructions for each lane, so that they match best with the ones
1956  // we have selected so far.
1957  SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1958 
1959  // This is a greedy single-pass algorithm. We are going over each lane
1960  // once and deciding on the best order right away with no back-tracking.
1961  // However, in order to increase its effectiveness, we start with the lane
1962  // that has operands that can move the least. For example, given the
1963  // following lanes:
1964  // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
1965  // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
1966  // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
1967  // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
1968  // we will start at Lane 1, since the operands of the subtraction cannot
1969  // be reordered. Then we will visit the rest of the lanes in a circular
1970  // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1971 
1972  // Find the first lane that we will start our search from.
1973  unsigned FirstLane = getBestLaneToStartReordering();
1974 
1975  // Initialize the modes.
1976  for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1977  Value *OpLane0 = getValue(OpIdx, FirstLane);
1978  // Keep track if we have instructions with all the same opcode on one
1979  // side.
1980  if (isa<LoadInst>(OpLane0))
1981  ReorderingModes[OpIdx] = ReorderingMode::Load;
1982  else if (isa<Instruction>(OpLane0)) {
1983  // Check if OpLane0 should be broadcast.
1984  if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1985  ReorderingModes[OpIdx] = ReorderingMode::Splat;
1986  else
1987  ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1988  }
1989  else if (isa<Constant>(OpLane0))
1990  ReorderingModes[OpIdx] = ReorderingMode::Constant;
1991  else if (isa<Argument>(OpLane0))
1992  // Our best hope is a Splat. It may save some cost in some cases.
1993  ReorderingModes[OpIdx] = ReorderingMode::Splat;
1994  else
1995  // NOTE: This should be unreachable.
1996  ReorderingModes[OpIdx] = ReorderingMode::Failed;
1997  }
1998 
1999  // Check that we don't have same operands. No need to reorder if operands
2000  // are just perfect diamond or shuffled diamond match. Do not do it only
2001  // for possible broadcasts or non-power of 2 number of scalars (just for
2002  // now).
2003  auto &&SkipReordering = [this]() {
2004  SmallPtrSet<Value *, 4> UniqueValues;
2005  ArrayRef<OperandData> Op0 = OpsVec.front();
2006  for (const OperandData &Data : Op0)
2007  UniqueValues.insert(Data.V);
2008  for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
2009  if (any_of(Op, [&UniqueValues](const OperandData &Data) {
2010  return !UniqueValues.contains(Data.V);
2011  }))
2012  return false;
2013  }
2014  // TODO: Check if we can remove a check for non-power-2 number of
2015  // scalars after full support of non-power-2 vectorization.
2016  return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
2017  };
2018 
2019  // If the initial strategy fails for any of the operand indexes, then we
2020  // perform reordering again in a second pass. This helps avoid assigning
2021  // high priority to the failed strategy, and should improve reordering for
2022  // the non-failed operand indexes.
2023  for (int Pass = 0; Pass != 2; ++Pass) {
2024  // Check if no need to reorder operands since they're are perfect or
2025  // shuffled diamond match.
2026  // Need to to do it to avoid extra external use cost counting for
2027  // shuffled matches, which may cause regressions.
2028  if (SkipReordering())
2029  break;
2030  // Skip the second pass if the first pass did not fail.
2031  bool StrategyFailed = false;
2032  // Mark all operand data as free to use.
2033  clearUsed();
2034  // We keep the original operand order for the FirstLane, so reorder the
2035  // rest of the lanes. We are visiting the nodes in a circular fashion,
2036  // using FirstLane as the center point and increasing the radius
2037  // distance.
2038  SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
2039  for (unsigned I = 0; I < NumOperands; ++I)
2040  MainAltOps[I].push_back(getData(I, FirstLane).V);
2041 
2042  for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
2043  // Visit the lane on the right and then the lane on the left.
2044  for (int Direction : {+1, -1}) {
2045  int Lane = FirstLane + Direction * Distance;
2046  if (Lane < 0 || Lane >= (int)NumLanes)
2047  continue;
2048  int LastLane = Lane - Direction;
2049  assert(LastLane >= 0 && LastLane < (int)NumLanes &&
2050  "Out of bounds");
2051  // Look for a good match for each operand.
2052  for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
2053  // Search for the operand that matches SortedOps[OpIdx][Lane-1].
2054  Optional<unsigned> BestIdx = getBestOperand(
2055  OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
2056  // By not selecting a value, we allow the operands that follow to
2057  // select a better matching value. We will get a non-null value in
2058  // the next run of getBestOperand().
2059  if (BestIdx) {
2060  // Swap the current operand with the one returned by
2061  // getBestOperand().
2062  swap(OpIdx, *BestIdx, Lane);
2063  } else {
2064  // We failed to find a best operand, set mode to 'Failed'.
2065  ReorderingModes[OpIdx] = ReorderingMode::Failed;
2066  // Enable the second pass.
2067  StrategyFailed = true;
2068  }
2069  // Try to get the alternate opcode and follow it during analysis.
2070  if (MainAltOps[OpIdx].size() != 2) {
2071  OperandData &AltOp = getData(OpIdx, Lane);
2072  InstructionsState OpS =
2073  getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}, TLI);
2074  if (OpS.getOpcode() && OpS.isAltShuffle())
2075  MainAltOps[OpIdx].push_back(AltOp.V);
2076  }
2077  }
2078  }
2079  }
2080  // Skip second pass if the strategy did not fail.
2081  if (!StrategyFailed)
2082  break;
2083  }
2084  }
2085 
2086 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2087  LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
2088  switch (RMode) {
2089  case ReorderingMode::Load:
2090  return "Load";
2091  case ReorderingMode::Opcode:
2092  return "Opcode";
2094  return "Constant";
2095  case ReorderingMode::Splat:
2096  return "Splat";
2098  return "Failed";
2099  }
2100  llvm_unreachable("Unimplemented Reordering Type");
2101  }
2102 
2103  LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
2104  raw_ostream &OS) {
2105  return OS << getModeStr(RMode);
2106  }
2107 
2108  /// Debug print.
2109  LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
2110  printMode(RMode, dbgs());
2111  }
2112 
2113  friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
2114  return printMode(RMode, OS);
2115  }
2116 
2118  const unsigned Indent = 2;
2119  unsigned Cnt = 0;
2120  for (const OperandDataVec &OpDataVec : OpsVec) {
2121  OS << "Operand " << Cnt++ << "\n";
2122  for (const OperandData &OpData : OpDataVec) {
2123  OS.indent(Indent) << "{";
2124  if (Value *V = OpData.V)
2125  OS << *V;
2126  else
2127  OS << "null";
2128  OS << ", APO:" << OpData.APO << "}\n";
2129  }
2130  OS << "\n";
2131  }
2132  return OS;
2133  }
2134 
2135  /// Debug print.
2136  LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2137 #endif
2138  };
2139 
2140  /// Evaluate each pair in \p Candidates and return index into \p Candidates
2141  /// for a pair which have highest score deemed to have best chance to form
2142  /// root of profitable tree to vectorize. Return None if no candidate scored
2143  /// above the LookAheadHeuristics::ScoreFail.
2144  /// \param Limit Lower limit of the cost, considered to be good enough score.
2146  findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
2147  int Limit = LookAheadHeuristics::ScoreFail) {
2148  LookAheadHeuristics LookAhead(*TLI, *DL, *SE, *this, /*NumLanes=*/2,
2150  int BestScore = Limit;
2152  for (int I : seq<int>(0, Candidates.size())) {
2153  int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2154  Candidates[I].second,
2155  /*U1=*/nullptr, /*U2=*/nullptr,
2156  /*Level=*/1, None);
2157  if (Score > BestScore) {
2158  BestScore = Score;
2159  Index = I;
2160  }
2161  }
2162  return Index;
2163  }
2164 
2165  /// Checks if the instruction is marked for deletion.
2166  bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2167 
2168  /// Removes an instruction from its block and eventually deletes it.
2169  /// It's like Instruction::eraseFromParent() except that the actual deletion
2170  /// is delayed until BoUpSLP is destructed.
2172  DeletedInstructions.insert(I);
2173  }
2174 
2175  /// Checks if the instruction was already analyzed for being possible
2176  /// reduction root.
2178  return AnalyzedReductionsRoots.count(I);
2179  }
2180  /// Register given instruction as already analyzed for being possible
2181  /// reduction root.
2183  AnalyzedReductionsRoots.insert(I);
2184  }
2185  /// Checks if the provided list of reduced values was checked already for
2186  /// vectorization.
2188  return AnalyzedReductionVals.contains(hash_value(VL));
2189  }
2190  /// Adds the list of reduced values to list of already checked values for the
2191  /// vectorization.
2193  AnalyzedReductionVals.insert(hash_value(VL));
2194  }
2195  /// Clear the list of the analyzed reduction root instructions.
2197  AnalyzedReductionsRoots.clear();
2198  AnalyzedReductionVals.clear();
2199  }
2200  /// Checks if the given value is gathered in one of the nodes.
2201  bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const {
2202  return any_of(MustGather, [&](Value *V) { return Vals.contains(V); });
2203  }
2204 
2205  /// Check if the value is vectorized in the tree.
2206  bool isVectorized(Value *V) const { return getTreeEntry(V); }
2207 
2208  ~BoUpSLP();
2209 
2210 private:
2211  /// Check if the operands on the edges \p Edges of the \p UserTE allows
2212  /// reordering (i.e. the operands can be reordered because they have only one
2213  /// user and reordarable).
2214  /// \param ReorderableGathers List of all gather nodes that require reordering
2215  /// (e.g., gather of extractlements or partially vectorizable loads).
2216  /// \param GatherOps List of gather operand nodes for \p UserTE that require
2217  /// reordering, subset of \p NonVectorized.
2218  bool
2219  canReorderOperands(TreeEntry *UserTE,
2220  SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2221  ArrayRef<TreeEntry *> ReorderableGathers,
2222  SmallVectorImpl<TreeEntry *> &GatherOps);
2223 
2224  /// Checks if the given \p TE is a gather node with clustered reused scalars
2225  /// and reorders it per given \p Mask.
2226  void reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const;
2227 
2228  /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2229  /// if any. If it is not vectorized (gather node), returns nullptr.
2230  TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2231  ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2232  TreeEntry *TE = nullptr;
2233  const auto *It = find_if(VL, [this, &TE](Value *V) {
2234  TE = getTreeEntry(V);
2235  return TE;
2236  });
2237  if (It != VL.end() && TE->isSame(VL))
2238  return TE;
2239  return nullptr;
2240  }
2241 
2242  /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2243  /// if any. If it is not vectorized (gather node), returns nullptr.
2244  const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2245  unsigned OpIdx) const {
2246  return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2247  const_cast<TreeEntry *>(UserTE), OpIdx);
2248  }
2249 
2250  /// Checks if all users of \p I are the part of the vectorization tree.
2251  bool areAllUsersVectorized(Instruction *I,
2252  ArrayRef<Value *> VectorizedVals) const;
2253 
2254  /// Return information about the vector formed for the specified index
2255  /// of a vector of (the same) instruction.
2257  unsigned OpIdx);
2258 
2259  /// \returns the cost of the vectorizable entry.
2260  InstructionCost getEntryCost(const TreeEntry *E,
2261  ArrayRef<Value *> VectorizedVals);
2262 
2263  /// This is the recursive part of buildTree.
2264  void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2265  const EdgeInfo &EI);
2266 
2267  /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2268  /// be vectorized to use the original vector (or aggregate "bitcast" to a
2269  /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2270  /// returns false, setting \p CurrentOrder to either an empty vector or a
2271  /// non-identity permutation that allows to reuse extract instructions.
2272  bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2273  SmallVectorImpl<unsigned> &CurrentOrder) const;
2274 
2275  /// Vectorize a single entry in the tree.
2276  Value *vectorizeTree(TreeEntry *E);
2277 
2278  /// Vectorize a single entry in the tree, the \p Idx-th operand of the entry
2279  /// \p E.
2280  Value *vectorizeOperand(TreeEntry *E, unsigned NodeIdx);
2281 
2282  /// Create a new vector from a list of scalar values. Produces a sequence
2283  /// which exploits values reused across lanes, and arranges the inserts
2284  /// for ease of later optimization.
2285  Value *createBuildVector(const TreeEntry *E);
2286 
2287  /// \returns the scalarization cost for this type. Scalarization in this
2288  /// context means the creation of vectors from a group of scalars. If \p
2289  /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2290  /// vector elements.
2291  InstructionCost getGatherCost(FixedVectorType *Ty,
2292  const APInt &ShuffledIndices,
2293  bool NeedToShuffle) const;
2294 
2295  /// Returns the instruction in the bundle, which can be used as a base point
2296  /// for scheduling. Usually it is the last instruction in the bundle, except
2297  /// for the case when all operands are external (in this case, it is the first
2298  /// instruction in the list).
2299  Instruction &getLastInstructionInBundle(const TreeEntry *E);
2300 
2301  /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2302  /// tree entries.
2303  /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2304  /// previous tree entries. \p Mask is filled with the shuffle mask.
2306  isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2308 
2309  /// \returns the scalarization cost for this list of values. Assuming that
2310  /// this subtree gets vectorized, we may need to extract the values from the
2311  /// roots. This method calculates the cost of extracting the values.
2312  InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2313 
2314  /// Set the Builder insert point to one after the last instruction in
2315  /// the bundle
2316  void setInsertPointAfterBundle(const TreeEntry *E);
2317 
2318  /// \returns a vector from a collection of scalars in \p VL.
2319  Value *gather(ArrayRef<Value *> VL);
2320 
2321  /// \returns whether the VectorizableTree is fully vectorizable and will
2322  /// be beneficial even the tree height is tiny.
2323  bool isFullyVectorizableTinyTree(bool ForReduction) const;
2324 
2325  /// Reorder commutative or alt operands to get better probability of
2326  /// generating vectorized code.
2327  static void reorderInputsAccordingToOpcode(
2329  SmallVectorImpl<Value *> &Right, const TargetLibraryInfo &TLI,
2330  const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R);
2331 
2332  /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2333  /// users of \p TE and collects the stores. It returns the map from the store
2334  /// pointers to the collected stores.
2336  collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2337 
2338  /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2339  /// stores in \p StoresVec can form a vector instruction. If so it returns true
2340  /// and populates \p ReorderIndices with the shuffle indices of the the stores
2341  /// when compared to the sorted vector.
2342  bool canFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2343  OrdersType &ReorderIndices) const;
2344 
2345  /// Iterates through the users of \p TE, looking for scalar stores that can be
2346  /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2347  /// their order and builds an order index vector for each store bundle. It
2348  /// returns all these order vectors found.
2349  /// We run this after the tree has formed, otherwise we may come across user
2350  /// instructions that are not yet in the tree.
2352  findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2353 
2354  struct TreeEntry {
2355  using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2356  TreeEntry(VecTreeTy &Container) : Container(Container) {}
2357 
2358  /// \returns true if the scalars in VL are equal to this entry.
2359  bool isSame(ArrayRef<Value *> VL) const {
2360  auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2361  if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2362  return std::equal(VL.begin(), VL.end(), Scalars.begin());
2363  return VL.size() == Mask.size() &&
2364  std::equal(VL.begin(), VL.end(), Mask.begin(),
2365  [Scalars](Value *V, int Idx) {
2366  return (isa<UndefValue>(V) &&
2367  Idx == UndefMaskElem) ||
2368  (Idx != UndefMaskElem && V == Scalars[Idx]);
2369  });
2370  };
2371  if (!ReorderIndices.empty()) {
2372  // TODO: implement matching if the nodes are just reordered, still can
2373  // treat the vector as the same if the list of scalars matches VL
2374  // directly, without reordering.
2376  inversePermutation(ReorderIndices, Mask);
2377  if (VL.size() == Scalars.size())
2378  return IsSame(Scalars, Mask);
2379  if (VL.size() == ReuseShuffleIndices.size()) {
2380  ::addMask(Mask, ReuseShuffleIndices);
2381  return IsSame(Scalars, Mask);
2382  }
2383  return false;
2384  }
2385  return IsSame(Scalars, ReuseShuffleIndices);
2386  }
2387 
2388  bool isOperandGatherNode(const EdgeInfo &UserEI) const {
2389  return State == TreeEntry::NeedToGather &&
2390  UserTreeIndices.front().EdgeIdx == UserEI.EdgeIdx &&
2391  UserTreeIndices.front().UserTE == UserEI.UserTE;
2392  }
2393 
2394  /// \returns true if current entry has same operands as \p TE.
2395  bool hasEqualOperands(const TreeEntry &TE) const {
2396  if (TE.getNumOperands() != getNumOperands())
2397  return false;
2398  SmallBitVector Used(getNumOperands());
2399  for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2400  unsigned PrevCount = Used.count();
2401  for (unsigned K = 0; K < E; ++K) {
2402  if (Used.test(K))
2403  continue;
2404  if (getOperand(K) == TE.getOperand(I)) {
2405  Used.set(K);
2406  break;
2407  }
2408  }
2409  // Check if we actually found the matching operand.
2410  if (PrevCount == Used.count())
2411  return false;
2412  }
2413  return true;
2414  }
2415 
2416  /// \return Final vectorization factor for the node. Defined by the total
2417  /// number of vectorized scalars, including those, used several times in the
2418  /// entry and counted in the \a ReuseShuffleIndices, if any.
2419  unsigned getVectorFactor() const {
2420  if (!ReuseShuffleIndices.empty())
2421  return ReuseShuffleIndices.size();
2422  return Scalars.size();
2423  };
2424 
2425  /// A vector of scalars.
2426  ValueList Scalars;
2427 
2428  /// The Scalars are vectorized into this value. It is initialized to Null.
2429  Value *VectorizedValue = nullptr;
2430 
2431  /// Do we need to gather this sequence or vectorize it
2432  /// (either with vector instruction or with scatter/gather
2433  /// intrinsics for store/load)?
2434  enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2435  EntryState State;
2436 
2437  /// Does this sequence require some shuffling?
2438  SmallVector<int, 4> ReuseShuffleIndices;
2439 
2440  /// Does this entry require reordering?
2441  SmallVector<unsigned, 4> ReorderIndices;
2442 
2443  /// Points back to the VectorizableTree.
2444  ///
2445  /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
2446  /// to be a pointer and needs to be able to initialize the child iterator.
2447  /// Thus we need a reference back to the container to translate the indices
2448  /// to entries.
2449  VecTreeTy &Container;
2450 
2451  /// The TreeEntry index containing the user of this entry. We can actually
2452  /// have multiple users so the data structure is not truly a tree.
2453  SmallVector<EdgeInfo, 1> UserTreeIndices;
2454 
2455  /// The index of this treeEntry in VectorizableTree.
2456  int Idx = -1;
2457 
2458  private:
2459  /// The operands of each instruction in each lane Operands[op_index][lane].
2460  /// Note: This helps avoid the replication of the code that performs the
2461  /// reordering of operands during buildTree_rec() and vectorizeTree().
2463 
2464  /// The main/alternate instruction.
2465  Instruction *MainOp = nullptr;
2466  Instruction *AltOp = nullptr;
2467 
2468  public:
2469  /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2470  void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2471  if (Operands.size() < OpIdx + 1)
2472  Operands.resize(OpIdx + 1);
2473  assert(Operands[OpIdx].empty() && "Already resized?");
2474  assert(OpVL.size() <= Scalars.size() &&
2475  "Number of operands is greater than the number of scalars.");
2476  Operands[OpIdx].resize(OpVL.size());
2477  copy(OpVL, Operands[OpIdx].begin());
2478  }
2479 
2480  /// Set the operands of this bundle in their original order.
2481  void setOperandsInOrder() {
2482  assert(Operands.empty() && "Already initialized?");
2483  auto *I0 = cast<Instruction>(Scalars[0]);
2484  Operands.resize(I0->getNumOperands());
2485  unsigned NumLanes = Scalars.size();
2486  for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2487  OpIdx != NumOperands; ++OpIdx) {
2488  Operands[OpIdx].resize(NumLanes);
2489  for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2490  auto *I = cast<Instruction>(Scalars[Lane]);
2491  assert(I->getNumOperands() == NumOperands &&
2492  "Expected same number of operands");
2493  Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2494  }
2495  }
2496  }
2497 
2498  /// Reorders operands of the node to the given mask \p Mask.
2499  void reorderOperands(ArrayRef<int> Mask) {
2500  for (ValueList &Operand : Operands)
2501  reorderScalars(Operand, Mask);
2502  }
2503 
2504  /// \returns the \p OpIdx operand of this TreeEntry.
2505  ValueList &getOperand(unsigned OpIdx) {
2506  assert(OpIdx < Operands.size() && "Off bounds");
2507  return Operands[OpIdx];
2508  }
2509 
2510  /// \returns the \p OpIdx operand of this TreeEntry.
2511  ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2512  assert(OpIdx < Operands.size() && "Off bounds");
2513  return Operands[OpIdx];
2514  }
2515 
2516  /// \returns the number of operands.
2517  unsigned getNumOperands() const { return Operands.size(); }
2518 
2519  /// \return the single \p OpIdx operand.
2520  Value *getSingleOperand(unsigned OpIdx) const {
2521  assert(OpIdx < Operands.size() && "Off bounds");
2522  assert(!Operands[OpIdx].empty() && "No operand available");
2523  return Operands[OpIdx][0];
2524  }
2525 
2526  /// Some of the instructions in the list have alternate opcodes.
2527  bool isAltShuffle() const { return MainOp != AltOp; }
2528 
2529  bool isOpcodeOrAlt(Instruction *I) const {
2530  unsigned CheckedOpcode = I->getOpcode();
2531  return (getOpcode() == CheckedOpcode ||
2532  getAltOpcode() == CheckedOpcode);
2533  }
2534 
2535  /// Chooses the correct key for scheduling data. If \p Op has the same (or
2536  /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2537  /// \p OpValue.
2538  Value *isOneOf(Value *Op) const {
2539  auto *I = dyn_cast<Instruction>(Op);
2540  if (I && isOpcodeOrAlt(I))
2541  return Op;
2542  return MainOp;
2543  }
2544 
2545  void setOperations(const InstructionsState &S) {
2546  MainOp = S.MainOp;
2547  AltOp = S.AltOp;
2548  }
2549 
2550  Instruction *getMainOp() const {
2551  return MainOp;
2552  }
2553 
2554  Instruction *getAltOp() const {
2555  return AltOp;
2556  }
2557 
2558  /// The main/alternate opcodes for the list of instructions.
2559  unsigned getOpcode() const {
2560  return MainOp ? MainOp->getOpcode() : 0;
2561  }
2562 
2563  unsigned getAltOpcode() const {
2564  return AltOp ? AltOp->getOpcode() : 0;
2565  }
2566 
2567  /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2568  /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2569  int findLaneForValue(Value *V) const {
2570  unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2571  assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2572  if (!ReorderIndices.empty())
2573  FoundLane = ReorderIndices[FoundLane];
2574  assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2575  if (!ReuseShuffleIndices.empty()) {
2576  FoundLane = std::distance(ReuseShuffleIndices.begin(),
2577  find(ReuseShuffleIndices, FoundLane));
2578  }
2579  return FoundLane;
2580  }
2581 
2582 #ifndef NDEBUG
2583  /// Debug printer.
2584  LLVM_DUMP_METHOD void dump() const {
2585  dbgs() << Idx << ".\n";
2586  for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2587  dbgs() << "Operand " << OpI << ":\n";
2588  for (const Value *V : Operands[OpI])
2589  dbgs().indent(2) << *V << "\n";
2590  }
2591  dbgs() << "Scalars: \n";
2592  for (Value *V : Scalars)
2593  dbgs().indent(2) << *V << "\n";
2594  dbgs() << "State: ";
2595  switch (State) {
2596  case Vectorize:
2597  dbgs() << "Vectorize\n";
2598  break;
2599  case ScatterVectorize:
2600  dbgs() << "ScatterVectorize\n";
2601  break;
2602  case NeedToGather:
2603  dbgs() << "NeedToGather\n";
2604  break;
2605  }
2606  dbgs() << "MainOp: ";
2607  if (MainOp)
2608  dbgs() << *MainOp << "\n";
2609  else
2610  dbgs() << "NULL\n";
2611  dbgs() << "AltOp: ";
2612  if (AltOp)
2613  dbgs() << *AltOp << "\n";
2614  else
2615  dbgs() << "NULL\n";
2616  dbgs() << "VectorizedValue: ";
2617  if (VectorizedValue)
2618  dbgs() << *VectorizedValue << "\n";
2619  else
2620  dbgs() << "NULL\n";
2621  dbgs() << "ReuseShuffleIndices: ";
2622  if (ReuseShuffleIndices.empty())
2623  dbgs() << "Empty";
2624  else
2625  for (int ReuseIdx : ReuseShuffleIndices)
2626  dbgs() << ReuseIdx << ", ";
2627  dbgs() << "\n";
2628  dbgs() << "ReorderIndices: ";
2629  for (unsigned ReorderIdx : ReorderIndices)
2630  dbgs() << ReorderIdx << ", ";
2631  dbgs() << "\n";
2632  dbgs() << "UserTreeIndices: ";
2633  for (const auto &EInfo : UserTreeIndices)
2634  dbgs() << EInfo << ", ";
2635  dbgs() << "\n";
2636  }
2637 #endif
2638  };
2639 
2640 #ifndef NDEBUG
2641  void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2642  InstructionCost VecCost,
2643  InstructionCost ScalarCost) const {
2644  dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2645  dbgs() << "SLP: Costs:\n";
2646  dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2647  dbgs() << "SLP: VectorCost = " << VecCost << "\n";
2648  dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n";
2649  dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " <<
2650  ReuseShuffleCost + VecCost - ScalarCost << "\n";
2651  }
2652 #endif
2653 
2654  /// Create a new VectorizableTree entry.
2655  TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2656  const InstructionsState &S,
2657  const EdgeInfo &UserTreeIdx,
2658  ArrayRef<int> ReuseShuffleIndices = None,
2659  ArrayRef<unsigned> ReorderIndices = None) {
2660  TreeEntry::EntryState EntryState =
2661  Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2662  return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2663  ReuseShuffleIndices, ReorderIndices);
2664  }
2665 
2666  TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2667  TreeEntry::EntryState EntryState,
2668  Optional<ScheduleData *> Bundle,
2669  const InstructionsState &S,
2670  const EdgeInfo &UserTreeIdx,
2671  ArrayRef<int> ReuseShuffleIndices = None,
2672  ArrayRef<unsigned> ReorderIndices = None) {
2673  assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2674  (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2675  "Need to vectorize gather entry?");
2676  VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2677  TreeEntry *Last = VectorizableTree.back().get();
2678  Last->Idx = VectorizableTree.size() - 1;
2679  Last->State = EntryState;
2680  Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2681  ReuseShuffleIndices.end());
2682  if (ReorderIndices.empty()) {
2683  Last->Scalars.assign(VL.begin(), VL.end());
2684  Last->setOperations(S);
2685  } else {
2686  // Reorder scalars and build final mask.
2687  Last->Scalars.assign(VL.size(), nullptr);
2688  transform(ReorderIndices, Last->Scalars.begin(),
2689  [VL](unsigned Idx) -> Value * {
2690  if (Idx >= VL.size())
2691  return UndefValue::get(VL.front()->getType());
2692  return VL[Idx];
2693  });
2694  InstructionsState S = getSameOpcode(Last->Scalars, *TLI);
2695  Last->setOperations(S);
2696  Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2697  }
2698  if (Last->State != TreeEntry::NeedToGather) {
2699  for (Value *V : VL) {
2700  assert(!getTreeEntry(V) && "Scalar already in tree!");
2701  ScalarToTreeEntry[V] = Last;
2702  }
2703  // Update the scheduler bundle to point to this TreeEntry.
2704  ScheduleData *BundleMember = *Bundle;
2705  assert((BundleMember || isa<PHINode>(S.MainOp) ||
2706  isVectorLikeInstWithConstOps(S.MainOp) ||
2707  doesNotNeedToSchedule(VL)) &&
2708  "Bundle and VL out of sync");
2709  if (BundleMember) {
2710  for (Value *V : VL) {
2711  if (doesNotNeedToBeScheduled(V))
2712  continue;
2713  assert(BundleMember && "Unexpected end of bundle.");
2714  BundleMember->TE = Last;
2715  BundleMember = BundleMember->NextInBundle;
2716  }
2717  }
2718  assert(!BundleMember && "Bundle and VL out of sync");
2719  } else {
2720  MustGather.insert(VL.begin(), VL.end());
2721  }
2722 
2723  if (UserTreeIdx.UserTE)
2724  Last->UserTreeIndices.push_back(UserTreeIdx);
2725 
2726  return Last;
2727  }
2728 
2729  /// -- Vectorization State --
2730  /// Holds all of the tree entries.
2731  TreeEntry::VecTreeTy VectorizableTree;
2732 
2733 #ifndef NDEBUG
2734  /// Debug printer.
2735  LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2736  for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2737  VectorizableTree[Id]->dump();
2738  dbgs() << "\n";
2739  }
2740  }
2741 #endif
2742 
2743  TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2744 
2745  const TreeEntry *getTreeEntry(Value *V) const {
2746  return ScalarToTreeEntry.lookup(V);
2747  }
2748 
2749  /// Maps a specific scalar to its tree entry.
2750  SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2751 
2752  /// Maps a value to the proposed vectorizable size.
2753  SmallDenseMap<Value *, unsigned> InstrElementSize;
2754 
2755  /// A list of scalars that we found that we need to keep as scalars.
2756  ValueSet MustGather;
2757 
2758  /// A map between the vectorized entries and the last instructions in the
2759  /// bundles. The bundles are built in use order, not in the def order of the
2760  /// instructions. So, we cannot rely directly on the last instruction in the
2761  /// bundle being the last instruction in the program order during
2762  /// vectorization process since the basic blocks are affected, need to
2763  /// pre-gather them before.
2764  DenseMap<const TreeEntry *, Instruction *> EntryToLastInstruction;
2765 
2766  /// This POD struct describes one external user in the vectorized tree.
2767  struct ExternalUser {
2768  ExternalUser(Value *S, llvm::User *U, int L)
2769  : Scalar(S), User(U), Lane(L) {}
2770 
2771  // Which scalar in our function.
2772  Value *Scalar;
2773 
2774  // Which user that uses the scalar.
2775  llvm::User *User;
2776 
2777  // Which lane does the scalar belong to.
2778  int Lane;
2779  };
2780  using UserList = SmallVector<ExternalUser, 16>;
2781 
2782  /// Checks if two instructions may access the same memory.
2783  ///
2784  /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2785  /// is invariant in the calling loop.
2786  bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2787  Instruction *Inst2) {
2788  // First check if the result is already in the cache.
2789  AliasCacheKey key = std::make_pair(Inst1, Inst2);
2790  Optional<bool> &result = AliasCache[key];
2791  if (result) {
2792  return result.value();
2793  }
2794  bool aliased = true;
2795  if (Loc1.Ptr && isSimple(Inst1))
2796  aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2797  // Store the result in the cache.
2798  result = aliased;
2799  return aliased;
2800  }
2801 
2802  using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2803 
2804  /// Cache for alias results.
2805  /// TODO: consider moving this to the AliasAnalysis itself.
2807 
2808  // Cache for pointerMayBeCaptured calls inside AA. This is preserved
2809  // globally through SLP because we don't perform any action which
2810  // invalidates capture results.
2811  BatchAAResults BatchAA;
2812 
2813  /// Temporary store for deleted instructions. Instructions will be deleted
2814  /// eventually when the BoUpSLP is destructed. The deferral is required to
2815  /// ensure that there are no incorrect collisions in the AliasCache, which
2816  /// can happen if a new instruction is allocated at the same address as a
2817  /// previously deleted instruction.
2818  DenseSet<Instruction *> DeletedInstructions;
2819 
2820  /// Set of the instruction, being analyzed already for reductions.
2821  SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
2822 
2823  /// Set of hashes for the list of reduction values already being analyzed.
2824  DenseSet<size_t> AnalyzedReductionVals;
2825 
2826  /// A list of values that need to extracted out of the tree.
2827  /// This list holds pairs of (Internal Scalar : External User). External User
2828  /// can be nullptr, it means that this Internal Scalar will be used later,
2829  /// after vectorization.
2830  UserList ExternalUses;
2831 
2832  /// Values used only by @llvm.assume calls.
2834 
2835  /// Holds all of the instructions that we gathered, shuffle instructions and
2836  /// extractelements.
2837  SetVector<Instruction *> GatherShuffleExtractSeq;
2838 
2839  /// A list of blocks that we are going to CSE.
2840  SetVector<BasicBlock *> CSEBlocks;
2841 
2842  /// Contains all scheduling relevant data for an instruction.
2843  /// A ScheduleData either represents a single instruction or a member of an
2844  /// instruction bundle (= a group of instructions which is combined into a
2845  /// vector instruction).
2846  struct ScheduleData {
2847  // The initial value for the dependency counters. It means that the
2848  // dependencies are not calculated yet.
2849  enum { InvalidDeps = -1 };
2850 
2851  ScheduleData() = default;
2852 
2853  void init(int BlockSchedulingRegionID, Value *OpVal) {
2854  FirstInBundle = this;
2855  NextInBundle = nullptr;
2856  NextLoadStore = nullptr;
2857  IsScheduled = false;
2858  SchedulingRegionID = BlockSchedulingRegionID;
2859  clearDependencies();
2860  OpValue = OpVal;
2861  TE = nullptr;
2862  }
2863 
2864  /// Verify basic self consistency properties
2865  void verify() {
2866  if (hasValidDependencies()) {
2867  assert(UnscheduledDeps <= Dependencies && "invariant");
2868  } else {
2869  assert(UnscheduledDeps == Dependencies && "invariant");
2870  }
2871 
2872  if (IsScheduled) {
2873  assert(isSchedulingEntity() &&
2874  "unexpected scheduled state");
2875  for (const ScheduleData *BundleMember = this; BundleMember;
2876  BundleMember = BundleMember->NextInBundle) {
2877  assert(BundleMember->hasValidDependencies() &&
2878  BundleMember->UnscheduledDeps == 0 &&
2879  "unexpected scheduled state");
2880  assert((BundleMember == this || !BundleMember->IsScheduled) &&
2881  "only bundle is marked scheduled");
2882  }
2883  }
2884 
2885  assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2886  "all bundle members must be in same basic block");
2887  }
2888 
2889  /// Returns true if the dependency information has been calculated.
2890  /// Note that depenendency validity can vary between instructions within
2891  /// a single bundle.
2892  bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2893 
2894  /// Returns true for single instructions and for bundle representatives
2895  /// (= the head of a bundle).
2896  bool isSchedulingEntity() const { return FirstInBundle == this; }
2897 
2898  /// Returns true if it represents an instruction bundle and not only a
2899  /// single instruction.
2900  bool isPartOfBundle() const {
2901  return NextInBundle != nullptr || FirstInBundle != this || TE;
2902  }
2903 
2904  /// Returns true if it is ready for scheduling, i.e. it has no more
2905  /// unscheduled depending instructions/bundles.
2906  bool isReady() const {
2907  assert(isSchedulingEntity() &&
2908  "can't consider non-scheduling entity for ready list");
2909  return unscheduledDepsInBundle() == 0 && !IsScheduled;
2910  }
2911 
2912  /// Modifies the number of unscheduled dependencies for this instruction,
2913  /// and returns the number of remaining dependencies for the containing
2914  /// bundle.
2915  int incrementUnscheduledDeps(int Incr) {
2916  assert(hasValidDependencies() &&
2917  "increment of unscheduled deps would be meaningless");
2918  UnscheduledDeps += Incr;
2919  return FirstInBundle->unscheduledDepsInBundle();
2920  }
2921 
2922  /// Sets the number of unscheduled dependencies to the number of
2923  /// dependencies.
2924  void resetUnscheduledDeps() {
2925  UnscheduledDeps = Dependencies;
2926  }
2927 
2928  /// Clears all dependency information.
2929  void clearDependencies() {
2930  Dependencies = InvalidDeps;
2931  resetUnscheduledDeps();
2932  MemoryDependencies.clear();
2933  ControlDependencies.clear();
2934  }
2935 
2936  int unscheduledDepsInBundle() const {
2937  assert(isSchedulingEntity() && "only meaningful on the bundle");
2938  int Sum = 0;
2939  for (const ScheduleData *BundleMember = this; BundleMember;
2940  BundleMember = BundleMember->NextInBundle) {
2941  if (BundleMember->UnscheduledDeps == InvalidDeps)
2942  return InvalidDeps;
2943  Sum += BundleMember->UnscheduledDeps;
2944  }
2945  return Sum;
2946  }
2947 
2948  void dump(raw_ostream &os) const {
2949  if (!isSchedulingEntity()) {
2950  os << "/ " << *Inst;
2951  } else if (NextInBundle) {
2952  os << '[' << *Inst;
2953  ScheduleData *SD = NextInBundle;
2954  while (SD) {
2955  os << ';' << *SD->Inst;
2956  SD = SD->NextInBundle;
2957  }
2958  os << ']';
2959  } else {
2960  os << *Inst;
2961  }
2962  }
2963 
2964  Instruction *Inst = nullptr;
2965 
2966  /// Opcode of the current instruction in the schedule data.
2967  Value *OpValue = nullptr;
2968 
2969  /// The TreeEntry that this instruction corresponds to.
2970  TreeEntry *TE = nullptr;
2971 
2972  /// Points to the head in an instruction bundle (and always to this for
2973  /// single instructions).
2974  ScheduleData *FirstInBundle = nullptr;
2975 
2976  /// Single linked list of all instructions in a bundle. Null if it is a
2977  /// single instruction.
2978  ScheduleData *NextInBundle = nullptr;
2979 
2980  /// Single linked list of all memory instructions (e.g. load, store, call)
2981  /// in the block - until the end of the scheduling region.
2982  ScheduleData *NextLoadStore = nullptr;
2983 
2984  /// The dependent memory instructions.
2985  /// This list is derived on demand in calculateDependencies().
2986  SmallVector<ScheduleData *, 4> MemoryDependencies;
2987 
2988  /// List of instructions which this instruction could be control dependent
2989  /// on. Allowing such nodes to be scheduled below this one could introduce
2990  /// a runtime fault which didn't exist in the original program.
2991  /// ex: this is a load or udiv following a readonly call which inf loops
2992  SmallVector<ScheduleData *, 4> ControlDependencies;
2993 
2994  /// This ScheduleData is in the current scheduling region if this matches
2995  /// the current SchedulingRegionID of BlockScheduling.
2996  int SchedulingRegionID = 0;
2997 
2998  /// Used for getting a "good" final ordering of instructions.
2999  int SchedulingPriority = 0;
3000 
3001  /// The number of dependencies. Constitutes of the number of users of the
3002  /// instruction plus the number of dependent memory instructions (if any).
3003  /// This value is calculated on demand.
3004  /// If InvalidDeps, the number of dependencies is not calculated yet.
3005  int Dependencies = InvalidDeps;
3006 
3007  /// The number of dependencies minus the number of dependencies of scheduled
3008  /// instructions. As soon as this is zero, the instruction/bundle gets ready
3009  /// for scheduling.
3010  /// Note that this is negative as long as Dependencies is not calculated.
3011  int UnscheduledDeps = InvalidDeps;
3012 
3013  /// True if this instruction is scheduled (or considered as scheduled in the
3014  /// dry-run).
3015  bool IsScheduled = false;
3016  };
3017 
3018 #ifndef NDEBUG
3019  friend inline raw_ostream &operator<<(raw_ostream &os,
3020  const BoUpSLP::ScheduleData &SD) {
3021  SD.dump(os);
3022  return os;
3023  }
3024 #endif
3025 
3026  friend struct GraphTraits<BoUpSLP *>;
3027  friend struct DOTGraphTraits<BoUpSLP *>;
3028 
3029  /// Contains all scheduling data for a basic block.
3030  /// It does not schedules instructions, which are not memory read/write
3031  /// instructions and their operands are either constants, or arguments, or
3032  /// phis, or instructions from others blocks, or their users are phis or from
3033  /// the other blocks. The resulting vector instructions can be placed at the
3034  /// beginning of the basic block without scheduling (if operands does not need
3035  /// to be scheduled) or at the end of the block (if users are outside of the
3036  /// block). It allows to save some compile time and memory used by the
3037  /// compiler.
3038  /// ScheduleData is assigned for each instruction in between the boundaries of
3039  /// the tree entry, even for those, which are not part of the graph. It is
3040  /// required to correctly follow the dependencies between the instructions and
3041  /// their correct scheduling. The ScheduleData is not allocated for the
3042  /// instructions, which do not require scheduling, like phis, nodes with
3043  /// extractelements/insertelements only or nodes with instructions, with
3044  /// uses/operands outside of the block.
3045  struct BlockScheduling {
3046  BlockScheduling(BasicBlock *BB)
3047  : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
3048 
3049  void clear() {
3050  ReadyInsts.clear();
3051  ScheduleStart = nullptr;
3052  ScheduleEnd = nullptr;
3053  FirstLoadStoreInRegion = nullptr;
3054  LastLoadStoreInRegion = nullptr;
3055  RegionHasStackSave = false;
3056 
3057  // Reduce the maximum schedule region size by the size of the
3058  // previous scheduling run.
3059  ScheduleRegionSizeLimit -= ScheduleRegionSize;
3060  if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
3061  ScheduleRegionSizeLimit = MinScheduleRegionSize;
3062  ScheduleRegionSize = 0;
3063 
3064  // Make a new scheduling region, i.e. all existing ScheduleData is not
3065  // in the new region yet.
3066  ++SchedulingRegionID;
3067  }
3068 
3069  ScheduleData *getScheduleData(Instruction *I) {
3070  if (BB != I->getParent())
3071  // Avoid lookup if can't possibly be in map.
3072  return nullptr;
3073  ScheduleData *SD = ScheduleDataMap.lookup(I);
3074  if (SD && isInSchedulingRegion(SD))
3075  return SD;
3076  return nullptr;
3077  }
3078 
3079  ScheduleData *getScheduleData(Value *V) {
3080  if (auto *I = dyn_cast<Instruction>(V))
3081  return getScheduleData(I);
3082  return nullptr;
3083  }
3084 
3085  ScheduleData *getScheduleData(Value *V, Value *Key) {
3086  if (V == Key)
3087  return getScheduleData(V);
3088  auto I = ExtraScheduleDataMap.find(V);
3089  if (I != ExtraScheduleDataMap.end()) {
3090  ScheduleData *SD = I->second.lookup(Key);
3091  if (SD && isInSchedulingRegion(SD))
3092  return SD;
3093  }
3094  return nullptr;
3095  }
3096 
3097  bool isInSchedulingRegion(ScheduleData *SD) const {
3098  return SD->SchedulingRegionID == SchedulingRegionID;
3099  }
3100 
3101  /// Marks an instruction as scheduled and puts all dependent ready
3102  /// instructions into the ready-list.
3103  template <typename ReadyListType>
3104  void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
3105  SD->IsScheduled = true;
3106  LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
3107 
3108  for (ScheduleData *BundleMember = SD; BundleMember;
3109  BundleMember = BundleMember->NextInBundle) {
3110  if (BundleMember->Inst != BundleMember->OpValue)
3111  continue;
3112 
3113  // Handle the def-use chain dependencies.
3114 
3115  // Decrement the unscheduled counter and insert to ready list if ready.
3116  auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
3117  doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
3118  if (OpDef && OpDef->hasValidDependencies() &&
3119  OpDef->incrementUnscheduledDeps(-1) == 0) {
3120  // There are no more unscheduled dependencies after
3121  // decrementing, so we can put the dependent instruction
3122  // into the ready list.
3123  ScheduleData *DepBundle = OpDef->FirstInBundle;
3124  assert(!DepBundle->IsScheduled &&
3125  "already scheduled bundle gets ready");
3126  ReadyList.insert(DepBundle);
3127  LLVM_DEBUG(dbgs()
3128  << "SLP: gets ready (def): " << *DepBundle << "\n");
3129  }
3130  });
3131  };
3132 
3133  // If BundleMember is a vector bundle, its operands may have been
3134  // reordered during buildTree(). We therefore need to get its operands
3135  // through the TreeEntry.
3136  if (TreeEntry *TE = BundleMember->TE) {
3137  // Need to search for the lane since the tree entry can be reordered.
3138  int Lane = std::distance(TE->Scalars.begin(),
3139  find(TE->Scalars, BundleMember->Inst));
3140  assert(Lane >= 0 && "Lane not set");
3141 
3142  // Since vectorization tree is being built recursively this assertion
3143  // ensures that the tree entry has all operands set before reaching
3144  // this code. Couple of exceptions known at the moment are extracts
3145  // where their second (immediate) operand is not added. Since
3146  // immediates do not affect scheduler behavior this is considered
3147  // okay.
3148  auto *In = BundleMember->Inst;
3149  assert(In &&
3150  (isa<ExtractValueInst, ExtractElementInst>(In) ||
3151  In->getNumOperands() == TE->getNumOperands()) &&
3152  "Missed TreeEntry operands?");
3153  (void)In; // fake use to avoid build failure when assertions disabled
3154 
3155  for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
3156  OpIdx != NumOperands; ++OpIdx)
3157  if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
3158  DecrUnsched(I);
3159  } else {
3160  // If BundleMember is a stand-alone instruction, no operand reordering
3161  // has taken place, so we directly access its operands.
3162  for (Use &U : BundleMember->Inst->operands())
3163  if (auto *I = dyn_cast<Instruction>(U.get()))
3164  DecrUnsched(I);
3165  }
3166  // Handle the memory dependencies.
3167  for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3168  if (MemoryDepSD->hasValidDependencies() &&
3169  MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3170  // There are no more unscheduled dependencies after decrementing,
3171  // so we can put the dependent instruction into the ready list.
3172  ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3173  assert(!DepBundle->IsScheduled &&
3174  "already scheduled bundle gets ready");
3175  ReadyList.insert(DepBundle);
3176  LLVM_DEBUG(dbgs()
3177  << "SLP: gets ready (mem): " << *DepBundle << "\n");
3178  }
3179  }
3180  // Handle the control dependencies.
3181  for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3182  if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3183  // There are no more unscheduled dependencies after decrementing,
3184  // so we can put the dependent instruction into the ready list.
3185  ScheduleData *DepBundle = DepSD->FirstInBundle;
3186  assert(!DepBundle->IsScheduled &&
3187  "already scheduled bundle gets ready");
3188  ReadyList.insert(DepBundle);
3189  LLVM_DEBUG(dbgs()
3190  << "SLP: gets ready (ctl): " << *DepBundle << "\n");
3191  }
3192  }
3193 
3194  }
3195  }
3196 
3197  /// Verify basic self consistency properties of the data structure.
3198  void verify() {
3199  if (!ScheduleStart)
3200  return;
3201 
3202  assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3203  ScheduleStart->comesBefore(ScheduleEnd) &&
3204  "Not a valid scheduling region?");
3205 
3206  for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3207  auto *SD = getScheduleData(I);
3208  if (!SD)
3209  continue;
3210  assert(isInSchedulingRegion(SD) &&
3211  "primary schedule data not in window?");
3212  assert(isInSchedulingRegion(SD->FirstInBundle) &&
3213  "entire bundle in window!");
3214  (void)SD;
3215  doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3216  }
3217 
3218  for (auto *SD : ReadyInsts) {
3219  assert(SD->isSchedulingEntity() && SD->isReady() &&
3220  "item in ready list not ready?");
3221  (void)SD;
3222  }
3223  }
3224 
3225  void doForAllOpcodes(Value *V,
3226  function_ref<void(ScheduleData *SD)> Action) {
3227  if (ScheduleData *SD = getScheduleData(V))
3228  Action(SD);
3229  auto I = ExtraScheduleDataMap.find(V);
3230  if (I != ExtraScheduleDataMap.end())
3231  for (auto &P : I->second)
3232  if (isInSchedulingRegion(P.second))
3233  Action(P.second);
3234  }
3235 
3236  /// Put all instructions into the ReadyList which are ready for scheduling.
3237  template <typename ReadyListType>
3238  void initialFillReadyList(ReadyListType &ReadyList) {
3239  for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3240  doForAllOpcodes(I, [&](ScheduleData *SD) {
3241  if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3242  SD->isReady()) {
3243  ReadyList.insert(SD);
3244  LLVM_DEBUG(dbgs()
3245  << "SLP: initially in ready list: " << *SD << "\n");
3246  }
3247  });
3248  }
3249  }
3250 
3251  /// Build a bundle from the ScheduleData nodes corresponding to the
3252  /// scalar instruction for each lane.
3253  ScheduleData *buildBundle(ArrayRef<Value *> VL);
3254 
3255  /// Checks if a bundle of instructions can be scheduled, i.e. has no
3256  /// cyclic dependencies. This is only a dry-run, no instructions are
3257  /// actually moved at this stage.
3258  /// \returns the scheduling bundle. The returned Optional value is non-None
3259  /// if \p VL is allowed to be scheduled.
3261  tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3262  const InstructionsState &S);
3263 
3264  /// Un-bundles a group of instructions.
3265  void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3266 
3267  /// Allocates schedule data chunk.
3268  ScheduleData *allocateScheduleDataChunks();
3269 
3270  /// Extends the scheduling region so that V is inside the region.
3271  /// \returns true if the region size is within the limit.
3272  bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3273 
3274  /// Initialize the ScheduleData structures for new instructions in the
3275  /// scheduling region.
3276  void initScheduleData(Instruction *FromI, Instruction *ToI,
3277  ScheduleData *PrevLoadStore,
3278  ScheduleData *NextLoadStore);
3279 
3280  /// Updates the dependency information of a bundle and of all instructions/
3281  /// bundles which depend on the original bundle.
3282  void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3283  BoUpSLP *SLP);
3284 
3285  /// Sets all instruction in the scheduling region to un-scheduled.
3286  void resetSchedule();
3287 
3288  BasicBlock *BB;
3289 
3290  /// Simple memory allocation for ScheduleData.
3291  std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3292 
3293  /// The size of a ScheduleData array in ScheduleDataChunks.
3294  int ChunkSize;
3295 
3296  /// The allocator position in the current chunk, which is the last entry
3297  /// of ScheduleDataChunks.
3298  int ChunkPos;
3299 
3300  /// Attaches ScheduleData to Instruction.
3301  /// Note that the mapping survives during all vectorization iterations, i.e.
3302  /// ScheduleData structures are recycled.
3304 
3305  /// Attaches ScheduleData to Instruction with the leading key.
3307  ExtraScheduleDataMap;
3308 
3309  /// The ready-list for scheduling (only used for the dry-run).
3310  SetVector<ScheduleData *> ReadyInsts;
3311 
3312  /// The first instruction of the scheduling region.
3313  Instruction *ScheduleStart = nullptr;
3314 
3315  /// The first instruction _after_ the scheduling region.
3316  Instruction *ScheduleEnd = nullptr;
3317 
3318  /// The first memory accessing instruction in the scheduling region
3319  /// (can be null).
3320  ScheduleData *FirstLoadStoreInRegion = nullptr;
3321 
3322  /// The last memory accessing instruction in the scheduling region
3323  /// (can be null).
3324  ScheduleData *LastLoadStoreInRegion = nullptr;
3325 
3326  /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3327  /// region? Used to optimize the dependence calculation for the
3328  /// common case where there isn't.
3329  bool RegionHasStackSave = false;
3330 
3331  /// The current size of the scheduling region.
3332  int ScheduleRegionSize = 0;
3333 
3334  /// The maximum size allowed for the scheduling region.
3335  int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3336 
3337  /// The ID of the scheduling region. For a new vectorization iteration this
3338  /// is incremented which "removes" all ScheduleData from the region.
3339  /// Make sure that the initial SchedulingRegionID is greater than the
3340  /// initial SchedulingRegionID in ScheduleData (which is 0).
3341  int SchedulingRegionID = 1;
3342  };
3343 
3344  /// Attaches the BlockScheduling structures to basic blocks.
3346 
3347  /// Performs the "real" scheduling. Done before vectorization is actually
3348  /// performed in a basic block.
3349  void scheduleBlock(BlockScheduling *BS);
3350 
3351  /// List of users to ignore during scheduling and that don't need extracting.
3352  const SmallDenseSet<Value *> *UserIgnoreList = nullptr;
3353 
3354  /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3355  /// sorted SmallVectors of unsigned.
3356  struct OrdersTypeDenseMapInfo {
3357  static OrdersType getEmptyKey() {
3358  OrdersType V;
3359  V.push_back(~1U);
3360  return V;
3361  }
3362 
3363  static OrdersType getTombstoneKey() {
3364  OrdersType V;
3365  V.push_back(~2U);
3366  return V;
3367  }
3368 
3369  static unsigned getHashValue(const OrdersType &V) {
3370  return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3371  }
3372 
3373  static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3374  return LHS == RHS;
3375  }
3376  };
3377 
3378  // Analysis and block reference.
3379  Function *F;
3380  ScalarEvolution *SE;
3382  TargetLibraryInfo *TLI;
3383  LoopInfo *LI;
3384  DominatorTree *DT;
3385  AssumptionCache *AC;
3386  DemandedBits *DB;
3387  const DataLayout *DL;
3389 
3390  unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3391  unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3392 
3393  /// Instruction builder to construct the vectorized tree.
3395 
3396  /// A map of scalar integer values to the smallest bit width with which they
3397  /// can legally be represented. The values map to (width, signed) pairs,
3398  /// where "width" indicates the minimum bit width and "signed" is True if the
3399  /// value must be signed-extended, rather than zero-extended, back to its
3400  /// original width.
3402 };
3403 
3404 } // end namespace slpvectorizer
3405 
3406 template <> struct GraphTraits<BoUpSLP *> {
3407  using TreeEntry = BoUpSLP::TreeEntry;
3408 
3409  /// NodeRef has to be a pointer per the GraphWriter.
3410  using NodeRef = TreeEntry *;
3411 
3412  using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3413 
3414  /// Add the VectorizableTree to the index iterator to be able to return
3415  /// TreeEntry pointers.
3416  struct ChildIteratorType
3417  : public iterator_adaptor_base<
3418  ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3420 
3422  ContainerTy &VT)
3423  : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3424 
3425  NodeRef operator*() { return I->UserTE; }
3426  };
3427 
3428  static NodeRef getEntryNode(BoUpSLP &R) {
3429  return R.VectorizableTree[0].get();
3430  }
3431 
3432  static ChildIteratorType child_begin(NodeRef N) {
3433  return {N->UserTreeIndices.begin(), N->Container};
3434  }
3435 
3436  static ChildIteratorType child_end(NodeRef N) {
3437  return {N->UserTreeIndices.end(), N->Container};
3438  }
3439 
3440  /// For the node iterator we just need to turn the TreeEntry iterator into a
3441  /// TreeEntry* iterator so that it dereferences to NodeRef.
3442  class nodes_iterator {
3443  using ItTy = ContainerTy::iterator;
3444  ItTy It;
3445 
3446  public:
3447  nodes_iterator(const ItTy &It2) : It(It2) {}
3448  NodeRef operator*() { return It->get(); }
3449  nodes_iterator operator++() {
3450  ++It;
3451  return *this;
3452  }
3453  bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3454  };
3455 
3456  static nodes_iterator nodes_begin(BoUpSLP *R) {
3457  return nodes_iterator(R->VectorizableTree.begin());
3458  }
3459 
3460  static nodes_iterator nodes_end(BoUpSLP *R) {
3461  return nodes_iterator(R->VectorizableTree.end());
3462  }
3463 
3464  static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3465 };
3466 
3467 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3468  using TreeEntry = BoUpSLP::TreeEntry;
3469 
3471 
3472  std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3473  std::string Str;
3474  raw_string_ostream OS(Str);
3475  if (isSplat(Entry->Scalars))
3476  OS << "<splat> ";
3477  for (auto *V : Entry->Scalars) {
3478  OS << *V;
3479  if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3480  return EU.Scalar == V;
3481  }))
3482  OS << " <extract>";
3483  OS << "\n";
3484  }
3485  return Str;
3486  }
3487 
3488  static std::string getNodeAttributes(const TreeEntry *Entry,
3489  const BoUpSLP *) {
3490  if (Entry->State == TreeEntry::NeedToGather)
3491  return "color=red";
3492  return "";
3493  }
3494 };
3495 
3496 } // end namespace llvm
3497 
3498 BoUpSLP::~BoUpSLP() {
3499  SmallVector<WeakTrackingVH> DeadInsts;
3500  for (auto *I : DeletedInstructions) {
3501  for (Use &U : I->operands()) {
3502  auto *Op = dyn_cast<Instruction>(U.get());
3503  if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3505  DeadInsts.emplace_back(Op);
3506  }
3507  I->dropAllReferences();
3508  }
3509  for (auto *I : DeletedInstructions) {
3510  assert(I->use_empty() &&
3511  "trying to erase instruction with users.");
3512  I->eraseFromParent();
3513  }
3514 
3515  // Cleanup any dead scalar code feeding the vectorized instructions
3517 
3518 #ifdef EXPENSIVE_CHECKS
3519  // If we could guarantee that this call is not extremely slow, we could
3520  // remove the ifdef limitation (see PR47712).
3521  assert(!verifyFunction(*F, &dbgs()));
3522 #endif
3523 }
3524 
3525 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3526 /// contains original mask for the scalars reused in the node. Procedure
3527 /// transform this mask in accordance with the given \p Mask.
3529  assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3530  "Expected non-empty mask.");
3531  SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3532  Prev.swap(Reuses);
3533  for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3534  if (Mask[I] != UndefMaskElem)
3535  Reuses[Mask[I]] = Prev[I];
3536 }
3537 
3538 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3539 /// the original order of the scalars. Procedure transforms the provided order
3540 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3541 /// identity order, \p Order is cleared.
3543  assert(!Mask.empty() && "Expected non-empty mask.");
3544  SmallVector<int> MaskOrder;
3545  if (Order.empty()) {
3546  MaskOrder.resize(Mask.size());
3547  std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3548  } else {
3549  inversePermutation(Order, MaskOrder);
3550  }
3551  reorderReuses(MaskOrder, Mask);
3552  if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3553  Order.clear();
3554  return;
3555  }
3556  Order.assign(Mask.size(), Mask.size());
3557  for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3558  if (MaskOrder[I] != UndefMaskElem)
3559  Order[MaskOrder[I]] = I;
3560  fixupOrderingIndices(Order);
3561 }
3562 
3564 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3565  assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3566  unsigned NumScalars = TE.Scalars.size();
3567  OrdersType CurrentOrder(NumScalars, NumScalars);
3568  SmallVector<int> Positions;
3569  SmallBitVector UsedPositions(NumScalars);
3570  const TreeEntry *STE = nullptr;
3571  // Try to find all gathered scalars that are gets vectorized in other
3572  // vectorize node. Here we can have only one single tree vector node to
3573  // correctly identify order of the gathered scalars.
3574  for (unsigned I = 0; I < NumScalars; ++I) {
3575  Value *V = TE.Scalars[I];
3576  if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3577  continue;
3578  if (const auto *LocalSTE = getTreeEntry(V)) {
3579  if (!STE)
3580  STE = LocalSTE;
3581  else if (STE != LocalSTE)
3582  // Take the order only from the single vector node.
3583  return None;
3584  unsigned Lane =
3585  std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3586  if (Lane >= NumScalars)
3587  return None;
3588  if (CurrentOrder[Lane] != NumScalars) {
3589  if (Lane != I)
3590  continue;
3591  UsedPositions.reset(CurrentOrder[Lane]);
3592  }
3593  // The partial identity (where only some elements of the gather node are
3594  // in the identity order) is good.
3595  CurrentOrder[Lane] = I;
3596  UsedPositions.set(I);
3597  }
3598  }
3599  // Need to keep the order if we have a vector entry and at least 2 scalars or
3600  // the vectorized entry has just 2 scalars.
3601  if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3602  auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3603  for (unsigned I = 0; I < NumScalars; ++I)
3604  if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3605  return false;
3606  return true;
3607  };
3608  if (IsIdentityOrder(CurrentOrder)) {
3609  CurrentOrder.clear();
3610  return CurrentOrder;
3611  }
3612  auto *It = CurrentOrder.begin();
3613  for (unsigned I = 0; I < NumScalars;) {
3614  if (UsedPositions.test(I)) {
3615  ++I;
3616  continue;
3617  }
3618  if (*It == NumScalars) {
3619  *It = I;
3620  ++I;
3621  }
3622  ++It;
3623  }
3624  return CurrentOrder;
3625  }
3626  return None;
3627 }
3628 
3629 namespace {
3630 /// Tracks the state we can represent the loads in the given sequence.
3631 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3632 } // anonymous namespace
3633 
3634 static bool arePointersCompatible(Value *Ptr1, Value *Ptr2,
3635  const TargetLibraryInfo &TLI,
3636  bool CompareOpcodes = true) {
3637  if (getUnderlyingObject(Ptr1) != getUnderlyingObject(Ptr2))
3638  return false;
3639  auto *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
3640  if (!GEP1)
3641  return false;
3642  auto *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
3643  if (!GEP2)
3644  return false;
3645  return GEP1->getNumOperands() == 2 && GEP2->getNumOperands() == 2 &&
3646  ((isConstant(GEP1->getOperand(1)) &&
3647  isConstant(GEP2->getOperand(1))) ||
3648  !CompareOpcodes ||
3649  getSameOpcode({GEP1->getOperand(1), GEP2->getOperand(1)}, TLI)
3650  .getOpcode());
3651 }
3652 
3653 /// Checks if the given array of loads can be represented as a vectorized,
3654 /// scatter or just simple gather.
3655 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3656  const TargetTransformInfo &TTI,
3657  const DataLayout &DL, ScalarEvolution &SE,
3658  LoopInfo &LI, const TargetLibraryInfo &TLI,
3660  SmallVectorImpl<Value *> &PointerOps) {
3661  // Check that a vectorized load would load the same memory as a scalar
3662  // load. For example, we don't want to vectorize loads that are smaller
3663  // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3664  // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3665  // from such a struct, we read/write packed bits disagreeing with the
3666  // unvectorized version.
3667  Type *ScalarTy = VL0->getType();
3668 
3669  if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3670  return LoadsState::Gather;
3671 
3672  // Make sure all loads in the bundle are simple - we can't vectorize
3673  // atomic or volatile loads.
3674  PointerOps.clear();
3675  PointerOps.resize(VL.size());
3676  auto *POIter = PointerOps.begin();
3677  for (Value *V : VL) {
3678  auto *L = cast<LoadInst>(V);
3679  if (!L->isSimple())
3680  return LoadsState::Gather;
3681  *POIter = L->getPointerOperand();
3682  ++POIter;
3683  }
3684 
3685  Order.clear();
3686  // Check the order of pointer operands or that all pointers are the same.
3687  bool IsSorted = sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order);
3688  if (IsSorted || all_of(PointerOps, [&](Value *P) {
3689  return arePointersCompatible(P, PointerOps.front(), TLI);
3690  })) {
3691  if (IsSorted) {
3692  Value *Ptr0;
3693  Value *PtrN;
3694  if (Order.empty()) {
3695  Ptr0 = PointerOps.front();
3696  PtrN = PointerOps.back();
3697  } else {
3698  Ptr0 = PointerOps[Order.front()];
3699  PtrN = PointerOps[Order.back()];
3700  }
3701  Optional<int> Diff =
3702  getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3703  // Check that the sorted loads are consecutive.
3704  if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3705  return LoadsState::Vectorize;
3706  }
3707  // TODO: need to improve analysis of the pointers, if not all of them are
3708  // GEPs or have > 2 operands, we end up with a gather node, which just
3709  // increases the cost.
3710  Loop *L = LI.getLoopFor(cast<LoadInst>(VL0)->getParent());
3711  bool ProfitableGatherPointers =
3712  static_cast<unsigned>(count_if(PointerOps, [L](Value *V) {
3713  return L && L->isLoopInvariant(V);
3714  })) <= VL.size() / 2 && VL.size() > 2;
3715  if (ProfitableGatherPointers || all_of(PointerOps, [IsSorted](Value *P) {
3716  auto *GEP = dyn_cast<GetElementPtrInst>(P);
3717  return (IsSorted && !GEP && doesNotNeedToBeScheduled(P)) ||
3718  (GEP && GEP->getNumOperands() == 2);
3719  })) {
3720  Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3721  for (Value *V : VL)
3722  CommonAlignment =
3723  std::min(CommonAlignment, cast<LoadInst>(V)->getAlign());
3724  auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
3725  if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) &&
3726  !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment))
3727  return LoadsState::ScatterVectorize;
3728  }
3729  }
3730 
3731  return LoadsState::Gather;
3732 }
3733 
3735  const DataLayout &DL, ScalarEvolution &SE,
3736  SmallVectorImpl<unsigned> &SortedIndices) {
3738  VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3739  "Expected list of pointer operands.");
3740  // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3741  // Ptr into, sort and return the sorted indices with values next to one
3742  // another.
3744  Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3745 
3746  unsigned Cnt = 1;
3747  for (Value *Ptr : VL.drop_front()) {
3748  bool Found = any_of(Bases, [&](auto &Base) {
3749  Optional<int> Diff =
3750  getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3751  /*StrictCheck=*/true);
3752  if (!Diff)
3753  return false;
3754 
3755  Base.second.emplace_back(Ptr, *Diff, Cnt++);
3756  return true;
3757  });
3758 
3759  if (!Found) {
3760  // If we haven't found enough to usefully cluster, return early.
3761  if (Bases.size() > VL.size() / 2 - 1)
3762  return false;
3763 
3764  // Not found already - add a new Base
3765  Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3766  }
3767  }
3768 
3769  // For each of the bases sort the pointers by Offset and check if any of the
3770  // base become consecutively allocated.
3771  bool AnyConsecutive = false;
3772  for (auto &Base : Bases) {
3773  auto &Vec = Base.second;
3774  if (Vec.size() > 1) {
3775  llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3776  const std::tuple<Value *, int, unsigned> &Y) {
3777  return std::get<1>(X) < std::get<1>(Y);
3778  });
3779  int InitialOffset = std::get<1>(Vec[0]);
3780  AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3781  return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3782  });
3783  }
3784  }
3785 
3786  // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3787  SortedIndices.clear();
3788  if (!AnyConsecutive)
3789  return false;
3790 
3791  for (auto &Base : Bases) {
3792  for (auto &T : Base.second)
3793  SortedIndices.push_back(std::get<2>(T));
3794  }
3795 
3796  assert(SortedIndices.size() == VL.size() &&
3797  "Expected SortedIndices to be the size of VL");
3798  return true;
3799 }
3800 
3802 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3803  assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3804  Type *ScalarTy = TE.Scalars[0]->getType();
3805 
3806  SmallVector<Value *> Ptrs;
3807  Ptrs.reserve(TE.Scalars.size());
3808  for (Value *V : TE.Scalars) {
3809  auto *L = dyn_cast<LoadInst>(V);
3810  if (!L || !L->isSimple())
3811  return None;
3812  Ptrs.push_back(L->getPointerOperand());
3813  }
3814 
3815  BoUpSLP::OrdersType Order;
3816  if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3817  return Order;
3818  return None;
3819 }
3820 
3821 /// Check if two insertelement instructions are from the same buildvector.
3824  function_ref<Value *(InsertElementInst *)> GetBaseOperand) {
3825  // Instructions must be from the same basic blocks.
3826  if (VU->getParent() != V->getParent())
3827  return false;
3828  // Checks if 2 insertelements are from the same buildvector.
3829  if (VU->getType() != V->getType())
3830  return false;
3831  // Multiple used inserts are separate nodes.
3832  if (!VU->hasOneUse() && !V->hasOneUse())
3833  return false;
3834  auto *IE1 = VU;
3835  auto *IE2 = V;
3836  Optional<unsigned> Idx1 = getInsertIndex(IE1);
3837  Optional<unsigned> Idx2 = getInsertIndex(IE2);
3838  if (Idx1 == None || Idx2 == None)
3839  return false;
3840  // Go through the vector operand of insertelement instructions trying to find
3841  // either VU as the original vector for IE2 or V as the original vector for
3842  // IE1.
3843  do {
3844  if (IE2 == VU)
3845  return VU->hasOneUse();
3846  if (IE1 == V)
3847  return V->hasOneUse();
3848  if (IE1) {
3849  if ((IE1 != VU && !IE1->hasOneUse()) ||
3850  getInsertIndex(IE1).value_or(*Idx2) == *Idx2)
3851  IE1 = nullptr;
3852  else
3853  IE1 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE1));
3854  }
3855  if (IE2) {
3856  if ((IE2 != V && !IE2->hasOneUse()) ||
3857  getInsertIndex(IE2).value_or(*Idx1) == *Idx1)
3858  IE2 = nullptr;
3859  else
3860  IE2 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE2));
3861  }
3862  } while (IE1 || IE2);
3863  return false;
3864 }
3865 
3866 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3867  bool TopToBottom) {
3868  // No need to reorder if need to shuffle reuses, still need to shuffle the
3869  // node.
3870  if (!TE.ReuseShuffleIndices.empty()) {
3871  // Check if reuse shuffle indices can be improved by reordering.
3872  // For this, check that reuse mask is "clustered", i.e. each scalar values
3873  // is used once in each submask of size <number_of_scalars>.
3874  // Example: 4 scalar values.
3875  // ReuseShuffleIndices mask: 0, 1, 2, 3, 3, 2, 0, 1 - clustered.
3876  // 0, 1, 2, 3, 3, 3, 1, 0 - not clustered, because
3877  // element 3 is used twice in the second submask.
3878  unsigned Sz = TE.Scalars.size();
3879  if (!ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
3880  Sz))
3881  return None;
3882  unsigned VF = TE.getVectorFactor();
3883  // Try build correct order for extractelement instructions.
3884  SmallVector<int> ReusedMask(TE.ReuseShuffleIndices.begin(),
3885  TE.ReuseShuffleIndices.end());
3886  if (TE.getOpcode() == Instruction::ExtractElement && !TE.isAltShuffle() &&
3887  all_of(TE.Scalars, [Sz](Value *V) {
3888  Optional<unsigned> Idx = getExtractIndex(cast<Instruction>(V));
3889  return Idx && *Idx < Sz;
3890  })) {
3891  SmallVector<int> ReorderMask(Sz, UndefMaskElem);
3892  if (TE.ReorderIndices.empty())
3893  std::iota(ReorderMask.begin(), ReorderMask.end(), 0);
3894  else
3895  inversePermutation(TE.ReorderIndices, ReorderMask);
3896  for (unsigned I = 0; I < VF; ++I) {
3897  int &Idx = ReusedMask[I];
3898  if (Idx == UndefMaskElem)
3899  continue;
3900  Value *V = TE.Scalars[ReorderMask[Idx]];
3901  Optional<unsigned> EI = getExtractIndex(cast<Instruction>(V));
3902  Idx = std::distance(ReorderMask.begin(), find(ReorderMask, *EI));
3903  }
3904  }
3905  // Build the order of the VF size, need to reorder reuses shuffles, they are
3906  // always of VF size.
3907  OrdersType ResOrder(VF);
3908  std::iota(ResOrder.begin(), ResOrder.end(), 0);
3909  auto *It = ResOrder.begin();
3910  for (unsigned K = 0; K < VF; K += Sz) {
3911  OrdersType CurrentOrder(TE.ReorderIndices);
3912  SmallVector<int> SubMask(makeArrayRef(ReusedMask).slice(K, Sz));
3913  if (SubMask.front() == UndefMaskElem)
3914  std::iota(SubMask.begin(), SubMask.end(), 0);
3915  reorderOrder(CurrentOrder, SubMask);
3916  transform(CurrentOrder, It, [K](unsigned Pos) { return Pos + K; });
3917  std::advance(It, Sz);
3918  }
3919  if (all_of(enumerate(ResOrder),
3920  [](const auto &Data) { return Data.index() == Data.value(); }))
3921  return {}; // Use identity order.
3922  return ResOrder;
3923  }
3924  if (TE.State == TreeEntry::Vectorize &&
3925  (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3926  (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3927  !TE.isAltShuffle())
3928  return TE.ReorderIndices;
3929  if (TE.State == TreeEntry::Vectorize && TE.getOpcode() == Instruction::PHI) {
3930  auto PHICompare = [](llvm::Value *V1, llvm::Value *V2) {
3931  if (!V1->hasOneUse() || !V2->hasOneUse())
3932  return false;
3933  auto *FirstUserOfPhi1 = cast<Instruction>(*V1->user_begin());
3934  auto *FirstUserOfPhi2 = cast<Instruction>(*V2->user_begin());
3935  if (auto *IE1 = dyn_cast<InsertElementInst>(FirstUserOfPhi1))
3936  if (auto *IE2 = dyn_cast<InsertElementInst>(FirstUserOfPhi2)) {
3938  IE1, IE2,
3939  [](InsertElementInst *II) { return II->getOperand(0); }))
3940  return false;
3941  Optional<unsigned> Idx1 = getInsertIndex(IE1);
3942  Optional<unsigned> Idx2 = getInsertIndex(IE2);
3943  if (Idx1 == None || Idx2 == None)
3944  return false;
3945  return *Idx1 < *Idx2;
3946  }
3947  if (auto *EE1 = dyn_cast<ExtractElementInst>(FirstUserOfPhi1))
3948  if (auto *EE2 = dyn_cast<ExtractElementInst>(FirstUserOfPhi2)) {
3949  if (EE1->getOperand(0) != EE2->getOperand(0))
3950  return false;
3951  Optional<unsigned> Idx1 = getExtractIndex(EE1);
3952  Optional<unsigned> Idx2 = getExtractIndex(EE2);
3953  if (Idx1 == None || Idx2 == None)
3954  return false;
3955  return *Idx1 < *Idx2;
3956  }
3957  return false;
3958  };
3959  auto IsIdentityOrder = [](const OrdersType &Order) {
3960  for (unsigned Idx : seq<unsigned>(0, Order.size()))
3961  if (Idx != Order[Idx])
3962  return false;
3963  return true;
3964  };
3965  if (!TE.ReorderIndices.empty())
3966  return TE.ReorderIndices;
3969  OrdersType ResOrder(TE.Scalars.size());
3970  for (unsigned Id = 0, Sz = TE.Scalars.size(); Id < Sz; ++Id) {
3971  PhiToId[TE.Scalars[Id]] = Id;
3972  Phis.push_back(TE.Scalars[Id]);
3973  }
3974  llvm::stable_sort(Phis, PHICompare);
3975  for (unsigned Id = 0, Sz = Phis.size(); Id < Sz; ++Id)
3976  ResOrder[Id] = PhiToId[Phis[Id]];
3977  if (IsIdentityOrder(ResOrder))
3978  return {};
3979  return ResOrder;
3980  }
3981  if (TE.State == TreeEntry::NeedToGather) {
3982  // TODO: add analysis of other gather nodes with extractelement
3983  // instructions and other values/instructions, not only undefs.
3984  if (((TE.getOpcode() == Instruction::ExtractElement &&
3985  !TE.isAltShuffle()) ||
3986  (all_of(TE.Scalars,
3987  [](Value *V) {
3988  return isa<UndefValue, ExtractElementInst>(V);
3989  }) &&
3990  any_of(TE.Scalars,
3991  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3992  all_of(TE.Scalars,
3993  [](Value *V) {
3994  auto *EE = dyn_cast<ExtractElementInst>(V);
3995  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3996  }) &&
3997  allSameType(TE.Scalars)) {
3998  // Check that gather of extractelements can be represented as
3999  // just a shuffle of a single vector.
4000  OrdersType CurrentOrder;
4001  bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
4002  if (Reuse || !CurrentOrder.empty()) {
4003  if (!CurrentOrder.empty())
4004  fixupOrderingIndices(CurrentOrder);
4005  return CurrentOrder;
4006  }
4007  }
4008  if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
4009  return CurrentOrder;
4010  if (TE.Scalars.size() >= 4)
4011  if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
4012  return Order;
4013  }
4014  return None;
4015 }
4016 
4017 /// Checks if the given mask is a "clustered" mask with the same clusters of
4018 /// size \p Sz, which are not identity submasks.
4020  unsigned Sz) {
4021  ArrayRef<int> FirstCluster = Mask.slice(0, Sz);
4022  if (ShuffleVectorInst::isIdentityMask(FirstCluster))
4023  return false;
4024  for (unsigned I = Sz, E = Mask.size(); I < E; I += Sz) {
4025  ArrayRef<int> Cluster = Mask.slice(I, Sz);
4026  if (Cluster != FirstCluster)
4027  return false;
4028  }
4029  return true;
4030 }
4031 
4032 void BoUpSLP::reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const {
4033  // Reorder reuses mask.
4034  reorderReuses(TE.ReuseShuffleIndices, Mask);
4035  const unsigned Sz = TE.Scalars.size();
4036  // For vectorized and non-clustered reused no need to do anything else.
4037  if (TE.State != TreeEntry::NeedToGather ||
4038  !ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
4039  Sz) ||
4040  !isRepeatedNonIdentityClusteredMask(TE.ReuseShuffleIndices, Sz))
4041  return;
4042  SmallVector<int> NewMask;
4043  inversePermutation(TE.ReorderIndices, NewMask);
4044  addMask(NewMask, TE.ReuseShuffleIndices);
4045  // Clear reorder since it is going to be applied to the new mask.
4046  TE.ReorderIndices.clear();
4047  // Try to improve gathered nodes with clustered reuses, if possible.
4048  reorderScalars(TE.Scalars, makeArrayRef(NewMask).slice(0, Sz));
4049  // Fill the reuses mask with the identity submasks.
4050  for (auto *It = TE.ReuseShuffleIndices.begin(),
4051  *End = TE.ReuseShuffleIndices.end();
4052  It != End; std::advance(It, Sz))
4053  std::iota(It, std::next(It, Sz), 0);
4054 }
4055 
4056 void BoUpSLP::reorderTopToBottom() {
4057  // Maps VF to the graph nodes.
4058  DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
4059  // ExtractElement gather nodes which can be vectorized and need to handle
4060  // their ordering.
4062 
4063  // Phi nodes can have preferred ordering based on their result users
4065 
4066  // AltShuffles can also have a preferred ordering that leads to fewer
4067  // instructions, e.g., the addsub instruction in x86.
4068  DenseMap<const TreeEntry *, OrdersType> AltShufflesToOrders;
4069 
4070  // Maps a TreeEntry to the reorder indices of external users.
4072  ExternalUserReorderMap;
4073  // FIXME: Workaround for syntax error reported by MSVC buildbots.
4074  TargetTransformInfo &TTIRef = *TTI;
4075  // Find all reorderable nodes with the given VF.
4076  // Currently the are vectorized stores,loads,extracts + some gathering of
4077  // extracts.
4078  for_each(VectorizableTree, [this, &TTIRef, &VFToOrderedEntries,
4079  &GathersToOrders, &ExternalUserReorderMap,
4080  &AltShufflesToOrders, &PhisToOrders](
4081  const std::unique_ptr<TreeEntry> &TE) {
4082  // Look for external users that will probably be vectorized.
4083  SmallVector<OrdersType, 1> ExternalUserReorderIndices =
4084  findExternalStoreUsersReorderIndices(TE.get());
4085  if (!ExternalUserReorderIndices.empty()) {
4086  VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4087  ExternalUserReorderMap.try_emplace(TE.get(),
4088  std::move(ExternalUserReorderIndices));
4089  }
4090 
4091  // Patterns like [fadd,fsub] can be combined into a single instruction in
4092  // x86. Reordering them into [fsub,fadd] blocks this pattern. So we need
4093  // to take into account their order when looking for the most used order.
4094  if (TE->isAltShuffle()) {
4095  VectorType *VecTy =
4096  FixedVectorType::get(TE->Scalars[0]->getType(), TE->Scalars.size());
4097  unsigned Opcode0 = TE->getOpcode();
4098  unsigned Opcode1 = TE->getAltOpcode();
4099  // The opcode mask selects between the two opcodes.
4100  SmallBitVector OpcodeMask(TE->Scalars.size(), false);
4101  for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size()))
4102  if (cast<Instruction>(TE->Scalars[Lane])->getOpcode() == Opcode1)
4103  OpcodeMask.set(Lane);
4104  // If this pattern is supported by the target then we consider the order.
4105  if (TTIRef.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask)) {
4106  VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4107  AltShufflesToOrders.try_emplace(TE.get(), OrdersType());
4108  }
4109  // TODO: Check the reverse order too.
4110  }
4111 
4112  if (Optional<OrdersType> CurrentOrder =
4113  getReorderingData(*TE, /*TopToBottom=*/true)) {
4114  // Do not include ordering for nodes used in the alt opcode vectorization,
4115  // better to reorder them during bottom-to-top stage. If follow the order
4116  // here, it causes reordering of the whole graph though actually it is
4117  // profitable just to reorder the subgraph that starts from the alternate
4118  // opcode vectorization node. Such nodes already end-up with the shuffle
4119  // instruction and it is just enough to change this shuffle rather than
4120  // rotate the scalars for the whole graph.
4121  unsigned Cnt = 0;
4122  const TreeEntry *UserTE = TE.get();
4123  while (UserTE && Cnt < RecursionMaxDepth) {
4124  if (UserTE->UserTreeIndices.size() != 1)
4125  break;
4126  if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
4127  return EI.UserTE->State == TreeEntry::Vectorize &&
4128  EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
4129  }))
4130  return;
4131  UserTE = UserTE->UserTreeIndices.back().UserTE;
4132  ++Cnt;
4133  }
4134  VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4135  if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty())
4136  GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
4137  if (TE->State == TreeEntry::Vectorize &&
4138  TE->getOpcode() == Instruction::PHI)
4139  PhisToOrders.try_emplace(TE.get(), *CurrentOrder);
4140  }
4141  });
4142 
4143  // Reorder the graph nodes according to their vectorization factor.
4144  for (unsigned VF = VectorizableTree.front()->getVectorFactor(); VF > 1;
4145  VF /= 2) {
4146  auto It = VFToOrderedEntries.find(VF);
4147  if (It == VFToOrderedEntries.end())
4148  continue;
4149  // Try to find the most profitable order. We just are looking for the most
4150  // used order and reorder scalar elements in the nodes according to this
4151  // mostly used order.
4152  ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
4153  // All operands are reordered and used only in this node - propagate the
4154  // most used order to the user node.
4155  MapVector<OrdersType, unsigned,
4157  OrdersUses;
4159  for (const TreeEntry *OpTE : OrderedEntries) {
4160  // No need to reorder this nodes, still need to extend and to use shuffle,
4161  // just need to merge reordering shuffle and the reuse shuffle.
4162  if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
4163  continue;
4164  // Count number of orders uses.
4165  const auto &Order = [OpTE, &GathersToOrders, &AltShufflesToOrders,
4166  &PhisToOrders]() -> const OrdersType & {
4167  if (OpTE->State == TreeEntry::NeedToGather ||
4168  !OpTE->ReuseShuffleIndices.empty()) {
4169  auto It = GathersToOrders.find(OpTE);
4170  if (It != GathersToOrders.end())
4171  return It->second;
4172  }
4173  if (OpTE->isAltShuffle()) {
4174  auto It = AltShufflesToOrders.find(OpTE);
4175  if (It != AltShufflesToOrders.end())
4176  return It->second;
4177  }
4178  if (OpTE->State == TreeEntry::Vectorize &&
4179  OpTE->getOpcode() == Instruction::PHI) {
4180  auto It = PhisToOrders.find(OpTE);
4181  if (It != PhisToOrders.end())
4182  return It->second;
4183  }
4184  return OpTE->ReorderIndices;
4185  }();
4186  // First consider the order of the external scalar users.
4187  auto It = ExternalUserReorderMap.find(OpTE);
4188  if (It != ExternalUserReorderMap.end()) {
4189  const auto &ExternalUserReorderIndices = It->second;
4190  // If the OpTE vector factor != number of scalars - use natural order,
4191  // it is an attempt to reorder node with reused scalars but with
4192  // external uses.
4193  if (OpTE->getVectorFactor() != OpTE->Scalars.size()) {
4194  OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
4195  ExternalUserReorderIndices.size();
4196  } else {
4197  for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
4198  ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
4199  }
4200  // No other useful reorder data in this entry.
4201  if (Order.empty())
4202  continue;
4203  }
4204  // Stores actually store the mask, not the order, need to invert.
4205  if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
4206  OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
4208  inversePermutation(Order, Mask);
4209  unsigned E = Order.size();
4210  OrdersType CurrentOrder(E, E);
4211  transform(Mask, CurrentOrder.begin(), [E](int Idx) {
4212  return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
4213  });
4214  fixupOrderingIndices(CurrentOrder);
4215  ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
4216  } else {
4217  ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
4218  }
4219  }
4220  // Set order of the user node.
4221  if (OrdersUses.empty())
4222  continue;
4223  // Choose the most used order.
4224  ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
4225  unsigned Cnt = OrdersUses.front().second;
4226  for (const auto &Pair : drop_begin(OrdersUses)) {
4227  if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
4228  BestOrder = Pair.first;
4229  Cnt = Pair.second;
4230  }
4231  }
4232  // Set order of the user node.
4233  if (BestOrder.empty())
4234  continue;
4236  inversePermutation(BestOrder, Mask);
4237  SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4238  unsigned E = BestOrder.size();
4239  transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4240  return I < E ? static_cast<int>(I) : UndefMaskElem;
4241  });
4242  // Do an actual reordering, if profitable.
4243  for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
4244  // Just do the reordering for the nodes with the given VF.
4245  if (TE->Scalars.size() != VF) {
4246  if (TE->ReuseShuffleIndices.size() == VF) {
4247  // Need to reorder the reuses masks of the operands with smaller VF to
4248  // be able to find the match between the graph nodes and scalar
4249  // operands of the given node during vectorization/cost estimation.
4250  assert(all_of(TE->UserTreeIndices,
4251  [VF, &TE](const EdgeInfo &EI) {
4252  return EI.UserTE->Scalars.size() == VF ||
4253  EI.UserTE->Scalars.size() ==
4254  TE->Scalars.size();
4255  }) &&
4256  "All users must be of VF size.");
4257  // Update ordering of the operands with the smaller VF than the given
4258  // one.
4259  reorderNodeWithReuses(*TE, Mask);
4260  }
4261  continue;
4262  }
4263  if (TE->State == TreeEntry::Vectorize &&
4265  InsertElementInst>(TE->getMainOp()) &&
4266  !TE->isAltShuffle()) {
4267  // Build correct orders for extract{element,value}, loads and
4268  // stores.
4269  reorderOrder(TE->ReorderIndices, Mask);
4270  if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
4271  TE->reorderOperands(Mask);
4272  } else {
4273  // Reorder the node and its operands.
4274  TE->reorderOperands(Mask);
4275  assert(TE->ReorderIndices.empty() &&
4276  "Expected empty reorder sequence.");
4277  reorderScalars(TE->Scalars, Mask);
4278  }
4279  if (!TE->ReuseShuffleIndices.empty()) {
4280  // Apply reversed order to keep the original ordering of the reused
4281  // elements to avoid extra reorder indices shuffling.
4282  OrdersType CurrentOrder;
4283  reorderOrder(CurrentOrder, MaskOrder);
4284  SmallVector<int> NewReuses;
4285  inversePermutation(CurrentOrder, NewReuses);
4286  addMask(NewReuses, TE->ReuseShuffleIndices);
4287  TE->ReuseShuffleIndices.swap(NewReuses);
4288  }
4289  }
4290  }
4291 }
4292 
4293 bool BoUpSLP::canReorderOperands(
4294  TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
4295  ArrayRef<TreeEntry *> ReorderableGathers,
4296  SmallVectorImpl<TreeEntry *> &GatherOps) {
4297  for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
4298  if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
4299  return OpData.first == I &&
4300  OpData.second->State == TreeEntry::Vectorize;
4301  }))
4302  continue;
4303  if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
4304  // Do not reorder if operand node is used by many user nodes.
4305  if (any_of(TE->UserTreeIndices,
4306  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
4307  return false;
4308  // Add the node to the list of the ordered nodes with the identity
4309  // order.
4310  Edges.emplace_back(I, TE);
4311  // Add ScatterVectorize nodes to the list of operands, where just
4312  // reordering of the scalars is required. Similar to the gathers, so
4313  // simply add to the list of gathered ops.
4314  // If there are reused scalars, process this node as a regular vectorize
4315  // node, just reorder reuses mask.
4316  if (TE->State != TreeEntry::Vectorize && TE->ReuseShuffleIndices.empty())
4317  GatherOps.push_back(TE);
4318  continue;
4319  }
4320  TreeEntry *Gather = nullptr;
4321  if (count_if(ReorderableGathers,
4322  [&Gather, UserTE, I](TreeEntry *TE) {
4323  assert(TE->State != TreeEntry::Vectorize &&
4324  "Only non-vectorized nodes are expected.");
4325  if (any_of(TE->UserTreeIndices,
4326  [UserTE, I](const EdgeInfo &EI) {
4327  return EI.UserTE == UserTE && EI.EdgeIdx == I;
4328  })) {
4329  assert(TE->isSame(UserTE->getOperand(I)) &&
4330  "Operand entry does not match operands.");
4331  Gather = TE;
4332  return true;
4333  }
4334  return false;
4335  }) > 1 &&
4336  !all_of(UserTE->getOperand(I), isConstant))
4337  return false;
4338  if (Gather)
4339  GatherOps.push_back(Gather);
4340  }
4341  return true;
4342 }
4343 
4344 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
4345  SetVector<TreeEntry *> OrderedEntries;
4347  // Find all reorderable leaf nodes with the given VF.
4348  // Currently the are vectorized loads,extracts without alternate operands +
4349  // some gathering of extracts.
4350  SmallVector<TreeEntry *> NonVectorized;
4351  for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
4352  &NonVectorized](
4353  const std::unique_ptr<TreeEntry> &TE) {
4354  if (TE->State != TreeEntry::Vectorize)
4355  NonVectorized.push_back(TE.get());
4356  if (Optional<OrdersType> CurrentOrder =
4357  getReorderingData(*TE, /*TopToBottom=*/false)) {
4358  OrderedEntries.insert(TE.get());
4359  if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty())
4360  GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
4361  }
4362  });
4363 
4364  // 1. Propagate order to the graph nodes, which use only reordered nodes.
4365  // I.e., if the node has operands, that are reordered, try to make at least
4366  // one operand order in the natural order and reorder others + reorder the
4367  // user node itself.
4369  while (!OrderedEntries.empty()) {
4370  // 1. Filter out only reordered nodes.
4371  // 2. If the entry has multiple uses - skip it and jump to the next node.
4373  SmallVector<TreeEntry *> Filtered;
4374  for (TreeEntry *TE : OrderedEntries) {
4375  if (!(TE->State == TreeEntry::Vectorize ||
4376  (TE->State == TreeEntry::NeedToGather &&
4377  GathersToOrders.count(TE))) ||
4378  TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4379  !all_of(drop_begin(TE->UserTreeIndices),
4380  [TE](const EdgeInfo &EI) {
4381  return EI.UserTE == TE->UserTreeIndices.front().UserTE;
4382  }) ||
4383  !Visited.insert(TE).second) {
4384  Filtered.push_back(TE);
4385  continue;
4386  }
4387  // Build a map between user nodes and their operands order to speedup
4388  // search. The graph currently does not provide this dependency directly.
4389  for (EdgeInfo &EI : TE->UserTreeIndices) {
4390  TreeEntry *UserTE = EI.UserTE;
4391  auto It = Users.find(UserTE);
4392  if (It == Users.end())
4393  It = Users.insert({UserTE, {}}).first;
4394  It->second.emplace_back(EI.EdgeIdx, TE);
4395  }
4396  }
4397  // Erase filtered entries.
4398  for_each(Filtered,
4399  [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
4400  SmallVector<
4401  std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>>
4402  UsersVec(Users.begin(), Users.end());
4403  sort(UsersVec, [](const auto &Data1, const auto &Data2) {
4404  return Data1.first->Idx > Data2.first->Idx;
4405  });
4406  for (auto &Data : UsersVec) {
4407  // Check that operands are used only in the User node.
4408  SmallVector<TreeEntry *> GatherOps;
4409  if (!canReorderOperands(Data.first, Data.second, NonVectorized,
4410  GatherOps)) {
4411  for_each(Data.second,
4412  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4413  OrderedEntries.remove(Op.second);
4414  });
4415  continue;
4416  }
4417  // All operands are reordered and used only in this node - propagate the
4418  // most used order to the user node.
4419  MapVector<OrdersType, unsigned,
4421  OrdersUses;
4422  // Do the analysis for each tree entry only once, otherwise the order of
4423  // the same node my be considered several times, though might be not
4424  // profitable.
4426  SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
4427  for (const auto &Op : Data.second) {
4428  TreeEntry *OpTE = Op.second;
4429  if (!VisitedOps.insert(OpTE).second)
4430  continue;
4431  if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
4432  continue;
4433  const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
4434  if (OpTE->State == TreeEntry::NeedToGather ||
4435  !OpTE->ReuseShuffleIndices.empty())
4436  return GathersToOrders.find(OpTE)->second;
4437  return OpTE->ReorderIndices;
4438  }();
4439  unsigned NumOps = count_if(
4440  Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
4441  return P.second == OpTE;
4442  });
4443  // Stores actually store the mask, not the order, need to invert.
4444  if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
4445  OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
4447  inversePermutation(Order, Mask);
4448  unsigned E = Order.size();
4449  OrdersType CurrentOrder(E, E);
4450  transform(Mask, CurrentOrder.begin(), [E](int Idx) {
4451  return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
4452  });
4453  fixupOrderingIndices(CurrentOrder);
4454  OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
4455  NumOps;
4456  } else {
4457  OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
4458  }
4459  auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
4460  const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
4461  const TreeEntry *TE) {
4462  if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4463  (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
4464  (IgnoreReorder && TE->Idx == 0))
4465  return true;
4466  if (TE->State == TreeEntry::NeedToGather) {
4467  auto It = GathersToOrders.find(TE);
4468  if (It != GathersToOrders.end())
4469  return !It->second.empty();
4470  return true;
4471  }
4472  return false;
4473  };
4474  for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
4475  TreeEntry *UserTE = EI.UserTE;
4476  if (!VisitedUsers.insert(UserTE).second)
4477  continue;
4478  // May reorder user node if it requires reordering, has reused
4479  // scalars, is an alternate op vectorize node or its op nodes require
4480  // reordering.
4481  if (AllowsReordering(UserTE))
4482  continue;
4483  // Check if users allow reordering.
4484  // Currently look up just 1 level of operands to avoid increase of
4485  // the compile time.
4486  // Profitable to reorder if definitely more operands allow
4487  // reordering rather than those with natural order.
4489  if (static_cast<unsigned>(count_if(
4490  Ops, [UserTE, &AllowsReordering](
4491  const std::pair<unsigned, TreeEntry *> &Op) {
4492  return AllowsReordering(Op.second) &&
4493  all_of(Op.second->UserTreeIndices,
4494  [UserTE](const EdgeInfo &EI) {
4495  return EI.UserTE == UserTE;
4496  });
4497  })) <= Ops.size() / 2)
4498  ++Res.first->second;
4499  }
4500  }
4501  // If no orders - skip current nodes and jump to the next one, if any.
4502  if (OrdersUses.empty()) {
4503  for_each(Data.second,
4504  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4505  OrderedEntries.remove(Op.second);
4506  });
4507  continue;
4508  }
4509  // Choose the best order.
4510  ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
4511  unsigned Cnt = OrdersUses.front().second;
4512  for (const auto &Pair : drop_begin(OrdersUses)) {
4513  if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
4514  BestOrder = Pair.first;
4515  Cnt = Pair.second;
4516  }
4517  }
4518  // Set order of the user node (reordering of operands and user nodes).
4519  if (BestOrder.empty()) {
4520  for_each(Data.second,
4521  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4522  OrderedEntries.remove(Op.second);
4523  });
4524  continue;
4525  }
4526  // Erase operands from OrderedEntries list and adjust their orders.
4527  VisitedOps.clear();
4529  inversePermutation(BestOrder, Mask);
4530  SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4531  unsigned E = BestOrder.size();
4532  transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4533  return I < E ? static_cast<int>(I) : UndefMaskElem;
4534  });
4535  for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4536  TreeEntry *TE = Op.second;
4537  OrderedEntries.remove(TE);
4538  if (!VisitedOps.insert(TE).second)
4539  continue;
4540  if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4541  reorderNodeWithReuses(*TE, Mask);
4542  continue;
4543  }
4544  // Gathers are processed separately.
4545  if (TE->State != TreeEntry::Vectorize)
4546  continue;
4547  assert((BestOrder.size() == TE->ReorderIndices.size() ||
4548  TE->ReorderIndices.empty()) &&
4549  "Non-matching sizes of user/operand entries.");
4550  reorderOrder(TE->ReorderIndices, Mask);
4551  if (IgnoreReorder && TE == VectorizableTree.front().get())
4552  IgnoreReorder = false;
4553  }
4554  // For gathers just need to reorder its scalars.
4555  for (TreeEntry *Gather : GatherOps) {
4556  assert(Gather->ReorderIndices.empty() &&
4557  "Unexpected reordering of gathers.");
4558  if (!Gather->ReuseShuffleIndices.empty()) {
4559  // Just reorder reuses indices.
4560  reorderReuses(Gather->ReuseShuffleIndices, Mask);
4561  continue;
4562  }
4563  reorderScalars(Gather->Scalars, Mask);
4564  OrderedEntries.remove(Gather);
4565  }
4566  // Reorder operands of the user node and set the ordering for the user
4567  // node itself.
4568  if (Data.first->State != TreeEntry::Vectorize ||
4569  !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4570  Data.first->getMainOp()) ||
4571  Data.first->isAltShuffle())
4572  Data.first->reorderOperands(Mask);
4573  if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4574  Data.first->isAltShuffle()) {
4575  reorderScalars(Data.first->Scalars, Mask);
4576  reorderOrder(Data.first->ReorderIndices, MaskOrder);
4577  if (Data.first->ReuseShuffleIndices.empty() &&
4578  !Data.first->ReorderIndices.empty() &&
4579  !Data.first->isAltShuffle()) {
4580  // Insert user node to the list to try to sink reordering deeper in
4581  // the graph.
4582  OrderedEntries.insert(Data.first);
4583  }
4584  } else {
4585  reorderOrder(Data.first->ReorderIndices, Mask);
4586  }
4587  }
4588  }
4589  // If the reordering is unnecessary, just remove the reorder.
4590  if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4591  VectorizableTree.front()->ReuseShuffleIndices.empty())
4592  VectorizableTree.front()->ReorderIndices.clear();
4593 }
4594 
4595 void BoUpSLP::buildExternalUses(
4596  const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4597  // Collect the values that we need to extract from the tree.
4598  for (auto &TEPtr : VectorizableTree) {
4599  TreeEntry *Entry = TEPtr.get();
4600 
4601  // No need to handle users of gathered values.
4602  if (Entry->State == TreeEntry::NeedToGather)
4603  continue;
4604 
4605  // For each lane:
4606  for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4607  Value *Scalar = Entry->Scalars[Lane];
4608  int FoundLane = Entry->findLaneForValue(Scalar);
4609 
4610  // Check if the scalar is externally used as an extra arg.
4611  auto ExtI = ExternallyUsedValues.find(Scalar);
4612  if (ExtI != ExternallyUsedValues.end()) {
4613  LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4614  << Lane << " from " << *Scalar << ".\n");
4615  ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4616  }
4617  for (User *U : Scalar->users()) {
4618  LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4619 
4620  Instruction *UserInst = dyn_cast<Instruction>(U);
4621  if (!UserInst)
4622  continue;
4623 
4624  if (isDeleted(UserInst))
4625  continue;
4626 
4627  // Skip in-tree scalars that become vectors
4628  if (TreeEntry *UseEntry = getTreeEntry(U)) {
4629  Value *UseScalar = UseEntry->Scalars[0];
4630  // Some in-tree scalars will remain as scalar in vectorized
4631  // instructions. If that is the case, the one in Lane 0 will
4632  // be used.
4633  if (UseScalar != U ||
4634  UseEntry->State == TreeEntry::ScatterVectorize ||
4635  !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4636  LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4637  << ".\n");
4638  assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4639  continue;
4640  }
4641  }
4642 
4643  // Ignore users in the user ignore list.
4644  if (UserIgnoreList && UserIgnoreList->contains(UserInst))
4645  continue;
4646 
4647  LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4648  << Lane << " from " << *Scalar << ".\n");
4649  ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4650  }
4651  }
4652  }
4653 }
4654 
4656 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4658  for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4659  Value *V = TE->Scalars[Lane];
4660  // To save compilation time we don't visit if we have too many users.
4661  static constexpr unsigned UsersLimit = 4;
4662  if (V->hasNUsesOrMore(UsersLimit))
4663  break;
4664 
4665  // Collect stores per pointer object.
4666  for (User *U : V->users()) {
4667  auto *SI = dyn_cast<StoreInst>(U);
4668  if (SI == nullptr || !SI->isSimple() ||
4669  !isValidElementType(SI->getValueOperand()->getType()))
4670  continue;
4671  // Skip entry if already
4672  if (getTreeEntry(U))
4673  continue;
4674 
4675  Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4676  auto &StoresVec = PtrToStoresMap[Ptr];
4677  // For now just keep one store per pointer object per lane.
4678  // TODO: Extend this to support multiple stores per pointer per lane
4679  if (StoresVec.size() > Lane)
4680  continue;
4681  // Skip if in different BBs.
4682  if (!StoresVec.empty() &&
4683  SI->getParent() != StoresVec.back()->getParent())
4684  continue;
4685  // Make sure that the stores are of the same type.
4686  if (!StoresVec.empty() &&
4687  SI->getValueOperand()->getType() !=
4688  StoresVec.back()->getValueOperand()->getType())
4689  continue;
4690  StoresVec.push_back(SI);
4691  }
4692  }
4693  return PtrToStoresMap;
4694 }
4695 
4696 bool BoUpSLP::canFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4697  OrdersType &ReorderIndices) const {
4698  // We check whether the stores in StoreVec can form a vector by sorting them
4699  // and checking whether they are consecutive.
4700 
4701  // To avoid calling getPointersDiff() while sorting we create a vector of
4702  // pairs {store, offset from first} and sort this instead.
4703  SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4704  StoreInst *S0 = StoresVec[0];
4705  StoreOffsetVec[0] = {S0, 0};
4706  Type *S0Ty = S0->getValueOperand()->getType();
4707  Value *S0Ptr = S0->getPointerOperand();
4708  for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4709  StoreInst *SI = StoresVec[Idx];
4710  Optional<int> Diff =
4711  getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4712  SI->getPointerOperand(), *DL, *SE,
4713  /*StrictCheck=*/true);
4714  // We failed to compare the pointers so just abandon this StoresVec.
4715  if (!Diff)
4716  return false;
4717  StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4718  }
4719 
4720  // Sort the vector based on the pointers. We create a copy because we may
4721  // need the original later for calculating the reorder (shuffle) indices.
4722  stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4723  const std::pair<StoreInst *, int> &Pair2) {
4724  int Offset1 = Pair1.second;
4725  int Offset2 = Pair2.second;
4726  return Offset1 < Offset2;
4727  });
4728 
4729  // Check if the stores are consecutive by checking if their difference is 1.
4730  for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
4731  if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
4732  return false;
4733 
4734  // Calculate the shuffle indices according to their offset against the sorted
4735  // StoreOffsetVec.
4736  ReorderIndices.reserve(StoresVec.size());
4737  for (StoreInst *SI : StoresVec) {
4738  unsigned Idx = find_if(StoreOffsetVec,
4739  [SI](const std::pair<StoreInst *, int> &Pair) {
4740  return Pair.first == SI;
4741  }) -
4742  StoreOffsetVec.begin();
4743  ReorderIndices.push_back(Idx);
4744  }
4745  // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4746  // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4747  // same convention here.
4748  auto IsIdentityOrder = [](const OrdersType &Order) {
4749  for (unsigned Idx : seq<unsigned>(0, Order.size()))
4750  if (Idx != Order[Idx])
4751  return false;
4752  return true;
4753  };
4754  if (IsIdentityOrder(ReorderIndices))
4755  ReorderIndices.clear();
4756 
4757  return true;
4758 }
4759 
4760 #ifndef NDEBUG
4761 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) {
4762  for (unsigned Idx : Order)
4763  dbgs() << Idx << ", ";
4764  dbgs() << "\n";
4765 }
4766 #endif
4767 
4769 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
4770  unsigned NumLanes = TE->Scalars.size();
4771 
4773  collectUserStores(TE);
4774 
4775  // Holds the reorder indices for each candidate store vector that is a user of
4776  // the current TreeEntry.
4777  SmallVector<OrdersType, 1> ExternalReorderIndices;
4778 
4779  // Now inspect the stores collected per pointer and look for vectorization
4780  // candidates. For each candidate calculate the reorder index vector and push
4781  // it into `ExternalReorderIndices`
4782  for (const auto &Pair : PtrToStoresMap) {
4783  auto &StoresVec = Pair.second;
4784  // If we have fewer than NumLanes stores, then we can't form a vector.
4785  if (StoresVec.size() != NumLanes)
4786  continue;
4787 
4788  // If the stores are not consecutive then abandon this StoresVec.
4789  OrdersType ReorderIndices;
4790  if (!canFormVector(StoresVec, ReorderIndices))
4791  continue;
4792 
4793  // We now know that the scalars in StoresVec can form a vector instruction,
4794  // so set the reorder indices.
4795  ExternalReorderIndices.push_back(ReorderIndices);
4796  }
4797  return ExternalReorderIndices;
4798 }
4799 
4800 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4801  const SmallDenseSet<Value *> &UserIgnoreLst) {
4802  deleteTree();
4803  UserIgnoreList = &UserIgnoreLst;
4804  if (!allSameType(Roots))
4805  return;
4806  buildTree_rec(Roots, 0, EdgeInfo());
4807 }
4808 
4809 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
4810  deleteTree();
4811  if (!allSameType(Roots))
4812  return;
4813  buildTree_rec(Roots, 0, EdgeInfo());
4814 }
4815 
4816 /// \return true if the specified list of values has only one instruction that
4817 /// requires scheduling, false otherwise.
4818 #ifndef NDEBUG
4820  Value *NeedsScheduling = nullptr;
4821  for (Value *V : VL) {
4822  if (doesNotNeedToBeScheduled(V))
4823  continue;
4824  if (!NeedsScheduling) {
4825  NeedsScheduling = V;
4826  continue;
4827  }
4828  return false;
4829  }
4830  return NeedsScheduling;
4831 }
4832 #endif
4833 
4834 /// Generates key/subkey pair for the given value to provide effective sorting
4835 /// of the values and better detection of the vectorizable values sequences. The
4836 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4837 /// and in values subgroups (subkeys).
4838 static std::pair<size_t, size_t> generateKeySubkey(
4839  Value *V, const TargetLibraryInfo *TLI,
4840  function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4841  bool AllowAlternate) {
4842  hash_code Key = hash_value(V->getValueID() + 2);
4843  hash_code SubKey = hash_value(0);
4844  // Sort the loads by the distance between the pointers.
4845  if (auto *LI = dyn_cast<LoadInst>(V)) {
4846  Key = hash_combine(LI->getType(), hash_value(Instruction::Load), Key);
4847  if (LI->isSimple())
4848  SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4849  else
4850  Key = SubKey = hash_value(LI);
4851  } else if (isVectorLikeInstWithConstOps(V)) {
4852  // Sort extracts by the vector operands.
4853  if (isa<ExtractElementInst, UndefValue>(V))
4854  Key = hash_value(Value::UndefValueVal + 1);
4855  if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4856  if (!isUndefVector(EI->getVectorOperand()).all() &&
4857  !isa<UndefValue>(EI->getIndexOperand()))
4858  SubKey = hash_value(EI->getVectorOperand());
4859  }
4860  } else if (auto *I = dyn_cast<Instruction>(V)) {
4861  // Sort other instructions just by the opcodes except for CMPInst.
4862  // For CMP also sort by the predicate kind.
4863  if ((isa<BinaryOperator, CastInst>(I)) &&
4864  isValidForAlternation(I->getOpcode())) {
4865  if (AllowAlternate)
4866  Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4867  else
4868  Key = hash_combine(hash_value(I->getOpcode()), Key);
4869  SubKey = hash_combine(
4870  hash_value(I->getOpcode()), hash_value(I->getType()),
4871  hash_value(isa<BinaryOperator>(I)
4872  ? I->getType()
4873  : cast<CastInst>(I)->getOperand(0)->getType()));
4874  // For casts, look through the only operand to improve compile time.
4875  if (isa<CastInst>(I)) {
4876  std::pair<size_t, size_t> OpVals =
4877  generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator,
4878  /*AllowAlternate=*/true);
4879  Key = hash_combine(OpVals.first, Key);
4880  SubKey = hash_combine(OpVals.first, SubKey);
4881  }
4882  } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4883  CmpInst::Predicate Pred = CI->getPredicate();
4884  if (CI->isCommutative())
4885  Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4887  SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4888  hash_value(SwapPred),
4889  hash_value(CI->getOperand(0)->getType()));
4890  } else if (auto *Call = dyn_cast<CallInst>(I)) {
4892  if (isTriviallyVectorizable(ID)) {
4893  SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4894  } else if (!VFDatabase(*Call).getMappings(*Call).empty()) {
4895  SubKey = hash_combine(hash_value(I->getOpcode()),
4896  hash_value(Call->getCalledFunction()));
4897  } else {
4898  Key = hash_combine(hash_value(Call), Key);
4899  SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4900  }
4901  for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4902  SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4903  hash_value(Op.Tag), SubKey);
4904  } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4905  if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4906  SubKey = hash_value(Gep->getPointerOperand());
4907  else
4908  SubKey = hash_value(Gep);
4909  } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4910  !isa<ConstantInt>(I->getOperand(1))) {
4911  // Do not try to vectorize instructions with potentially high cost.
4912  SubKey = hash_value(I);
4913  } else {
4914  SubKey = hash_value(I->getOpcode());
4915  }
4916  Key = hash_combine(hash_value(I->getParent()), Key);
4917  }
4918  return std::make_pair(Key, SubKey);
4919 }
4920 
4921 /// Checks if the specified instruction \p I is an alternate operation for
4922 /// the given \p MainOp and \p AltOp instructions.
4923 static bool isAlternateInstruction(const Instruction *I,
4924  const Instruction *MainOp,
4925  const Instruction *AltOp,
4926  const TargetLibraryInfo &TLI);
4927 
4928 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4929  const EdgeInfo &UserTreeIdx) {
4930  assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4931 
4932  SmallVector<int> ReuseShuffleIndicies;
4933  SmallVector<Value *> UniqueValues;
4934  auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4935  &UserTreeIdx,
4936  this](const InstructionsState &S) {
4937  // Check that every instruction appears once in this bundle.
4938  DenseMap<Value *, unsigned> UniquePositions(VL.size());
4939  for (Value *V : VL) {
4940  if (isConstant(V)) {
4941  ReuseShuffleIndicies.emplace_back(
4942  isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4943  UniqueValues.emplace_back(V);
4944  continue;
4945  }
4946  auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4947  ReuseShuffleIndicies.emplace_back(Res.first->second);
4948  if (Res.second)
4949  UniqueValues.emplace_back(V);
4950  }
4951  size_t NumUniqueScalarValues = UniqueValues.size();
4952  if (NumUniqueScalarValues == VL.size()) {
4953  ReuseShuffleIndicies.clear();
4954  } else {
4955  LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4956  if (NumUniqueScalarValues <= 1 ||
4957  (UniquePositions.size() == 1 && all_of(UniqueValues,
4958  [](Value *V) {
4959  return isa<UndefValue>(V) ||
4960  !isConstant(V);
4961  })) ||
4962  !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4963  LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4964  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4965  return false;
4966  }
4967  VL = UniqueValues;
4968  }
4969  return true;
4970  };
4971 
4972  InstructionsState S = getSameOpcode(VL, *TLI);
4973 
4974  // Gather if we hit the RecursionMaxDepth, unless this is a load (or z/sext of
4975  // a load), in which case peek through to include it in the tree, without
4976  // ballooning over-budget.
4977  if (Depth >= RecursionMaxDepth &&
4978  !(S.MainOp && isa<Instruction>(S.MainOp) && S.MainOp == S.AltOp &&
4979  VL.size() >= 4 &&
4980  (match(S.MainOp, m_Load(m_Value())) || all_of(VL, [&S](const Value *I) {
4981  return match(I,
4983  cast<Instruction>(I)->getOpcode() ==
4984  cast<Instruction>(S.MainOp)->getOpcode();
4985  })))) {
4986  LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4987  if (TryToFindDuplicates(S))
4988  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4989  ReuseShuffleIndicies);
4990  return;
4991  }
4992 
4993  // Don't handle scalable vectors
4994  if (S.getOpcode() == Instruction::ExtractElement &&
4995  isa<ScalableVectorType>(
4996  cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4997  LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4998  if (TryToFindDuplicates(S))
4999  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5000  ReuseShuffleIndicies);
5001  return;
5002  }
5003 
5004  // Don't handle vectors.
5005  if (S.OpValue->getType()->isVectorTy() &&
5006  !isa<InsertElementInst>(S.OpValue)) {
5007  LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
5008  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
5009  return;
5010  }
5011 
5012  if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
5013  if (SI->getValueOperand()->getType()->isVectorTy()) {
5014  LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
5015  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
5016  return;
5017  }
5018 
5019  // If all of the operands are identical or constant we have a simple solution.
5020  // If we deal with insert/extract instructions, they all must have constant
5021  // indices, otherwise we should gather them, not try to vectorize.
5022  // If alternate op node with 2 elements with gathered operands - do not
5023  // vectorize.
5024  auto &&NotProfitableForVectorization = [&S, this,
5025  Depth](ArrayRef<Value *> VL) {
5026  if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2)
5027  return false;
5028  if (VectorizableTree.size() < MinTreeSize)
5029  return false;
5030  if (Depth >= RecursionMaxDepth - 1)
5031  return true;
5032  // Check if all operands are extracts, part of vector node or can build a
5033  // regular vectorize node.
5034  SmallVector<unsigned, 2> InstsCount(VL.size(), 0);
5035  for (Value *V : VL) {
5036  auto *I = cast<Instruction>(V);
5037  InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) {
5038  return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op);
5039  }));
5040  }
5041  bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp);
5042  if ((IsCommutative &&
5043  std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) ||
5044  (!IsCommutative &&
5045  all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; })))
5046  return true;
5047  assert(VL.size() == 2 && "Expected only 2 alternate op instructions.");
5049  auto *I1 = cast<Instruction>(VL.front());
5050  auto *I2 = cast<Instruction>(VL.back());
5051  for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
5052  Candidates.emplace_back().emplace_back(I1->getOperand(Op),
5053  I2->getOperand(Op));
5054  if (static_cast<unsigned>(count_if(
5055  Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
5056  return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
5057  })) >= S.MainOp->getNumOperands() / 2)
5058  return false;
5059  if (S.MainOp->getNumOperands() > 2)
5060  return true;
5061  if (IsCommutative) {
5062  // Check permuted operands.
5063  Candidates.clear();
5064  for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
5065  Candidates.emplace_back().emplace_back(I1->getOperand(Op),
5066  I2->getOperand((Op + 1) % E));
5067  if (any_of(
5068  Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
5069  return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
5070  }))
5071  return false;
5072  }
5073  return true;
5074  };
5075  SmallVector<unsigned> SortedIndices;
5076  BasicBlock *BB = nullptr;
5077  bool IsScatterVectorizeUserTE =
5078  UserTreeIdx.UserTE &&
5079  UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize;
5080  bool AreAllSameInsts =
5081  (S.getOpcode() && allSameBlock(VL)) ||
5082  (S.OpValue->getType()->isPointerTy() && IsScatterVectorizeUserTE &&
5083  VL.size() > 2 &&
5084  all_of(VL,
5085  [&BB](Value *V) {
5086  auto *I = dyn_cast<GetElementPtrInst>(V);
5087  if (!I)
5088  return doesNotNeedToBeScheduled(V);
5089  if (!BB)
5090  BB = I->getParent();
5091  return BB == I->getParent() && I->getNumOperands() == 2;
5092  }) &&
5093  BB &&
5094  sortPtrAccesses(VL, UserTreeIdx.UserTE->getMainOp()->getType(), *DL, *SE,
5095  SortedIndices));
5096  if (!AreAllSameInsts || allConstant(VL) || isSplat(VL) ||
5097  (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(
5098  S.OpValue) &&
5100  NotProfitableForVectorization(VL)) {
5101  LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n");
5102  if (TryToFindDuplicates(S))
5103  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5104  ReuseShuffleIndicies);
5105  return;
5106  }
5107 
5108  // We now know that this is a vector of instructions of the same type from
5109  // the same block.
5110 
5111  // Don't vectorize ephemeral values.
5112  if (!EphValues.empty()) {
5113  for (Value *V : VL) {
5114  if (EphValues.count(V)) {
5115  LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
5116  << ") is ephemeral.\n");
5117  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
5118  return;
5119  }
5120  }
5121  }
5122 
5123  // Check if this is a duplicate of another entry.
5124  if (TreeEntry *E = getTreeEntry(S.OpValue)) {
5125  LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
5126  if (!E->isSame(VL)) {
5127  LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
5128  if (TryToFindDuplicates(S))
5129  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5130  ReuseShuffleIndicies);
5131  return;
5132  }
5133  // Record the reuse of the tree node. FIXME, currently this is only used to
5134  // properly draw the graph rather than for the actual vectorization.
5135  E->UserTreeIndices.push_back(UserTreeIdx);
5136  LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
5137  << ".\n");
5138  return;
5139  }
5140 
5141  // Check that none of the instructions in the bundle are already in the tree.
5142  for (Value *V : VL) {
5143  if (!IsScatterVectorizeUserTE && !isa<Instruction>(V))
5144  continue;
5145  if (getTreeEntry(V)) {
5146  LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
5147  << ") is already in tree.\n");
5148  if (TryToFindDuplicates(S))
5149  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5150  ReuseShuffleIndicies);
5151  return;
5152  }
5153  }
5154 
5155  // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
5156  if (UserIgnoreList && !UserIgnoreList->empty()) {
5157  for (Value *V : VL) {
5158  if (UserIgnoreList && UserIgnoreList->contains(V)) {
5159  LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
5160  if (TryToFindDuplicates(S))
5161  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5162  ReuseShuffleIndicies);
5163  return;
5164  }
5165  }
5166  }
5167 
5168  // Special processing for sorted pointers for ScatterVectorize node with
5169  // constant indeces only.
5170  if (AreAllSameInsts && UserTreeIdx.UserTE &&
5171  UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize &&
5172  !(S.getOpcode() && allSameBlock(VL))) {
5173  assert(S.OpValue->getType()->isPointerTy() &&
5174  count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >=
5175  2 &&
5176  "Expected pointers only.");
5177  // Reset S to make it GetElementPtr kind of node.
5178  const auto *It = find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); });
5179  assert(It != VL.end() && "Expected at least one GEP.");
5180  S = getSameOpcode(*It, *TLI);
5181  }
5182 
5183  // Check that all of the users of the scalars that we want to vectorize are
5184  // schedulable.
5185  auto *VL0 = cast<Instruction>(S.OpValue);
5186  BB = VL0->getParent();
5187 
5188  if (!DT->isReachableFromEntry(BB)) {
5189  // Don't go into unreachable blocks. They may contain instructions with
5190  // dependency cycles which confuse the final scheduling.
5191  LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
5192  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
5193  return;
5194  }
5195 
5196  // Don't go into catchswitch blocks, which can happen with PHIs.
5197  // Such blocks can only have PHIs and the catchswitch. There is no
5198  // place to insert a shuffle if we need to, so just avoid that issue.
5199  if (isa<CatchSwitchInst>(BB->getTerminator())) {
5200  LLVM_DEBUG(dbgs() << "SLP: bundle in catchswitch block.\n");
5201  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
5202  return;
5203  }
5204 
5205  // Check that every instruction appears once in this bundle.
5206  if (!TryToFindDuplicates(S))
5207  return;
5208 
5209  auto &BSRef = BlocksSchedules[BB];
5210  if (!BSRef)
5211  BSRef = std::make_unique<BlockScheduling>(BB);
5212 
5213  BlockScheduling &BS = *BSRef;
5214 
5215  Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
5216 #ifdef EXPENSIVE_CHECKS
5217  // Make sure we didn't break any internal invariants
5218  BS.verify();
5219 #endif
5220  if (!Bundle) {
5221  LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
5222  assert((!BS.getScheduleData(VL0) ||
5223  !BS.getScheduleData(VL0)->isPartOfBundle()) &&
5224  "tryScheduleBundle should cancelScheduling on failure");
5225  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5226  ReuseShuffleIndicies);
5227  return;
5228  }
5229  LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
5230 
5231  unsigned ShuffleOrOp = S.isAltShuffle() ?
5232  (unsigned) Instruction::ShuffleVector : S.getOpcode();
5233  switch (ShuffleOrOp) {
5234  case Instruction::PHI: {
5235  auto *PH = cast<PHINode>(VL0);
5236 
5237  // Check for terminator values (e.g. invoke).
5238  for (Value *V : VL)
5239  for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
5240  Instruction *Term = dyn_cast<Instruction>(Incoming);
5241  if (Term && Term->isTerminator()) {
5242  LLVM_DEBUG(dbgs()
5243  << "SLP: Need to swizzle PHINodes (terminator use).\n");
5244  BS.cancelScheduling(VL, VL0);
5245  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5246  ReuseShuffleIndicies);
5247  return;
5248  }
5249  }
5250 
5251  TreeEntry *TE =
5252  newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
5253  LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
5254 
5255  // Keeps the reordered operands to avoid code duplication.
5256  SmallVector<ValueList, 2> OperandsVec;
5257  for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
5258  if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
5259  ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
5260  TE->setOperand(I, Operands);
5261  OperandsVec.push_back(Operands);
5262  continue;
5263  }
5264  ValueList Operands;
5265  // Prepare the operand vector.
5266  for (Value *V : VL)
5267  Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
5268  PH->getIncomingBlock(I)));
5269  TE->setOperand(I, Operands);
5270  OperandsVec.push_back(Operands);
5271  }
5272  for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
5273  buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
5274  return;
5275  }
5276  case Instruction::ExtractValue:
5277  case Instruction::ExtractElement: {
5278  OrdersType CurrentOrder;
5279  bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
5280  if (Reuse) {
5281  LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
5282  newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5283  ReuseShuffleIndicies);
5284  // This is a special case, as it does not gather, but at the same time
5285  // we are not extending buildTree_rec() towards the operands.
5286  ValueList Op0;
5287  Op0.assign(VL.size(), VL0->getOperand(0));
5288  VectorizableTree.back()->setOperand(0, Op0);
5289  return;
5290  }
5291  if (!CurrentOrder.empty()) {
5292  LLVM_DEBUG({
5293  dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
5294  "with order";
5295  for (unsigned Idx : CurrentOrder)
5296  dbgs() << " " << Idx;
5297  dbgs() << "\n";
5298  });
5299  fixupOrderingIndices(CurrentOrder);
5300  // Insert new order with initial value 0, if it does not exist,
5301  // otherwise return the iterator to the existing one.
5302  newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5303  ReuseShuffleIndicies, CurrentOrder);
5304  // This is a special case, as it does not gather, but at the same time
5305  // we are not extending buildTree_rec() towards the operands.
5306  ValueList Op0;
5307  Op0.assign(VL.size(), VL0->getOperand(0));
5308  VectorizableTree.back()->setOperand(0, Op0);
5309  return;
5310  }
5311  LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
5312  newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5313  ReuseShuffleIndicies);
5314  BS.cancelScheduling(VL, VL0);
5315  return;