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