LLVM 24.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
27#include "VectorizeOptions.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/ScopeExit.h"
33#include "llvm/ADT/SetVector.h"
36#include "llvm/ADT/SmallSet.h"
39#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/iterator.h"
50#include "llvm/Analysis/Loads.h"
60#include "llvm/IR/Attributes.h"
61#include "llvm/IR/BasicBlock.h"
62#include "llvm/IR/CFG.h"
63#include "llvm/IR/Constant.h"
64#include "llvm/IR/Constants.h"
65#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/Dominators.h"
68#include "llvm/IR/Function.h"
69#include "llvm/IR/IRBuilder.h"
70#include "llvm/IR/InstrTypes.h"
71#include "llvm/IR/Instruction.h"
74#include "llvm/IR/Intrinsics.h"
75#include "llvm/IR/MDBuilder.h"
76#include "llvm/IR/Module.h"
77#include "llvm/IR/Operator.h"
80#include "llvm/IR/Type.h"
81#include "llvm/IR/Use.h"
82#include "llvm/IR/User.h"
83#include "llvm/IR/Value.h"
84#include "llvm/IR/ValueHandle.h"
86#ifdef EXPENSIVE_CHECKS
87#include "llvm/IR/Verifier.h"
88#endif
89#include "llvm/Pass.h"
93#include "llvm/Support/Debug.h"
106#include <algorithm>
107#include <cassert>
108#include <cstdint>
109#include <iterator>
110#include <map>
111#include <memory>
112#include <optional>
113#include <string>
114#include <tuple>
115#include <utility>
116
117using namespace llvm;
118using namespace llvm::PatternMatch;
119using namespace slpvectorizer;
120using namespace std::placeholders;
121
122#define SV_NAME "slp-vectorizer"
123#define DEBUG_TYPE "SLP"
124
125STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
126STATISTIC(NumStridedStoreChains, "Number of vectorized stride stores");
127STATISTIC(NumStoreChains, "Number of vector stores created");
128STATISTIC(NumVectorizedStores, "Number of vectorized stores");
129
130DEBUG_COUNTER(VectorizedGraphs, "slp-vectorized",
131 "Controls which SLP graphs should be vectorized.");
132
133// Limit the number of alias checks. The limit is chosen so that
134// it has no negative effect on the llvm benchmarks.
135static const unsigned AliasedCheckLimit = 10;
136
137// Another limit for the alias checks: The maximum distance between load/store
138// instructions where alias checks are done.
139// This limit is useful for very large basic blocks.
140static const unsigned MaxMemDepDistance = 160;
141
142/// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
143/// regions to be handled.
144static const int MinScheduleRegionSize = 16;
145
146/// If the reduction budget is exhausted, we allow small reduction trees to be
147/// handled.
148static const unsigned MinReductionTreeSize = 2048;
149
150/// Maximum allowed number of operands in the PHI nodes.
151static const unsigned MaxPHINumOperands = 128;
152
153namespace {
154/// A vectorized part of a split reduction, combined into the final reduction
155/// result by the horizontal reduction emitter.
156struct ReductionVectorPart {
157 /// The vectorized value, tracked in case it is replaced while other parts
158 /// are vectorized.
159 WeakTrackingVH Vec;
160 /// The number of times each lane is repeated in the reduction (emitted as a
161 /// multiplication by the scale for add/fadd reductions).
162 unsigned Scale = 1;
163 /// Signedness of \p Vec for reductions, operating on truncated types.
164 bool IsSigned = false;
165 /// True if the value was already reduced in-tree.
166 bool ReducedInTree = false;
167 /// True if the part contribution is subtracted from (rather than added to)
168 /// the final reduction result. Used for reassociated fadd reductions,
169 /// flattened through fsub/fneg operations.
170 bool Negated = false;
171};
172} // namespace
173
174namespace {
175class HorizontalReduction;
176} // namespace
177
178/// Bottom Up SLP Vectorizer.
180 class TreeEntry;
181 class ScheduleEntity;
182 class ScheduleData;
183 class ScheduleCopyableData;
184 class ScheduleBundle;
187
188public:
189 /// If we decide to generate strided load / store, this struct contains all
190 /// the necessary info. It's fields are calculated by analyzeRtStrideCandidate
191 /// and analyzeConstantStrideCandidate. Note that Stride can be given either
192 /// as a SCEV or as a Value if it already exists. To get the stride in bytes,
193 /// StrideVal (or value obtained from StrideSCEV) has to by multiplied by the
194 /// size of element of FixedVectorType.
196 Value *StrideVal = nullptr;
197 const SCEV *StrideSCEV = nullptr;
198 FixedVectorType *Ty = nullptr;
199 };
200
201 /// Tracks the state we can represent the loads in the given sequence.
210
217
218 const VectorizeOptions &Opts;
219
220 BoUpSLP(const VectorizeOptions &Opts, Function *Func, ScalarEvolution *Se,
223 DemandedBits *DB, const DataLayout *DL,
225 : Opts(Opts), AA(Aa), BatchAA(std::in_place, *Aa), F(Func), SE(Se),
226 TTI(Tti), TLI(TLi), LI(Li), DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE),
227 CostKind(getSLPCostKind(Func)),
228 Builder(Se->getModule(), TargetFolder(*DL)) {
229 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
230 // Use the vector register size specified by the target unless overridden
231 // by a command-line option.
232 // TODO: It would be better to limit the vectorization factor based on
233 // data type rather than just register size. For example, x86 AVX has
234 // 256-bit registers, but it does not support integer operations
235 // at that width (that requires AVX2).
236 MaxVecRegSize = Opts.slp_max_reg_size.value_or(
237 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
238 .getFixedValue());
239 MinVecRegSize =
240 Opts.slp_min_reg_size.value_or(TTI->getMinVectorRegisterBitWidth());
241 }
242
243 /// Vectorize the tree that starts with the elements in \p VL.
244 /// Returns the vectorized root.
246
247 /// Vectorize the tree but with the list of externally used values \p
248 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
249 /// generated extractvalue instructions.
250 Value *
251 vectorizeTree(const ExtraValueToDebugLocsMap &ExternallyUsedValues,
252 Instruction *ReductionRoot = nullptr,
253 ArrayRef<ReductionVectorPart> VectorValuesAndScales = {});
254
255 /// \returns the cost incurred by unwanted spills and fills, caused by
256 /// holding live values over call sites.
258
260
261 /// Calculates the cost of the subtrees, trims non-profitable ones and returns
262 /// final cost.
265 Instruction *RdxRoot = nullptr);
266
267 /// Finds i1 and/or nodes whose operand nodes are booleanized wide leaves
268 /// (one-use truncs of wide values or zero-tests of values from [0, 1]) and
269 /// registers them in MinBWs to be emitted in the wide leaf type.
271
272 /// \returns the vectorization cost of the subtree that starts at \p VL.
273 /// A negative number means that this is profitable.
275 ArrayRef<Value *> VectorizedVals = {},
276 InstructionCost ReductionCost = TTI::TCC_Free,
277 Instruction *RdxRoot = nullptr);
278
279 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
280 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
281 void buildTree(ArrayRef<Value *> Roots,
282 const SmallDenseSet<Value *> &UserIgnoreLst);
283
284 /// Construct a vectorizable tree that starts at \p Roots.
285 void buildTree(ArrayRef<Value *> Roots);
286
287 /// Sets the narrowed reduction chain instructions, dropped together with
288 /// the reduction.
290 NarrowedChainInsts.insert(Insts.begin(), Insts.end());
291 }
292
293 /// Returns true if the last buildTree() observed a may-alias memory
294 /// dependency between two distinct, range-checkable base objects, i.e. a
295 /// dependency that could be turned into a runtime alias check.
297 return HasRuntimeCheckableBlockers;
298 }
299
300 /// Records whether a may-alias dependency between distinct, range-checkable
301 /// base objects has been observed, so the caller can decide to retry with
302 /// runtime alias checks enabled.
304 HasRuntimeCheckableBlockers = V;
305 }
306
307 /// Returns true if the last buildTree() kept a may-alias memory dependency
308 /// that is not runtime-checkable (call or a non-simple mem access). Such a
309 /// dependency cannot be dropped, so a runtime-checks retry cannot unblock the
310 /// region and would be pure overhead.
311 bool hasNonCheckableMemBlocker() const { return HasNonCheckableMemBlocker; }
312
313 /// Records that a non-runtime-checkable may-alias dependency was kept.
314 void setHasNonCheckableMemBlocker(bool V) { HasNonCheckableMemBlocker = V; }
315
316 /// Returns true if the current vectorization attempt may drop
317 /// runtime-checkable may-alias dependencies and guard the region with
318 /// runtime alias checks.
319 bool isTryingRuntimeAliasChecks() const { return TryRuntimeAliasChecks; }
320
321 /// Enables or disables dropping runtime-checkable may-alias dependencies in
322 /// favor of runtime alias checks for the current vectorization attempt.
323 void setTryRuntimeAliasChecks(bool V) { TryRuntimeAliasChecks = V; }
324
325 /// Splits the stored values of the root stores into halves, vectorized as
326 /// separate subtrees, while the returned guard is alive.
328 return SaveAndRestore<bool>(SplitStoredValues, true);
329 }
330
331 /// Checks if the graph is built for the \p Stores and their stored values,
332 /// looking through the vectorized cast node, are vectorized as the alternate
333 /// node with the different opcodes in the halves.
335 if (VectorizableTree.empty() || getRootNode().isGather() ||
336 getRootNodeScalars() != Stores)
337 return false;
338 const TreeEntry *E = getOperandEntry(&getRootNode(), 0);
339 bool IsCast = E->State == TreeEntry::Vectorize && !E->isAltShuffle() &&
340 E->getMainOp()->isCast();
341 if (IsCast)
342 E = getOperandEntry(E, 0);
343 if (E->State != TreeEntry::Vectorize || !E->isAltShuffle())
344 return false;
345 auto GetOpcode = [&](Value *V) -> unsigned {
346 V = cast<StoreInst>(V)->getValueOperand();
347 if (auto *CI = dyn_cast<CastInst>(V); CI && IsCast)
348 V = CI->getOperand(0);
349 auto *I = dyn_cast<Instruction>(V);
350 return I ? I->getOpcode() : 0;
351 };
352 unsigned Opcode0 = GetOpcode(Stores.front());
353 unsigned Opcode1 = GetOpcode(Stores.back());
354 ArrayRef<Value *> Half = Stores.take_front(Stores.size() / 2);
355 return Opcode0 != Opcode1 &&
356 all_of(Half, [&](Value *V) { return GetOpcode(V) == Opcode0; }) &&
357 all_of(Stores.drop_front(Half.size()),
358 [&](Value *V) { return GetOpcode(V) == Opcode1; });
359 }
360
361 /// Resets the runtime alias check data.
363 HasRuntimeCheckableBlockers = false;
364 HasNonCheckableMemBlocker = false;
365 RTChecksFinalized = false;
366 RTChecks.clear();
367 RTOrigBodyOrder.clear();
368 }
369
370 /// Snapshots RTChecks.BB's body (non-PHI, non-alloca, non-terminator) into
371 /// RTOrigBodyOrder in program order, for the scalar fallback.
373
374 /// Returns true if \p BB satisfies the block-level preconditions for runtime
375 /// alias check versioning (straight-line, duplicable, not a scalar fallback,
376 /// function not optimized for size). These checks do not depend on the
377 /// collected checks, so they can gate the (expensive) optimistic retry before
378 /// any tree is rebuilt.
380
381 /// Returns true if the runtime alias checks can be safely emitted to guard
382 /// the vectorized region.
384
385 /// Returns true if \p BB is a scalar fallback block created by runtime alias
386 /// check versioning.
388 return ScalarFallbackBlocks.contains(BB);
389 }
390
391 /// Returns true if an optimistic runtime-checks versioning attempt already
392 /// failed for \p BB, so further retries in the same block can be skipped.
394 return FailedRuntimeChecksBlocks.contains(BB);
395 }
396
397 /// Records that an optimistic runtime-checks versioning attempt failed for
398 /// \p BB.
400 FailedRuntimeChecksBlocks.insert(BB);
401 }
402
403 /// Returns the modeled cost of the runtime alias checks collected during the
404 /// last (optimistic) buildTree().
406
407 /// Returns true if the last (optimistic) buildTree() collected any runtime
408 /// alias checks that must guard the vectorized region.
409 bool hasRuntimeAliasChecks() const { return !RTChecks.BasePairs.empty(); }
410
411 /// Returns true if vectorization changed the CFG (i.e. a block was versioned
412 /// with runtime alias checks). When true, CFG analyses must not be preserved.
413 bool isCFGChanged() const { return CFGChanged; }
414
415 TreeEntry &getRootNode() {
416 assert(!VectorizableTree.empty() && "No graph to get the first node from");
417 return *VectorizableTree.front();
418 }
419
420 const TreeEntry &getRootNode() const {
421 assert(!VectorizableTree.empty() && "No graph to get the first node from");
422 return *VectorizableTree.front();
423 }
424
425 /// Returns the scalars of the root node.
427
428 /// Returns the lane the given value is vectorized to in the root node.
429 unsigned findRootLaneForValue(Value *V) const {
430 return getRootNode().findLaneForValue(V);
431 }
432
433 /// Returns the type/is-signed info for the root node in the graph without
434 /// casting.
435 std::optional<std::pair<Type *, bool>> getRootNodeTypeWithNoCast() const {
436 const TreeEntry &Root = getRootNode();
437 if (Root.State != TreeEntry::Vectorize || Root.isAltShuffle() ||
438 !Root.Scalars.front()->getType()->isIntegerTy())
439 return std::nullopt;
440 auto It = MinBWs.find(&Root);
441 if (It != MinBWs.end())
442 return std::make_pair(IntegerType::get(Root.Scalars.front()->getContext(),
443 It->second.first),
444 It->second.second);
445 if (Root.getOpcode() == Instruction::ZExt ||
446 Root.getOpcode() == Instruction::SExt)
447 return std::make_pair(cast<CastInst>(Root.getMainOp())->getSrcTy(),
448 Root.getOpcode() == Instruction::SExt);
449 return std::nullopt;
450 }
451
452 /// Checks if the root graph node can be emitted with narrower bitwidth at
453 /// codegen and returns it signedness, if so.
455 return MinBWs.at(&getRootNode()).second;
456 }
457
458 /// Returns reduction type after minbitdth analysis.
460 if (ReductionBitWidth == 0 ||
461 !getRootNodeScalars().front()->getType()->isIntegerTy() ||
462 ReductionBitWidth >=
463 DL->getTypeSizeInBits(getRootNodeScalars().front()->getType()))
466 getRootNode().getVectorFactor()));
469 ReductionBitWidth),
470 getRootNode().getVectorFactor()));
471 }
472
473 /// Returns true if the tree results in one of the reduced bitcasts variants.
474 bool isReducedBitcastRoot() const {
475 return getRootNode().hasState() &&
476 (getRootNode().CombinedOp == TreeEntry::ReducedBitcast ||
477 getRootNode().CombinedOp == TreeEntry::ReducedBitcastBSwap ||
478 getRootNode().CombinedOp == TreeEntry::ReducedBitcastLoads ||
479 getRootNode().CombinedOp == TreeEntry::ReducedBitcastBSwapLoads ||
480 getRootNode().CombinedOp == TreeEntry::ReducedBitPack) &&
481 getRootNode().State == TreeEntry::Vectorize;
482 }
483
484 /// Returns true if the tree results in the reduced cmp bitcast root.
486 return getRootNode().hasState() &&
487 getRootNode().CombinedOp == TreeEntry::ReducedCmpBitcast &&
488 getRootNode().State == TreeEntry::Vectorize;
489 }
490
491 /// Returns true if the tree is a reduction tree.
492 bool isReductionTree() const { return UserIgnoreList != nullptr; }
493
494 /// Builds external uses of the vectorized scalars, i.e. the list of
495 /// vectorized scalars to be extracted, their lanes and their scalar users. \p
496 /// ExternallyUsedValues contains additional list of external uses to handle
497 /// vectorization of reductions.
498 void
499 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
500
501 /// Transforms graph nodes to target specific representations, if profitable.
502 void transformNodes();
503
504 /// Clear the internal data structures that are created by 'buildTree'.
505 void deleteTree() {
506 VectorizableTree.clear();
507 ScalarToTreeEntries.clear();
508 DeletedNodes.clear();
509 TransformedToGatherNodes.clear();
510 OperandsToTreeEntry.clear();
511 ScalarsInSplitNodes.clear();
512 CopyableLoadsToTreeEntries.clear();
513 MustGather.clear();
514 ReassocScalarToTreeEntries.clear();
515 KeptReassocScalars.clear();
516 NonScheduledFirst.clear();
517 EntryToLastInstruction.clear();
518 LastInstructionToPos.clear();
519 LoadEntriesToVectorize.clear();
520 IsGraphTransformMode = false;
521 GatheredLoadsEntriesFirst.reset();
522 SplatGatheredScalarsRoots.clear();
523 NumCanonicalSplatSubtreeEntries = 0;
524 CompressEntryToData.clear();
525 ExternalUses.clear();
526 ExternalUsesAsOriginalScalar.clear();
527 ExternalUsesWithNonUsers.clear();
528 ExternalUseReplacements.clear();
529 RTChecks.clear();
530 HasRuntimeCheckableBlockers = false;
531 HasNonCheckableMemBlocker = false;
532 RTChecksFinalized = false;
533 for (BlockScheduling *BS : TreeBlocksSchedules)
534 BS->clear();
535 TreeBlocksSchedules.clear();
536 MinBWs.clear();
537 ReductionBitWidth = 0;
538 BaseGraphSize = 1;
539 CastMaxMinBWSizes.reset();
540 ExtraBitWidthNodes.clear();
541 InstrElementSize.clear();
542 UserIgnoreList = nullptr;
543 NarrowedChainInsts.clear();
544 PostponedGathers.clear();
545 ExpandedOperandFreezes.clear();
546 ValueToGatherNodes.clear();
547 TreeEntryToStridedPtrInfoMap.clear();
548 CurrentLoopNest.clear();
549 MergedLoopBTCs.clear();
550 }
551
552 unsigned getTreeSize() const { return VectorizableTree.size(); }
553
554 /// Returns the size of the current tree, stopping at gathers
555 /// For instance, even though we continue adding tree entries after
556 /// a split node, this function stops counting at the split node
557 /// since it is a gather. This matches the behavior of MinBWs
558 /// computation.
560 unsigned Cnt = 0;
561 SmallBitVector GatherTreeNodes(VectorizableTree.size(), false);
562 for (unsigned NodeIdx : seq<unsigned>(VectorizableTree.size())) {
563 auto &TE = VectorizableTree[NodeIdx];
564 if (DeletedNodes.contains(TE.get()))
565 continue;
566 auto IsGather = [&](TreeEntry *TE) {
567 return TE->isGather() || TransformedToGatherNodes.contains(TE) ||
568 GatherTreeNodes.test(TE->Idx);
569 };
570 if (IsGather(TE.get()) || (!TE->UserTreeIndex.UserTE && NodeIdx != 0) ||
571 (TE->UserTreeIndex.UserTE && (IsGather(TE->UserTreeIndex.UserTE)))) {
572 GatherTreeNodes.set(NodeIdx);
573 continue;
574 }
575 ++Cnt;
576 }
577 return Cnt;
578 }
579
580 /// Returns true if the tree gathers any scalars other than constants.
582 return any_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
583 return !DeletedNodes.contains(TE.get()) &&
584 (TE->isGather() || TransformedToGatherNodes.contains(TE.get())) &&
585 !allConstant(TE->Scalars);
586 });
587 }
588
589 /// Returns the base graph size, before any transformations.
590 unsigned getCanonicalGraphSize() const { return BaseGraphSize; }
591
592 /// Number of tree entries that form the splat gather subtrees.
593 unsigned getNumSplatSubtreeEntries() const {
594 return NumCanonicalSplatSubtreeEntries;
595 }
596
597 /// Perform LICM and CSE on the newly generated gather sequences.
599
600 /// Does this non-empty order represent an identity order? Identity
601 /// should be represented as an empty order, so this is used to
602 /// decide if we can canonicalize a computed order. Undef elements
603 /// (represented as size) are ignored.
605 assert(!Order.empty() && "expected non-empty order");
606 const unsigned Sz = Order.size();
607 return all_of(enumerate(Order), [&](const auto &P) {
608 return P.value() == P.index() || P.value() == Sz;
609 });
610 }
611
612 /// Checks if the specified gather tree entry \p TE can be represented as a
613 /// shuffled vector entry + (possibly) permutation with other gathers. It
614 /// implements the checks only for possibly ordered scalars (Loads,
615 /// ExtractElement, ExtractValue), which can be part of the graph.
616 /// \param TopToBottom If true, used for the whole tree rotation, false - for
617 /// sub-tree rotations. \param IgnoreReorder true, if the order of the root
618 /// node might be ignored.
619 std::optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE,
620 bool TopToBottom,
621 bool IgnoreReorder);
622
623 /// Sort loads into increasing pointers offsets to allow greater clustering.
624 std::optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
625
626 /// Gets reordering data for the given tree entry. If the entry is vectorized
627 /// - just return ReorderIndices, otherwise check if the scalars can be
628 /// reordered and return the most optimal order.
629 /// \return std::nullopt if ordering is not important, empty order, if
630 /// identity order is important, or the actual order.
631 /// \param TopToBottom If true, include the order of vectorized stores and
632 /// insertelement nodes, otherwise skip them.
633 /// \param IgnoreReorder true, if the root node order can be ignored.
634 std::optional<OrdersType>
635 getReorderingData(const TreeEntry &TE, bool TopToBottom, bool IgnoreReorder);
636
637 /// Checks if it is profitable to reorder the current tree.
638 /// If the tree does not contain many profitable reordable nodes, better to
639 /// skip it to save compile time.
640 bool isProfitableToReorder() const;
641
642 /// Reorders the current graph to the most profitable order starting from the
643 /// root node to the leaf nodes. The best order is chosen only from the nodes
644 /// of the same size (vectorization factor). Smaller nodes are considered
645 /// parts of subgraph with smaller VF and they are reordered independently. We
646 /// can make it because we still need to extend smaller nodes to the wider VF
647 /// and we can merge reordering shuffles with the widening shuffles.
648 void reorderTopToBottom();
649
650 /// Reorders the current graph to the most profitable order starting from
651 /// leaves to the root. It allows to rotate small subgraphs and reduce the
652 /// number of reshuffles if the leaf nodes use the same order. In this case we
653 /// can merge the orders and just shuffle user node instead of shuffling its
654 /// operands. Plus, even the leaf nodes have different orders, it allows to
655 /// sink reordering in the graph closer to the root node and merge it later
656 /// during analysis.
657 void reorderBottomToTop(bool IgnoreReorder = false);
658
659 /// Marks the schedule data of the copyable-modeled operands of \p TE for
660 /// dependency recalculation at the next bundle scheduling.
661 void markCopyableDepsForRecalc(TreeEntry &TE);
662
663 /// \return The vector element size in bits to use when vectorizing the
664 /// expression tree ending at \p V. If V is a store, the size is the width of
665 /// the stored value. Otherwise, the size is the width of the largest loaded
666 /// value reaching V. This method is used by the vectorizer to calculate
667 /// vectorization factors.
668 unsigned getVectorElementSize(Value *V);
669
670 /// Compute the minimum type sizes required to represent the entries in a
671 /// vectorizable tree.
673
674 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
675 unsigned getMaxVecRegSize() const {
676 return MaxVecRegSize;
677 }
678
679 /// \returns the -slp-threshold value, 0 if unset.
680 int getCostThreshold() const { return Opts.slp_threshold.value_or(0); }
681
682 // \returns minimum vector register size as set by cl::opt.
683 unsigned getMinVecRegSize() const {
684 return MinVecRegSize;
685 }
686
687 /// \returns the number of parts, the type \p VecTy is split at the codegen
688 /// phase. The type legalization queries are repeated for the very same types
689 /// during the analysis, so the results are cached for the function.
691 Type *VecTy, Type *ScalarTy,
692 unsigned Limit = std::numeric_limits<unsigned>::max()) const {
693 auto [It, Inserted] =
694 NumberOfPartsCache.try_emplace(std::make_tuple(VecTy, ScalarTy, Limit));
695 if (Inserted)
697 /*QueryNumParts=*/true, *TTI, VecTy, ScalarTy, Opts.slp_revec, Limit);
698 return It->second;
699 }
700
701 /// \returns the number of parts, the type \p VecTy is split at the codegen
702 /// phase. The type legalization queries are repeated for the very same types
703 /// during the analysis, so the results are cached for the function.
705 Type *VecTy, Type *ScalarTy,
706 unsigned Limit = std::numeric_limits<unsigned>::max()) const {
707 auto [It, Inserted] =
708 NumberOfRegsCache.try_emplace(std::make_tuple(VecTy, ScalarTy, Limit));
709 if (Inserted)
711 /*QueryNumParts=*/false, *TTI, VecTy, ScalarTy, Opts.slp_revec,
712 Limit);
713 return It->second;
714 }
715
716 unsigned getMinVF(unsigned Sz) const {
717 return std::max(2U, getMinVecRegSize() / Sz);
718 }
719
720 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
721 unsigned MaxVF =
722 Opts.slp_max_vf.value_or(TTI->getMaximumVF(ElemWidth, Opcode));
723 return MaxVF ? MaxVF : UINT_MAX;
724 }
725
726 /// Check if homogeneous aggregate is isomorphic to some VectorType.
727 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
728 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
729 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
730 ///
731 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
732 unsigned canMapToVector(Type *T) const;
733
734 /// \returns true if the vectorized insertvalue result can be stored directly
735 /// as a vector, i.e. every insertvalue with an external user is consumed by a
736 /// single store only.
737 bool canVectorStoreInsertValue(const TreeEntry *E) const;
738
739 /// \returns the source vector type for an InsertElement/InsertValue
740 /// buildvector node \p E: the inserted vector type for insertelement, or a
741 /// vector of the inserted scalar type wide enough to cover the highest
742 /// inserted index for insertvalue.
743 FixedVectorType *getInsertBuildVectorSrcTy(const TreeEntry *E) const;
744
745 /// \returns True if the VectorizableTree is both tiny and not fully
746 /// vectorizable. We do not vectorize such trees.
747 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
748
749 /// Checks if the graph and all its subgraphs cannot be better vectorized.
750 /// It may happen, if all gather nodes are loads and they cannot be
751 /// "clusterized". In this case even subgraphs cannot be vectorized more
752 /// effectively than the base graph.
753 bool isTreeNotExtendable() const;
754
755 bool isStridedLoad(ArrayRef<Value *> PointerOps, Type *ScalarTy,
756 Align Alignment, const int64_t Diff,
757 const size_t Sz) const;
758
759 /// Returns true for widened strided loads, where each lane of the strided
760 /// load covers a group of consecutive scalars. Reversed widened strided
761 /// loads must be emitted with a positive stride and a reorder shuffle.
762 bool isWidenedStridedLoad(const TreeEntry *E) const;
763
764 /// Return true if an array of scalar loads can be replaced with a strided
765 /// load (with constant stride).
766 ///
767 /// It is possible that the load gets "widened". Suppose that originally each
768 /// load loads `k` bytes and `PointerOps` can be arranged as follows (`%s` is
769 /// constant): %b + 0 * %s + 0 %b + 0 * %s + 1 %b + 0 * %s + 2
770 /// ...
771 /// %b + 0 * %s + (w - 1)
772 ///
773 /// %b + 1 * %s + 0
774 /// %b + 1 * %s + 1
775 /// %b + 1 * %s + 2
776 /// ...
777 /// %b + 1 * %s + (w - 1)
778 /// ...
779 ///
780 /// %b + (n - 1) * %s + 0
781 /// %b + (n - 1) * %s + 1
782 /// %b + (n - 1) * %s + 2
783 /// ...
784 /// %b + (n - 1) * %s + (w - 1)
785 ///
786 /// In this case we will generate a strided load of type `<n x (k * w)>`.
787 ///
788 /// \param PointerOps list of pointer arguments of loads.
789 /// \param ElemTy original scalar type of loads.
790 /// \param Alignment alignment of the first load.
791 /// \param SortedIndices is the order of PointerOps as returned by
792 /// `sortPtrAccesses`
793 /// \param Diff Pointer difference between the lowest and the highes pointer
794 /// in `PointerOps` as returned by `getPointersDiff`.
795 /// \param Ptr0 first pointer in `PointersOps`.
796 /// \param PtrN last pointer in `PointersOps`.
797 /// \param SPtrInfo If the function return `true`, it also sets all the fields
798 /// of `SPtrInfo` necessary to generate the strided load later.
800 const ArrayRef<Value *> PointerOps, Type *ElemTy, Align Alignment,
801 const SmallVectorImpl<unsigned> &SortedIndices, const int64_t Diff,
802 Value *Ptr0, StridedPtrInfo &SPtrInfo) const;
803
804 /// Return true if an array of scalar loads can be replaced with a strided
805 /// load (with run-time stride).
806 /// \param PointerOps list of pointer arguments of loads.
807 /// \param ScalarTy type of loads.
808 /// \param CommonAlignment common alignement of loads as computed by
809 /// `computeCommonAlignment<LoadInst>`.
810 /// \param SortedIndicies is a list of indicies computed by this function such
811 /// that the sequence `PointerOps[SortedIndices[0]],
812 /// PointerOps[SortedIndicies[1]], ..., PointerOps[SortedIndices[n]]` is
813 /// ordered by the coefficient of the stride. For example, if PointerOps is
814 /// `%base + %stride, %base, %base + 2 * stride` the `SortedIndices` will be
815 /// `[1, 0, 2]`. We follow the convention that if `SortedIndices` has to be
816 /// `0, 1, 2, 3, ...` we return empty vector for `SortedIndicies`.
817 /// \param SPtrInfo If the function return `true`, it also sets all the fields
818 /// of `SPtrInfo` necessary to generate the strided load later.
819 /// \param IsLoad Is this a strided load (true) or strided store (false)
820 bool analyzeRtStrideCandidate(ArrayRef<Value *> PointerOps, Type *ScalarTy,
821 Align CommonAlignment,
822 SmallVectorImpl<unsigned> &SortedIndices,
823 StridedPtrInfo &SPtrInfo, bool IsLoad) const;
824
825 /// Checks if the given array of loads can be represented as a vectorized,
826 /// scatter or just simple gather.
827 /// \param VL list of loads.
828 /// \param VL0 main load value.
829 /// \param Order returned order of load instructions.
830 /// \param PointerOps returned list of pointer operands.
831 /// \param BestVF return best vector factor, if recursive check found better
832 /// vectorization sequences rather than masked gather.
833 /// \param TryRecursiveCheck used to check if long masked gather can be
834 /// represented as a serie of loads/insert subvector, if profitable.
837 SmallVectorImpl<Value *> &PointerOps,
838 StridedPtrInfo &SPtrInfo,
839 unsigned *BestVF = nullptr,
840 bool TryRecursiveCheck = true) const;
841
842 /// Checks whether some existing tree entry has scalars equal to \p VL.
843 /// \p S is the common opcode of \p VL when one exists; an empty \p S means
844 /// the values have no common opcode (mixed buildvector/gather candidates).
846 auto IsSame = [&](const TreeEntry *TE) { return TE->isSame(VL); };
847 if (S) {
848 // Any vectorized or gather entry equal to VL must contain S.getMainOp()
849 // (the representative instruction, which is also the recorded scalar
850 // for copyable-elements bundles), so probing the MainOp-indexed maps
851 // is sufficient and avoids scanning the whole tree.
852 return any_of(getTreeEntries(S.getMainOp()), IsSame) ||
853 any_of(ValueToGatherNodes.lookup(S.getMainOp()), IsSame);
854 }
855 // No common opcode: only gather entries can match. Each non-constant
856 // value in VL has to be in the gather entry's scalar list and is
857 // therefore present in ValueToGatherNodes. Probe by VL members instead
858 // of scanning the whole tree (O(tree) -> O(|VL|)).
860 for (Value *V : VL) {
861 // Constants/poisons are not tracked in ValueToGatherNodes.
862 if (isConstant(V))
863 continue;
864 for (const TreeEntry *TE : ValueToGatherNodes.lookup(V)) {
865 if (!Visited.insert(TE).second)
866 continue;
867 if (IsSame(TE))
868 return true;
869 }
870 }
871 return false;
872 }
873
874 /// Registers non-vectorizable sequence of loads
875 template <typename T> void registerNonVectorizableLoads(ArrayRef<T *> VL) {
876 ListOfKnonwnNonVectorizableLoads.insert(hash_value(VL));
877 }
878
879 /// Checks if the given loads sequence is known as not vectorizable
880 template <typename T>
882 return ListOfKnonwnNonVectorizableLoads.contains(hash_value(VL));
883 }
884
886
887 /// This structure holds any data we need about the edges being traversed
888 /// during buildTreeRec(). We keep track of:
889 /// (i) the user TreeEntry index, and
890 /// (ii) the index of the edge.
891 struct EdgeInfo {
892 EdgeInfo() = default;
893 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
895 /// The user TreeEntry.
896 TreeEntry *UserTE = nullptr;
897 /// The operand index of the use.
898 unsigned EdgeIdx = UINT_MAX;
899#ifndef NDEBUG
901 const BoUpSLP::EdgeInfo &EI) {
902 EI.dump(OS);
903 return OS;
904 }
905 /// Debug print.
906 void dump(raw_ostream &OS) const {
907 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
908 << " EdgeIdx:" << EdgeIdx << "}";
909 }
910 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
911#endif
912 bool operator == (const EdgeInfo &Other) const {
913 return UserTE == Other.UserTE && EdgeIdx == Other.EdgeIdx;
914 }
915
916 operator bool() const { return UserTE != nullptr; }
917 };
918 friend struct DenseMapInfo<EdgeInfo>;
919
920 /// A helper class used for scoring candidates for two consecutive lanes.
922 const TargetLibraryInfo &TLI;
923 const DataLayout &DL;
924 ScalarEvolution &SE;
925 const BoUpSLP &R;
926 int NumLanes; // Total number of lanes (aka vectorization factor).
927 int MaxLevel; // The maximum recursion depth for accumulating score.
928
929 public:
931 ScalarEvolution &SE, const BoUpSLP &R, int NumLanes,
932 int MaxLevel)
933 : TLI(TLI), DL(DL), SE(SE), R(R), NumLanes(NumLanes),
934 MaxLevel(MaxLevel) {}
935
936 // The hard-coded scores listed here are not very important, though it shall
937 // be higher for better matches to improve the resulting cost. When
938 // computing the scores of matching one sub-tree with another, we are
939 // basically counting the number of values that are matching. So even if all
940 // scores are set to 1, we would still get a decent matching result.
941 // However, sometimes we have to break ties. For example we may have to
942 // choose between matching loads vs matching opcodes. This is what these
943 // scores are helping us with: they provide the order of preference. Also,
944 // this is important if the scalar is externally used or used in another
945 // tree entry node in the different lane.
946
947 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
948 static constexpr int ScoreConsecutiveLoads = 40;
949 /// The same load multiple times. This should have a better score than
950 /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
951 /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
952 /// a vector load and 1.0 for a broadcast.
953 static constexpr int ScoreSplatLoads = 30;
954 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
955 static constexpr int ScoreReversedLoads = 30;
956 /// A load candidate for masked gather.
957 static constexpr int ScoreMaskedGatherCandidate = 10;
958 /// ExtractElementInst from same vector and consecutive indexes.
959 static constexpr int ScoreConsecutiveExtracts = 40;
960 /// ExtractElementInst from same vector and reversed indices.
961 static constexpr int ScoreReversedExtracts = 30;
962 /// Constants.
963 static constexpr int ScoreConstants = 15;
964 /// Same constants.
965 static constexpr int ScoreSameConstants = 17;
966 /// Instructions with the same opcode.
967 static constexpr int ScoreSameOpcode = 20;
968 /// Instructions with alt opcodes (e.g, add + sub).
969 static constexpr int ScoreAltOpcodes = 10;
970 /// Identical instructions (a.k.a. splat or broadcast).
971 static constexpr int ScoreSplat = 10;
972 /// Matching with an undef is preferable to failing.
973 static constexpr int ScoreUndef = 10;
974 /// Score for failing to find a decent match.
975 static constexpr int ScoreFail = 0;
976 /// Score if all users are vectorized.
977 static constexpr int ScoreAllUserVectorized = 10;
978
979 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
980 /// \p U1 and \p U2 are the users of \p V1 and \p V2.
981 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
982 /// MainAltOps.
984 ArrayRef<Value *> MainAltOps) const {
985 if (!isValidElementType(V1->getType(), R.Opts.slp_revec) ||
986 !isValidElementType(V2->getType(), R.Opts.slp_revec))
988
989 if (V1 == V2) {
990 if (isa<LoadInst>(V1)) {
991 // Retruns true if the users of V1 and V2 won't need to be extracted.
992 auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
993 // Bail out if we have too many uses to save compilation time.
994 if (V1->hasNUsesOrMore(UsesLimit) || V2->hasNUsesOrMore(UsesLimit))
995 return false;
996
997 auto AllUsersVectorized = [U1, U2, this](Value *V) {
998 return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
999 return U == U1 || U == U2 || R.isVectorized(U);
1000 });
1001 };
1002 return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1003 };
1004 // A broadcast of a load can be cheaper on some targets.
1005 if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1006 ElementCount::getFixed(NumLanes)) &&
1007 ((int)V1->getNumUses() == NumLanes ||
1008 AllUsersAreInternal(V1, V2)))
1010 }
1011 if (isa<UndefValue>(V1))
1013 if (isConstant(V1))
1016 }
1017
1018 auto CheckSameEntryOrFail = [&]() {
1019 if (ArrayRef<TreeEntry *> TEs1 = R.getTreeEntries(V1); !TEs1.empty()) {
1021 if (ArrayRef<TreeEntry *> TEs2 = R.getTreeEntries(V2);
1022 !TEs2.empty() &&
1023 any_of(TEs2, [&](TreeEntry *E) { return Set.contains(E); }))
1025 }
1027 };
1028
1029 auto *LI1 = dyn_cast<LoadInst>(V1);
1030 auto *LI2 = dyn_cast<LoadInst>(V2);
1031 if (LI1 && LI2) {
1032 if (LI1->getParent() != LI2->getParent() || !LI1->isSimple() ||
1033 !LI2->isSimple())
1034 return CheckSameEntryOrFail();
1035
1036 std::optional<int64_t> Dist = R.getPointersDiff(
1037 LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1038 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1039 if (!Dist || *Dist == 0) {
1040 if (getUnderlyingObject(LI1->getPointerOperand()) ==
1041 getUnderlyingObject(LI2->getPointerOperand()) &&
1042 R.TTI->isLegalMaskedGather(
1043 getWidenedType(LI1->getType(), NumLanes), LI1->getAlign()))
1045 return CheckSameEntryOrFail();
1046 }
1047 // The distance is too large - still may be profitable to use masked
1048 // loads/gathers.
1049 if (std::abs(*Dist) > NumLanes / 2)
1051 // This still will detect consecutive loads, but we might have "holes"
1052 // in some cases. It is ok for non-power-2 vectorization and may produce
1053 // better results. It should not affect current vectorization.
1056 }
1057
1058 auto *C1 = dyn_cast<Constant>(V1);
1059 auto *C2 = dyn_cast<Constant>(V2);
1060 if (C1 && C2)
1062
1063 // Consider constants and buildvector compatible.
1064 if ((C1 && isa<InsertElementInst>(V2)) ||
1065 (C2 && isa<InsertElementInst>(V1)))
1067
1068 // Extracts from consecutive indexes of the same vector better score as
1069 // the extracts could be optimized away.
1070 Value *EV1;
1071 ConstantInt *Ex1Idx;
1072 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1073 // Undefs are always profitable for extractelements.
1074 // Compiler can easily combine poison and extractelement <non-poison> or
1075 // undef and extractelement <poison>. But combining undef +
1076 // extractelement <non-poison-but-may-produce-poison> requires some
1077 // extra operations.
1078 if (isa<UndefValue>(V2))
1079 return (isa<PoisonValue>(V2) || isUndefVector(EV1).all())
1082 Value *EV2 = nullptr;
1083 ConstantInt *Ex2Idx = nullptr;
1084 if (match(V2,
1086 m_Undef())))) {
1087 // Undefs are always profitable for extractelements.
1088 if (!Ex2Idx)
1090 if (isUndefVector(EV2).all() && EV2->getType() == EV1->getType())
1092 if (EV2 == EV1) {
1093 int Idx1 = Ex1Idx->getZExtValue();
1094 int Idx2 = Ex2Idx->getZExtValue();
1095 int Dist = Idx2 - Idx1;
1096 // The distance is too large - still may be profitable to use
1097 // shuffles.
1098 if (std::abs(Dist) == 0)
1100 if (std::abs(Dist) > NumLanes / 2)
1104 }
1106 }
1107 return CheckSameEntryOrFail();
1108 }
1109
1110 auto *I1 = dyn_cast<Instruction>(V1);
1111 auto *I2 = dyn_cast<Instruction>(V2);
1112 if (I1 && I2) {
1113 if (I1->getParent() != I2->getParent())
1114 return CheckSameEntryOrFail();
1115 Value *V;
1116 Value *Cond;
1117 // ZExt i1 to something must be considered same opcode for select i1
1118 // cmp, x, y
1119 // Required to better match the transformation after
1120 // BoUpSLP::matchesInversedZExtSelect analysis.
1121 if ((match(I1, m_ZExt(m_Value(V))) &&
1122 match(I2, m_Select(m_Value(Cond), m_Value(), m_Value())) &&
1123 V->getType() == Cond->getType()) ||
1124 (match(I2, m_ZExt(m_Value(V))) &&
1125 match(I1, m_Select(m_Value(Cond), m_Value(), m_Value())) &&
1126 V->getType() == Cond->getType()))
1128 SmallVector<Value *, 4> Ops(MainAltOps);
1129 Ops.push_back(I1);
1130 Ops.push_back(I2);
1132 // Note: Only consider instructions with <= 2 operands to avoid
1133 // complexity explosion.
1134 if (S &&
1135 (S.getMainOp()->getNumOperands() <= 2 || !MainAltOps.empty() ||
1136 !S.isAltShuffle()) &&
1138 return I->getNumOperands() == S.getMainOp()->getNumOperands() ||
1139 (S.getOpcode() == Instruction::ICmp && isa<TruncInst>(I));
1140 }))
1143 }
1144
1145 if (I1 && isa<PoisonValue>(V2))
1147
1148 if (isa<UndefValue>(V2))
1150
1151 return CheckSameEntryOrFail();
1152 }
1153
1154 /// Go through the operands of \p LHS and \p RHS recursively until
1155 /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1156 /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1157 /// of \p U1 and \p U2), except at the beginning of the recursion where
1158 /// these are set to nullptr.
1159 ///
1160 /// For example:
1161 /// \verbatim
1162 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1]
1163 /// \ / \ / \ / \ /
1164 /// + + + +
1165 /// G1 G2 G3 G4
1166 /// \endverbatim
1167 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1168 /// each level recursively, accumulating the score. It starts from matching
1169 /// the additions at level 0, then moves on to the loads (level 1). The
1170 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1171 /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1172 /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1173 /// Please note that the order of the operands does not matter, as we
1174 /// evaluate the score of all profitable combinations of operands. In
1175 /// other words the score of G1 and G4 is the same as G1 and G2. This
1176 /// heuristic is based on ideas described in:
1177 /// Look-ahead SLP: Auto-vectorization in the presence of commutative
1178 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1179 /// Luís F. W. Góes
1181 Instruction *U2, int CurrLevel,
1182 ArrayRef<Value *> MainAltOps) const {
1183
1184 // Get the shallow score of V1 and V2.
1185 int ShallowScoreAtThisLevel =
1186 getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1187
1188 // If reached MaxLevel,
1189 // or if V1 and V2 are not instructions,
1190 // or if they are SPLAT,
1191 // or if they are not consecutive,
1192 // or if profitable to vectorize loads or extractelements, early return
1193 // the current cost.
1194 auto *I1 = dyn_cast<Instruction>(LHS);
1195 auto *I2 = dyn_cast<Instruction>(RHS);
1196 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1197 ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1198 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1199 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1201 ShallowScoreAtThisLevel))
1202 return ShallowScoreAtThisLevel;
1203 assert(I1 && I2 && "Should have early exited.");
1204
1205 // Contains the I2 operand indexes that got matched with I1 operands.
1206 SmallSet<unsigned, 4> Op2Used;
1207
1208 // Recursion towards the operands of I1 and I2. We are trying all possible
1209 // operand pairs, and keeping track of the best score.
1210 if (I1->getNumOperands() != I2->getNumOperands())
1212 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1213 OpIdx1 != NumOperands1; ++OpIdx1) {
1214 // Try to pair op1I with the best operand of I2.
1215 int MaxTmpScore = 0;
1216 unsigned MaxOpIdx2 = 0;
1217 bool FoundBest = false;
1218 // If I2 is commutative try all combinations.
1219 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1220 unsigned ToIdx = isCommutative(I2)
1221 ? I2->getNumOperands()
1222 : std::min(I2->getNumOperands(), OpIdx1 + 1);
1223 assert(FromIdx <= ToIdx && "Bad index");
1224 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1225 // Skip operands already paired with OpIdx1.
1226 if (Op2Used.count(OpIdx2))
1227 continue;
1228 // Recursively calculate the cost at each level
1229 int TmpScore =
1230 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1231 I1, I2, CurrLevel + 1, {});
1232 // Look for the best score.
1233 if (TmpScore > LookAheadHeuristics::ScoreFail &&
1234 TmpScore > MaxTmpScore) {
1235 MaxTmpScore = TmpScore;
1236 MaxOpIdx2 = OpIdx2;
1237 FoundBest = true;
1238 }
1239 }
1240 if (FoundBest) {
1241 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1242 Op2Used.insert(MaxOpIdx2);
1243 ShallowScoreAtThisLevel += MaxTmpScore;
1244 }
1245 }
1246 return ShallowScoreAtThisLevel;
1247 }
1248 };
1249 /// A helper data structure to hold the operands of a vector of instructions.
1250 /// This supports a fixed vector length for all operand vectors.
1252 /// For each operand we need (i) the value, and (ii) the opcode that it
1253 /// would be attached to if the expression was in a left-linearized form.
1254 /// This is required to avoid illegal operand reordering.
1255 /// For example:
1256 /// \verbatim
1257 /// 0 Op1
1258 /// |/
1259 /// Op1 Op2 Linearized + Op2
1260 /// \ / ----------> |/
1261 /// - -
1262 ///
1263 /// Op1 - Op2 (0 + Op1) - Op2
1264 /// \endverbatim
1265 ///
1266 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1267 ///
1268 /// Another way to think of this is to track all the operations across the
1269 /// path from the operand all the way to the root of the tree and to
1270 /// calculate the operation that corresponds to this path. For example, the
1271 /// path from Op2 to the root crosses the RHS of the '-', therefore the
1272 /// corresponding operation is a '-' (which matches the one in the
1273 /// linearized tree, as shown above).
1274 ///
1275 /// For lack of a better term, we refer to this operation as Accumulated
1276 /// Path Operation (APO).
1277 struct OperandData {
1278 OperandData() = default;
1279 OperandData(Value *V, bool APO, bool IsUsed)
1280 : V(V), APO(APO), IsUsed(IsUsed) {}
1281 /// The operand value.
1282 Value *V = nullptr;
1283 /// TreeEntries only allow a single opcode, or an alternate sequence of
1284 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1285 /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1286 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1287 /// (e.g., Add/Mul)
1288 bool APO = false;
1289 /// Helper data for the reordering function.
1290 bool IsUsed = false;
1291 };
1292
1293 /// During operand reordering, we are trying to select the operand at lane
1294 /// that matches best with the operand at the neighboring lane. Our
1295 /// selection is based on the type of value we are looking for. For example,
1296 /// if the neighboring lane has a load, we need to look for a load that is
1297 /// accessing a consecutive address. These strategies are summarized in the
1298 /// 'ReorderingMode' enumerator.
1299 enum class ReorderingMode {
1300 Load, ///< Matching loads to consecutive memory addresses
1301 Opcode, ///< Matching instructions based on opcode (same or alternate)
1302 Constant, ///< Matching constants
1303 Splat, ///< Matching the same instruction multiple times (broadcast)
1304 Failed, ///< We failed to create a vectorizable group
1305 };
1306
1307 using OperandDataVec = SmallVector<OperandData, 2>;
1308
1309 /// A vector of operand vectors.
1311 /// When VL[0] is IntrinsicInst, ArgSize is CallBase::arg_size. When VL[0]
1312 /// is not IntrinsicInst, ArgSize is User::getNumOperands.
1313 unsigned ArgSize = 0;
1314
1315 const TargetLibraryInfo &TLI;
1316 const DataLayout &DL;
1317 ScalarEvolution &SE;
1318 const BoUpSLP &R;
1319 const Loop *L = nullptr;
1320
1321 /// \returns the operand data at \p OpIdx and \p Lane.
1322 OperandData &getData(unsigned OpIdx, unsigned Lane) {
1323 return OpsVec[OpIdx][Lane];
1324 }
1325
1326 /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1327 const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1328 return OpsVec[OpIdx][Lane];
1329 }
1330
1331 /// Clears the used flag for all entries.
1332 void clearUsed() {
1333 for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1334 OpIdx != NumOperands; ++OpIdx)
1335 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1336 ++Lane)
1337 OpsVec[OpIdx][Lane].IsUsed = false;
1338 }
1339
1340 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1341 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1342 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1343 }
1344
1345 /// \param Lane lane of the operands under analysis.
1346 /// \param OpIdx operand index in \p Lane lane we're looking the best
1347 /// candidate for.
1348 /// \param Idx operand index of the current candidate value.
1349 /// \returns The additional score due to possible broadcasting of the
1350 /// elements in the lane. It is more profitable to have power-of-2 unique
1351 /// elements in the lane, it will be vectorized with higher probability
1352 /// after removing duplicates. Currently the SLP vectorizer supports only
1353 /// vectorization of the power-of-2 number of unique scalars.
1354 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx,
1355 const SmallBitVector &UsedLanes) const {
1356 Value *IdxLaneV = getData(Idx, Lane).V;
1357 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V ||
1358 isa<ExtractElementInst>(IdxLaneV))
1359 return 0;
1361 for (unsigned Ln : seq<unsigned>(getNumLanes())) {
1362 if (Ln == Lane)
1363 continue;
1364 Value *OpIdxLnV = getData(OpIdx, Ln).V;
1365 if (!isa<Instruction>(OpIdxLnV))
1366 return 0;
1367 Uniques.try_emplace(OpIdxLnV, Ln);
1368 }
1369 unsigned UniquesCount = Uniques.size();
1370 auto IdxIt = Uniques.find(IdxLaneV);
1371 unsigned UniquesCntWithIdxLaneV =
1372 IdxIt != Uniques.end() ? UniquesCount : UniquesCount + 1;
1373 Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1374 auto OpIdxIt = Uniques.find(OpIdxLaneV);
1375 unsigned UniquesCntWithOpIdxLaneV =
1376 OpIdxIt != Uniques.end() ? UniquesCount : UniquesCount + 1;
1377 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1378 return 0;
1379 return std::min(bit_ceil(UniquesCntWithOpIdxLaneV) -
1380 UniquesCntWithOpIdxLaneV,
1381 UniquesCntWithOpIdxLaneV -
1382 bit_floor(UniquesCntWithOpIdxLaneV)) -
1383 ((IdxIt != Uniques.end() && UsedLanes.test(IdxIt->second))
1384 ? UniquesCntWithIdxLaneV - bit_floor(UniquesCntWithIdxLaneV)
1385 : bit_ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1386 }
1387
1388 /// \param Lane lane of the operands under analysis.
1389 /// \param OpIdx operand index in \p Lane lane we're looking the best
1390 /// candidate for.
1391 /// \param Idx operand index of the current candidate value.
1392 /// \returns The additional score for the scalar which users are all
1393 /// vectorized.
1394 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1395 Value *IdxLaneV = getData(Idx, Lane).V;
1396 Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1397 // Do not care about number of uses for vector-like instructions
1398 // (extractelement/extractvalue with constant indices), they are extracts
1399 // themselves and already externally used. Vectorization of such
1400 // instructions does not add extra extractelement instruction, just may
1401 // remove it.
1402 if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1403 isVectorLikeInstWithConstOps(OpIdxLaneV))
1405 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1406 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1407 return 0;
1408 return R.areAllUsersVectorized(IdxLaneI)
1410 : 0;
1411 }
1412
1413 /// Score scaling factor for fully compatible instructions but with
1414 /// different number of external uses. Allows better selection of the
1415 /// instructions with less external uses.
1416 static constexpr int ScoreScaleFactor = 10;
1417 /// Scale factor for constants only.
1418 static constexpr int ScoreConstantScaleFactor = 6;
1419
1420 /// \Returns the look-ahead score, which tells us how much the sub-trees
1421 /// rooted at \p LHS and \p RHS match, the more they match the higher the
1422 /// score. This helps break ties in an informed way when we cannot decide on
1423 /// the order of the operands by just considering the immediate
1424 /// predecessors.
1425 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1426 int Lane, unsigned OpIdx, unsigned Idx,
1427 bool &IsUsed, const SmallBitVector &UsedLanes) {
1428 LookAheadHeuristics LookAhead(TLI, DL, SE, R, getNumLanes(),
1429 R.Opts.slp_max_look_ahead_depth);
1430 // Keep track of the instruction stack as we recurse into the operands
1431 // during the look-ahead score exploration.
1432 int Score =
1433 LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1434 /*CurrLevel=*/1, MainAltOps);
1435 if (Score) {
1436 int SplatScore =
1437 getSplatScore(Lane, OpIdx, Idx, UsedLanes) * ScoreScaleFactor;
1438 if (Score <= -SplatScore) {
1439 // Failed score.
1440 Score = 0;
1441 } else {
1442 Score += SplatScore;
1443 // Scale score to see the difference between different operands
1444 // and similar operands but all vectorized/not all vectorized
1445 // uses. It does not affect actual selection of the best
1446 // compatible operand in general, just allows to select the
1447 // operand with all vectorized uses.
1448 const int SF = (LHS == RHS && isConstant(LHS))
1449 ? ScoreConstantScaleFactor
1450 : ScoreScaleFactor;
1451 Score *= SF;
1452 Score += getExternalUseScore(Lane, OpIdx, Idx);
1453 IsUsed = true;
1454 }
1455 }
1456 return Score;
1457 }
1458
1459 /// Best defined scores per lanes between the passes. Used to choose the
1460 /// best operand (with the highest score) between the passes.
1461 /// The key - {Operand Index, Lane}.
1462 /// The value - the best score between the passes for the lane and the
1463 /// operand.
1465 BestScoresPerLanes;
1466
1467 // Search all operands in Ops[*][Lane] for the one that matches best
1468 // Ops[OpIdx][LastLane] and return its opreand index.
1469 // If no good match can be found, return std::nullopt.
1470 std::optional<unsigned>
1471 getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1472 ArrayRef<ReorderingMode> ReorderingModes,
1473 ArrayRef<Value *> MainAltOps,
1474 const SmallBitVector &UsedLanes) {
1475 unsigned NumOperands = getNumOperands();
1476
1477 // The operand of the previous lane at OpIdx.
1478 Value *OpLastLane = getData(OpIdx, LastLane).V;
1479
1480 // Our strategy mode for OpIdx.
1481 ReorderingMode RMode = ReorderingModes[OpIdx];
1482 if (RMode == ReorderingMode::Failed)
1483 return std::nullopt;
1484
1485 // The linearized opcode of the operand at OpIdx, Lane.
1486 bool OpIdxAPO = getData(OpIdx, Lane).APO;
1487
1488 // The best operand index and its score.
1489 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1490 // are using the score to differentiate between the two.
1491 struct BestOpData {
1492 std::optional<unsigned> Idx;
1493 unsigned Score = 0;
1494 } BestOp;
1495 BestOp.Score =
1496 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1497 .first->second;
1498
1499 // Track if the operand must be marked as used. If the operand is set to
1500 // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1501 // want to reestimate the operands again on the following iterations).
1502 bool IsUsed = RMode == ReorderingMode::Splat ||
1503 RMode == ReorderingMode::Constant ||
1504 RMode == ReorderingMode::Load;
1505 // Iterate through all unused operands and look for the best.
1506 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1507 // Get the operand at Idx and Lane.
1508 OperandData &OpData = getData(Idx, Lane);
1509 Value *Op = OpData.V;
1510 bool OpAPO = OpData.APO;
1511
1512 // Skip already selected operands.
1513 if (OpData.IsUsed)
1514 continue;
1515
1516 // Skip if we are trying to move the operand to a position with a
1517 // different opcode in the linearized tree form. This would break the
1518 // semantics.
1519 if (OpAPO != OpIdxAPO)
1520 continue;
1521
1522 // Look for an operand that matches the current mode.
1523 switch (RMode) {
1524 case ReorderingMode::Load:
1525 case ReorderingMode::Opcode: {
1526 bool LeftToRight = Lane > LastLane;
1527 Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1528 Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1529 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1530 OpIdx, Idx, IsUsed, UsedLanes);
1531 if (Score > static_cast<int>(BestOp.Score) ||
1532 (Score > 0 && Score == static_cast<int>(BestOp.Score) &&
1533 Idx == OpIdx)) {
1534 BestOp.Idx = Idx;
1535 BestOp.Score = Score;
1536 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1537 }
1538 break;
1539 }
1540 case ReorderingMode::Constant:
1541 if (isa<Constant>(Op) ||
1542 (!BestOp.Score && L && L->isLoopInvariant(Op))) {
1543 BestOp.Idx = Idx;
1544 if (isa<Constant>(Op)) {
1546 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] =
1548 }
1550 IsUsed = false;
1551 }
1552 break;
1553 case ReorderingMode::Splat:
1554 if (Op == OpLastLane || (!BestOp.Score && isa<Constant>(Op))) {
1555 IsUsed = Op == OpLastLane;
1556 if (Op == OpLastLane) {
1557 BestOp.Score = LookAheadHeuristics::ScoreSplat;
1558 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] =
1560 }
1561 BestOp.Idx = Idx;
1562 }
1563 break;
1564 case ReorderingMode::Failed:
1565 llvm_unreachable("Not expected Failed reordering mode.");
1566 }
1567 }
1568
1569 if (BestOp.Idx) {
1570 getData(*BestOp.Idx, Lane).IsUsed = IsUsed;
1571 return BestOp.Idx;
1572 }
1573 // If we could not find a good match return std::nullopt.
1574 return std::nullopt;
1575 }
1576
1577 /// Helper for reorderOperandVecs.
1578 /// \returns the lane that we should start reordering from. This is the one
1579 /// which has the least number of operands that can freely move about or
1580 /// less profitable because it already has the most optimal set of operands.
1581 unsigned getBestLaneToStartReordering() const {
1582 unsigned Min = UINT_MAX;
1583 unsigned SameOpNumber = 0;
1584 // std::pair<unsigned, unsigned> is used to implement a simple voting
1585 // algorithm and choose the lane with the least number of operands that
1586 // can freely move about or less profitable because it already has the
1587 // most optimal set of operands. The first unsigned is a counter for
1588 // voting, the second unsigned is the counter of lanes with instructions
1589 // with same/alternate opcodes and same parent basic block.
1591 // Try to be closer to the original results, if we have multiple lanes
1592 // with same cost. If 2 lanes have the same cost, use the one with the
1593 // highest index.
1594 for (int I = getNumLanes(); I > 0; --I) {
1595 unsigned Lane = I - 1;
1596 OperandsOrderData NumFreeOpsHash =
1597 getMaxNumOperandsThatCanBeReordered(Lane);
1598 // Compare the number of operands that can move and choose the one with
1599 // the least number.
1600 if (NumFreeOpsHash.NumOfAPOs < Min) {
1601 Min = NumFreeOpsHash.NumOfAPOs;
1602 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1603 HashMap.clear();
1604 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1605 } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1606 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1607 // Select the most optimal lane in terms of number of operands that
1608 // should be moved around.
1609 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1610 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1611 } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1612 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1613 auto [It, Inserted] =
1614 HashMap.try_emplace(NumFreeOpsHash.Hash, 1, Lane);
1615 if (!Inserted)
1616 ++It->second.first;
1617 }
1618 }
1619 // Select the lane with the minimum counter.
1620 unsigned BestLane = 0;
1621 unsigned CntMin = UINT_MAX;
1622 for (const auto &Data : reverse(HashMap)) {
1623 if (Data.second.first < CntMin) {
1624 CntMin = Data.second.first;
1625 BestLane = Data.second.second;
1626 }
1627 }
1628 return BestLane;
1629 }
1630
1631 /// Data structure that helps to reorder operands.
1632 struct OperandsOrderData {
1633 /// The best number of operands with the same APOs, which can be
1634 /// reordered.
1635 unsigned NumOfAPOs = UINT_MAX;
1636 /// Number of operands with the same/alternate instruction opcode and
1637 /// parent.
1638 unsigned NumOpsWithSameOpcodeParent = 0;
1639 /// Hash for the actual operands ordering.
1640 /// Used to count operands, actually their position id and opcode
1641 /// value. It is used in the voting mechanism to find the lane with the
1642 /// least number of operands that can freely move about or less profitable
1643 /// because it already has the most optimal set of operands. Can be
1644 /// replaced with SmallVector<unsigned> instead but hash code is faster
1645 /// and requires less memory.
1646 unsigned Hash = 0;
1647 };
1648 /// \returns the maximum number of operands that are allowed to be reordered
1649 /// for \p Lane and the number of compatible instructions(with the same
1650 /// parent/opcode). This is used as a heuristic for selecting the first lane
1651 /// to start operand reordering.
1652 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1653 unsigned CntTrue = 0;
1654 unsigned NumOperands = getNumOperands();
1655 // Operands with the same APO can be reordered. We therefore need to count
1656 // how many of them we have for each APO, like this: Cnt[APO] = x.
1657 // Since we only have two APOs, namely true and false, we can avoid using
1658 // a map. Instead we can simply count the number of operands that
1659 // correspond to one of them (in this case the 'true' APO), and calculate
1660 // the other by subtracting it from the total number of operands.
1661 // Operands with the same instruction opcode and parent are more
1662 // profitable since we don't need to move them in many cases, with a high
1663 // probability such lane already can be vectorized effectively.
1664 bool AllUndefs = true;
1665 unsigned NumOpsWithSameOpcodeParent = 0;
1666 Instruction *OpcodeI = nullptr;
1667 BasicBlock *Parent = nullptr;
1668 unsigned Hash = 0;
1669 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1670 const OperandData &OpData = getData(OpIdx, Lane);
1671 if (OpData.APO)
1672 ++CntTrue;
1673 // Use Boyer-Moore majority voting for finding the majority opcode and
1674 // the number of times it occurs.
1675 if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1676 if (!OpcodeI || !getSameOpcode({OpcodeI, I}, TLI) ||
1677 I->getParent() != Parent) {
1678 if (NumOpsWithSameOpcodeParent == 0) {
1679 NumOpsWithSameOpcodeParent = 1;
1680 OpcodeI = I;
1681 Parent = I->getParent();
1682 } else {
1683 --NumOpsWithSameOpcodeParent;
1684 }
1685 } else {
1686 ++NumOpsWithSameOpcodeParent;
1687 }
1688 }
1689 Hash = hash_combine(
1690 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1691 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1692 }
1693 if (AllUndefs)
1694 return {};
1695 OperandsOrderData Data;
1696 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1697 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1698 Data.Hash = Hash;
1699 return Data;
1700 }
1701
1702 /// Go through the instructions in VL and append their operands.
1703 void appendOperands(ArrayRef<Value *> VL, ArrayRef<ValueList> Operands,
1704 const InstructionsState &S) {
1705 assert(!Operands.empty() && !VL.empty() && "Bad list of operands");
1706 assert((empty() || all_of(Operands,
1707 [this](const ValueList &VL) {
1708 return VL.size() == getNumLanes();
1709 })) &&
1710 "Expected same number of lanes");
1711 assert(S.valid() && "InstructionsState is invalid.");
1712 // IntrinsicInst::isCommutative returns true if swapping the first "two"
1713 // arguments to the intrinsic produces the same result.
1714 Instruction *MainOp = S.getMainOp();
1715 ArgSize = getNumberOfPotentiallyCommutativeOps(MainOp);
1716 OpsVec.resize(ArgSize);
1717 unsigned NumLanes = VL.size();
1718 for (OperandDataVec &Ops : OpsVec)
1719 Ops.resize(NumLanes);
1720 for (unsigned Lane : seq<unsigned>(NumLanes)) {
1721 // Our tree has just 3 nodes: the root and two operands.
1722 // It is therefore trivial to get the APO. We only need to check the
1723 // opcode of V and whether the operand at OpIdx is the LHS or RHS
1724 // operand. The LHS operand of both add and sub is never attached to an
1725 // inversese operation in the linearized form, therefore its APO is
1726 // false. The RHS is true only if V is an inverse operation.
1727
1728 // Since operand reordering is performed on groups of commutative
1729 // operations or alternating sequences (e.g., +, -), we can safely tell
1730 // the inverse operations by checking commutativity.
1731 auto *I = dyn_cast<Instruction>(VL[Lane]);
1732 if (!I && isa<PoisonValue>(VL[Lane])) {
1733 for (unsigned OpIdx : seq<unsigned>(ArgSize))
1734 OpsVec[OpIdx][Lane] = {Operands[OpIdx][Lane], true, false};
1735 continue;
1736 }
1737 bool IsInverseOperation = false;
1738 if (S.isCopyableElement(VL[Lane])) {
1739 // The value is a copyable element.
1740 IsInverseOperation =
1741 !isCommutative(MainOp, VL[Lane], /*IsCopyable=*/true);
1742 } else {
1743 assert(I && "Expected instruction");
1744 Instruction *SelectedOp = convertTo(I, S).first;
1745 // We cannot check commutativity by the converted instruction
1746 // (SelectedOp) because isCommutative also examines def-use
1747 // relationships.
1748 IsInverseOperation = !isCommutative(SelectedOp, I);
1749 }
1750 for (unsigned OpIdx : seq<unsigned>(ArgSize)) {
1751 bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1752 OpsVec[OpIdx][Lane] = {Operands[OpIdx][Lane], APO, false};
1753 }
1754 }
1755 }
1756
1757 /// \returns the number of operands.
1758 unsigned getNumOperands() const { return ArgSize; }
1759
1760 /// \returns the number of lanes.
1761 unsigned getNumLanes() const { return OpsVec[0].size(); }
1762
1763 /// \returns the operand value at \p OpIdx and \p Lane.
1764 Value *getValue(unsigned OpIdx, unsigned Lane) const {
1765 return getData(OpIdx, Lane).V;
1766 }
1767
1768 /// \returns true if the data structure is empty.
1769 bool empty() const { return OpsVec.empty(); }
1770
1771 /// Clears the data.
1772 void clear() { OpsVec.clear(); }
1773
1774 /// \Returns true if there are enough operands identical to \p Op to fill
1775 /// the whole vector (it is mixed with constants or loop invariant values).
1776 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1777 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1778 assert(Op == getValue(OpIdx, Lane) &&
1779 "Op is expected to be getValue(OpIdx, Lane).");
1780 // Small number of loads - try load matching.
1781 if (isa<LoadInst>(Op) && getNumLanes() == 2 && getNumOperands() == 2)
1782 return false;
1783 bool OpAPO = getData(OpIdx, Lane).APO;
1784 bool IsInvariant = L && L->isLoopInvariant(Op);
1785 unsigned Cnt = 0;
1786 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1787 if (Ln == Lane)
1788 continue;
1789 // This is set to true if we found a candidate for broadcast at Lane.
1790 bool FoundCandidate = false;
1791 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1792 OperandData &Data = getData(OpI, Ln);
1793 if (Data.APO != OpAPO || Data.IsUsed)
1794 continue;
1795 Value *OpILane = getValue(OpI, Lane);
1796 bool IsConstantOp = isa<Constant>(OpILane);
1797 // Consider the broadcast candidate if:
1798 // 1. Same value is found in one of the operands.
1799 if (Data.V == Op ||
1800 // 2. The operand in the given lane is not constant but there is a
1801 // constant operand in another lane (which can be moved to the
1802 // given lane). In this case we can represent it as a simple
1803 // permutation of constant and broadcast.
1804 (!IsConstantOp &&
1805 ((Lns > 2 && isa<Constant>(Data.V)) ||
1806 // 2.1. If we have only 2 lanes, need to check that value in the
1807 // next lane does not build same opcode sequence.
1808 (Lns == 2 &&
1809 !getSameOpcode({Op, getValue((OpI + 1) % OpE, Ln)}, TLI) &&
1810 isa<Constant>(Data.V)))) ||
1811 // 3. The operand in the current lane is loop invariant (can be
1812 // hoisted out) and another operand is also a loop invariant
1813 // (though not a constant). In this case the whole vector can be
1814 // hoisted out.
1815 // FIXME: need to teach the cost model about this case for better
1816 // estimation.
1817 (IsInvariant && !isa<Constant>(Data.V) &&
1818 !getSameOpcode({Op, Data.V}, TLI) &&
1819 L->isLoopInvariant(Data.V))) {
1820 FoundCandidate = true;
1821 Data.IsUsed = Data.V == Op;
1822 if (Data.V == Op)
1823 ++Cnt;
1824 break;
1825 }
1826 }
1827 if (!FoundCandidate)
1828 return false;
1829 }
1830 return getNumLanes() == 2 || Cnt > 1;
1831 }
1832
1833 /// Checks if there is at least single compatible operand in lanes other
1834 /// than \p Lane, compatible with the operand \p Op.
1835 bool canBeVectorized(Instruction *Op, unsigned OpIdx, unsigned Lane) const {
1836 assert(Op == getValue(OpIdx, Lane) &&
1837 "Op is expected to be getValue(OpIdx, Lane).");
1838 bool OpAPO = getData(OpIdx, Lane).APO;
1839 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1840 if (Ln == Lane)
1841 continue;
1842 if (any_of(seq<unsigned>(getNumOperands()), [&](unsigned OpI) {
1843 const OperandData &Data = getData(OpI, Ln);
1844 if (Data.APO != OpAPO || Data.IsUsed)
1845 return true;
1846 Value *OpILn = getValue(OpI, Ln);
1847 return (L && L->isLoopInvariant(OpILn)) ||
1848 (getSameOpcode({Op, OpILn}, TLI) &&
1849 allSameBlock({Op, OpILn}));
1850 }))
1851 return true;
1852 }
1853 return false;
1854 }
1855
1856 public:
1857 /// Initialize with all the operands of the instruction vector \p RootVL.
1859 const InstructionsState &S, const BoUpSLP &R)
1860 : TLI(*R.TLI), DL(*R.DL), SE(*R.SE), R(R),
1861 L(R.LI->getLoopFor(S.getMainOp()->getParent())) {
1862 // Append all the operands of RootVL.
1863 appendOperands(RootVL, Operands, S);
1864 }
1865
1866 /// Initialize with flattened operand columns of an associative node.
1867 /// ArgSize is taken from \p Operands, APO is always false.
1869 const BoUpSLP &R)
1870 : TLI(*R.TLI), DL(*R.DL), SE(*R.SE), R(R), L(R.LI->getLoopFor(BB)) {
1871 assert(!Operands.empty() && "Expected at least one operand column");
1872 ArgSize = Operands.size();
1873 OpsVec.resize(ArgSize);
1874 unsigned NumLanes = Operands.front().size();
1875 for (auto [OpIdx, Ops] : enumerate(OpsVec)) {
1876 Ops.resize(NumLanes);
1877 for (unsigned Lane : seq<unsigned>(NumLanes))
1878 Ops[Lane] = OperandData(Operands[OpIdx][Lane], /*APO=*/false,
1879 /*IsUsed=*/false);
1880 }
1881 }
1882
1883 /// \Returns a value vector with the operands across all lanes for the
1884 /// opearnd at \p OpIdx.
1885 ValueList getVL(unsigned OpIdx) const {
1886 ValueList OpVL(OpsVec[OpIdx].size());
1887 assert(OpsVec[OpIdx].size() == getNumLanes() &&
1888 "Expected same num of lanes across all operands");
1889 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1890 OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1891 return OpVL;
1892 }
1893
1894 // Performs operand reordering for 2 or more operands.
1895 // The original operands are in OrigOps[OpIdx][Lane].
1896 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1897 void reorder() {
1898 unsigned NumOperands = getNumOperands();
1899 unsigned NumLanes = getNumLanes();
1900 // Each operand has its own mode. We are using this mode to help us select
1901 // the instructions for each lane, so that they match best with the ones
1902 // we have selected so far.
1903 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1904
1905 // This is a greedy single-pass algorithm. We are going over each lane
1906 // once and deciding on the best order right away with no back-tracking.
1907 // However, in order to increase its effectiveness, we start with the lane
1908 // that has operands that can move the least. For example, given the
1909 // following lanes:
1910 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
1911 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
1912 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
1913 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
1914 // we will start at Lane 1, since the operands of the subtraction cannot
1915 // be reordered. Then we will visit the rest of the lanes in a circular
1916 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1917
1918 // Find the first lane that we will start our search from.
1919 unsigned FirstLane = getBestLaneToStartReordering();
1920
1921 // Initialize the modes.
1922 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1923 Value *OpLane0 = getValue(OpIdx, FirstLane);
1924 // Keep track if we have instructions with all the same opcode on one
1925 // side.
1926 if (auto *OpILane0 = dyn_cast<Instruction>(OpLane0)) {
1927 // Check if OpLane0 should be broadcast.
1928 if (shouldBroadcast(OpLane0, OpIdx, FirstLane) ||
1929 !canBeVectorized(OpILane0, OpIdx, FirstLane))
1930 ReorderingModes[OpIdx] = ReorderingMode::Splat;
1931 else if (isa<LoadInst>(OpILane0))
1932 ReorderingModes[OpIdx] = ReorderingMode::Load;
1933 else
1934 ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1935 } else if (isa<Constant>(OpLane0)) {
1936 ReorderingModes[OpIdx] = ReorderingMode::Constant;
1937 } else if (isa<Argument>(OpLane0)) {
1938 // Our best hope is a Splat. It may save some cost in some cases.
1939 ReorderingModes[OpIdx] = ReorderingMode::Splat;
1940 } else {
1941 llvm_unreachable("Unexpected value kind.");
1942 }
1943 }
1944
1945 // Check that we don't have same operands. No need to reorder if operands
1946 // are just perfect diamond or shuffled diamond match. Do not do it only
1947 // for possible broadcasts.
1948 auto &&SkipReordering = [this]() {
1949 SmallPtrSet<Value *, 4> UniqueValues;
1950 ArrayRef<OperandData> Op0 = OpsVec.front();
1951 for (const OperandData &Data : Op0)
1952 UniqueValues.insert(Data.V);
1954 ArrayRef(OpsVec).slice(1, getNumOperands() - 1)) {
1955 if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1956 return !UniqueValues.contains(Data.V);
1957 }))
1958 return false;
1959 }
1960 return UniqueValues.size() != 2;
1961 };
1962
1963 // If the initial strategy fails for any of the operand indexes, then we
1964 // perform reordering again in a second pass. This helps avoid assigning
1965 // high priority to the failed strategy, and should improve reordering for
1966 // the non-failed operand indexes.
1967 for (int Pass = 0; Pass != 2; ++Pass) {
1968 // Check if no need to reorder operands since they're are perfect or
1969 // shuffled diamond match.
1970 // Need to do it to avoid extra external use cost counting for
1971 // shuffled matches, which may cause regressions.
1972 if (SkipReordering())
1973 break;
1974 // Skip the second pass if the first pass did not fail.
1975 bool StrategyFailed = false;
1976 // Mark all operand data as free to use.
1977 clearUsed();
1978 // We keep the original operand order for the FirstLane, so reorder the
1979 // rest of the lanes. We are visiting the nodes in a circular fashion,
1980 // using FirstLane as the center point and increasing the radius
1981 // distance.
1982 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1983 for (unsigned I = 0; I < NumOperands; ++I)
1984 MainAltOps[I].push_back(getData(I, FirstLane).V);
1985
1986 SmallBitVector UsedLanes(NumLanes);
1987 UsedLanes.set(FirstLane);
1988 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1989 // Visit the lane on the right and then the lane on the left.
1990 for (int Direction : {+1, -1}) {
1991 int Lane = FirstLane + Direction * Distance;
1992 if (Lane < 0 || Lane >= (int)NumLanes)
1993 continue;
1994 UsedLanes.set(Lane);
1995 int LastLane = Lane - Direction;
1996 assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1997 "Out of bounds");
1998 // Look for a good match for each operand.
1999 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
2000 // Search for the operand that matches SortedOps[OpIdx][Lane-1].
2001 std::optional<unsigned> BestIdx =
2002 getBestOperand(OpIdx, Lane, LastLane, ReorderingModes,
2003 MainAltOps[OpIdx], UsedLanes);
2004 // By not selecting a value, we allow the operands that follow to
2005 // select a better matching value. We will get a non-null value in
2006 // the next run of getBestOperand().
2007 if (BestIdx) {
2008 // Swap the current operand with the one returned by
2009 // getBestOperand().
2010 swap(OpIdx, *BestIdx, Lane);
2011 } else {
2012 // Enable the second pass.
2013 StrategyFailed = true;
2014 }
2015 // Try to get the alternate opcode and follow it during analysis.
2016 if (MainAltOps[OpIdx].size() != 2) {
2017 OperandData &AltOp = getData(OpIdx, Lane);
2018 InstructionsState OpS =
2019 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}, TLI);
2020 if (OpS && OpS.isAltShuffle())
2021 MainAltOps[OpIdx].push_back(AltOp.V);
2022 }
2023 }
2024 }
2025 }
2026 // Skip second pass if the strategy did not fail.
2027 if (!StrategyFailed)
2028 break;
2029 }
2030 }
2031
2032#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2033 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
2034 switch (RMode) {
2035 case ReorderingMode::Load:
2036 return "Load";
2037 case ReorderingMode::Opcode:
2038 return "Opcode";
2039 case ReorderingMode::Constant:
2040 return "Constant";
2041 case ReorderingMode::Splat:
2042 return "Splat";
2043 case ReorderingMode::Failed:
2044 return "Failed";
2045 }
2046 llvm_unreachable("Unimplemented Reordering Type");
2047 }
2048
2049 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
2050 raw_ostream &OS) {
2051 return OS << getModeStr(RMode);
2052 }
2053
2054 /// Debug print.
2055 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
2056 printMode(RMode, dbgs());
2057 }
2058
2059 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
2060 return printMode(RMode, OS);
2061 }
2062
2064 const unsigned Indent = 2;
2065 unsigned Cnt = 0;
2066 for (const OperandDataVec &OpDataVec : OpsVec) {
2067 OS << "Operand " << Cnt++ << "\n";
2068 for (const OperandData &OpData : OpDataVec) {
2069 OS.indent(Indent) << "{";
2070 if (Value *V = OpData.V)
2071 OS << *V;
2072 else
2073 OS << "null";
2074 OS << ", APO:" << OpData.APO << "}\n";
2075 }
2076 OS << "\n";
2077 }
2078 return OS;
2079 }
2080
2081 /// Debug print.
2082 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2083#endif
2084 };
2085
2086 /// Evaluate each pair in \p Candidates and return index into \p Candidates
2087 /// for a pair which have highest score deemed to have best chance to form
2088 /// root of profitable tree to vectorize. Return std::nullopt if no candidate
2089 /// scored above the LookAheadHeuristics::ScoreFail. \param Limit Lower limit
2090 /// of the cost, considered to be good enough score.
2091 std::pair<std::optional<int>, int>
2092 findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
2093 int Limit = LookAheadHeuristics::ScoreFail) const {
2094 LookAheadHeuristics LookAhead(*TLI, *DL, *SE, *this, /*NumLanes=*/2,
2095 Opts.slp_max_root_look_ahead_depth);
2096 int BestScore = Limit;
2097 std::optional<int> Index;
2098 for (int I : seq<int>(0, Candidates.size())) {
2099 int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2100 Candidates[I].second,
2101 /*U1=*/nullptr, /*U2=*/nullptr,
2102 /*CurrLevel=*/1, {});
2103 if (Score > BestScore) {
2104 BestScore = Score;
2105 Index = I;
2106 }
2107 }
2108 return std::make_pair(Index, BestScore);
2109 }
2110
2111 /// Checks if the instruction is marked for deletion.
2112 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2113
2114 /// Cached llvm::getPointersDiff(), see SLPAnalysisCache.
2115 std::optional<int64_t>
2116 getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, Value *PtrB,
2117 const DataLayout &DL, ScalarEvolution &SE,
2118 bool StrictCheck = false, bool CheckType = true) const {
2119 return Cache.getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
2120 StrictCheck, CheckType);
2121 }
2122
2123 /// Returns the cached analyses results, shared by all the trees built for
2124 /// the function.
2125 SLPAnalysisCache &getAnalysisCache() const { return Cache; }
2126
2127 /// Checks if the value is used only by the assume-like intrinsics.
2128 bool isEphemeralValue(const Value *V) const { return EphValues.contains(V); }
2129
2130 /// Removes an instruction from its block and eventually deletes it.
2131 /// It's like Instruction::eraseFromParent() except that the actual deletion
2132 /// is delayed until BoUpSLP is destructed.
2134 DeletedInstructions.insert(I);
2135 }
2136
2137 /// Remove instructions from the parent function and clear the operands of \p
2138 /// DeadVals instructions, marking for deletion trivially dead operands.
2139 template <typename T>
2141 ArrayRef<T *> DeadVals,
2142 ArrayRef<ReductionVectorPart> VectorValuesAndScales) {
2144 for (T *V : DeadVals) {
2145 auto *I = cast<Instruction>(V);
2147 }
2148 DenseSet<Value *> Processed;
2149 for (T *V : DeadVals) {
2150 if (!V || !Processed.insert(V).second)
2151 continue;
2152 auto *I = cast<Instruction>(V);
2154 ArrayRef<TreeEntry *> Entries = getTreeEntries(I);
2155 for (Use &U : I->operands()) {
2156 if (auto *OpI = dyn_cast<Instruction>(U.get());
2157 OpI && !DeletedInstructions.contains(OpI) && OpI->hasOneUser() &&
2159 !ExternalUseReplacements.contains(OpI) &&
2160 (Entries.empty() || none_of(Entries, [&](const TreeEntry *Entry) {
2161 return Entry->VectorizedValue == OpI;
2162 })))
2163 DeadInsts.push_back(OpI);
2164 }
2165 I->dropAllReferences();
2166 }
2167 for (T *V : DeadVals) {
2168 auto *I = cast<Instruction>(V);
2169 if (!I->getParent())
2170 continue;
2171 assert((I->use_empty() || all_of(I->uses(),
2172 [&](Use &U) {
2173 return isDeleted(
2174 cast<Instruction>(U.getUser()));
2175 })) &&
2176 "trying to erase instruction with users.");
2177 I->removeFromParent();
2178 SE->forgetValue(I);
2179 }
2180 // Process the dead instruction list until empty.
2181 while (!DeadInsts.empty()) {
2182 Value *V = DeadInsts.pop_back_val();
2184 if (!VI || !VI->getParent())
2185 continue;
2187 "Live instruction found in dead worklist!");
2188 assert(VI->use_empty() && "Instructions with uses are not dead.");
2189
2190 // Don't lose the debug info while deleting the instructions.
2191 salvageDebugInfo(*VI);
2192
2193 // Null out all of the instruction's operands to see if any operand
2194 // becomes dead as we go.
2195 for (Use &OpU : VI->operands()) {
2196 Value *OpV = OpU.get();
2197 if (!OpV)
2198 continue;
2199 OpU.set(nullptr);
2200
2201 if (!OpV->use_empty())
2202 continue;
2203
2204 // If the operand is an instruction that became dead as we nulled out
2205 // the operand, and if it is 'trivially' dead, delete it in a future
2206 // loop iteration.
2207 if (auto *OpI = dyn_cast<Instruction>(OpV))
2208 if (!DeletedInstructions.contains(OpI) &&
2209 !ExternalUseReplacements.contains(OpI) &&
2210 (!OpI->getType()->isVectorTy() ||
2211 none_of(VectorValuesAndScales,
2212 [&](const ReductionVectorPart &V) {
2213 return V.Vec == OpI;
2214 })) &&
2216 DeadInsts.push_back(OpI);
2217 }
2218
2219 VI->removeFromParent();
2220 eraseInstruction(VI);
2221 SE->forgetValue(VI);
2222 }
2223 }
2224
2225 /// Checks if the instruction was already analyzed for being possible
2226 /// reduction root.
2228 return AnalyzedReductionsRoots.count(I);
2229 }
2230 /// Register given instruction as already analyzed for being possible
2231 /// reduction root.
2233 AnalyzedReductionsRoots.insert(I);
2234 }
2235 /// Checks if the provided list of reduced values was checked already for
2236 /// vectorization.
2238 return AnalyzedReductionVals.contains(hash_value(VL));
2239 }
2240 /// Adds the list of reduced values to list of already checked values for the
2241 /// vectorization.
2243 AnalyzedReductionVals.insert(hash_value(VL));
2244 }
2245 /// Checks if the value was already a part of the analyzed vector node.
2246 bool isAnalyzedScalar(const Value *V) const {
2247 return AnalyzedScalars.contains(V);
2248 }
2249 /// Checks if the given bundle was already rejected as non-vectorizable.
2251 return AnalyzedBundles.contains(hash_value(VL));
2252 }
2253 /// Registers the bundle as rejected for the vectorization.
2255 AnalyzedBundles.insert(hash_value(VL));
2256 }
2257 /// Clear the list of the analyzed reduction root instructions.
2259 AnalyzedReductionsRoots.clear();
2260 AnalyzedReductionVals.clear();
2261 AnalyzedBundles.clear();
2262 AnalyzedMinBWVals.clear();
2263 }
2264 /// Checks if the given value is gathered in one of the nodes.
2265 bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const {
2266 return any_of(MustGather, [&](Value *V) { return Vals.contains(V); });
2267 }
2268 /// Checks if the given value is gathered in one of the nodes.
2269 bool isGathered(const Value *V) const {
2270 return MustGather.contains(V);
2271 }
2272 /// Checks if the specified value was not schedule.
2273 bool isNotScheduled(const Value *V) const {
2274 return NonScheduledFirst.contains(V);
2275 }
2276
2277 /// Check if \p V is a peeled reassociated scalar still owned by a live
2278 /// (non-deleted, non-gathered) tree entry.
2279 bool isReassocScalarVectorized(const Value *V) const {
2280 auto It = ReassocScalarToTreeEntries.find(V);
2281 return It != ReassocScalarToTreeEntries.end() &&
2282 any_of(It->second, [&](const TreeEntry *E) {
2283 return !DeletedNodes.contains(E) &&
2284 !TransformedToGatherNodes.contains(E);
2285 });
2286 }
2287
2288 /// Check if the value is vectorized in the tree.
2289 bool isVectorized(const Value *V) const {
2290 assert(V && "V cannot be nullptr.");
2292 return true;
2293 return any_of(getTreeEntries(V), [&](const TreeEntry *E) {
2294 return !DeletedNodes.contains(E) && !TransformedToGatherNodes.contains(E);
2295 });
2296 }
2297
2298 /// Returns true if the role of \p I is already decided by its user: a deleted
2299 /// user was folded into some other vector by an earlier attempt.
2301 return any_of(I->users(), [&](User *U) {
2302 auto *UI = dyn_cast<Instruction>(U);
2303 return UI && isDeleted(UI);
2304 });
2305 }
2306
2307 /// Checks if it is legal and profitable to build SplitVectorize node for the
2308 /// given \p VL.
2309 /// \param Op1 first homogeneous scalars.
2310 /// \param Op2 second homogeneous scalars.
2311 /// \param ReorderIndices indices to reorder the scalars.
2312 /// \returns true if the node was successfully built.
2314 const InstructionsState &LocalState,
2317 OrdersType &ReorderIndices) const;
2318
2319 /// \returns Cast context for the given graph node.
2321 getCastContextHint(const TreeEntry &TE) const;
2322
2323 ~BoUpSLP();
2324
2325private:
2326 /// Determine if a node \p E in can be demoted to a smaller type with a
2327 /// truncation. We collect the entries that will be demoted in ToDemote.
2328 /// \param E Node for analysis
2329 /// \param ToDemote indices of the nodes to be demoted.
2330 bool collectValuesToDemote(
2331 const TreeEntry &E, bool IsProfitableToDemoteRoot, unsigned &BitWidth,
2333 const SmallDenseSet<unsigned, 8> &NodesToKeepBWs, unsigned &MaxDepthLevel,
2334 bool &IsProfitableToDemote, bool IsTruncRoot) const;
2335
2336 /// Builds the list of reorderable operands on the edges \p Edges of the \p
2337 /// UserTE, which allow reordering (i.e. the operands can be reordered because
2338 /// they have only one user and reordarable).
2339 /// \param ReorderableGathers List of all gather nodes that require reordering
2340 /// (e.g., gather of extractlements or partially vectorizable loads).
2341 /// \param GatherOps List of gather operand nodes for \p UserTE that require
2342 /// reordering, subset of \p NonVectorized.
2343 void buildReorderableOperands(
2344 TreeEntry *UserTE,
2345 SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2346 const SmallPtrSetImpl<const TreeEntry *> &ReorderableGathers,
2347 SmallVectorImpl<TreeEntry *> &GatherOps);
2348
2349 /// Checks if the given \p TE is a gather node with clustered reused scalars
2350 /// and reorders it per given \p Mask.
2351 void reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const;
2352
2353 /// Checks if all users of \p I are the part of the vectorization tree.
2354 bool areAllUsersVectorized(
2355 Instruction *I,
2356 const SmallDenseSet<Value *> *VectorizedVals = nullptr) const;
2357
2358 /// Estimates the number of scalar instructions in the tree, each weighted by
2359 /// its loop-nest trip count (nest-invariant entries are dropped when
2360 /// \p TreeLoop is non-null).
2361 uint64_t getNumScalarInsts(bool HasTreeLoop);
2362
2363 /// Estimates the number of vector instructions (including buildvectors,
2364 /// shuffles, and, if \p CountExtracts is set, extracts) the tree produces,
2365 /// weighted like getNumScalarInsts().
2366 uint64_t getNumVectorInsts(bool HasTreeLoop, bool CountExtracts = true);
2367
2368 /// Returns true if the instruction-count veto is skipped for a tree costed at
2369 /// \p TreeCost because it contains a poor-throughput operation whose real
2370 /// vector savings the count check does not model.
2371 bool bypassesInstCountCheck(InstructionCost TreeCost) const;
2372
2373 /// Collects into \p UserOps the user operations of the gathers of the scalars
2374 /// of \p E, for TTI::getBuildVectorContextHint(). Returns false if no user is
2375 /// found or some user cannot be described.
2376 bool
2377 collectGatherUserOps(const TreeEntry &E,
2379
2380 /// \returns the fadd/fsub user of the single-use fmul \p I, which the
2381 /// backend fuses with \p I into an fmuladd in the scalar code, and the cost
2382 /// of that fmuladd, or {nullptr, invalid cost}. If \p InTree is set, the
2383 /// users, whose fusion is accounted for by the tree, are not returned.
2384 std::pair<Instruction *, InstructionCost>
2385 getFMulFusingUser(Instruction *I, bool InTree = true) const;
2386
2387 /// \returns true if the fadd/fsub \p U, fused with its fmul operand by the
2388 /// backend, is a vectorized tree scalar whose lane is priced as fmuladd.
2389 /// Peeled reassociated scalars are priced as plain fadd/fsub.
2390 bool isFusedVectorizedFAddSub(Instruction *U) const;
2391
2392 /// \returns the scalar cost of the fmul lanes of \p TE that are priced as
2393 /// fused into their vectorized fadd/fsub users. If the node is turned into a
2394 /// gather, these fmuls stay scalar and lose the fusion, so the gather
2395 /// alternative must pay their full price.
2396 InstructionCost getUnfusedFMulsPenalty(const TreeEntry &TE) const;
2397
2398 /// \returns the graph entry for the \p Idx operand of the \p E entry.
2399 const TreeEntry *getOperandEntry(const TreeEntry *E, unsigned Idx) const;
2400 TreeEntry *getOperandEntry(TreeEntry *E, unsigned Idx) {
2401 return const_cast<TreeEntry *>(
2402 getOperandEntry(const_cast<const TreeEntry *>(E), Idx));
2403 }
2404
2405 /// Gets the root instruction for the given node. If the node is a
2406 /// non-widened strided load/store node with the reverse order, the root
2407 /// instruction is the last one, otherwise it is the main operation.
2408 Instruction *getRootEntryInstruction(const TreeEntry &Entry) const;
2409
2410 /// \returns the scale of the given tree entry to the loop iteration.
2411 /// \p Scalar is the scalar value from the entry, if using the parent for the
2412 /// external use.
2413 /// \p U is the user of the vectorized value from the entry, if using the
2414 /// parent for the external use.
2415 uint64_t getScaleToLoopIterations(const TreeEntry &TE,
2416 Value *Scalar = nullptr,
2417 Instruction *U = nullptr);
2418
2419 /// \returns the product of trip counts of the loop \p L and all of its
2420 /// enclosing loops. Unlike the state kept by getScaleToLoopIterations(),
2421 /// this helper depends only on the loop structure and is independent of
2422 /// per-entry operand invariance. Returns 1 when loop-aware cost modeling
2423 /// is disabled or \p L is null.
2424 uint64_t getLoopNestScale(const Loop *L);
2425
2426 /// \returns a refined execution scale for a gather/buildvector tree entry
2427 /// \p TE. The scale is computed as the average of per-lane execution
2428 /// scales: each lane's scale is the loop-nest scale of the loop that
2429 /// contains the lane's defining instruction (or 1 if the lane is a
2430 /// constant / loop-invariant non-instruction value). This models the
2431 /// LICM hoisting that optimizeGatherSequence() performs after vectorization
2432 /// for inserts with loop-invariant operands. Falls back to the whole-entry
2433 /// scale when per-lane information is unavailable or the feature is off.
2434 uint64_t getGatherNodeEffectiveScale(const TreeEntry &TE,
2435 Instruction *U = nullptr);
2436
2437 /// \returns the loop-nest execution scale of \p TE.
2438 uint64_t getEntryEffectiveScale(const TreeEntry &TE,
2439 Instruction *U = nullptr);
2440
2441 /// Get the loop nest for the given loop \p L.
2442 ArrayRef<const Loop *> getLoopNest(const Loop *L);
2443
2444 /// \returns the cost of the vectorizable entry.
2445 InstructionCost getEntryCost(const TreeEntry *E,
2446 ArrayRef<Value *> VectorizedVals,
2447 SmallPtrSetImpl<Value *> &CheckedExtracts);
2448
2449 /// Estimates spill/reload cost from vector register pressure for \p E at the
2450 /// point of emitting its vector result type \p FinalVecTy. \p ScalarTy is the
2451 /// scalar/slot type used to widen into \p VecTy/\p FinalVecTy and may itself
2452 /// be a FixedVectorType in ReVec mode or an adjusted type due to MinBWs.
2454 getVectorSpillReloadCost(const TreeEntry *E, Type *ScalarTy, Type *VecTy,
2455 Type *FinalVecTy,
2456 const TTI::TargetCostKind CostKind) const;
2457
2458 /// This is the recursive part of buildTree.
2459 void buildTreeRec(ArrayRef<Value *> Roots, unsigned Depth, const EdgeInfo &EI,
2460 unsigned InterleaveFactor = 0);
2461
2462 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2463 /// be vectorized to use the original vector (or aggregate "bitcast" to a
2464 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2465 /// returns false, setting \p CurrentOrder to either an empty vector or a
2466 /// non-identity permutation that allows to reuse extract instructions.
2467 /// \param ResizeAllowed indicates whether it is allowed to handle subvector
2468 /// extract order.
2469 bool canReuseExtract(ArrayRef<Value *> VL,
2470 SmallVectorImpl<unsigned> &CurrentOrder,
2471 bool ResizeAllowed = false) const;
2472
2473 /// Vectorize a single entry in the tree.
2474 Value *vectorizeTree(TreeEntry *E);
2475
2476 /// Vectorize a single entry in the tree, the \p Idx-th operand of the entry
2477 /// \p E.
2478 Value *vectorizeOperand(TreeEntry *E, unsigned NodeIdx);
2479
2480 /// Create a new vector from a list of scalar values. Produces a sequence
2481 /// which exploits values reused across lanes, and arranges the inserts
2482 /// for ease of later optimization.
2483 template <typename BVTy, typename ResTy, typename... Args>
2484 ResTy processBuildVector(const TreeEntry *E, Type *ScalarTy, Args &...Params);
2485
2486 /// Handles the gather of zero-extended sub-fields of the same wider integer
2487 /// scalar, emitted as a bitcast to the field vector plus a permutation and
2488 /// an extension to the lane type, if the gathered values match.
2489 template <typename ResTy, typename BVTy>
2490 std::optional<ResTy> processExtractedFieldsGather(
2491 BVTy &ShuffleBuilder, const TreeEntry *E, Type *ScalarTy,
2493 ArrayRef<std::pair<const TreeEntry *, unsigned>> SubVectors);
2494
2495 /// Create a new vector from a list of scalar values. Produces a sequence
2496 /// which exploits values reused across lanes, and arranges the inserts
2497 /// for ease of later optimization.
2498 Value *createBuildVector(const TreeEntry *E, Type *ScalarTy);
2499
2500 /// Returns the instruction in the bundle, which can be used as a base point
2501 /// for scheduling. Usually it is the last instruction in the bundle, except
2502 /// for the case when all operands are external (in this case, it is the first
2503 /// instruction in the list).
2504 Instruction &getLastInstructionInBundle(const TreeEntry *E);
2505
2506 /// Tries to find extractelement instructions with constant indices from fixed
2507 /// vector type and gather such instructions into a bunch, which highly likely
2508 /// might be detected as a shuffle of 1 or 2 input vectors. If this attempt
2509 /// was successful, the matched scalars are replaced by poison values in \p VL
2510 /// for future analysis.
2511 std::optional<TargetTransformInfo::ShuffleKind>
2512 tryToGatherSingleRegisterExtractElements(MutableArrayRef<Value *> VL,
2513 SmallVectorImpl<int> &Mask) const;
2514
2515 /// Tries to find extractelement instructions with constant indices from fixed
2516 /// vector type and gather such instructions into a bunch, which highly likely
2517 /// might be detected as a shuffle of 1 or 2 input vectors. If this attempt
2518 /// was successful, the matched scalars are replaced by poison values in \p VL
2519 /// for future analysis.
2521 tryToGatherExtractElements(SmallVectorImpl<Value *> &VL,
2523 unsigned NumParts) const;
2524
2525 /// Checks if the gathered \p VL can be represented as a single register
2526 /// shuffle(s) of previous tree entries.
2527 /// \param TE Tree entry checked for permutation.
2528 /// \param VL List of scalars (a subset of the TE scalar), checked for
2529 /// permutations. Must form single-register vector.
2530 /// \param ForOrder Tries to fetch the best candidates for ordering info. Also
2531 /// commands to build the mask using the original vector value, without
2532 /// relying on the potential reordering.
2533 /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2534 /// previous tree entries. \p Part of \p Mask is filled with the shuffle mask.
2535 std::optional<TargetTransformInfo::ShuffleKind>
2536 isGatherShuffledSingleRegisterEntry(
2537 const TreeEntry *TE, ArrayRef<Value *> VL, MutableArrayRef<int> Mask,
2538 SmallVectorImpl<const TreeEntry *> &Entries, unsigned Part, bool ForOrder,
2539 unsigned SliceSize);
2540
2541 /// Checks if the gathered \p VL can be represented as multi-register
2542 /// shuffle(s) of previous tree entries.
2543 /// \param TE Tree entry checked for permutation.
2544 /// \param VL List of scalars (a subset of the TE scalar), checked for
2545 /// permutations.
2546 /// \param ForOrder Tries to fetch the best candidates for ordering info. Also
2547 /// commands to build the mask using the original vector value, without
2548 /// relying on the potential reordering.
2549 /// \returns per-register series of ShuffleKind, if gathered values can be
2550 /// represented as shuffles of previous tree entries. \p Mask is filled with
2551 /// the shuffle mask (also on per-register base).
2553 isGatherShuffledEntry(
2554 const TreeEntry *TE, ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask,
2556 unsigned NumParts, Type *ScalarTy, bool ForOrder = false);
2557
2558 /// \returns the cost of gathering (inserting) the values in \p VL into a
2559 /// vector.
2560 /// \param ForPoisonSrc true if initial vector is poison, false otherwise.
2561 InstructionCost getGatherCost(ArrayRef<Value *> VL, bool ForPoisonSrc,
2562 Type *ScalarTy) const;
2563
2564 /// Set the Builder insert point to one after the last instruction in
2565 /// the bundle
2566 void setInsertPointAfterBundle(const TreeEntry *E);
2567
2568 /// \returns a vector from a collection of scalars in \p VL. if \p Root is not
2569 /// specified, the starting vector value is poison.
2570 Value *
2571 gather(ArrayRef<Value *> VL, Value *Root, Type *ScalarTy,
2572 function_ref<Value *(Value *, Value *, ArrayRef<int>)> CreateShuffle);
2573
2574 /// \returns whether the VectorizableTree is fully vectorizable and will
2575 /// be beneficial even the tree height is tiny.
2576 bool isFullyVectorizableTinyTree(bool ForReduction) const;
2577
2578 /// Run through the list of all gathered loads in the graph and try to find
2579 /// vector loads/masked gathers instead of regular gathers. Later these loads
2580 /// are reshufled to build final gathered nodes.
2581 void tryToVectorizeGatheredLoads(
2582 const SmallMapVector<
2583 std::tuple<BasicBlock *, Value *, Type *>,
2584 SmallVector<SmallVector<std::pair<LoadInst *, int64_t>>>, 8>
2585 &GatheredLoads);
2586
2587 /// Run through the gather nodes that are splats of the same instruction and
2588 /// try to vectorize the unique splatted values together as a separate
2589 /// subtree. The splat gathers are then emitted as broadcasts of the
2590 /// vectorized subtree instead of insertion sequences.
2591 void tryToVectorizeSplatGatheredScalars();
2592
2593 /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2594 /// users of \p TE and collects the stores. It returns the map from the store
2595 /// pointers to the collected stores.
2597 collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2598
2599 /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2600 /// stores in \p StoresVec can form a vector instruction. If so it returns
2601 /// true and populates \p ReorderIndices with the shuffle indices of the
2602 /// stores when compared to the sorted vector.
2603 bool canFormVector(ArrayRef<StoreInst *> StoresVec,
2604 OrdersType &ReorderIndices) const;
2605
2606 /// Iterates through the users of \p TE, looking for scalar stores that can be
2607 /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2608 /// their order and builds an order index vector for each store bundle. It
2609 /// returns all these order vectors found.
2610 /// We run this after the tree has formed, otherwise we may come across user
2611 /// instructions that are not yet in the tree.
2613 findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2614
2615 /// Tries to reorder the gathering node for better vectorization
2616 /// opportunities.
2617 void reorderGatherNode(TreeEntry &TE);
2618
2619 /// Checks if the tree represents disjoint or reduction of shl(zext, (0, 8,
2620 /// .., 56))-like pattern.
2621 /// If the int shifts unique, also strided, but not ordered, sets \p Order.
2622 /// If the node can be represented as a bitcast + bswap, sets \p IsBSwap.
2623 /// If the root nodes are loads, sets \p ForLoads to true.
2624 bool matchesShlZExt(const TreeEntry &TE, OrdersType &Order, bool &IsBSwap,
2625 bool &ForLoads) const;
2626
2627 /// Computes the packing layout of an or reduction of masked shifted values
2628 /// packing per-lane byte fields of the scalar result (and(shl(x, s), m) per
2629 /// lane). The field analysis proves the disjointness of the fields, so the
2630 /// reduction operations are not required to be marked disjoint.
2631 std::optional<BitPackInfo> computeBitPackLayout(const TreeEntry &TE) const;
2632
2633 /// Returns the node packed for the shl operand \p LhsTE of a bitpack root.
2634 /// If \p LhsTE is a (zext of) and(lshr/shl(x, C), mask) chain extracting
2635 /// the same bits of every lane of x, returns the node of x and sets the
2636 /// shift amounts of \p Info to the field offset in the lanes of x.
2637 /// Otherwise, returns \p LhsTE.
2638 const TreeEntry *getBitPackSource(const TreeEntry &LhsTE,
2639 BitPackInfo &Info) const;
2640
2641 /// Checks if the tree entry is the root of such a reduction, the tree nodes
2642 /// are in the expected state and it is profitable to model as a bit pack.
2643 bool matchesBitPack(const TreeEntry &TE) const;
2644
2645 /// If the node's lanes are a plain zext, returns the source bit width:
2646 /// compacting the vectorized lanes back to it is free. Copyable lanes force
2647 /// a blend after the extend, so the vectorized value is not a plain zext.
2648 unsigned getZExtSrcWidth(const TreeEntry &TE) const;
2649
2650 /// Checks if the \p SelectTE matches zext+selects, which can be inversed for
2651 /// better codegen in case like zext (icmp ne), select (icmp eq), ....
2652 bool matchesInversedZExtSelect(
2653 const TreeEntry &SelectTE,
2654 SmallVectorImpl<unsigned> &InversedCmpsIndices) const;
2655
2656 /// Checks if the tree is reduction or of bit selects, like select %cmp, <1,
2657 /// 2, 4, 8, ..>, zeroinitializer, which can be reduced just to a bitcast %cmp
2658 /// to in.
2659 bool matchesSelectOfBits(const TreeEntry &SelectTE) const;
2660
2661 class TreeEntry {
2662 public:
2663 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2664 TreeEntry(VecTreeTy &Container) : Container(Container) {}
2665
2666 /// \returns Common mask for reorder indices and reused scalars.
2667 SmallVector<int> getCommonMask() const {
2668 if (State == TreeEntry::SplitVectorize)
2669 return {};
2670 SmallVector<int> Mask;
2671 inversePermutation(ReorderIndices, Mask);
2672 addMask(Mask, ReuseShuffleIndices);
2673 return Mask;
2674 }
2675
2676 /// \returns The mask for split nodes.
2677 SmallVector<int> getSplitMask() const {
2678 assert(State == TreeEntry::SplitVectorize && !ReorderIndices.empty() &&
2679 "Expected only split vectorize node.");
2680 unsigned CommonVF = std::max<unsigned>(
2681 CombinedEntriesWithIndices.back().second,
2682 Scalars.size() - CombinedEntriesWithIndices.back().second);
2683 const unsigned Scale = getNumElements(Scalars.front()->getType());
2684 CommonVF *= Scale;
2685 SmallVector<int> Mask(getVectorFactor() * Scale, PoisonMaskElem);
2686 for (auto [Idx, I] : enumerate(ReorderIndices)) {
2687 for (unsigned K : seq<unsigned>(Scale)) {
2688 Mask[Scale * I + K] =
2689 Scale * Idx + K +
2690 (Idx >= CombinedEntriesWithIndices.back().second
2691 ? CommonVF - CombinedEntriesWithIndices.back().second * Scale
2692 : 0);
2693 }
2694 }
2695 return Mask;
2696 }
2697
2698 /// Updates (reorders) SplitVectorize node according to the given mask \p
2699 /// Mask and order \p MaskOrder.
2700 void reorderSplitNode(unsigned Idx, ArrayRef<int> Mask,
2701 ArrayRef<int> MaskOrder);
2702
2703 /// \returns true if the scalars in VL are equal to this entry.
2704 bool isSame(ArrayRef<Value *> VL) const {
2705 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2706 if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2707 return std::equal(VL.begin(), VL.end(), Scalars.begin());
2708 return VL.size() == Mask.size() &&
2709 std::equal(VL.begin(), VL.end(), Mask.begin(),
2710 [Scalars](Value *V, int Idx) {
2711 return isa<PoisonValue>(V) ||
2712 (Idx != PoisonMaskElem && V == Scalars[Idx]);
2713 });
2714 };
2715 if (!ReorderIndices.empty()) {
2716 // TODO: implement matching if the nodes are just reordered, still can
2717 // treat the vector as the same if the list of scalars matches VL
2718 // directly, without reordering.
2719 SmallVector<int> Mask;
2720 inversePermutation(ReorderIndices, Mask);
2721 if (VL.size() == Scalars.size())
2722 return IsSame(Scalars, Mask);
2723 if (VL.size() == ReuseShuffleIndices.size()) {
2724 addMask(Mask, ReuseShuffleIndices);
2725 return IsSame(Scalars, Mask);
2726 }
2727 return false;
2728 }
2729 return IsSame(Scalars, ReuseShuffleIndices);
2730 }
2731
2732 /// \returns true if current entry has same operands as \p TE.
2733 bool hasEqualOperands(const TreeEntry &TE) const {
2734 if (TE.getNumOperands() != getNumOperands())
2735 return false;
2736 SmallBitVector Used(getNumOperands());
2737 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2738 unsigned PrevCount = Used.count();
2739 for (unsigned K = 0; K < E; ++K) {
2740 if (Used.test(K))
2741 continue;
2742 if (getOperand(K) == TE.getOperand(I)) {
2743 Used.set(K);
2744 break;
2745 }
2746 }
2747 // Check if we actually found the matching operand.
2748 if (PrevCount == Used.count())
2749 return false;
2750 }
2751 return true;
2752 }
2753
2754 /// \return Final vectorization factor for the node. Defined by the total
2755 /// number of vectorized scalars, including those, used several times in the
2756 /// entry and counted in the \a ReuseShuffleIndices, if any.
2757 unsigned getVectorFactor() const {
2758 if (!ReuseShuffleIndices.empty())
2759 return ReuseShuffleIndices.size();
2760 return Scalars.size();
2761 };
2762
2763 /// Checks if the current node is a gather node.
2764 bool isGather() const { return State == NeedToGather; }
2765
2766 /// Checks if the current node is in reverse order.
2767 bool isReverse() const {
2768 return !ReorderIndices.empty() && isReverseOrder(ReorderIndices);
2769 }
2770
2771 /// A vector of scalars.
2772 ValueList Scalars;
2773
2774 /// The Scalars are vectorized into this value. It is initialized to Null.
2775 WeakTrackingVH VectorizedValue = nullptr;
2776
2777 /// Do we need to gather this sequence or vectorize it
2778 /// (either with vector instruction or with scatter/gather
2779 /// intrinsics for store/load)?
2780 enum EntryState {
2781 Vectorize, ///< The node is regularly vectorized.
2782 ScatterVectorize, ///< Masked scatter/gather node.
2783 StridedVectorize, ///< Strided loads (and stores)
2784 ExpandVectorize, ///< Masked stores, the values are expanded into
2785 ///< a wider vector and vectorized with a mask.
2786 CompressVectorize, ///< (Masked) load with compress.
2787 BlendedLoadVectorize, ///< (Masked) loads blended via `select` from two
2788 ///< candidate base pointers.
2789 NeedToGather, ///< Gather/buildvector node.
2790 CombinedVectorize, ///< Vectorized node, combined with its user into more
2791 ///< complex node like select/cmp to minmax, mul/add to
2792 ///< fma, etc. Must be used for the following nodes in
2793 ///< the pattern, not the very first one.
2794 SplitVectorize, ///< Splits the node into 2 subnodes, vectorizes them
2795 ///< independently and then combines back.
2796 };
2797 EntryState State;
2798
2799 /// List of combined opcodes supported by the vectorizer.
2800 enum CombinedOpcode {
2801 NotCombinedOp = -1,
2802 MinMax = Instruction::OtherOpsEnd + 1,
2803 FMulAdd,
2804 ReducedBitcast,
2805 ReducedBitcastBSwap,
2806 ReducedBitcastLoads,
2807 ReducedBitcastBSwapLoads,
2808 ReducedBitPack,
2809 ReducedCmpBitcast,
2810 ExtractedFieldsBSwap,
2811 };
2812 CombinedOpcode CombinedOp = NotCombinedOp;
2813
2814 /// Does this sequence require some shuffling?
2815 SmallVector<int, 4> ReuseShuffleIndices;
2816
2817 /// Does this entry require reordering?
2818 SmallVector<unsigned, 4> ReorderIndices;
2819
2820 /// Points back to the VectorizableTree.
2821 ///
2822 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
2823 /// to be a pointer and needs to be able to initialize the child iterator.
2824 /// Thus we need a reference back to the container to translate the indices
2825 /// to entries.
2826 VecTreeTy &Container;
2827
2828 /// The TreeEntry index containing the user of this entry.
2829 EdgeInfo UserTreeIndex;
2830
2831 /// The index of this treeEntry in VectorizableTree.
2832 unsigned Idx = 0;
2833
2834 /// For gather/buildvector/alt opcode nodes, which are combined from
2835 /// other nodes as a series of insertvector instructions.
2836 SmallVector<std::pair<unsigned, unsigned>, 2> CombinedEntriesWithIndices;
2837
2838 /// For ExtractValue entries that are vectorized via the struct-call path
2839 /// (checkEVsForVecCalls succeeded during tree building), stores the common
2840 /// field-index path shared by all scalars in the bundle. Empty for all
2841 /// other entry kinds.
2842 SmallVector<unsigned, 1> StructEVIndices;
2843
2844 private:
2845 /// The operands of each instruction in each lane Operands[op_index][lane].
2846 /// Note: This helps avoid the replication of the code that performs the
2847 /// reordering of operands during buildTreeRec() and vectorizeTree().
2848 SmallVector<ValueList, 2> Operands;
2849
2850 /// Copyable elements of the entry node.
2851 SmallPtrSet<const Value *, 4> CopyableElements;
2852
2853 /// Intermediate instructions peeled from an associative chain (e.g. the
2854 /// inner add in add(add(v0,x),v1)). Not part of Scalars.
2855 SmallVector<Value *, 4> ReassocScalars;
2856
2857 /// Sign of each flattened operand column of a reassociated add/sub
2858 /// chain, parallel to the operand columns: a negated column is
2859 /// subtracted from the positive total. Empty when no column is negated.
2860 SmallBitVector ReassocNegatedOps;
2861
2862 /// MainOp and AltOp are recorded inside. S should be obtained from
2863 /// newTreeEntry.
2864 InstructionsState S = InstructionsState::invalid();
2865
2866 /// Interleaving factor for interleaved loads Vectorize nodes.
2867 unsigned InterleaveFactor = 0;
2868
2869 /// True if the node does not require scheduling.
2870 bool DoesNotNeedToSchedule = false;
2871
2872 /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2873 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2874 if (Operands.size() < OpIdx + 1)
2875 Operands.resize(OpIdx + 1);
2876 assert(Operands[OpIdx].empty() && "Already resized?");
2877 assert(OpVL.size() <= Scalars.size() &&
2878 "Number of operands is greater than the number of scalars.");
2879 Operands[OpIdx].resize(OpVL.size());
2880 copy(OpVL, Operands[OpIdx].begin());
2881 }
2882
2883 /// Maps values to their lanes in the node.
2884 mutable SmallDenseMap<Value *, unsigned> ValueToLane;
2885
2886 public:
2887 /// Returns interleave factor for interleave nodes.
2888 unsigned getInterleaveFactor() const { return InterleaveFactor; }
2889 /// Sets interleaving factor for the interleaving nodes.
2890 void setInterleave(unsigned Factor) { InterleaveFactor = Factor; }
2891
2892 /// Marks the node as one that does not require scheduling.
2893 void setDoesNotNeedToSchedule() { DoesNotNeedToSchedule = true; }
2894 /// Returns true if the node is marked as one that does not require
2895 /// scheduling.
2896 bool doesNotNeedToSchedule() const { return DoesNotNeedToSchedule; }
2897
2898 /// Set this bundle's operands from \p Operands.
2899 void setOperands(ArrayRef<ValueList> Operands) {
2900 for (unsigned I : seq<unsigned>(Operands.size()))
2901 setOperand(I, Operands[I]);
2902 }
2903
2904 /// Reorders operands of the node to the given mask \p Mask.
2905 void reorderOperands(ArrayRef<int> Mask) {
2906 for (ValueList &Operand : Operands)
2907 reorderScalars(Operand, Mask);
2908 }
2909
2910 /// \returns the \p OpIdx operand of this TreeEntry.
2911 ValueList &getOperand(unsigned OpIdx) {
2912 assert(OpIdx < Operands.size() && "Off bounds");
2913 return Operands[OpIdx];
2914 }
2915
2916 /// \returns the \p OpIdx operand of this TreeEntry.
2917 ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2918 assert(OpIdx < Operands.size() && "Off bounds");
2919 return Operands[OpIdx];
2920 }
2921
2922 /// \returns the number of operands.
2923 unsigned getNumOperands() const { return Operands.size(); }
2924
2925 /// \return the single \p OpIdx operand.
2926 Value *getSingleOperand(unsigned OpIdx) const {
2927 assert(OpIdx < Operands.size() && "Off bounds");
2928 assert(!Operands[OpIdx].empty() && "No operand available");
2929 return Operands[OpIdx][0];
2930 }
2931
2932 /// Some of the instructions in the list have alternate opcodes.
2933 bool isAltShuffle() const { return S.isAltShuffle(); }
2934
2935 Instruction *getMatchingMainOpOrAltOp(Instruction *I) const {
2936 return S.getMatchingMainOpOrAltOp(I);
2937 }
2938
2939 void setOperations(const InstructionsState &S) {
2940 assert(S && "InstructionsState is invalid.");
2941 this->S = S;
2942 }
2943
2944 Instruction *getMainOp() const { return S.getMainOp(); }
2945
2946 Instruction *getAltOp() const { return S.getAltOp(); }
2947
2948 /// Returns the first load of the loads node, the base of the wide load.
2949 /// The main op of the copyable loads may be not the first load.
2950 LoadInst *getFirstLoad() const {
2951 if (!hasCopyableElements())
2952 return cast<LoadInst>(getMainOp());
2953 return cast<LoadInst>(*find_if(Scalars, IsaPred<LoadInst>));
2954 }
2955
2956 /// The main/alternate opcodes for the list of instructions.
2957 unsigned getOpcode() const { return S.getOpcode(); }
2958
2959 unsigned getAltOpcode() const { return S.getAltOpcode(); }
2960
2961 bool hasState() const { return S.valid(); }
2962
2963 /// Add \p V to the list of copyable elements.
2964 void addCopyableElement(Value *V) {
2965 assert(S.isCopyableElement(V) && "Not a copyable element.");
2966 CopyableElements.insert(V);
2967 }
2968
2969 /// Returns true if \p V is a copyable element.
2970 bool isCopyableElement(Value *V) const {
2971 return CopyableElements.contains(V);
2972 }
2973
2974 /// Checks if the value \p V is a transformed instruction, compatible either
2975 /// with main or alternate ops.
2976 bool isExpandedBinOp(Value *V) const {
2977 assert(hasState() && "InstructionsState is invalid.");
2978 if (isCopyableElement(V))
2979 return false;
2980 return S.isExpandedBinOp(V);
2981 }
2982
2983 /// Checks if the operand at index \p Idx of instruction \p I is an expanded
2984 /// operand.
2985 bool isExpandedOperand(Instruction *I, unsigned Idx) const {
2986 assert(hasState() && "InstructionsState is invalid.");
2987 if (isCopyableElement(I))
2988 return false;
2989 if (!isExpandedBinOp(I))
2990 return false;
2991 return S.isExpandedOperand(I, Idx);
2992 }
2993
2994 /// Returns true if any scalar in the list is a copyable element.
2995 bool hasCopyableElements() const { return !CopyableElements.empty(); }
2996
2997 /// Adds \p V to the peeled reassociated scalars.
2998 void addReassocScalar(Value *V) { ReassocScalars.push_back(V); }
2999
3000 /// True if operands were gathered from an associative chain.
3001 bool hasReassocScalars() const { return !ReassocScalars.empty(); }
3002
3003 /// Returns peeled reassociated scalars.
3004 ArrayRef<Value *> getReassocScalars() const { return ReassocScalars; }
3005
3006 /// Records the signs of the flattened operand columns.
3007 void setReassocNegatedOps(const SmallBitVector &NegatedOps) {
3008 assert(NegatedOps.size() == getNumOperands() &&
3009 "Signs must cover all operand columns.");
3010 ReassocNegatedOps = NegatedOps;
3011 }
3012
3013 /// True if operand column \p Idx is subtracted rather than added.
3014 bool isReassocNegatedOp(unsigned Idx) const {
3015 return Idx < ReassocNegatedOps.size() && ReassocNegatedOps[Idx];
3016 }
3017
3018 /// Returns the state of the operations.
3019 const InstructionsState &getOperations() const { return S; }
3020
3021 /// When ReuseReorderShuffleIndices is empty it just returns position of \p
3022 /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
3023 unsigned findLaneForValue(Value *V) const {
3024 auto Res = ValueToLane.try_emplace(V, getVectorFactor());
3025 if (!Res.second)
3026 return Res.first->second;
3027 unsigned &FoundLane = Res.first->getSecond();
3028 // Poison can take any lane, match it to the lane of the first non-poison
3029 // scalar.
3030 auto IsMatch = [V](Value *S) {
3031 return isa<PoisonValue>(V) ? !isa<PoisonValue>(S) : S == V;
3032 };
3033 for (auto *It = find_if(Scalars, IsMatch), *End = Scalars.end();
3034 It != End; std::advance(It, 1)) {
3035 if (!IsMatch(*It))
3036 continue;
3037 FoundLane = std::distance(Scalars.begin(), It);
3038 assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
3039 if (!ReorderIndices.empty())
3040 FoundLane = ReorderIndices[FoundLane];
3041 assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
3042 if (ReuseShuffleIndices.empty())
3043 break;
3044 if (auto *RIt = find(ReuseShuffleIndices, FoundLane);
3045 RIt != ReuseShuffleIndices.end()) {
3046 FoundLane = std::distance(ReuseShuffleIndices.begin(), RIt);
3047 break;
3048 }
3049 }
3050 assert(FoundLane < getVectorFactor() && "Unable to find given value.");
3051 return FoundLane;
3052 }
3053
3054 /// Build a shuffle mask for graph entry which represents a merge of main
3055 /// and alternate operations.
3056 void
3057 buildAltOpShuffleMask(const function_ref<bool(Instruction *)> IsAltOp,
3058 SmallVectorImpl<int> &Mask,
3059 SmallVectorImpl<Value *> *OpScalars = nullptr,
3060 SmallVectorImpl<Value *> *AltScalars = nullptr) const;
3061
3062 /// Return true if this is a non-power-of-2 node.
3063 bool isNonPowOf2Vec() const {
3064 bool IsNonPowerOf2 = !has_single_bit(Scalars.size());
3065 return IsNonPowerOf2;
3066 }
3067
3068 Value *getOrdered(unsigned Idx) const {
3069 if (ReorderIndices.empty())
3070 return Scalars[Idx];
3071 SmallVector<int> Mask;
3072 inversePermutation(ReorderIndices, Mask);
3073 return Scalars[Mask[Idx]];
3074 }
3075
3076#ifndef NDEBUG
3077 /// Debug printer.
3078 LLVM_DUMP_METHOD void dump() const {
3079 dbgs() << Idx << ".\n";
3080 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
3081 dbgs() << "Operand " << OpI << ":\n";
3082 for (const Value *V : Operands[OpI])
3083 dbgs().indent(2) << *V << "\n";
3084 }
3085 dbgs() << "Scalars: \n";
3086 for (Value *V : Scalars) {
3087 dbgs().indent(2) << *V
3088 << ((S && S.isExpandedBinOp(V)) ? " [[Expanded]]\n"
3089 : "\n");
3090 }
3091 dbgs() << "State: ";
3092 if (S && hasCopyableElements())
3093 dbgs() << "[[Copyable]] ";
3094 switch (State) {
3095 case Vectorize:
3096 if (InterleaveFactor > 0) {
3097 dbgs() << "Vectorize with interleave factor " << InterleaveFactor
3098 << "\n";
3099 } else {
3100 dbgs() << "Vectorize\n";
3101 }
3102 break;
3103 case ScatterVectorize:
3104 dbgs() << "ScatterVectorize\n";
3105 break;
3106 case StridedVectorize:
3107 dbgs() << "StridedVectorize\n";
3108 break;
3109 case ExpandVectorize:
3110 dbgs() << "ExpandVectorize\n";
3111 break;
3112 case CompressVectorize:
3113 dbgs() << "CompressVectorize\n";
3114 break;
3115 case BlendedLoadVectorize:
3116 dbgs() << "BlendedLoadVectorize\n";
3117 break;
3118 case NeedToGather:
3119 dbgs() << "NeedToGather\n";
3120 break;
3121 case CombinedVectorize:
3122 dbgs() << "CombinedVectorize\n";
3123 break;
3124 case SplitVectorize:
3125 dbgs() << "SplitVectorize\n";
3126 break;
3127 }
3128 if (S) {
3129 dbgs() << "MainOp: " << *S.getMainOp() << "\n";
3130 dbgs() << "AltOp: " << *S.getAltOp() << "\n";
3131 } else {
3132 dbgs() << "MainOp: NULL\n";
3133 dbgs() << "AltOp: NULL\n";
3134 }
3135 dbgs() << "VectorizedValue: ";
3136 if (VectorizedValue)
3137 dbgs() << *VectorizedValue << "\n";
3138 else
3139 dbgs() << "NULL\n";
3140 dbgs() << "ReuseShuffleIndices: ";
3141 if (ReuseShuffleIndices.empty())
3142 dbgs() << "Empty";
3143 else
3144 for (int ReuseIdx : ReuseShuffleIndices)
3145 dbgs() << ReuseIdx << ", ";
3146 dbgs() << "\n";
3147 dbgs() << "ReorderIndices: ";
3148 for (unsigned ReorderIdx : ReorderIndices)
3149 dbgs() << ReorderIdx << ", ";
3150 dbgs() << "\n";
3151 dbgs() << "UserTreeIndex: ";
3152 if (UserTreeIndex)
3153 dbgs() << UserTreeIndex;
3154 else
3155 dbgs() << "<invalid>";
3156 dbgs() << "\n";
3157 if (!StructEVIndices.empty()) {
3158 dbgs() << "StructEVIndices: ";
3159 interleaveComma(StructEVIndices, dbgs());
3160 dbgs() << "\n";
3161 }
3162 if (!CombinedEntriesWithIndices.empty()) {
3163 dbgs() << "Combined entries: ";
3164 interleaveComma(CombinedEntriesWithIndices, dbgs(), [&](const auto &P) {
3165 dbgs() << "Entry index " << P.first << " with offset " << P.second;
3166 });
3167 dbgs() << "\n";
3168 }
3169 }
3170#endif
3171 };
3172
3173#ifndef NDEBUG
3174 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
3175 InstructionCost VecCost, InstructionCost ScalarCost,
3176 StringRef Banner) const {
3177 dbgs() << "SLP: " << Banner << ":\n";
3178 E->dump();
3179 dbgs() << "SLP: Costs:\n";
3180 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n";
3181 dbgs() << "SLP: VectorCost = " << VecCost << "\n";
3182 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n";
3183 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = "
3184 << ReuseShuffleCost + VecCost - ScalarCost << "\n";
3185 }
3186#endif
3187
3188 /// Create a new gather TreeEntry
3189 TreeEntry *newGatherTreeEntry(ArrayRef<Value *> VL,
3190 const InstructionsState &S,
3191 const EdgeInfo &UserTreeIdx,
3192 ArrayRef<int> ReuseShuffleIndices = {}) {
3193 auto Invalid = ScheduleBundle::invalid();
3194 return newTreeEntry(VL, Invalid, S, UserTreeIdx, ReuseShuffleIndices);
3195 }
3196
3197 /// Create a new VectorizableTree entry.
3198 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, ScheduleBundle &Bundle,
3199 const InstructionsState &S,
3200 const EdgeInfo &UserTreeIdx,
3201 ArrayRef<int> ReuseShuffleIndices = {},
3202 ArrayRef<unsigned> ReorderIndices = {},
3203 unsigned InterleaveFactor = 0) {
3204 TreeEntry::EntryState EntryState =
3205 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
3206 TreeEntry *E = newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
3207 ReuseShuffleIndices, ReorderIndices);
3208 if (E && InterleaveFactor > 0)
3209 E->setInterleave(InterleaveFactor);
3210 return E;
3211 }
3212
3213 TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
3214 TreeEntry::EntryState EntryState,
3215 ScheduleBundle &Bundle, const InstructionsState &S,
3216 const EdgeInfo &UserTreeIdx,
3217 ArrayRef<int> ReuseShuffleIndices = {},
3218 ArrayRef<unsigned> ReorderIndices = {}) {
3219 assert(((!Bundle && (EntryState == TreeEntry::NeedToGather ||
3220 EntryState == TreeEntry::SplitVectorize)) ||
3221 (Bundle && EntryState != TreeEntry::NeedToGather &&
3222 EntryState != TreeEntry::SplitVectorize)) &&
3223 "Need to vectorize gather entry?");
3224 // Gathered loads still gathered? Do not create entry, use the original one.
3225 if (GatheredLoadsEntriesFirst.has_value() &&
3226 EntryState == TreeEntry::NeedToGather && S &&
3227 S.getOpcode() == Instruction::Load && UserTreeIdx.EdgeIdx == UINT_MAX &&
3228 !UserTreeIdx.UserTE)
3229 return nullptr;
3230 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
3231 TreeEntry *Last = VectorizableTree.back().get();
3232 Last->Idx = VectorizableTree.size() - 1;
3233 Last->State = EntryState;
3234 if (UserTreeIdx.UserTE)
3235 OperandsToTreeEntry.try_emplace(
3236 std::make_pair(UserTreeIdx.UserTE, UserTreeIdx.EdgeIdx), Last);
3237 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
3238 ReuseShuffleIndices.end());
3239 if (ReorderIndices.empty()) {
3240 Last->Scalars.assign(VL.begin(), VL.end());
3241 if (S)
3242 Last->setOperations(S);
3243 } else {
3244 // Reorder scalars and build final mask.
3245 Last->Scalars.assign(VL.size(), nullptr);
3246 transform(ReorderIndices, Last->Scalars.begin(),
3247 [VL](unsigned Idx) -> Value * {
3248 if (Idx >= VL.size())
3249 return UndefValue::get(VL.front()->getType());
3250 return VL[Idx];
3251 });
3252 // The main op of the copyable loads stays in the block of the wide load.
3253 if (S && S.getOpcode() == Instruction::Load &&
3255 Last->setOperations(S);
3256 else if (InstructionsState S = getSameOpcode(Last->Scalars, *TLI))
3257 Last->setOperations(S);
3258 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
3259 }
3260 if (EntryState == TreeEntry::SplitVectorize) {
3261 assert(S && "Split nodes must have operations.");
3262 Last->setOperations(S);
3263 SmallPtrSet<Value *, 4> Processed;
3264 for (Instruction *I : make_isa_range<Instruction>(VL)) {
3265 auto It = ScalarsInSplitNodes.find(I);
3266 if (It == ScalarsInSplitNodes.end()) {
3267 ScalarsInSplitNodes.try_emplace(I).first->getSecond().push_back(Last);
3268 (void)Processed.insert(I);
3269 } else if (Processed.insert(I).second) {
3270 assert(!is_contained(It->getSecond(), Last) &&
3271 "Value already associated with the node.");
3272 It->getSecond().push_back(Last);
3273 }
3274 }
3275 } else if (!Last->isGather()) {
3276 if (isa<PHINode>(S.getMainOp()) ||
3279 doesNotNeedToSchedule(VL)) ||
3280 all_of(VL, [&](Value *V) { return S.isNonSchedulable(V); }))
3281 Last->setDoesNotNeedToSchedule();
3282 SmallPtrSet<Value *, 4> Processed;
3283 for (Value *V : make_filter_range(
3284 VL, [](Value *V) { return !isa<PoisonValue>(V); })) {
3285 if (S.isCopyableElement(V)) {
3286 Last->addCopyableElement(V);
3287 if (isa<LoadInst>(V) && S.getOpcode() == Instruction::Load &&
3288 Processed.insert(V).second)
3289 CopyableLoadsToTreeEntries[V].push_back(Last);
3290 continue;
3291 }
3292 auto It = ScalarToTreeEntries.find(V);
3293 if (It == ScalarToTreeEntries.end()) {
3294 ScalarToTreeEntries.try_emplace(V).first->getSecond().push_back(Last);
3295 (void)Processed.insert(V);
3296 } else if (Processed.insert(V).second) {
3297 assert(!is_contained(It->getSecond(), Last) &&
3298 "Value already associated with the node.");
3299 It->getSecond().push_back(Last);
3300 }
3301 }
3302 // Update the scheduler bundle to point to this TreeEntry.
3303 assert((!Bundle.getBundle().empty() || Last->doesNotNeedToSchedule()) &&
3304 "Bundle and VL out of sync");
3305 if (!Bundle.getBundle().empty()) {
3306#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
3307 auto *BundleMember = Bundle.getBundle().begin();
3308 SmallPtrSet<Value *, 4> Processed;
3309 for (Value *V : VL) {
3310 if (S.isNonSchedulable(V) || !Processed.insert(V).second)
3311 continue;
3312 ++BundleMember;
3313 }
3314 assert(BundleMember == Bundle.getBundle().end() &&
3315 "Bundle and VL out of sync");
3316#endif
3317 Bundle.setTreeEntry(Last);
3318 }
3319 } else {
3320 // Build a map for gathered scalars to the nodes where they are used.
3321 bool AllConstsOrCasts = true;
3322 for (Value *V : VL) {
3325 Last->addCopyableElement(V);
3326 if (!isConstant(V)) {
3327 auto *I = dyn_cast<CastInst>(V);
3328 AllConstsOrCasts &= I && I->getType()->isIntegerTy();
3329 if (UserTreeIdx.EdgeIdx != UINT_MAX || !UserTreeIdx.UserTE ||
3330 !UserTreeIdx.UserTE->isGather())
3331 ValueToGatherNodes.try_emplace(V).first->getSecond().insert(Last);
3332 }
3333 }
3334 if (AllConstsOrCasts)
3335 CastMaxMinBWSizes =
3336 std::make_pair(std::numeric_limits<unsigned>::max(), 1);
3337 MustGather.insert_range(VL);
3338 }
3339
3340 if (UserTreeIdx.UserTE)
3341 Last->UserTreeIndex = UserTreeIdx;
3342 return Last;
3343 }
3344
3345 /// -- Vectorization State --
3346 /// Holds all of the tree entries.
3347 TreeEntry::VecTreeTy VectorizableTree;
3348
3349#ifndef NDEBUG
3350 /// Debug printer.
3351 LLVM_DUMP_METHOD void dumpVectorizableTree() const {
3352 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
3353 VectorizableTree[Id]->dump();
3354 if (TransformedToGatherNodes.contains(VectorizableTree[Id].get()))
3355 dbgs() << "[[TRANSFORMED TO GATHER]]";
3356 else if (DeletedNodes.contains(VectorizableTree[Id].get()))
3357 dbgs() << "[[DELETED NODE]]";
3358 dbgs() << "\n";
3359 }
3360 }
3361#endif
3362
3363 /// Get list of vector entries, associated with the value \p V.
3364 ArrayRef<TreeEntry *> getTreeEntries(const Value *V) const {
3365 assert(V && "V cannot be nullptr.");
3366 auto It = ScalarToTreeEntries.find(V);
3367 if (It == ScalarToTreeEntries.end())
3368 return {};
3369 return It->getSecond();
3370 }
3371
3372 /// Get list of split vector entries, associated with the value \p V.
3373 ArrayRef<TreeEntry *> getSplitTreeEntries(Value *V) const {
3374 assert(V && "V cannot be nullptr.");
3375 auto It = ScalarsInSplitNodes.find(V);
3376 if (It == ScalarsInSplitNodes.end())
3377 return {};
3378 return It->getSecond();
3379 }
3380
3381 /// Returns first vector node for value \p V, matching values \p VL.
3382 TreeEntry *getSameValuesTreeEntry(Value *V, ArrayRef<Value *> VL,
3383 bool SameVF = false) const {
3384 assert(V && "V cannot be nullptr.");
3385 for (TreeEntry *TE : ScalarToTreeEntries.lookup(V))
3386 if ((!SameVF || TE->getVectorFactor() == VL.size()) && TE->isSame(VL))
3387 return TE;
3388 return nullptr;
3389 }
3390
3391 /// Contains all the outputs of legality analysis for a list of values to
3392 /// vectorize.
3393 class ScalarsVectorizationLegality {
3394 InstructionsState S;
3395 bool IsLegal;
3396 bool TryToFindDuplicates;
3397 bool TrySplitVectorize;
3398
3399 public:
3400 ScalarsVectorizationLegality(InstructionsState S, bool IsLegal,
3401 bool TryToFindDuplicates = true,
3402 bool TrySplitVectorize = false)
3403 : S(S), IsLegal(IsLegal), TryToFindDuplicates(TryToFindDuplicates),
3404 TrySplitVectorize(TrySplitVectorize) {
3405 assert((!IsLegal || (S.valid() && TryToFindDuplicates)) &&
3406 "Inconsistent state");
3407 }
3408 const InstructionsState &getInstructionsState() const { return S; };
3409 bool isLegal() const { return IsLegal; }
3410 bool tryToFindDuplicates() const { return TryToFindDuplicates; }
3411 bool trySplitVectorize() const { return TrySplitVectorize; }
3412 };
3413
3414 /// Checks if the specified list of the instructions/values can be vectorized
3415 /// in general.
3416 ScalarsVectorizationLegality
3417 getScalarsVectorizationLegality(ArrayRef<Value *> VL, unsigned Depth,
3418 const EdgeInfo &UserTreeIdx) const;
3419
3420 /// Checks if the specified list of the instructions/values can be vectorized
3421 /// and fills required data before actual scheduling of the instructions.
3422 TreeEntry::EntryState getScalarsVectorizationState(
3423 const InstructionsState &S, ArrayRef<Value *> VL,
3424 bool IsScatterVectorizeUserTE, OrdersType &CurrentOrder,
3425 SmallVectorImpl<Value *> &PointerOps, StridedPtrInfo &SPtrInfo,
3426 SmallVectorImpl<int> &ReuseShuffleIndices);
3427
3428 /// Maps a specific scalar to its tree entry(ies).
3429 SmallDenseMap<Value *, SmallVector<TreeEntry *>> ScalarToTreeEntries;
3430
3431 /// List of deleted non-profitable nodes.
3432 SmallPtrSet<const TreeEntry *, 8> DeletedNodes;
3433
3434 /// List of nodes, transformed to gathered, with their conservative
3435 /// gather/buildvector cost estimation.
3436 SmallDenseMap<const TreeEntry *, InstructionCost> TransformedToGatherNodes;
3437
3438 /// Maps the operand index and entry to the corresponding tree entry.
3439 SmallDenseMap<std::pair<const TreeEntry *, unsigned>, TreeEntry *>
3440 OperandsToTreeEntry;
3441
3442 /// Scalars, used in split vectorize nodes.
3443 SmallDenseMap<Value *, SmallVector<TreeEntry *>> ScalarsInSplitNodes;
3444
3445 /// Copyable loads from the predecessor block, covered by the wide loads.
3446 SmallDenseMap<Value *, SmallVector<TreeEntry *>> CopyableLoadsToTreeEntries;
3447
3448 /// Maps a value to the proposed vectorizable size.
3449 SmallDenseMap<Value *, unsigned> InstrElementSize;
3450
3451 /// A list of scalars that we found that we need to keep as scalars.
3452 ValueSet MustGather;
3453
3454 /// Maps each peeled reassociated scalar to owning entries. Keeps them
3455 /// treated as vectorized while an owner is live.
3456 SmallDenseMap<const Value *, SmallVector<const TreeEntry *>>
3457 ReassocScalarToTreeEntries;
3458
3459 /// Peeled reassociated scalars that must survive erasure: claimed by a
3460 /// gather node, listed in some tree entry's scalars, or feeding another
3461 /// kept scalar.
3462 SmallPtrSet<const Value *, 8> KeptReassocScalars;
3463
3464 /// A set of first non-schedulable values.
3465 ValueSet NonScheduledFirst;
3466
3467 /// A map between the vectorized entries and the last instructions in the
3468 /// bundles. The bundles are built in use order, not in the def order of the
3469 /// instructions. So, we cannot rely directly on the last instruction in the
3470 /// bundle being the last instruction in the program order during
3471 /// vectorization process since the basic blocks are affected, need to
3472 /// pre-gather them before.
3473 SmallDenseMap<const TreeEntry *, WeakTrackingVH> EntryToLastInstruction;
3474
3475 /// Keeps the mapping between the last instructions and their insertion
3476 /// points, which is an instruction-after-the-last-instruction.
3477 SmallDenseMap<const Instruction *, Instruction *> LastInstructionToPos;
3478
3479 /// List of gather nodes, depending on other gather/vector nodes, which should
3480 /// be emitted after the vector instruction emission process to correctly
3481 /// handle order of the vector instructions and shuffles.
3482 SetVector<const TreeEntry *> PostponedGathers;
3483
3484 /// Frozen operands of the expanded binops with the shuffles, which blend the
3485 /// frozen expanded lanes into the other operands.
3487 ExpandedOperandFreezes;
3488
3489 using ValueToGatherNodesMap =
3490 DenseMap<Value *, SmallSetVector<const TreeEntry *, 4>>;
3491 ValueToGatherNodesMap ValueToGatherNodes;
3492
3493 SmallDenseMap<TreeEntry *, StridedPtrInfo> TreeEntryToStridedPtrInfoMap;
3494
3495 /// A list of the load entries (node indices), which can be vectorized using
3496 /// strided or masked gather approach, but attempted to be represented as
3497 /// contiguous loads.
3498 SetVector<unsigned> LoadEntriesToVectorize;
3499
3500 /// true if graph nodes transforming mode is on.
3501 bool IsGraphTransformMode = false;
3502
3503 /// The index of the first gathered load entry in the VectorizeTree.
3504 std::optional<unsigned> GatheredLoadsEntriesFirst;
3505
3506 /// Root entries of the subtrees built for the splat gather nodes' unique
3507 /// scalars. They have no users in the tree and must be emitted explicitly
3508 /// before the root node.
3509 SmallVector<TreeEntry *> SplatGatheredScalarsRoots;
3510
3511 /// Checks if any of \p Entries is an internal gather of a splat gather
3512 /// subtree.
3513 bool hasSplatSubtreeGather(
3515 if (SplatGatheredScalarsRoots.empty())
3516 return false;
3517 return any_of(Entries, [&](ArrayRef<const TreeEntry *> TEs) {
3518 return any_of(TEs, [&](const TreeEntry *TE) {
3519 if (!TE->isGather())
3520 return false;
3521 while (TE->UserTreeIndex)
3522 TE = TE->UserTreeIndex.UserTE;
3523 return is_contained(SplatGatheredScalarsRoots, TE);
3524 });
3525 });
3526 }
3527
3528 /// Number of tree entries added while building the splat gather subtrees.
3529 /// The subtrees are auxiliary and must not inflate the tree size recorded
3530 /// for failed store chain attempts.
3531 unsigned NumCanonicalSplatSubtreeEntries = 0;
3532
3533 /// Maps compress entries to their mask data for the final codegen.
3534 SmallDenseMap<const TreeEntry *,
3535 std::tuple<SmallVector<int>, VectorType *, unsigned, bool>>
3536 CompressEntryToData;
3537
3538 /// The loop nest, used to check if only a single loop nest is vectorized, not
3539 /// multiple, to avoid side-effects from the loop-aware cost model.
3540 SmallVector<const Loop *> CurrentLoopNest;
3541
3542 /// Per-depth SCEVs trip counts at every loop level where the tree builder has
3543 /// joined diverging sibling loops.
3544 SmallVector<const SCEV *> MergedLoopBTCs;
3545
3546 /// Maps the loops to their loop nests.
3547 SmallDenseMap<const Loop *, SmallVector<const Loop *>> LoopToLoopNest;
3548
3549 /// Per-loop cache of nest scale factors: the product of trip counts of the
3550 /// loop and all of its ancestors. Shared by getLoopNestScale() and (via it)
3551 /// by getScaleToLoopIterations() and getGatherNodeEffectiveScale().
3552 SmallDenseMap<const Loop *, uint64_t> LoopNestScaleCache;
3553
3554 /// This POD struct describes one external user in the vectorized tree.
3555 struct ExternalUser {
3556 ExternalUser(Value *S, llvm::User *U, const TreeEntry &E, unsigned L)
3557 : Scalar(S), User(U), E(E), Lane(L) {}
3558
3559 /// Which scalar in our function.
3560 Value *Scalar = nullptr;
3561
3562 /// Which user that uses the scalar.
3563 llvm::User *User = nullptr;
3564
3565 /// Vector node, the value is part of.
3566 const TreeEntry &E;
3567
3568 /// Which lane does the scalar belong to.
3569 unsigned Lane;
3570 };
3571 using UserList = SmallVector<ExternalUser, 16>;
3572
3573 /// Checks if two instructions may access the same memory.
3574 ///
3575 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
3576 /// is invariant in the calling loop.
3577 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
3578 Instruction *Inst2) {
3579 assert(Loc1.Ptr && isSimple(Inst1) && "Expected simple first instruction.");
3580 // First check if the result is already in the cache.
3581 AliasCacheKey Key = std::make_pair(Inst1, Inst2);
3582 auto Res = AliasCache.try_emplace(Key);
3583 if (!Res.second)
3584 return Res.first->second;
3585 bool Aliased = isModOrRefSet(BatchAA->getModRefInfo(Inst2, Loc1));
3586 // Store the result in the cache.
3587 Res.first->getSecond() = Aliased;
3588 return Aliased;
3589 }
3590
3591 /// Checks if the memory of the simple load \p LI may be modified after it
3592 /// in its block or anywhere in the successor block \p BB.
3593 bool isLoadMemoryModified(LoadInst *LI, BasicBlock *BB) {
3594 MemoryLocation Loc = MemoryLocation::get(LI);
3595 unsigned NumWrites = 0;
3596 return any_of(concat<Instruction>(make_range(std::next(LI->getIterator()),
3597 LI->getParent()->end()),
3598 *BB),
3599 [&](Instruction &I) {
3600 return I.mayWriteToMemory() &&
3601 (++NumWrites > MaxMemDepDistance ||
3602 isAliased(Loc, LI, &I));
3603 });
3604 }
3605
3606 /// Returns true if the may-alias dependency between simple load/store
3607 /// instructions \p Inst1 and \p Inst2 could be disambiguated by a runtime
3608 /// alias check.
3609 bool isRuntimeCheckableAliasPair(Instruction *Inst1, Instruction *Inst2);
3610
3611 /// Records the (distinct base object) pair behind the may-alias dependency
3612 /// of \p Inst1 and \p Inst2 as a runtime alias check guarding the region in
3613 /// block \p BB. Returns true if the pair was recorded.
3614 bool recordRuntimeAliasCheck(BasicBlock *BB, Instruction *Inst1,
3615 Instruction *Inst2);
3616
3617 /// Emits the collected runtime alias checks and versions the affected block,
3618 /// duplicating its body into a scalar fallback guarded by the checks.
3619 void versionBlocksForRuntimeChecks();
3620
3621 /// Builds the i1 value that is true when any pair of checked base objects
3622 /// overlaps at runtime. The base address bounds are materialized from their
3623 /// SCEVs with \p Exp.
3624 Value *emitRuntimeAliasCheck(IRBuilderBase &Builder, SCEVExpander &Exp);
3625
3626 /// Data to model and emit the runtime alias checks.
3627 struct RuntimeAliasCheckInfo {
3628 /// The block whose body is guarded by the checks. Exactly one block is
3629 /// supported per attempt.
3630 BasicBlock *BB = nullptr;
3631 /// Pairs of base objects that must be proven disjoint.
3632 SmallSetVector<std::pair<const Value *, const Value *>, 4> BasePairs;
3633 /// Accessed address range [Low, High) for each involved base object.
3634 SmallMapVector<const Value *, std::pair<const SCEV *, const SCEV *>, 4>
3635 Bounds;
3636
3637 void clear() {
3638 BB = nullptr;
3639 BasePairs.clear();
3640 Bounds.clear();
3641 }
3642 };
3643
3644 /// When true, scheduling drops may-alias memory dependencies between
3645 /// distinct, range-checkable base objects and records them as runtime alias
3646 /// checks instead.
3647 bool TryRuntimeAliasChecks = false;
3648
3649 /// When true, the stored values of the root store node are split into
3650 /// halves, which are vectorized as separate subtrees.
3651 bool SplitStoredValues = false;
3652
3653 /// Runtime alias checks collected during the last optimistic buildTree().
3654 RuntimeAliasCheckInfo RTChecks;
3655
3656 /// Base-object pairs already proven disjoint by the block's runtime alias
3657 /// check.
3658 SmallDenseMap<BasicBlock *,
3659 SmallDenseSet<std::pair<const Value *, const Value *>, 4>, 2>
3660 VersionedBlockCheckedPairs;
3661
3662 /// Scalar fallback blocks.
3663 SmallPtrSet<BasicBlock *, 4> ScalarFallbackBlocks;
3664
3665 /// Blocks for which a runtime-checks versioning attempt was made
3666 /// and did not produce a profitable versioning.
3667 SmallPtrSet<BasicBlock *, 8> FailedRuntimeChecksBlocks;
3668
3669 /// Returns true if a may-alias dependency between the simple load/store
3670 /// instructions \p Inst1 and \p Inst2 in block \p BB is already covered by a
3671 /// runtime alias check emitted for \p BB by a previous versioning.
3672 bool isCoveredByExistingVersionCheck(BasicBlock *BB, Instruction *Inst1,
3673 Instruction *Inst2) const;
3674
3675 /// True, if a may-alias dependency between distinct, range-checkable base
3676 /// objects is observed (whether or not it was dropped).
3677 bool HasRuntimeCheckableBlockers = false;
3678
3679 /// True, if a kept may-alias dependency is not runtime-checkable (call or a
3680 /// non-simple memaccess).
3681 bool HasNonCheckableMemBlocker = false;
3682
3683 /// Runtime checks are validated and bounded the collected checks.
3684 bool RTChecksFinalized = false;
3685
3686 /// Set when a block was versioned with runtime alias checks, which changes
3687 /// the CFG. Used to drop CFG-analysis preservation for the run.
3688 bool CFGChanged = false;
3689
3690 /// Guarded block body (non-PHI, non-alloca, non-terminator) in original
3691 /// source order.
3692 SmallVector<Instruction *> RTOrigBodyOrder;
3693
3694 using AliasCacheKey = std::pair<Instruction *, Instruction *>;
3695
3696 /// Cache for alias results.
3697 /// TODO: consider moving this to the AliasAnalysis itself.
3698 SmallDenseMap<AliasCacheKey, bool> AliasCache;
3699
3700 AAResults *AA;
3701
3702 // Cache for pointerMayBeCaptured calls inside AA. Vectorizing a tree can
3703 // create new captures (e.g. a pointer inserted into a vector of pointers
3704 // feeding a masked gather), so this is reset after each vectorized tree.
3705 std::optional<BatchAAResults> BatchAA;
3706
3707 /// Temporary store for deleted instructions. Instructions will be deleted
3708 /// eventually when the BoUpSLP is destructed. The deferral is required to
3709 /// ensure that there are no incorrect collisions in the AliasCache, which
3710 /// can happen if a new instruction is allocated at the same address as a
3711 /// previously deleted instruction.
3712 DenseSet<Instruction *> DeletedInstructions;
3713
3714 /// The cached analyses results, cleared after each successful
3715 /// vectorizeTree().
3716 mutable SLPAnalysisCache Cache;
3717
3718 /// Set of the instruction, being analyzed already for reductions.
3719 SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
3720
3721 /// Set of hashes for the list of reduction values already being analyzed.
3722 DenseSet<size_t> AnalyzedReductionVals;
3723
3724 /// Set of hashes for the bundles, rejected as non-vectorizable.
3725 SmallDenseSet<size_t, 8> AnalyzedBundles;
3726
3727 /// Set of the values, which were a part of the analyzed vector nodes.
3728 SmallPtrSet<const Value *, 32> AnalyzedScalars;
3729
3730 /// Cache of the number of parts for the types and the parts limit.
3731 mutable SmallDenseMap<std::tuple<Type *, Type *, unsigned>, unsigned>
3732 NumberOfPartsCache;
3733
3734 /// Cache of the number of regs for the types and the parts limit.
3735 mutable SmallDenseMap<std::tuple<Type *, Type *, unsigned>, unsigned>
3736 NumberOfRegsCache;
3737
3738 /// Values already analyzed for minimal bitwidth and found to be
3739 /// non-profitable, mapped to the size of the tree used for the analysis.
3740 SmallDenseMap<Value *, unsigned> AnalyzedMinBWVals;
3741
3742 /// A list of values that need to extracted out of the tree.
3743 /// This list holds pairs of (Internal Scalar : External User). External User
3744 /// can be nullptr, it means that this Internal Scalar will be used later,
3745 /// after vectorization.
3746 UserList ExternalUses;
3747
3748 /// A list of GEPs which can be reaplced by scalar GEPs instead of
3749 /// extractelement instructions.
3750 SmallPtrSet<Value *, 4> ExternalUsesAsOriginalScalar;
3751
3752 /// A list of scalar to be extracted without specific user necause of too many
3753 /// uses.
3754 SmallPtrSet<Value *, 4> ExternalUsesWithNonUsers;
3755
3756 /// Externally used values and replacements emitted for the external uses
3757 /// without users, consumed after the tree vectorization; must not be
3758 /// collected as dead operands of the erased scalars.
3759 SmallPtrSet<Value *, 4> ExternalUseReplacements;
3760
3761 /// Values used only by @llvm.assume calls.
3762 SmallPtrSet<const Value *, 32> EphValues;
3763
3764 /// Holds all of the instructions that we gathered, shuffle instructions and
3765 /// extractelements.
3766 SetVector<Instruction *> GatherShuffleExtractSeq;
3767
3768 /// A list of blocks that we are going to CSE.
3769 DenseSet<BasicBlock *> CSEBlocks;
3770
3771 /// List of hashes of vector of loads, which are known to be non vectorizable.
3772 DenseSet<size_t> ListOfKnonwnNonVectorizableLoads;
3773
3774 /// Represents a scheduling entity, either ScheduleData, ScheduleCopyableData
3775 /// or ScheduleBundle. ScheduleData used to gather dependecies for a single
3776 /// instructions, while ScheduleBundle represents a batch of instructions,
3777 /// going to be groupped together. ScheduleCopyableData models extra user for
3778 /// "copyable" instructions.
3779 class ScheduleEntity {
3780 friend class ScheduleBundle;
3781 friend class ScheduleData;
3782 friend class ScheduleCopyableData;
3783
3784 protected:
3785 enum class Kind { ScheduleData, ScheduleBundle, ScheduleCopyableData };
3786 Kind getKind() const { return K; }
3787 ScheduleEntity(Kind K) : K(K) {}
3788
3789 private:
3790 /// Used for getting a "good" final ordering of instructions.
3791 int SchedulingPriority = 0;
3792 /// True if this instruction (or bundle) is scheduled (or considered as
3793 /// scheduled in the dry-run).
3794 bool IsScheduled = false;
3795 /// The kind of the ScheduleEntity.
3796 const Kind K = Kind::ScheduleData;
3797
3798 public:
3799 ScheduleEntity() = delete;
3800 /// Gets/sets the scheduling priority.
3801 void setSchedulingPriority(int Priority) { SchedulingPriority = Priority; }
3802 int getSchedulingPriority() const { return SchedulingPriority; }
3803 bool isReady() const {
3804 if (const auto *SD = dyn_cast<ScheduleData>(this))
3805 return SD->isReady();
3806 if (const auto *CD = dyn_cast<ScheduleCopyableData>(this))
3807 return CD->isReady();
3808 return cast<ScheduleBundle>(this)->isReady();
3809 }
3810 /// Returns true if the dependency information has been calculated.
3811 /// Note that depenendency validity can vary between instructions within
3812 /// a single bundle.
3813 bool hasValidDependencies() const {
3814 if (const auto *SD = dyn_cast<ScheduleData>(this))
3815 return SD->hasValidDependencies();
3816 if (const auto *CD = dyn_cast<ScheduleCopyableData>(this))
3817 return CD->hasValidDependencies();
3818 return cast<ScheduleBundle>(this)->hasValidDependencies();
3819 }
3820 /// Gets the number of unscheduled dependencies.
3821 int getUnscheduledDeps() const {
3822 if (const auto *SD = dyn_cast<ScheduleData>(this))
3823 return SD->getUnscheduledDeps();
3824 if (const auto *CD = dyn_cast<ScheduleCopyableData>(this))
3825 return CD->getUnscheduledDeps();
3826 return cast<ScheduleBundle>(this)->unscheduledDepsInBundle();
3827 }
3828 /// Increments the number of unscheduled dependencies.
3829 int incrementUnscheduledDeps(int Incr) {
3830 if (auto *SD = dyn_cast<ScheduleData>(this))
3831 return SD->incrementUnscheduledDeps(Incr);
3832 return cast<ScheduleCopyableData>(this)->incrementUnscheduledDeps(Incr);
3833 }
3834 /// Gets the number of dependencies.
3835 int getDependencies() const {
3836 if (const auto *SD = dyn_cast<ScheduleData>(this))
3837 return SD->getDependencies();
3838 return cast<ScheduleCopyableData>(this)->getDependencies();
3839 }
3840 /// Gets the instruction.
3841 Instruction *getInst() const {
3842 if (const auto *SD = dyn_cast<ScheduleData>(this))
3843 return SD->getInst();
3844 return cast<ScheduleCopyableData>(this)->getInst();
3845 }
3846
3847 /// Gets/sets if the bundle is scheduled.
3848 bool isScheduled() const { return IsScheduled; }
3849 void setScheduled(bool Scheduled) { IsScheduled = Scheduled; }
3850
3851 static bool classof(const ScheduleEntity *) { return true; }
3852
3853#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3854 void dump(raw_ostream &OS) const {
3855 if (const auto *SD = dyn_cast<ScheduleData>(this))
3856 return SD->dump(OS);
3857 if (const auto *CD = dyn_cast<ScheduleCopyableData>(this))
3858 return CD->dump(OS);
3859 return cast<ScheduleBundle>(this)->dump(OS);
3860 }
3861
3862 LLVM_DUMP_METHOD void dump() const {
3863 dump(dbgs());
3864 dbgs() << '\n';
3865 }
3866#endif // if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3867 };
3868
3869#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3871 const BoUpSLP::ScheduleEntity &SE) {
3872 SE.dump(OS);
3873 return OS;
3874 }
3875#endif
3876
3877 /// Contains all scheduling relevant data for an instruction.
3878 /// A ScheduleData either represents a single instruction or a member of an
3879 /// instruction bundle (= a group of instructions which is combined into a
3880 /// vector instruction).
3881 class ScheduleData final : public ScheduleEntity {
3882 public:
3883 // The initial value for the dependency counters. It means that the
3884 // dependencies are not calculated yet.
3885 enum { InvalidDeps = -1 };
3886
3887 ScheduleData() : ScheduleEntity(Kind::ScheduleData) {}
3888 static bool classof(const ScheduleEntity *Entity) {
3889 return Entity->getKind() == Kind::ScheduleData;
3890 }
3891
3892 void init(int BlockSchedulingRegionID, Instruction *I) {
3893 NextLoadStore = nullptr;
3894 IsScheduled = false;
3895 SchedulingRegionID = BlockSchedulingRegionID;
3896 clearDependencies();
3897 Inst = I;
3898 }
3899
3900 /// Verify basic self consistency properties
3901 void verify() {
3902 if (hasValidDependencies()) {
3903 assert(UnscheduledDeps <= Dependencies && "invariant");
3904 } else {
3905 assert(UnscheduledDeps == Dependencies && "invariant");
3906 }
3907
3908 if (IsScheduled) {
3909 assert(hasValidDependencies() && UnscheduledDeps == 0 &&
3910 "unexpected scheduled state");
3911 }
3912 }
3913
3914 /// Returns true if the dependency information has been calculated.
3915 /// Note that depenendency validity can vary between instructions within
3916 /// a single bundle.
3917 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
3918
3919 /// Returns true if it is ready for scheduling, i.e. it has no more
3920 /// unscheduled depending instructions/bundles.
3921 bool isReady() const { return UnscheduledDeps == 0 && !IsScheduled; }
3922
3923 /// Modifies the number of unscheduled dependencies for this instruction,
3924 /// and returns the number of remaining dependencies for the containing
3925 /// bundle.
3926 int incrementUnscheduledDeps(int Incr) {
3927 assert(hasValidDependencies() &&
3928 "increment of unscheduled deps would be meaningless");
3929 UnscheduledDeps += Incr;
3930 assert(UnscheduledDeps >= 0 &&
3931 "Expected valid number of unscheduled deps");
3932 return UnscheduledDeps;
3933 }
3934
3935 /// Sets the number of unscheduled dependencies to the number of
3936 /// dependencies.
3937 void resetUnscheduledDeps() { UnscheduledDeps = Dependencies; }
3938
3939 /// Clears all dependency information.
3940 void clearDependencies() {
3941 clearDirectDependencies();
3942 MemoryDependencies.clear();
3943 ControlDependencies.clear();
3944 IsRegisteredAsDependent = false;
3945 }
3946
3947 /// Clears all direct dependencies only, except for control and memory
3948 /// dependencies.
3949 /// Required for copyable elements to correctly handle control/memory deps
3950 /// and avoid extra reclaculation of such deps.
3951 void clearDirectDependencies() {
3952 Dependencies = InvalidDeps;
3953 resetUnscheduledDeps();
3954 IsScheduled = false;
3955 }
3956
3957 /// Gets the number of unscheduled dependencies.
3958 int getUnscheduledDeps() const { return UnscheduledDeps; }
3959 /// Gets the number of dependencies.
3960 int getDependencies() const { return Dependencies; }
3961 /// Initializes the number of dependencies.
3962 void initDependencies() { Dependencies = 0; }
3963 /// Increments the number of dependencies.
3964 void incDependencies() { Dependencies++; }
3965
3966 /// Gets scheduling region ID.
3967 int getSchedulingRegionID() const { return SchedulingRegionID; }
3968
3969 /// Gets the instruction.
3970 Instruction *getInst() const { return Inst; }
3971
3972 /// Gets the list of memory dependencies.
3973 ArrayRef<ScheduleData *> getMemoryDependencies() const {
3974 return MemoryDependencies;
3975 }
3976 /// Adds a memory dependency.
3977 void addMemoryDependency(ScheduleData *Dep) {
3978 MemoryDependencies.push_back(Dep);
3979 }
3980 /// Gets the list of control dependencies.
3981 ArrayRef<ScheduleData *> getControlDependencies() const {
3982 return ControlDependencies;
3983 }
3984 /// Adds a control dependency.
3985 void addControlDependency(ScheduleData *Dep) {
3986 ControlDependencies.push_back(Dep);
3987 }
3988 /// Marks this instruction as added to the memory and control dependencies
3989 /// of the instructions it depends on. \returns the previous state.
3990 bool setRegisteredAsDependent() {
3991 return std::exchange(IsRegisteredAsDependent, true);
3992 }
3993 /// Gets/sets if the instruction may write to memory.
3994 bool mayWriteToMemory() const { return MayWriteToMemory; }
3995 void setMayWriteToMemory(bool MayWrite) { MayWriteToMemory = MayWrite; }
3996 /// Gets/sets the next load/store instruction in the block.
3997 ScheduleData *getNextLoadStore() const { return NextLoadStore; }
3998 void setNextLoadStore(ScheduleData *Next) { NextLoadStore = Next; }
3999
4000 void dump(raw_ostream &OS) const { OS << *Inst; }
4001
4002 LLVM_DUMP_METHOD void dump() const {
4003 dump(dbgs());
4004 dbgs() << '\n';
4005 }
4006
4007 private:
4008 Instruction *Inst = nullptr;
4009
4010 /// Single linked list of all memory instructions (e.g. load, store, call)
4011 /// in the block - until the end of the scheduling region.
4012 ScheduleData *NextLoadStore = nullptr;
4013
4014 /// The dependent memory instructions.
4015 /// This list is derived on demand in calculateDependencies().
4016 SmallVector<ScheduleData *> MemoryDependencies;
4017
4018 /// List of instructions which this instruction could be control dependent
4019 /// on. Allowing such nodes to be scheduled below this one could introduce
4020 /// a runtime fault which didn't exist in the original program.
4021 /// ex: this is a load or udiv following a readonly call which inf loops
4022 SmallVector<ScheduleData *> ControlDependencies;
4023
4024 /// This ScheduleData is in the current scheduling region if this matches
4025 /// the current SchedulingRegionID of BlockScheduling.
4026 int SchedulingRegionID = 0;
4027
4028 /// The number of dependencies. Constitutes of the number of users of the
4029 /// instruction plus the number of dependent memory instructions (if any).
4030 /// This value is calculated on demand.
4031 /// If InvalidDeps, the number of dependencies is not calculated yet.
4032 int Dependencies = InvalidDeps;
4033
4034 /// The number of dependencies minus the number of dependencies of scheduled
4035 /// instructions. As soon as this is zero, the instruction/bundle gets ready
4036 /// for scheduling.
4037 /// Note that this is negative as long as Dependencies is not calculated.
4038 int UnscheduledDeps = InvalidDeps;
4039
4040 /// True if this instruction is in the memory and control dependencies of
4041 /// the instructions it depends on. The recalculation of the direct
4042 /// dependencies finds the same instructions, so they are not added twice.
4043 bool IsRegisteredAsDependent = false;
4044
4045 /// True if the instruction may write to memory. Set for the instructions
4046 /// in the list of memory accessing instructions.
4047 bool MayWriteToMemory = false;
4048 };
4049
4050#ifndef NDEBUG
4052 const BoUpSLP::ScheduleData &SD) {
4053 SD.dump(OS);
4054 return OS;
4055 }
4056#endif
4057
4058 class ScheduleBundle final : public ScheduleEntity {
4059 /// The schedule data for the instructions in the bundle.
4061 /// True if this bundle is valid.
4062 bool IsValid = true;
4063 /// The TreeEntry that this instruction corresponds to.
4064 TreeEntry *TE = nullptr;
4065 /// The member, which had unscheduled dependencies last time.
4066 mutable unsigned UnscheduledMember = 0;
4067 ScheduleBundle(bool IsValid)
4068 : ScheduleEntity(Kind::ScheduleBundle), IsValid(IsValid) {}
4069
4070 public:
4071 ScheduleBundle() : ScheduleEntity(Kind::ScheduleBundle) {}
4072 static bool classof(const ScheduleEntity *Entity) {
4073 return Entity->getKind() == Kind::ScheduleBundle;
4074 }
4075
4076 /// Verify basic self consistency properties
4077 void verify() const {
4078 for (const ScheduleEntity *SD : Bundle) {
4079 if (SD->hasValidDependencies()) {
4080 assert(SD->getUnscheduledDeps() <= SD->getDependencies() &&
4081 "invariant");
4082 } else {
4083 assert(SD->getUnscheduledDeps() == SD->getDependencies() &&
4084 "invariant");
4085 }
4086
4087 if (isScheduled()) {
4088 assert(SD->hasValidDependencies() && SD->getUnscheduledDeps() == 0 &&
4089 "unexpected scheduled state");
4090 }
4091 }
4092 }
4093
4094 /// Returns the number of unscheduled dependencies in the bundle.
4095 int unscheduledDepsInBundle() const {
4096 assert(*this && "bundle must not be empty");
4097 int Sum = 0;
4098 for (const ScheduleEntity *BundleMember : Bundle) {
4099 if (BundleMember->getUnscheduledDeps() == ScheduleData::InvalidDeps)
4100 return ScheduleData::InvalidDeps;
4101 Sum += BundleMember->getUnscheduledDeps();
4102 }
4103 return Sum;
4104 }
4105
4106 /// Returns true if some member of the bundle has unscheduled dependencies
4107 /// or no calculated dependencies. The search starts from the member found
4108 /// last time, the members get scheduled mostly in order, so the bundle is
4109 /// checked in the amortized constant time.
4110 bool hasUnscheduledDeps() const {
4111 auto HasUnscheduledDeps = [](const ScheduleEntity *SE) {
4112 return SE->getUnscheduledDeps() != 0;
4113 };
4114 auto *Start = std::next(Bundle.begin(), UnscheduledMember);
4115 auto *It = std::find_if(Start, Bundle.end(), HasUnscheduledDeps);
4116 if (It == Bundle.end()) {
4117 It = std::find_if(Bundle.begin(), Start, HasUnscheduledDeps);
4118 if (It == Start)
4119 return false;
4120 }
4121 UnscheduledMember = std::distance(Bundle.begin(), It);
4122 return true;
4123 }
4124
4125 /// Returns true if the dependency information has been calculated.
4126 /// Note that depenendency validity can vary between instructions within
4127 /// a single bundle.
4128 bool hasValidDependencies() const {
4129 return all_of(Bundle, [](const ScheduleEntity *SD) {
4130 return SD->hasValidDependencies();
4131 });
4132 }
4133
4134 /// Returns true if it is ready for scheduling, i.e. it has no more
4135 /// unscheduled depending instructions/bundles.
4136 bool isReady() const {
4137 assert(*this && "bundle must not be empty");
4138 return !isScheduled() && !hasUnscheduledDeps();
4139 }
4140
4141 /// Returns the bundle of scheduling data, associated with the current
4142 /// instruction.
4143 ArrayRef<ScheduleEntity *> getBundle() { return Bundle; }
4144 ArrayRef<const ScheduleEntity *> getBundle() const { return Bundle; }
4145 /// Adds an instruction to the bundle.
4146 void add(ScheduleEntity *SD) { Bundle.push_back(SD); }
4147
4148 /// Gets/sets the associated tree entry.
4149 void setTreeEntry(TreeEntry *TE) { this->TE = TE; }
4150 TreeEntry *getTreeEntry() const { return TE; }
4151
4152 static ScheduleBundle invalid() { return {false}; }
4153
4154 operator bool() const { return IsValid; }
4155
4156#ifndef NDEBUG
4157 void dump(raw_ostream &OS) const {
4158 if (!*this) {
4159 OS << "[]";
4160 return;
4161 }
4162 OS << '[';
4163 interleaveComma(Bundle, OS, [&](const ScheduleEntity *SD) {
4165 OS << "<Copyable>";
4166 OS << *SD->getInst();
4167 });
4168 OS << ']';
4169 }
4170
4171 LLVM_DUMP_METHOD void dump() const {
4172 dump(dbgs());
4173 dbgs() << '\n';
4174 }
4175#endif // NDEBUG
4176 };
4177
4178#ifndef NDEBUG
4180 const BoUpSLP::ScheduleBundle &Bundle) {
4181 Bundle.dump(OS);
4182 return OS;
4183 }
4184#endif
4185
4186 /// Contains all scheduling relevant data for the copyable instruction.
4187 /// It models the virtual instructions, supposed to replace the original
4188 /// instructions. E.g., if instruction %0 = load is a part of the bundle [%0,
4189 /// %1], where %1 = add, then the ScheduleCopyableData models virtual
4190 /// instruction %virt = add %0, 0.
4191 class ScheduleCopyableData final : public ScheduleEntity {
4192 /// The source schedule data for the instruction.
4193 Instruction *Inst = nullptr;
4194 /// The edge information for the instruction.
4195 const EdgeInfo EI;
4196 /// This ScheduleData is in the current scheduling region if this matches
4197 /// the current SchedulingRegionID of BlockScheduling.
4198 int SchedulingRegionID = 0;
4199 /// Bundle, this data is part of.
4200 ScheduleBundle &Bundle;
4201
4202 public:
4203 ScheduleCopyableData(int BlockSchedulingRegionID, Instruction *I,
4204 const EdgeInfo &EI, ScheduleBundle &Bundle)
4205 : ScheduleEntity(Kind::ScheduleCopyableData), Inst(I), EI(EI),
4206 SchedulingRegionID(BlockSchedulingRegionID), Bundle(Bundle) {}
4207 static bool classof(const ScheduleEntity *Entity) {
4208 return Entity->getKind() == Kind::ScheduleCopyableData;
4209 }
4210
4211 /// Returns true if the dependency information has been calculated.
4212 /// Note that depenendency validity can vary between instructions within
4213 /// a single bundle.
4214 bool hasValidDependencies() const {
4215 return Dependencies != ScheduleData::InvalidDeps;
4216 }
4217
4218 /// Returns true if it is ready for scheduling, i.e. it has no more
4219 /// unscheduled depending instructions/bundles.
4220 bool isReady() const { return UnscheduledDeps == 0 && !IsScheduled; }
4221
4222 /// Modifies the number of unscheduled dependencies for this instruction,
4223 /// and returns the number of remaining dependencies for the containing
4224 /// bundle.
4225 int incrementUnscheduledDeps(int Incr) {
4226 assert(hasValidDependencies() &&
4227 "increment of unscheduled deps would be meaningless");
4228 UnscheduledDeps += Incr;
4229 assert(UnscheduledDeps >= 0 && "invariant");
4230 return UnscheduledDeps;
4231 }
4232
4233 /// Sets the number of unscheduled dependencies to the number of
4234 /// dependencies.
4235 void resetUnscheduledDeps() { UnscheduledDeps = Dependencies; }
4236
4237 /// Gets the number of unscheduled dependencies.
4238 int getUnscheduledDeps() const { return UnscheduledDeps; }
4239 /// Gets the number of dependencies.
4240 int getDependencies() const { return Dependencies; }
4241 /// Initializes the number of dependencies.
4242 void initDependencies() { Dependencies = 0; }
4243 /// Increments the number of dependencies.
4244 void incDependencies() { Dependencies++; }
4245
4246 /// Gets scheduling region ID.
4247 int getSchedulingRegionID() const { return SchedulingRegionID; }
4248
4249 /// Gets the instruction.
4250 Instruction *getInst() const { return Inst; }
4251
4252 /// Clears all dependency information.
4253 void clearDependencies() {
4254 Dependencies = ScheduleData::InvalidDeps;
4255 UnscheduledDeps = ScheduleData::InvalidDeps;
4256 IsScheduled = false;
4257 }
4258
4259 /// Gets the edge information.
4260 const EdgeInfo &getEdgeInfo() const { return EI; }
4261
4262 /// Gets the bundle.
4263 ScheduleBundle &getBundle() { return Bundle; }
4264 const ScheduleBundle &getBundle() const { return Bundle; }
4265
4266#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4267 void dump(raw_ostream &OS) const { OS << "[Copyable]" << *getInst(); }
4268
4269 LLVM_DUMP_METHOD void dump() const {
4270 dump(dbgs());
4271 dbgs() << '\n';
4272 }
4273#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4274
4275 private:
4276 /// true, if it has valid dependency information. These nodes always have
4277 /// only single dependency.
4278 int Dependencies = ScheduleData::InvalidDeps;
4279
4280 /// The number of dependencies minus the number of dependencies of scheduled
4281 /// instructions. As soon as this is zero, the instruction/bundle gets ready
4282 /// for scheduling.
4283 /// Note that this is negative as long as Dependencies is not calculated.
4284 int UnscheduledDeps = ScheduleData::InvalidDeps;
4285 };
4286
4287#ifndef NDEBUG
4288 friend inline raw_ostream &
4289 operator<<(raw_ostream &OS, const BoUpSLP::ScheduleCopyableData &SD) {
4290 SD.dump(OS);
4291 return OS;
4292 }
4293#endif
4294
4295 friend struct GraphTraits<BoUpSLP *>;
4296 friend struct DOTGraphTraits<BoUpSLP *>;
4297 friend class ::HorizontalReduction;
4298
4299 /// Contains all scheduling data for a basic block.
4300 /// It does not schedules instructions, which are not memory read/write
4301 /// instructions and their operands are either constants, or arguments, or
4302 /// phis, or instructions from others blocks, or their users are phis or from
4303 /// the other blocks. The resulting vector instructions can be placed at the
4304 /// beginning of the basic block without scheduling (if operands does not need
4305 /// to be scheduled) or at the end of the block (if users are outside of the
4306 /// block). It allows to save some compile time and memory used by the
4307 /// compiler.
4308 /// ScheduleData is assigned for each instruction in between the boundaries of
4309 /// the tree entry, even for those, which are not part of the graph. It is
4310 /// required to correctly follow the dependencies between the instructions and
4311 /// their correct scheduling. The ScheduleData is not allocated for the
4312 /// instructions, which do not require scheduling, like phis, nodes with
4313 /// extractelements/insertelements only or nodes with instructions, with
4314 /// uses/operands outside of the block.
4315 struct BlockScheduling {
4316 BlockScheduling(BasicBlock *BB, int ScheduleRegionSizeLimit)
4317 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
4318 ScheduleRegionSizeLimit(ScheduleRegionSizeLimit) {}
4319
4320 void clear() {
4321 ScheduledBundles.clear();
4322 ScheduledBundlesList.clear();
4323 ScheduleCopyableDataMap.clear();
4324 ScheduleCopyableDataMapByInst.clear();
4325 ScheduleCopyableDataMapByInstUser.clear();
4326 ScheduleCopyableDataMapByUsers.clear();
4327 ReadyInsts.clear();
4328 RecalcCopyableOperandDeps.clear();
4329 IgnoredMemDeps.clear();
4330 RegionScheduleData.clear();
4331 ScheduleStart = nullptr;
4332 ScheduleEnd = nullptr;
4333 FirstLoadStoreInRegion = nullptr;
4334 LastLoadStoreInRegion = nullptr;
4335 RegionHasStackSave = false;
4336 RegionHasMayThrow = false;
4337
4338 // Reduce the maximum schedule region size by the size of the
4339 // previous scheduling run.
4340 ScheduleRegionSizeLimit -= ScheduleRegionSize;
4341 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
4342 ScheduleRegionSizeLimit = MinScheduleRegionSize;
4343 ScheduleRegionSize = 0;
4344
4345 // Make a new scheduling region, i.e. all existing ScheduleData is not
4346 // in the new region yet.
4347 ++SchedulingRegionID;
4348 }
4349
4350 ScheduleData *getScheduleData(Instruction *I) {
4351 if (!I)
4352 return nullptr;
4353 if (BB != I->getParent())
4354 // Avoid lookup if can't possibly be in map.
4355 return nullptr;
4356 ScheduleData *SD = ScheduleDataMap.lookup(I);
4357 if (SD && isInSchedulingRegion(*SD))
4358 return SD;
4359 return nullptr;
4360 }
4361
4362 ScheduleData *getScheduleData(Value *V) {
4363 return getScheduleData(dyn_cast<Instruction>(V));
4364 }
4365
4366 /// Returns the ScheduleCopyableData for the given edge (user tree entry and
4367 /// operand number) and value.
4368 ScheduleCopyableData *getScheduleCopyableData(const EdgeInfo &EI,
4369 const Value *V) const {
4370 if (ScheduleCopyableDataMap.empty())
4371 return nullptr;
4372 auto It = ScheduleCopyableDataMap.find(std::make_pair(EI, V));
4373 if (It == ScheduleCopyableDataMap.end())
4374 return nullptr;
4375 ScheduleCopyableData *SD = It->getSecond().get();
4376 if (!isInSchedulingRegion(*SD))
4377 return nullptr;
4378 return SD;
4379 }
4380
4381 /// Returns the ScheduleCopyableData for the given user \p User, operand
4382 /// number and operand \p V.
4384 getScheduleCopyableData(const Value *User, unsigned OperandIdx,
4385 const Value *V) {
4386 if (ScheduleCopyableDataMapByInstUser.empty())
4387 return {};
4388 const auto It = ScheduleCopyableDataMapByInstUser.find(
4389 std::make_pair(std::make_pair(User, OperandIdx), V));
4390 if (It == ScheduleCopyableDataMapByInstUser.end())
4391 return {};
4393 for (ScheduleCopyableData *SD : It->getSecond()) {
4394 if (isInSchedulingRegion(*SD))
4395 Res.push_back(SD);
4396 }
4397 return Res;
4398 }
4399
4400 /// Returns true if all operands of the given instruction \p User are
4401 /// replaced by copyable data.
4402 /// \param User The user instruction.
4403 /// \param Op The operand, which might be replaced by the copyable data.
4404 /// \param SLP The SLP tree.
4405 /// \param NumOps The number of operands used. If the instruction uses the
4406 /// same operand several times, check for the first use, then the second,
4407 /// etc.
4408 bool areAllOperandsReplacedByCopyableData(Instruction *User,
4409 Instruction *Op, BoUpSLP &SLP,
4410 unsigned NumOps) const {
4411 assert(NumOps > 0 && "No operands");
4412 if (ScheduleCopyableDataMap.empty())
4413 return false;
4414 SmallDenseMap<TreeEntry *, unsigned> PotentiallyReorderedEntriesCount;
4415 ArrayRef<TreeEntry *> Entries = SLP.getTreeEntries(User);
4416 if (Entries.empty())
4417 return false;
4418 unsigned CurNumOps = 0;
4419 for (const Use &U : make_filter_range(
4420 User->operands(), [&](const Use &U) { return U.get() == Op; })) {
4421 ++CurNumOps;
4422 // Check all tree entries, if they have operands replaced by copyable
4423 // data.
4424 for (TreeEntry *TE : Entries) {
4425 unsigned Inc = 0;
4426 bool IsNonSchedulableWithParentPhiNode =
4427 TE->doesNotNeedToSchedule() && TE->UserTreeIndex &&
4428 TE->UserTreeIndex.UserTE->hasState() &&
4429 TE->UserTreeIndex.UserTE->State != TreeEntry::SplitVectorize &&
4430 TE->UserTreeIndex.UserTE->getOpcode() == Instruction::PHI;
4431 // Count the number of unique phi nodes, which are the parent for
4432 // parent entry, and exit, if all the unique phis are processed.
4433 if (IsNonSchedulableWithParentPhiNode) {
4434 SmallPtrSet<Value *, 4> ParentsUniqueUsers;
4435 const TreeEntry *ParentTE = TE->UserTreeIndex.UserTE;
4436 for (PHINode *PHI : make_isa_range<PHINode>(ParentTE->Scalars))
4437 if (ParentsUniqueUsers.insert(PHI).second &&
4438 is_contained(PHI->incoming_values(), User))
4439 ++Inc;
4440 } else {
4441 Inc = count(TE->Scalars, User);
4442 }
4443
4444 // Check if the user is commutative.
4445 // The commutatives are handled later, as their operands can be
4446 // reordered.
4447 // Same applies even for non-commutative cmps, because we can invert
4448 // their predicate potentially and, thus, reorder the operands.
4449 bool IsCommutativeUser =
4451 isCommutableOperand(User, User, U.getOperandNo());
4452 if (!IsCommutativeUser) {
4453 Instruction *MainOp = TE->getMatchingMainOpOrAltOp(User);
4454 IsCommutativeUser =
4455 isCommutative(MainOp, User) &&
4456 isCommutableOperand(MainOp, User, U.getOperandNo());
4457 }
4458 // The commutative user with the same operands can be safely
4459 // considered as non-commutative, operands reordering does not change
4460 // the semantics. Same for cmps with the same operands: inverting
4461 // the predicate does not change the operand columns in this case.
4462 assert(
4463 (!IsCommutativeUser ||
4466 (isCommutative(TE->getMatchingMainOpOrAltOp(User), User) &&
4467 isCommutableOperand(TE->getMatchingMainOpOrAltOp(User), User,
4468 0) &&
4469 isCommutableOperand(TE->getMatchingMainOpOrAltOp(User), User,
4470 1))))) &&
4471 "Expected commutative user with 2 first commutable operands");
4472 bool IsCommutativeWithSameOps =
4473 IsCommutativeUser && User->getOperand(0) == User->getOperand(1);
4474 if ((!IsCommutativeUser || IsCommutativeWithSameOps) &&
4475 (!isa<CmpInst>(User) ||
4476 User->getOperand(0) == User->getOperand(1))) {
4477 if (CurNumOps != NumOps)
4478 continue;
4479 // A reassociated node flattens the operand chain, so the operand
4480 // may be placed in any operand column rather than at the
4481 // instruction's operand number.
4482 if (TE->hasReassocScalars()) {
4483 bool ReplacedByCopyable = false;
4484 for (auto It = find(TE->Scalars, User); It != TE->Scalars.end();
4485 It = find(make_range(std::next(It), TE->Scalars.end()),
4486 User)) {
4487 int Lane = std::distance(TE->Scalars.begin(), It);
4488 for (unsigned OpIdx : seq<unsigned>(TE->getNumOperands()))
4489 ReplacedByCopyable |=
4490 TE->getOperand(OpIdx)[Lane] == Op &&
4491 getScheduleCopyableData(EdgeInfo(TE, OpIdx), Op);
4492 }
4493 if (ReplacedByCopyable)
4494 continue;
4495 return false;
4496 }
4497 EdgeInfo EI(TE, U.getOperandNo());
4498 if (getScheduleCopyableData(EI, Op))
4499 continue;
4500 return false;
4501 }
4502 // Only count the occurrence matching this call's NumOps.
4503 if (CurNumOps != NumOps)
4504 continue;
4505 PotentiallyReorderedEntriesCount.try_emplace(TE, 0)
4506 .first->getSecond() += Inc;
4507 }
4508 }
4509 if (PotentiallyReorderedEntriesCount.empty())
4510 return true;
4511 // Check the commutative/cmp entries.
4512 for (auto &P : PotentiallyReorderedEntriesCount) {
4513 SmallPtrSet<Value *, 4> ParentsUniqueUsers;
4514 bool IsNonSchedulableWithParentPhiNode =
4515 P.first->doesNotNeedToSchedule() && P.first->UserTreeIndex &&
4516 P.first->UserTreeIndex.UserTE->hasState() &&
4517 P.first->UserTreeIndex.UserTE->State != TreeEntry::SplitVectorize &&
4518 P.first->UserTreeIndex.UserTE->getOpcode() == Instruction::PHI;
4519 auto *It = find(P.first->Scalars, User);
4520 do {
4521 assert(It != P.first->Scalars.end() &&
4522 "User is not in the tree entry");
4523 int Lane = std::distance(P.first->Scalars.begin(), It);
4524 assert(Lane >= 0 && "Lane is not found");
4526 !P.first->ReorderIndices.empty())
4527 Lane = P.first->ReorderIndices[Lane];
4528 assert(Lane < static_cast<int>(P.first->Scalars.size()) &&
4529 "Couldn't find extract lane");
4530 // Count the number of unique phi nodes, which are the parent for
4531 // parent entry, and exit, if all the unique phis are processed.
4532 if (IsNonSchedulableWithParentPhiNode) {
4533 const TreeEntry *ParentTE = P.first->UserTreeIndex.UserTE;
4534 Value *User = ParentTE->Scalars[Lane];
4535 if (!ParentsUniqueUsers.insert(User).second) {
4536 It =
4537 find(make_range(std::next(It), P.first->Scalars.end()), User);
4538 continue;
4539 }
4540 }
4541 // Flattened nodes may place an operand in any column; scan all of
4542 // them so copyable scheduling does not double-count.
4543 for (unsigned OpIdx :
4544 seq<unsigned>(P.first->hasReassocScalars()
4545 ? P.first->getNumOperands()
4547 P.first->getMainOp()))) {
4548 if (P.first->getOperand(OpIdx)[Lane] == Op &&
4549 getScheduleCopyableData(EdgeInfo(P.first, OpIdx), Op))
4550 --P.getSecond();
4551 }
4552 // If parent node is schedulable, it will be handled correctly.
4553 It = find(make_range(std::next(It), P.first->Scalars.end()), User);
4554 } while (It != P.first->Scalars.end());
4555 }
4556 return all_of(PotentiallyReorderedEntriesCount,
4557 [&](const auto &P) { return P.second == NumOps - 1; });
4558 }
4559
4561 getScheduleCopyableData(const Instruction *I) const {
4562 if (ScheduleCopyableDataMapByInst.empty())
4563 return {};
4564 const auto It = ScheduleCopyableDataMapByInst.find(I);
4565 if (It == ScheduleCopyableDataMapByInst.end())
4566 return {};
4568 for (ScheduleCopyableData *SD : It->getSecond()) {
4569 if (isInSchedulingRegion(*SD))
4570 Res.push_back(SD);
4571 }
4572 return Res;
4573 }
4574
4576 getScheduleCopyableDataUsers(const Instruction *User) const {
4577 if (ScheduleCopyableDataMapByUsers.empty())
4578 return {};
4579 const auto It = ScheduleCopyableDataMapByUsers.find(User);
4580 if (It == ScheduleCopyableDataMapByUsers.end())
4581 return {};
4583 for (ScheduleCopyableData *SD : It->getSecond()) {
4584 if (isInSchedulingRegion(*SD))
4585 Res.push_back(SD);
4586 }
4587 return Res;
4588 }
4589
4590 /// Reordering \p TE permutes its operand columns and may move an operand
4591 /// between the edges covered and not covered by copyable scheduling
4592 /// data, making the computed dependency counts stale. Mark the schedule
4593 /// data of \p TE's copyable-modeled operands for recalculation at the
4594 /// next bundle scheduling.
4595 void markCopyableDepsForRecalc(const TreeEntry &TE) {
4596 for (unsigned OpIdx : seq<unsigned>(TE.getNumOperands()))
4597 for (Instruction *I : make_isa_range<Instruction>(TE.getOperand(OpIdx)))
4598 if (ScheduleData *SD = getScheduleData(I);
4599 SD && !getScheduleCopyableData(I).empty())
4600 RecalcCopyableOperandDeps.insert(SD);
4601 }
4602
4603 ScheduleCopyableData &addScheduleCopyableData(const EdgeInfo &EI,
4604 Instruction *I,
4605 int SchedulingRegionID,
4606 ScheduleBundle &Bundle) {
4607 assert(!getScheduleCopyableData(EI, I) && "already in the map");
4608 ScheduleCopyableData *CD =
4609 ScheduleCopyableDataMap
4610 .try_emplace(std::make_pair(EI, I),
4611 std::make_unique<ScheduleCopyableData>(
4612 SchedulingRegionID, I, EI, Bundle))
4613 .first->getSecond()
4614 .get();
4615 ScheduleCopyableDataMapByInst[I].push_back(CD);
4616 if (EI.UserTE) {
4617 ArrayRef<Value *> Op = EI.UserTE->getOperand(EI.EdgeIdx);
4618 const auto *It = find(Op, I);
4619 assert(It != Op.end() && "Lane not set");
4621 do {
4622 int Lane = std::distance(Op.begin(), It);
4623 assert(Lane >= 0 && "Lane not set");
4625 EI.UserTE->Scalars[Lane]) &&
4626 !EI.UserTE->ReorderIndices.empty())
4627 Lane = std::distance(EI.UserTE->ReorderIndices.begin(),
4628 find(EI.UserTE->ReorderIndices, Lane));
4629 assert(Lane < static_cast<int>(EI.UserTE->Scalars.size()) &&
4630 "Couldn't find extract lane");
4631 auto *In = cast<Instruction>(EI.UserTE->Scalars[Lane]);
4632 if (!Visited.insert(In).second) {
4633 It = find(make_range(std::next(It), Op.end()), I);
4634 continue;
4635 }
4636 ScheduleCopyableDataMapByInstUser
4637 .try_emplace(std::make_pair(std::make_pair(In, EI.EdgeIdx), I))
4638 .first->getSecond()
4639 .push_back(CD);
4640 ScheduleCopyableDataMapByUsers.try_emplace(I)
4641 .first->getSecond()
4642 .insert(CD);
4643 // Remove extra deps for users, becoming non-immediate users of the
4644 // instruction. It may happen, if the chain of same copyable elements
4645 // appears in the tree. With the self-operand modeling (op(V, V)) the
4646 // user node may have the value on an operand column without copyable
4647 // data, so its copyable data releases the instruction's schedule
4648 // data directly and must stay a counted user.
4649 if (In == I) {
4650 unsigned NumCols = 0;
4651 for (unsigned OpIdx : seq<unsigned>(EI.UserTE->getNumOperands()))
4652 NumCols += EI.UserTE->getOperand(OpIdx)[Lane] == I &&
4653 !getScheduleCopyableData({EI.UserTE, OpIdx}, I);
4654 if (NumCols == 0) {
4655 EdgeInfo UserEI = EI.UserTE->UserTreeIndex;
4656 if (ScheduleCopyableData *UserCD =
4657 getScheduleCopyableData(UserEI, In))
4658 ScheduleCopyableDataMapByUsers[I].remove(UserCD);
4659 }
4660 }
4661 It = find(make_range(std::next(It), Op.end()), I);
4662 } while (It != Op.end());
4663 } else {
4664 ScheduleCopyableDataMapByUsers.try_emplace(I).first->getSecond().insert(
4665 CD);
4666 }
4667 return *CD;
4668 }
4669
4670 /// Unregisters \p Bundle from its instructions and removes its copyable
4671 /// data. The caller must destroy the bundle and recalculate the
4672 /// dependencies.
4673 void cancelScheduling(ScheduleBundle &Bundle) {
4674 for (ScheduleEntity *SE : Bundle.getBundle()) {
4675 Instruction *I = SE->getInst();
4676 auto *CD = dyn_cast<ScheduleCopyableData>(SE);
4677 if (!CD) {
4678 llvm::erase(ScheduledBundles.find(I)->getSecond(), &Bundle);
4679 continue;
4680 }
4681 const EdgeInfo EI = CD->getEdgeInfo();
4682 llvm::erase(ScheduleCopyableDataMapByInst.find(I)->getSecond(), CD);
4683 ScheduleCopyableDataMapByUsers[I].remove(CD);
4684 if (EI.UserTE) {
4685 ArrayRef<Value *> Op = EI.UserTE->getOperand(EI.EdgeIdx);
4686 const auto *It = find(Op, I);
4687 assert(It != Op.end() && "Lane not set");
4689 bool HadSelfUse = false;
4690 do {
4691 int Lane = std::distance(Op.begin(), It);
4692 assert(Lane >= 0 && "Lane not set");
4694 EI.UserTE->Scalars[Lane]) &&
4695 !EI.UserTE->ReorderIndices.empty())
4696 Lane = std::distance(EI.UserTE->ReorderIndices.begin(),
4697 find(EI.UserTE->ReorderIndices, Lane));
4698 assert(Lane < static_cast<int>(EI.UserTE->Scalars.size()) &&
4699 "Couldn't find extract lane");
4700 auto *In = cast<Instruction>(EI.UserTE->Scalars[Lane]);
4701 if (!Visited.insert(In).second) {
4702 It = find(make_range(std::next(It), Op.end()), I);
4703 continue;
4704 }
4705 HadSelfUse |= In == I;
4706 auto ByUserIt = ScheduleCopyableDataMapByInstUser.find(
4707 std::make_pair(std::make_pair(In, EI.EdgeIdx), I));
4708 assert(ByUserIt != ScheduleCopyableDataMapByInstUser.end() &&
4709 is_contained(ByUserIt->getSecond(), CD) &&
4710 "copyable data is not registered for the user");
4711 llvm::erase(ByUserIt->getSecond(), CD);
4712 It = find(make_range(std::next(It), Op.end()), I);
4713 } while (It != Op.end());
4714 // Restore the parent-edge copyable data as a user of I only if the
4715 // cancelled data displaced it at creation (chained copyable
4716 // self-use); otherwise the extra user dependency is never released.
4717 if (HadSelfUse) {
4718 EdgeInfo UserEI = EI.UserTE->UserTreeIndex;
4719 if (ScheduleCopyableData *UserCD =
4720 getScheduleCopyableData(UserEI, I))
4721 ScheduleCopyableDataMapByUsers[I].insert(UserCD);
4722 }
4723 }
4724 if (ScheduleCopyableDataMapByUsers[I].empty())
4725 ScheduleCopyableDataMapByUsers.erase(I);
4726 ScheduleCopyableDataMap.erase(std::make_pair(EI, I));
4727 }
4728 }
4729
4730 /// Clears the dependencies of all schedule data in the scheduling region.
4731 void clearDependencies() {
4732 for_each(ScheduleDataMap, [&](auto &P) {
4733 if (BB != P.first->getParent())
4734 return;
4735 ScheduleData *SD = P.second;
4736 if (isInSchedulingRegion(*SD))
4737 SD->clearDependencies();
4738 });
4739 for_each(ScheduleCopyableDataMapByInst, [&](auto &P) {
4740 for_each(P.second, [&](ScheduleCopyableData *SD) {
4741 if (isInSchedulingRegion(*SD))
4742 SD->clearDependencies();
4743 });
4744 });
4745 }
4746
4747 ArrayRef<ScheduleBundle *> getScheduleBundles(Value *V) const {
4748 auto *I = dyn_cast<Instruction>(V);
4749 if (!I)
4750 return {};
4751 auto It = ScheduledBundles.find(I);
4752 if (It == ScheduledBundles.end())
4753 return {};
4754 return It->getSecond();
4755 }
4756
4757 /// Returns true if the entity is in the scheduling region.
4758 bool isInSchedulingRegion(const ScheduleEntity &SD) const {
4759 if (const auto *Data = dyn_cast<ScheduleData>(&SD))
4760 return Data->getSchedulingRegionID() == SchedulingRegionID;
4761 if (const auto *CD = dyn_cast<ScheduleCopyableData>(&SD))
4762 return CD->getSchedulingRegionID() == SchedulingRegionID;
4763 return all_of(cast<ScheduleBundle>(SD).getBundle(),
4764 [&](const ScheduleEntity *BundleMember) {
4765 return isInSchedulingRegion(*BundleMember);
4766 });
4767 }
4768
4769 /// Marks an instruction as scheduled and puts all dependent ready
4770 /// instructions into the ready-list.
4771 template <typename ReadyListType>
4772 void schedule(const BoUpSLP &R, const InstructionsState &S,
4773 const EdgeInfo &EI, ScheduleEntity *Data,
4774 ReadyListType &ReadyList) {
4775 // The lanes of the scalars of the big tree entries are collected once,
4776 // otherwise the search for the lanes of each bundle member is linear.
4777 DenseMap<const TreeEntry *,
4779 TreeEntryLanes;
4780 auto GetLanes = [&](const TreeEntry *TE, const Value *V) {
4781 constexpr unsigned SmallTreeEntrySize = 16;
4783 if (TE->Scalars.size() <= SmallTreeEntrySize) {
4784 for (auto [Lane, Scalar] : enumerate(TE->Scalars))
4785 if (Scalar == V)
4786 Lanes.push_back(Lane);
4787 return Lanes;
4788 }
4789 auto [It, Inserted] = TreeEntryLanes.try_emplace(TE);
4790 if (Inserted)
4791 for (auto [Lane, Scalar] : enumerate(TE->Scalars))
4792 It->second[Scalar].push_back(Lane);
4793 return It->second.lookup(V);
4794 };
4795 auto ProcessBundleMember = [&](ScheduleEntity *BundleMember,
4797 // Handle the def-use chain dependencies.
4798
4799 // Decrement the unscheduled counter and insert to ready list if ready.
4800 auto DecrUnsched = [&](auto *Data, bool IsControl = false) {
4801 if ((IsControl || Data->hasValidDependencies()) &&
4802 Data->incrementUnscheduledDeps(-1) == 0) {
4803 // There are no more unscheduled dependencies after
4804 // decrementing, so we can put the dependent instruction
4805 // into the ready list.
4806 SmallVector<ScheduleBundle *, 1> CopyableBundle;
4808 if (auto *CD = dyn_cast<ScheduleCopyableData>(Data)) {
4809 CopyableBundle.push_back(&CD->getBundle());
4810 Bundles = CopyableBundle;
4811 } else {
4812 Bundles = getScheduleBundles(Data->getInst());
4813 }
4814 if (!Bundles.empty()) {
4815 for (ScheduleBundle *Bundle : Bundles) {
4816 if (!Bundle->hasUnscheduledDeps()) {
4817 assert(!Bundle->isScheduled() &&
4818 "already scheduled bundle gets ready");
4819 ReadyList.insert(Bundle);
4821 << "SLP: gets ready: " << *Bundle << "\n");
4822 }
4823 }
4824 return;
4825 }
4826 assert(!Data->isScheduled() &&
4827 "already scheduled bundle gets ready");
4829 "Expected non-copyable data");
4830 ReadyList.insert(Data);
4831 LLVM_DEBUG(dbgs() << "SLP: gets ready: " << *Data << "\n");
4832 }
4833 };
4834
4835 auto DecrUnschedForInst = [&](Instruction *User, unsigned OpIdx,
4836 Instruction *I) {
4837 if (!ScheduleCopyableDataMap.empty()) {
4839 getScheduleCopyableData(User, OpIdx, I);
4840 bool ReleasedAsCopyable = false;
4841 // Copyable elements modeled on a copyable user lane depend on
4842 // the user's copyable scheduling data, not on the user itself,
4843 // and are released when that copyable data is scheduled. The
4844 // user's own schedule data still carries the def-use dependency
4845 // in this case, so it must be released below.
4846 auto IsNotCopyable = [&](ScheduleCopyableData *CD) {
4847 return !CD->getEdgeInfo().UserTE->isCopyableElement(User);
4848 };
4849 for (ScheduleCopyableData *CD :
4850 make_filter_range(CopyableData, IsNotCopyable)) {
4851 DecrUnsched(CD, /*IsControl=*/false);
4852 ReleasedAsCopyable = true;
4853 }
4854 if (ReleasedAsCopyable)
4855 return;
4856 }
4857 if (ScheduleData *OpSD = getScheduleData(I))
4858 DecrUnsched(OpSD, /*IsControl=*/false);
4859 };
4860
4861 // If BundleMember is a vector bundle, its operands may have been
4862 // reordered during buildTree(). We therefore need to get its operands
4863 // through the TreeEntry.
4864 if (!Bundles.empty()) {
4865 auto *In = BundleMember->getInst();
4866 // Count uses of each instruction operand.
4868 unsigned TotalOpCount = 0;
4869 if (isa<ScheduleCopyableData>(BundleMember)) {
4870 // Copyable data is used only once (uses itself).
4871 TotalOpCount = OperandsUses[In] = 1;
4872 } else {
4873 for (const Use &U : In->operands()) {
4874 if (auto *I = dyn_cast<Instruction>(U.get())) {
4875 auto Res = OperandsUses.try_emplace(I, 0);
4876 unsigned ExtraDeps = 1;
4877 // Count all expanded operands in the binops.
4878 for (ScheduleBundle *Bundle : Bundles) {
4879 if (const TreeEntry *TE = Bundle->getTreeEntry()) {
4880 if (TE->isExpandedBinOp(In))
4881 ++ExtraDeps;
4882 } else if (S.isExpandedBinOp(In)) {
4883 ++ExtraDeps;
4884 }
4885 }
4886 Res.first->getSecond() += ExtraDeps;
4887 TotalOpCount += ExtraDeps;
4888 }
4889 }
4890 }
4891 // Tracks whether the bundle member instruction itself shows up in
4892 // some operand column of its node (only copyable elements modeled
4893 // through their own operands, like absorbed fmuls, do not).
4894 bool FoundInOpColumns = false;
4895 // Decrement the unscheduled counter and insert to ready list if
4896 // ready.
4897 auto DecrUnschedForInst =
4898 [&](Instruction *I, TreeEntry *UserTE, unsigned OpIdx,
4900 &Checked,
4901 bool IsExpandedOperand = false,
4902 bool CopyableDepsOnly = false) {
4903 if (!ScheduleCopyableDataMap.empty()) {
4904 const EdgeInfo EI = {UserTE, OpIdx};
4905 if (ScheduleCopyableData *CD =
4906 getScheduleCopyableData(EI, I)) {
4907 if (!Checked.insert(std::make_pair(CD, OpIdx)).second)
4908 return;
4909 DecrUnsched(CD, /*IsControl=*/false);
4910 return;
4911 }
4912 }
4913 if (CopyableDepsOnly)
4914 return;
4915 auto It = OperandsUses.find(I);
4916 if (It == OperandsUses.end()) {
4917 // Column value may be a peeled intermediate, not a direct
4918 // operand of In; its deps are released when it is scheduled.
4919 LLVM_DEBUG(dbgs() << "SLP: operand " << *I
4920 << " not modeled as a direct operand of "
4921 << *In << ", skipping.\n");
4922 return;
4923 }
4924 if (It->second > 0) {
4925 if (ScheduleData *OpSD = getScheduleData(I)) {
4926 if (!IsExpandedOperand &&
4927 !Checked.insert(std::make_pair(OpSD, OpIdx)).second)
4928 return;
4929 --It->getSecond();
4930 assert(TotalOpCount > 0 && "No more operands to decrement");
4931 --TotalOpCount;
4932 DecrUnsched(OpSD, /*IsControl=*/false);
4933 } else {
4934 --It->getSecond();
4935 assert(TotalOpCount > 0 && "No more operands to decrement");
4936 --TotalOpCount;
4937 }
4938 }
4939 };
4940
4942 for (ScheduleBundle *Bundle : Bundles) {
4943 if (ScheduleCopyableDataMap.empty() && TotalOpCount == 0)
4944 break;
4945 SmallPtrSet<Value *, 4> ParentsUniqueUsers;
4946 // Need to search for the lane since the tree entry can be
4947 // reordered.
4948 SmallVector<unsigned, 1> InLanes =
4949 GetLanes(Bundle->getTreeEntry(), In);
4950 assert(!InLanes.empty() && "Couldn't find extract lane");
4951 bool IsNonSchedulableWithParentPhiNode =
4952 Bundle->getTreeEntry()->doesNotNeedToSchedule() &&
4953 Bundle->getTreeEntry()->UserTreeIndex &&
4954 Bundle->getTreeEntry()->UserTreeIndex.UserTE->hasState() &&
4955 Bundle->getTreeEntry()->UserTreeIndex.UserTE->State !=
4956 TreeEntry::SplitVectorize &&
4957 Bundle->getTreeEntry()->UserTreeIndex.UserTE->getOpcode() ==
4958 Instruction::PHI;
4959 for (int Lane : InLanes) {
4961 !Bundle->getTreeEntry()->ReorderIndices.empty())
4962 Lane = Bundle->getTreeEntry()->ReorderIndices[Lane];
4963 assert(Lane < static_cast<int>(
4964 Bundle->getTreeEntry()->Scalars.size()) &&
4965 "Couldn't find extract lane");
4966
4967 // Since vectorization tree is being built recursively this
4968 // assertion ensures that the tree entry has all operands set
4969 // before reaching this code. Couple of exceptions known at the
4970 // moment are extracts where their second (immediate) operand is
4971 // not added. Since immediates do not affect scheduler behavior
4972 // this is considered okay.
4973 assert(
4974 In &&
4976 In->getNumOperands() ==
4977 Bundle->getTreeEntry()->getNumOperands() ||
4978 (isa<ZExtInst>(In) && Bundle->getTreeEntry()->getOpcode() ==
4979 Instruction::Select) ||
4980 Bundle->getTreeEntry()->isCopyableElement(In) ||
4981 Bundle->getTreeEntry()->hasReassocScalars()) &&
4982 "Missed TreeEntry operands?");
4983
4984 // Count the number of unique phi nodes, which are the parent
4985 // entry, and handle the non-copyable deps only on the first lane
4986 // for each such phi. Copyable deps are counted per operand column
4987 // lane and are released on every lane.
4988 bool CopyableDepsOnly =
4989 IsNonSchedulableWithParentPhiNode &&
4990 !ParentsUniqueUsers
4991 .insert(Bundle->getTreeEntry()
4992 ->UserTreeIndex.UserTE->Scalars[Lane])
4993 .second;
4994
4995 // A blended-load operand node is the synthetic blend mask, not an
4996 // IR operand of the load. Use the real pointer operand for
4997 // scheduling so the def-use counters stay balanced; the mask is
4998 // available earlier through the pointer's select.
4999 bool IsBlended = Bundle->getTreeEntry()->State ==
5000 TreeEntry::BlendedLoadVectorize;
5001 for (unsigned OpIdx :
5002 seq<unsigned>(Bundle->getTreeEntry()->getNumOperands()))
5003 if (auto *I = dyn_cast<Instruction>(
5004 IsBlended ? In->getOperand(OpIdx)
5005 : Bundle->getTreeEntry()->getOperand(
5006 OpIdx)[Lane])) {
5007 FoundInOpColumns |= (I == In) && !CopyableDepsOnly;
5008 LLVM_DEBUG(dbgs() << "SLP: check for readiness (def): "
5009 << *I << "\n");
5010 DecrUnschedForInst(
5011 I, Bundle->getTreeEntry(), OpIdx, Checked,
5012 Bundle->getTreeEntry()->isExpandedOperand(In, OpIdx),
5013 /*CopyableDepsOnly=*/CopyableDepsOnly);
5014 }
5015 // If parent node is schedulable, it will be handled correctly.
5016 if (Bundle->getTreeEntry()->isCopyableElement(In))
5017 break;
5018 }
5019 }
5020 // A copyable element absorbed into its user modeling (e.g. a
5021 // copyable fmul turned into fmuladd(a, b, -0.0)) does not appear in
5022 // the operand columns of its own node, so the scan above never
5023 // releases the schedule data of the copyable instruction itself.
5024 // Release it here to keep the unscheduled-deps counters balanced,
5025 // consuming its self-use count so the reassociated-operand release
5026 // below cannot release the same schedule data twice.
5027 if (isa<ScheduleCopyableData>(BundleMember) && !FoundInOpColumns) {
5028 auto UseIt = OperandsUses.find(In);
5029 if (UseIt != OperandsUses.end() && UseIt->second > 0) {
5030 --UseIt->getSecond();
5031 --TotalOpCount;
5032 }
5033 if (ScheduleData *OpSD = getScheduleData(In))
5034 DecrUnsched(OpSD, /*IsControl=*/false);
5035 }
5036 // Vector intrinsics may keep some arguments scalar (e.g. the
5037 // exponent of llvm.powi). Such scalar arguments are not modeled as
5038 // tree-entry operands, so the per-lane loop above never releases the
5039 // dependency that calculateDependencies() registered for the
5040 // definition feeding such an argument. Release it here to keep the
5041 // unscheduled-deps counters balanced; otherwise the operand's bundle
5042 // may never become ready and scheduling would assert.
5043 if (TotalOpCount > 0) {
5044 if (auto *CI = dyn_cast<CallInst>(In)) {
5046 for (unsigned ArgIdx : seq<unsigned>(CI->arg_size())) {
5047 if (!isVectorIntrinsicWithScalarOpAtArg(ID, ArgIdx, R.TTI))
5048 continue;
5049 auto *OpI = dyn_cast<Instruction>(CI->getArgOperand(ArgIdx));
5050 if (!OpI)
5051 continue;
5052 auto UseIt = OperandsUses.find(OpI);
5053 if (UseIt == OperandsUses.end() || UseIt->second == 0)
5054 continue;
5055 --UseIt->getSecond();
5056 --TotalOpCount;
5057 if (ScheduleData *OpSD = getScheduleData(OpI)) {
5059 << "SLP: check for readiness (scalar arg): "
5060 << *OpI << "\n");
5061 DecrUnsched(OpSD, /*IsControl=*/false);
5062 }
5063 }
5064 }
5065 // Peeled intermediates stay as direct operands but drop out of
5066 // operand columns; release their scheduling deps here.
5067 for (const ScheduleBundle *Bundle : Bundles) {
5068 if (TotalOpCount == 0)
5069 break;
5070 TreeEntry *TE = Bundle->getTreeEntry();
5071 if (!TE->hasReassocScalars())
5072 continue;
5073 for (Instruction *OpI :
5074 make_isa_range<Instruction>(TE->getReassocScalars())) {
5075 auto UseIt = OperandsUses.find(OpI);
5076 if (UseIt == OperandsUses.end() || UseIt->second == 0)
5077 continue;
5078 LLVM_DEBUG(dbgs() << "SLP: check for readiness "
5079 "(reassociated operand): "
5080 << *OpI << "\n");
5081 // Copyable deps may live on per-edge ScheduleCopyableData.
5082 bool ReleasedAsCopyable = false;
5083 if (!ScheduleCopyableDataMap.empty()) {
5084 auto MatchesOp = [&](const Use &U) { return U.get() == OpI; };
5085 for (const Use &U :
5086 make_filter_range(In->operands(), MatchesOp)) {
5087 for (ScheduleCopyableData *CD :
5088 getScheduleCopyableData(In, U.getOperandNo(), OpI)) {
5089 // Deps of reassoc scalars modeled as copyable tree
5090 // operands are released by the operand scan above;
5091 // release each remaining dep only once.
5092 if (Checked.insert(std::make_pair(CD, U.getOperandNo()))
5093 .second)
5094 DecrUnsched(CD, /*IsControl=*/false);
5095 }
5096 }
5097 // The dep is released through copyable data only if this
5098 // very entry models the scalar as a copyable operand on one
5099 // of its edges, mirroring the dependency calculation;
5100 // copyable data on some other entry's edge does not cover
5101 // the dep registered for this entry.
5102 for (auto It = find(TE->Scalars, In);
5103 It != TE->Scalars.end() && !ReleasedAsCopyable;
5104 It = find(make_range(std::next(It), TE->Scalars.end()),
5105 In)) {
5106 int Lane = std::distance(TE->Scalars.begin(), It);
5107 for (unsigned OpIdx : seq<unsigned>(TE->getNumOperands()))
5108 ReleasedAsCopyable |=
5109 TE->getOperand(OpIdx)[Lane] == OpI &&
5110 getScheduleCopyableData(EdgeInfo(TE, OpIdx), OpI);
5111 }
5112 }
5113 if (!ReleasedAsCopyable) {
5114 if (ScheduleData *OpSD = getScheduleData(OpI))
5115 for (unsigned I = 0, E = UseIt->second; I != E; ++I)
5116 DecrUnsched(OpSD, /*IsControl=*/false);
5117 }
5118 TotalOpCount -= UseIt->second;
5119 UseIt->second = 0;
5120 }
5121 }
5122 }
5123 } else {
5124 // If BundleMember is a stand-alone instruction, no operand reordering
5125 // has taken place, so we directly access its operands.
5126 for (Use &U : BundleMember->getInst()->operands()) {
5127 if (auto *I = dyn_cast<Instruction>(U.get())) {
5129 << "SLP: check for readiness (def): " << *I << "\n");
5130 DecrUnschedForInst(BundleMember->getInst(), U.getOperandNo(), I);
5131 }
5132 }
5133 }
5134 // Handle the memory dependencies.
5135 auto *SD = dyn_cast<ScheduleData>(BundleMember);
5136 if (!SD)
5137 return;
5138 for (ScheduleData *MemoryDep : SD->getMemoryDependencies()) {
5139 // There are no more unscheduled dependencies after decrementing,
5140 // so we can put the dependent instruction into the ready list.
5141 LLVM_DEBUG(dbgs() << "SLP: check for readiness (mem): "
5142 << *MemoryDep << "\n");
5143 DecrUnsched(MemoryDep);
5144 }
5145 // Handle the control dependencies.
5146 for (ScheduleData *Dep : SD->getControlDependencies()) {
5147 // There are no more unscheduled dependencies after decrementing,
5148 // so we can put the dependent instruction into the ready list.
5150 << "SLP: check for readiness (ctrl): " << *Dep << "\n");
5151 DecrUnsched(Dep, /*IsControl=*/true);
5152 }
5153 };
5154 if (auto *SD = dyn_cast<ScheduleData>(Data)) {
5155 SD->setScheduled(/*Scheduled=*/true);
5156 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
5159 Instruction *In = SD->getInst();
5160 ArrayRef<TreeEntry *> Entries = R.getTreeEntries(In);
5161 if (!Entries.empty()) {
5162 for (TreeEntry *TE : make_filter_range(Entries, [&](TreeEntry *TE) {
5164 In) ||
5165 In->getNumOperands() == TE->getNumOperands() ||
5166 TE->hasReassocScalars();
5167 })) {
5168 auto &BundlePtr =
5169 PseudoBundles.emplace_back(std::make_unique<ScheduleBundle>());
5170 BundlePtr->setTreeEntry(TE);
5171 BundlePtr->add(SD);
5172 Bundles.push_back(BundlePtr.get());
5173 }
5174 }
5175 ProcessBundleMember(SD, Bundles);
5176 } else {
5177 ScheduleBundle &Bundle = *cast<ScheduleBundle>(Data);
5178 Bundle.setScheduled(/*Scheduled=*/true);
5179 LLVM_DEBUG(dbgs() << "SLP: schedule " << Bundle << "\n");
5180 auto AreAllBundlesScheduled =
5181 [&](const ScheduleEntity *SD,
5182 ArrayRef<ScheduleBundle *> SDBundles) {
5184 return true;
5185 return !SDBundles.empty() &&
5186 all_of(SDBundles, [&](const ScheduleBundle *SDBundle) {
5187 return SDBundle->isScheduled();
5188 });
5189 };
5190 for (ScheduleEntity *SD : Bundle.getBundle()) {
5193 SDBundles = getScheduleBundles(SD->getInst());
5194 if (!AreAllBundlesScheduled(SD, SDBundles))
5195 continue;
5196 SD->setScheduled(/*Scheduled=*/true);
5197 Instruction *In = SD->getInst();
5198 // The instruction may also belong to tree entries that do not need
5199 // scheduling (e.g. all their values are used outside the block), so
5200 // no schedule bundle is registered for them. Such an entry can still
5201 // model one of this instruction's operands as a copyable element, or
5202 // model the instruction itself as an expanded binop, registered on
5203 // that non-scheduled parent edge. That dependency would never be
5204 // decremented when the instruction is scheduled through a different
5205 // bundle, leaving the operand's bundle permanently unscheduled and
5206 // tripping the unscheduled-deps assertion. Add pseudo-bundles for
5207 // these missing tree entries, so their operand dependencies are
5208 // decremented here as well. Real operand dependencies are protected
5209 // against double counting by the per-operand use counter.
5210 if (isa<ScheduleCopyableData>(SD) ||
5211 (ScheduleCopyableDataMap.empty() &&
5212 none_of(R.getTreeEntries(In), [&](const TreeEntry *TE) {
5213 return TE->isExpandedBinOp(In);
5214 }))) {
5215 ProcessBundleMember(SD, isa<ScheduleCopyableData>(SD) ? &Bundle
5216 : SDBundles);
5217 continue;
5218 }
5220 SmallVector<ScheduleBundle *> AllBundles(SDBundles.begin(),
5221 SDBundles.end());
5222 for (TreeEntry *TE :
5223 make_filter_range(R.getTreeEntries(In), [&](TreeEntry *TE) {
5224 return !TE->isCopyableElement(In);
5225 })) {
5227 In->getNumOperands() != TE->getNumOperands() &&
5228 !TE->hasReassocScalars())
5229 continue;
5230 if (any_of(SDBundles, [&](const ScheduleBundle *SDBundle) {
5231 return SDBundle->getTreeEntry() == TE;
5232 }))
5233 continue;
5234 ScheduleBundle &PseudoBundle =
5235 *PseudoBundles.emplace_back(std::make_unique<ScheduleBundle>());
5236 PseudoBundle.setTreeEntry(TE);
5237 PseudoBundle.add(SD);
5238 AllBundles.push_back(&PseudoBundle);
5239 }
5240 ProcessBundleMember(SD, AllBundles);
5241 }
5242 }
5243 }
5244
5245 /// Verify basic self consistency properties of the data structure.
5246 void verify() {
5247 if (!ScheduleStart)
5248 return;
5249
5250 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
5251 ScheduleStart->comesBefore(ScheduleEnd) &&
5252 "Not a valid scheduling region?");
5253
5254 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5255 ArrayRef<ScheduleBundle *> Bundles = getScheduleBundles(I);
5256 if (!Bundles.empty()) {
5257 for (ScheduleBundle *Bundle : Bundles) {
5258 assert(isInSchedulingRegion(*Bundle) &&
5259 "primary schedule data not in window?");
5260 Bundle->verify();
5261 }
5262 continue;
5263 }
5264 auto *SD = getScheduleData(I);
5265 if (!SD)
5266 continue;
5267 assert(isInSchedulingRegion(*SD) &&
5268 "primary schedule data not in window?");
5269 SD->verify();
5270 }
5271
5272 assert(all_of(ReadyInsts,
5273 [](const ScheduleEntity *Bundle) {
5274 return Bundle->isReady();
5275 }) &&
5276 "item in ready list not ready?");
5277 }
5278
5279 /// Put all instructions into the ReadyList which are ready for scheduling.
5280 template <typename ReadyListType>
5281 void initialFillReadyList(ReadyListType &ReadyList) {
5283 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5284 ScheduleData *SD = getScheduleData(I);
5285 if (SD && SD->hasValidDependencies() && SD->isReady()) {
5286 if (ArrayRef<ScheduleBundle *> Bundles = getScheduleBundles(I);
5287 !Bundles.empty()) {
5288 for (ScheduleBundle *Bundle :
5289 make_filter_range(Bundles, [&](ScheduleBundle *Bundle) {
5290 return Visited.insert(Bundle).second;
5291 })) {
5292 if (Bundle->hasValidDependencies() && Bundle->isReady()) {
5293 ReadyList.insert(Bundle);
5294 LLVM_DEBUG(dbgs() << "SLP: initially in ready list: "
5295 << *Bundle << "\n");
5296 }
5297 }
5298 continue;
5299 }
5300 ReadyList.insert(SD);
5302 << "SLP: initially in ready list: " << *SD << "\n");
5303 }
5304 }
5305 }
5306
5307 /// Build a bundle from the ScheduleData nodes corresponding to the
5308 /// scalar instruction for each lane.
5309 /// \param VL The list of scalar instructions.
5310 /// \param S The state of the instructions.
5311 /// \param EI The edge in the SLP graph or the user node/operand number.
5312 ScheduleBundle &buildBundle(ArrayRef<Value *> VL,
5313 const InstructionsState &S, const EdgeInfo &EI);
5314
5315 /// Checks if a bundle of instructions can be scheduled, i.e. has no
5316 /// cyclic dependencies. This is only a dry-run, no instructions are
5317 /// actually moved at this stage.
5318 /// \returns the scheduling bundle. The returned Optional value is not
5319 /// std::nullopt if \p VL is allowed to be scheduled.
5320 std::optional<ScheduleBundle *>
5321 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
5322 const InstructionsState &S, const EdgeInfo &EI);
5323
5324 /// Allocates schedule data chunk.
5325 ScheduleData *allocateScheduleDataChunks();
5326
5327 /// Extends the scheduling region so that V is inside the region.
5328 /// \returns true if the region size is within the limit.
5329 bool extendSchedulingRegion(Value *V, const InstructionsState &S);
5330
5331 /// Initialize the ScheduleData structures for new instructions in the
5332 /// scheduling region.
5333 void initScheduleData(Instruction *FromI, Instruction *ToI,
5334 ScheduleData *PrevLoadStore,
5335 ScheduleData *NextLoadStore);
5336
5337 /// Updates the dependency information of a bundle and of all instructions/
5338 /// bundles which depend on the original bundle. \p IsRootStoreBundle is
5339 /// true if \p Bundle is the root bundle of stores in a new region.
5340 void calculateDependencies(ScheduleBundle &Bundle, bool InsertInReadyList,
5341 BoUpSLP *SLP,
5342 const SmallPtrSetImpl<Value *> &ExpandedOps,
5343 ArrayRef<ScheduleData *> ControlDeps = {},
5344 bool IsRootStoreBundle = false);
5345
5346 /// Sets all instruction in the scheduling region to un-scheduled.
5347 void resetSchedule();
5348
5349 BasicBlock *BB;
5350
5351 /// Simple memory allocation for ScheduleData.
5353
5354 /// The size of a ScheduleData array in ScheduleDataChunks.
5355 int ChunkSize;
5356
5357 /// The allocator position in the current chunk, which is the last entry
5358 /// of ScheduleDataChunks.
5359 int ChunkPos;
5360
5361 /// Attaches ScheduleData to Instruction.
5362 /// Note that the mapping survives during all vectorization iterations, i.e.
5363 /// ScheduleData structures are recycled.
5365
5366 /// The ScheduleData in the scheduling region.
5367 SmallVector<ScheduleData *> RegionScheduleData;
5368
5369 /// Attaches ScheduleCopyableData to EdgeInfo (UserTreeEntry + operand
5370 /// number) and the operand instruction, represented as copyable element.
5372 std::unique_ptr<ScheduleCopyableData>>
5373 ScheduleCopyableDataMap;
5374
5375 /// Represents mapping between instruction and all related
5376 /// ScheduleCopyableData (for all uses in the tree, represenedt as copyable
5377 /// element). The SLP tree may contain several representations of the same
5378 /// instruction.
5380 ScheduleCopyableDataMapByInst;
5381
5382 /// Represents mapping between user value and operand number, the operand
5383 /// value and all related ScheduleCopyableData. The relation is 1:n, because
5384 /// the same user may refernce the same operand in different tree entries
5385 /// and the operand may be modelled by the different copyable data element.
5388 ScheduleCopyableDataMapByInstUser;
5389
5390 /// Represents mapping between instruction and all related
5391 /// ScheduleCopyableData. It represents the mapping between the actual
5392 /// instruction and the last copyable data element in the chain. E.g., if
5393 /// the graph models the following instructions:
5394 /// %0 = non-add instruction ...
5395 /// ...
5396 /// %4 = add %3, 1
5397 /// %5 = add %4, 1
5398 /// %6 = insertelement poison, %0, 0
5399 /// %7 = insertelement %6, %5, 1
5400 /// And the graph is modeled as:
5401 /// [%5, %0] -> [%4, copyable %0 <0> ] -> [%3, copyable %0 <1> ]
5402 /// -> [1, 0] -> [%1, 0]
5403 ///
5404 /// this map will map %0 only to the copyable element <1>, which is the last
5405 /// user (direct user of the actual instruction). <0> uses <1>, so <1> will
5406 /// keep the map to <0>, not the %0.
5407 SmallDenseMap<const Instruction *,
5409 ScheduleCopyableDataMapByUsers;
5410
5411 /// Attaches ScheduleBundle to Instruction.
5413 ScheduledBundles;
5414 /// The list of ScheduleBundles.
5415 SmallVector<std::unique_ptr<ScheduleBundle>> ScheduledBundlesList;
5416
5417 /// The ready-list for scheduling (only used for the dry-run).
5418 SetVector<ScheduleEntity *> ReadyInsts;
5419
5420 /// The first instruction of the scheduling region.
5421 Instruction *ScheduleStart = nullptr;
5422
5423 /// The first instruction _after_ the scheduling region.
5424 Instruction *ScheduleEnd = nullptr;
5425
5426 /// The first memory accessing instruction in the scheduling region
5427 /// (can be null).
5428 ScheduleData *FirstLoadStoreInRegion = nullptr;
5429
5430 /// The last memory accessing instruction in the scheduling region
5431 /// (can be null).
5432 ScheduleData *LastLoadStoreInRegion = nullptr;
5433
5434 /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
5435 /// region? Used to optimize the dependence calculation for the
5436 /// common case where there isn't.
5437 bool RegionHasStackSave = false;
5438
5439 /// Used to skip the dependencies calculation for writes that are visible
5440 /// after unwinding.
5441 bool RegionHasMayThrow = false;
5442
5443 /// Returns true if \p I writes memory that the caller can still see
5444 /// after an unwind.
5445 bool isWriteVisibleOnUnwind(Instruction *I) const {
5446 if (!RegionHasMayThrow || !I->mayWriteToMemory())
5447 return false;
5449 if (!Loc.Ptr)
5450 return true;
5451 bool RequiresNoCaptureBeforeUnwind = false;
5453 RequiresNoCaptureBeforeUnwind) ||
5454 RequiresNoCaptureBeforeUnwind;
5455 }
5456
5457 /// The current size of the scheduling region.
5458 int ScheduleRegionSize = 0;
5459
5460 /// The maximum size allowed for the scheduling region.
5461 int ScheduleRegionSizeLimit;
5462
5463 /// Operands that are modeled as copyable elements in a previously built
5464 /// vectorized node and that are used directly by another,
5465 /// not-yet-registered node sharing a schedulable instruction with it. Their
5466 /// direct dependencies must be recomputed at the next bundle scheduling,
5467 /// when the new node is already registered in the tree, so that the direct
5468 /// use is accounted for. If the new node is the last scheduled bundle and
5469 /// no further scheduling consumes this list, the leftover entries are
5470 /// dropped on the next region reset and the dependencies are recomputed
5471 /// against the full tree in scheduleBlock instead. A set is used to avoid
5472 /// recomputing the same operand more than once.
5473 SmallSetVector<ScheduleData *, 8> RecalcCopyableOperandDeps;
5474
5475 /// Ordered pairs (Src, Dst) of memory instructions whose may-alias
5476 /// dependency has been dropped in favor of a runtime alias check.
5478
5479 /// The ID of the scheduling region. For a new vectorization iteration this
5480 /// is incremented which "removes" all ScheduleData from the region.
5481 /// Make sure that the initial SchedulingRegionID is greater than the
5482 /// initial SchedulingRegionID in ScheduleData (which is 0).
5483 int SchedulingRegionID = 1;
5484 };
5485
5486 /// Attaches the BlockScheduling structures to basic blocks.
5488
5489 /// The BlockScheduling structures, used by the current tree. The others have
5490 /// no scheduling data to clear.
5491 SmallSetVector<BlockScheduling *, 4> TreeBlocksSchedules;
5492
5493 /// Performs the "real" scheduling. Done before vectorization is actually
5494 /// performed in a basic block.
5495 void scheduleBlock(const BoUpSLP &R, BlockScheduling *BS);
5496
5497 /// List of users to ignore during scheduling and that don't need extracting.
5498 const SmallDenseSet<Value *> *UserIgnoreList = nullptr;
5499
5500 /// Narrowed reduction chain instructions, dropped together with the
5501 /// reduction. Subset of UserIgnoreList.
5502 SmallPtrSet<Value *, 4> NarrowedChainInsts;
5503
5504 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
5505 /// sorted SmallVectors of unsigned.
5506 struct OrdersTypeDenseMapInfo {
5507 static unsigned getHashValue(const OrdersType &V) {
5508 return static_cast<unsigned>(hash_combine_range(V));
5509 }
5510
5511 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
5512 return LHS == RHS;
5513 }
5514 };
5515
5516 // Analysis and block reference.
5517 Function *F;
5518 ScalarEvolution *SE;
5519 TargetTransformInfo *TTI;
5520 TargetLibraryInfo *TLI;
5521 LoopInfo *LI;
5522 DominatorTree *DT;
5523 AssumptionCache *AC;
5524 DemandedBits *DB;
5525 const DataLayout *DL;
5526 OptimizationRemarkEmitter *ORE;
5527 /// Cached cost-model mode for this function.
5528 /// If -Os/-Oz, use CodeSize. Otherwise use RecipThroughput.
5530
5531 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
5532 unsigned MinVecRegSize; // Set by cl::opt (default: 128).
5533
5534 /// Instruction builder to construct the vectorized tree.
5535 IRBuilder<TargetFolder> Builder;
5536
5537 /// A map of scalar integer values to the smallest bit width with which they
5538 /// can legally be represented. The values map to (width, signed) pairs,
5539 /// where "width" indicates the minimum bit width and "signed" is True if the
5540 /// value must be signed-extended, rather than zero-extended, back to its
5541 /// original width.
5542 DenseMap<const TreeEntry *, std::pair<uint64_t, bool>> MinBWs;
5543
5544 /// A booleanized node is an i1 node registered in MinBWs to be emitted in
5545 /// the wide leaf type. Genuine demoted nodes never have i1 scalars (i1
5546 /// cannot be demoted), so an i1 node in MinBWs is always a booleanized one.
5547 bool isBooleanizedNode(const TreeEntry *E) const {
5548 auto It = MinBWs.find(E);
5549 return It != MinBWs.end() && E->Scalars.front()->getType()->isIntegerTy(1);
5550 }
5551
5552 /// Final size of the reduced vector, if the current graph represents the
5553 /// input for the reduction and it was possible to narrow the size of the
5554 /// reduction.
5555 unsigned ReductionBitWidth = 0;
5556
5557 /// Canonical graph size before the transformations.
5558 unsigned BaseGraphSize = 1;
5559
5560 /// If the tree contains any zext/sext/trunc nodes, contains max-min pair of
5561 /// type sizes, used in the tree.
5562 std::optional<std::pair<unsigned, unsigned>> CastMaxMinBWSizes;
5563
5564 /// Indices of the vectorized nodes, which supposed to be the roots of the new
5565 /// bitwidth analysis attempt, like trunc, IToFP or ICmp.
5566 DenseSet<unsigned> ExtraBitWidthNodes;
5567};
5568
5569template <> struct llvm::DenseMapInfo<BoUpSLP::EdgeInfo> {
5572 static unsigned getHashValue(const BoUpSLP::EdgeInfo &Val) {
5573 return detail::combineHashValue(FirstInfo::getHashValue(Val.UserTE),
5574 SecondInfo::getHashValue(Val.EdgeIdx));
5575 }
5576
5577 static bool isEqual(const BoUpSLP::EdgeInfo &LHS,
5578 const BoUpSLP::EdgeInfo &RHS) {
5579 return LHS == RHS;
5580 }
5581};
5582
5583template <> struct llvm::GraphTraits<BoUpSLP *> {
5584 using TreeEntry = BoUpSLP::TreeEntry;
5585
5586 /// NodeRef has to be a pointer per the GraphWriter.
5588
5589 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
5590
5591 /// Add the VectorizableTree to the index iterator to be able to return
5592 /// TreeEntry pointers.
5594 : public iterator_adaptor_base<
5595 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
5597
5601
5602 NodeRef operator*() { return I->UserTE; }
5603 };
5604
5605 static NodeRef getEntryNode(BoUpSLP &R) { return &R.getRootNode(); }
5606
5608 return {&N->UserTreeIndex, N->Container};
5609 }
5610
5612 return {&N->UserTreeIndex + 1, N->Container};
5613 }
5614
5615 /// For the node iterator we just need to turn the TreeEntry iterator into a
5616 /// TreeEntry* iterator so that it dereferences to NodeRef.
5618 using ItTy = ContainerTy::iterator;
5619 ItTy It;
5620
5621 public:
5622 nodes_iterator(const ItTy &It2) : It(It2) {}
5623 NodeRef operator*() { return It->get(); }
5625 ++It;
5626 return *this;
5627 }
5628 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
5629 };
5630
5632 return nodes_iterator(R->VectorizableTree.begin());
5633 }
5634
5636 return nodes_iterator(R->VectorizableTree.end());
5637 }
5638
5639 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
5640};
5641
5642template <>
5644 using TreeEntry = BoUpSLP::TreeEntry;
5645
5646 DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
5647
5648 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
5649 std::string Str;
5650 raw_string_ostream OS(Str);
5651 OS << Entry->Idx << ".\n";
5652 if (isSplat(Entry->Scalars))
5653 OS << "<splat> ";
5654 for (auto *V : Entry->Scalars) {
5655 OS << *V;
5656 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
5657 return EU.Scalar == V;
5658 }))
5659 OS << " <extract>";
5660 OS << "\n";
5661 }
5662 return Str;
5663 }
5664
5665 static std::string getNodeAttributes(const TreeEntry *Entry,
5666 const BoUpSLP *) {
5667 if (Entry->isGather())
5668 return "color=red";
5669 if (Entry->State == TreeEntry::ScatterVectorize ||
5670 Entry->State == TreeEntry::StridedVectorize ||
5671 Entry->State == TreeEntry::ExpandVectorize ||
5672 Entry->State == TreeEntry::CompressVectorize ||
5673 Entry->State == TreeEntry::BlendedLoadVectorize)
5674 return "color=blue";
5675 return "";
5676 }
5677};
5678
5681 for (auto *I : DeletedInstructions) {
5682 if (!I->getParent()) {
5683 // Temporarily insert instruction back to erase them from parent and
5684 // memory later.
5685 if (isa<PHINode>(I))
5686 // Phi nodes must be the very first instructions in the block.
5687 I->insertBefore(F->getEntryBlock(),
5688 F->getEntryBlock().getFirstNonPHIIt());
5689 else
5690 I->insertBefore(F->getEntryBlock().getTerminator()->getIterator());
5691 continue;
5692 }
5693 for (Instruction *Op : make_isa_range<Instruction>(I->operands()))
5694 if (!DeletedInstructions.count(Op) && Op->hasOneUser() &&
5696 DeadInsts.emplace_back(Op);
5697 I->dropAllReferences();
5698 }
5699 for (auto *I : DeletedInstructions) {
5700 assert(I->use_empty() &&
5701 "trying to erase instruction with users.");
5702 I->eraseFromParent();
5703 }
5704
5705 // Cleanup any dead scalar code feeding the vectorized instructions
5707
5708#ifdef EXPENSIVE_CHECKS
5709 // If we could guarantee that this call is not extremely slow, we could
5710 // remove the ifdef limitation (see PR47712).
5711 assert(!verifyFunction(*F, &dbgs()));
5712#endif
5713}
5714
5715std::optional<BoUpSLP::OrdersType>
5716BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE,
5717 bool TopToBottom, bool IgnoreReorder) {
5718 assert(TE.isGather() && "Expected gather node only.");
5719 // Try to find subvector extract/insert patterns and reorder only such
5720 // patterns.
5721 SmallVector<Value *> GatheredScalars(TE.Scalars.begin(), TE.Scalars.end());
5722 Type *ScalarTy = GatheredScalars.front()->getType();
5723 size_t NumScalars = GatheredScalars.size();
5724 if (!isValidElementType(ScalarTy, Opts.slp_revec))
5725 return std::nullopt;
5726 auto *VecTy = getWidenedType(ScalarTy, NumScalars);
5727 unsigned NumParts = getNumberOfParts(VecTy, ScalarTy, NumScalars);
5728 SmallVector<int> ExtractMask;
5729 SmallVector<int> Mask;
5732 tryToGatherExtractElements(GatheredScalars, ExtractMask, NumParts);
5734 isGatherShuffledEntry(&TE, GatheredScalars, Mask, Entries, NumParts,
5735 ScalarTy, /*ForOrder=*/true);
5736 // The internal gathers of the splat gather subtrees are not used as shuffle
5737 // sources, do not reorder the tree to match them.
5738 if (hasSplatSubtreeGather(Entries)) {
5739 GatherShuffles.clear();
5740 Entries.clear();
5741 }
5742 // No shuffled operands - ignore.
5743 if (GatherShuffles.empty() && ExtractShuffles.empty())
5744 return std::nullopt;
5745 OrdersType CurrentOrder(NumScalars, NumScalars);
5746 if (GatherShuffles.size() == 1 &&
5747 *GatherShuffles.front() == TTI::SK_PermuteSingleSrc &&
5748 Entries.front().front()->isSame(TE.Scalars)) {
5749 // If the full matched node in whole tree rotation - no need to consider the
5750 // matching order, rotating the whole tree.
5751 if (TopToBottom)
5752 return std::nullopt;
5753 // No need to keep the order for the same user node.
5754 if (Entries.front().front()->UserTreeIndex.UserTE ==
5755 TE.UserTreeIndex.UserTE)
5756 return std::nullopt;
5757 // No need to keep the order for the matched root node, if it can be freely
5758 // reordered.
5759 if (!IgnoreReorder && Entries.front().front()->Idx == 0)
5760 return std::nullopt;
5761 // If shuffling 2 elements only and the matching node has reverse reuses -
5762 // no need to count order, both work fine.
5763 if (!Entries.front().front()->ReuseShuffleIndices.empty() &&
5764 TE.getVectorFactor() == 2 && Mask.size() == 2 &&
5765 any_of(enumerate(Entries.front().front()->ReuseShuffleIndices),
5766 [](const auto &P) {
5767 return P.value() % 2 != static_cast<int>(P.index()) % 2;
5768 }))
5769 return std::nullopt;
5770
5771 // Perfect match in the graph, will reuse the previously vectorized
5772 // node. Cost is 0.
5773 std::iota(CurrentOrder.begin(), CurrentOrder.end(), 0);
5774 return CurrentOrder;
5775 }
5776 auto IsSplatMask = [](ArrayRef<int> Mask) {
5777 int SingleElt = PoisonMaskElem;
5778 return all_of(Mask, [&](int I) {
5779 if (SingleElt == PoisonMaskElem && I != PoisonMaskElem)
5780 SingleElt = I;
5781 return I == PoisonMaskElem || I == SingleElt;
5782 });
5783 };
5784 // Exclusive broadcast mask - ignore.
5785 if ((ExtractShuffles.empty() && IsSplatMask(Mask) &&
5786 (Entries.size() != 1 ||
5787 Entries.front().front()->ReorderIndices.empty())) ||
5788 (GatherShuffles.empty() && IsSplatMask(ExtractMask)))
5789 return std::nullopt;
5790 SmallBitVector ShuffledSubMasks(NumParts);
5791 auto TransformMaskToOrder = [&](MutableArrayRef<unsigned> CurrentOrder,
5792 ArrayRef<int> Mask, int PartSz, int NumParts,
5793 function_ref<unsigned(unsigned)> GetVF) {
5794 for (int I : seq<int>(NumParts)) {
5795 if (ShuffledSubMasks.test(I))
5796 continue;
5797 const int VF = GetVF(I);
5798 if (VF == 0)
5799 continue;
5800 unsigned Limit = getNumElems(CurrentOrder.size(), PartSz, I);
5801 MutableArrayRef<unsigned> Slice = CurrentOrder.slice(I * PartSz, Limit);
5802 // Shuffle of at least 2 vectors - ignore.
5803 if (any_of(Slice, not_equal_to(NumScalars))) {
5804 llvm::fill(Slice, NumScalars);
5805 ShuffledSubMasks.set(I);
5806 continue;
5807 }
5808 // Try to include as much elements from the mask as possible.
5809 int FirstMin = INT_MAX;
5810 int SecondVecFound = false;
5811 for (int K : seq<int>(Limit)) {
5812 int Idx = Mask[I * PartSz + K];
5813 if (Idx == PoisonMaskElem) {
5814 Value *V = GatheredScalars[I * PartSz + K];
5815 if (isConstant(V) && !isa<PoisonValue>(V)) {
5816 SecondVecFound = true;
5817 break;
5818 }
5819 continue;
5820 }
5821 if (Idx < VF) {
5822 if (FirstMin > Idx)
5823 FirstMin = Idx;
5824 } else {
5825 SecondVecFound = true;
5826 break;
5827 }
5828 }
5829 FirstMin = (FirstMin / PartSz) * PartSz;
5830 // Shuffle of at least 2 vectors - ignore.
5831 if (SecondVecFound) {
5832 llvm::fill(Slice, NumScalars);
5833 ShuffledSubMasks.set(I);
5834 continue;
5835 }
5836 for (int K : seq<int>(Limit)) {
5837 int Idx = Mask[I * PartSz + K];
5838 if (Idx == PoisonMaskElem)
5839 continue;
5840 Idx -= FirstMin;
5841 if (Idx >= PartSz) {
5842 // Cross-part / second-vector reference: this slice cannot be
5843 // ordered as a single first-vector permutation, give up.
5844 SecondVecFound = true;
5845 break;
5846 }
5847 // For the last partial slice, Limit < PartSz and Idx in [Limit,
5848 // PartSz) addresses the unused padded tail (no scalar at that
5849 // position). Skip the write but keep ordering the remaining K's.
5850 if (static_cast<unsigned>(I * PartSz + Idx) >= CurrentOrder.size())
5851 continue;
5852 if (CurrentOrder[I * PartSz + Idx] >
5853 static_cast<unsigned>(I * PartSz + K) &&
5854 CurrentOrder[I * PartSz + Idx] !=
5855 static_cast<unsigned>(I * PartSz + Idx))
5856 CurrentOrder[I * PartSz + Idx] = I * PartSz + K;
5857 }
5858 // Shuffle of at least 2 vectors - ignore.
5859 if (SecondVecFound) {
5860 llvm::fill(Slice, NumScalars);
5861 ShuffledSubMasks.set(I);
5862 continue;
5863 }
5864 }
5865 };
5866 int PartSz = getPartNumElems(NumScalars, NumParts);
5867 if (!ExtractShuffles.empty())
5868 TransformMaskToOrder(
5869 CurrentOrder, ExtractMask, PartSz, NumParts, [&](unsigned I) {
5870 if (I >= ExtractShuffles.size() || !ExtractShuffles[I])
5871 return 0U;
5872 unsigned VF = 0;
5873 unsigned Sz = getNumElems(TE.getVectorFactor(), PartSz, I);
5874 for (unsigned Idx : seq<unsigned>(Sz)) {
5875 int K = I * PartSz + Idx;
5876 if (static_cast<unsigned>(K) >= ExtractMask.size())
5877 break;
5878 if (ExtractMask[K] == PoisonMaskElem)
5879 continue;
5880 if (!TE.ReuseShuffleIndices.empty())
5881 K = TE.ReuseShuffleIndices[K];
5882 if (K == PoisonMaskElem)
5883 continue;
5884 if (!TE.ReorderIndices.empty())
5885 K = std::distance(TE.ReorderIndices.begin(),
5886 find(TE.ReorderIndices, K));
5887 auto *EI = dyn_cast<ExtractElementInst>(TE.Scalars[K]);
5888 if (!EI)
5889 continue;
5890 VF = std::max(VF, EI->getVectorOperandType()
5891 ->getElementCount()
5892 .getKnownMinValue());
5893 }
5894 return VF;
5895 });
5896 // Check special corner case - single shuffle of the same entry.
5897 if (GatherShuffles.size() == 1 && NumParts != 1) {
5898 if (ShuffledSubMasks.any())
5899 return std::nullopt;
5900 PartSz = NumScalars;
5901 NumParts = 1;
5902 }
5903 if (!Entries.empty())
5904 TransformMaskToOrder(CurrentOrder, Mask, PartSz, NumParts, [&](unsigned I) {
5905 if (I >= GatherShuffles.size() || !GatherShuffles[I])
5906 return 0U;
5907 return std::max(Entries[I].front()->getVectorFactor(),
5908 Entries[I].back()->getVectorFactor());
5909 });
5910 unsigned NumUndefs = count(CurrentOrder, NumScalars);
5911 if (ShuffledSubMasks.all() || (NumScalars > 2 && NumUndefs >= NumScalars / 2))
5912 return std::nullopt;
5913 return std::move(CurrentOrder);
5914}
5915
5916/// Checks if strided loads can be generated out of \p VL loads with pointers \p
5917/// PointerOps:
5918/// 1. Target with strided load support is detected.
5919/// 2. The number of loads is greater than MinProfitableStridedLoads, or the
5920/// potential stride <= MaxProfitableStride and the potential stride is
5921/// power-of-2 (to avoid perf regressions for the very small number of loads)
5922/// and max distance > number of loads, or potential stride is -1.
5923/// 3. The loads are ordered, or number of unordered loads <=
5924/// MaxProfitableUnorderedLoads, or loads are in reversed order. (this check is
5925/// to avoid extra costs for very expensive shuffles).
5926/// 4. Any pointer operand is an instruction with the users outside of the
5927/// current graph (for masked gathers extra extractelement instructions
5928/// might be required).
5930 Align Alignment, const int64_t Diff,
5931 const size_t Sz) const {
5932 if (Diff % (Sz - 1) != 0)
5933 return false;
5934
5935 // Try to generate strided load node.
5936 auto IsAnyPointerUsedOutGraph =
5937 any_of(make_isa_range<Instruction>(PointerOps), [&](Instruction *I) {
5938 return any_of(I->users(), [&](User *U) {
5939 return !isVectorized(U) && !MustGather.contains(U);
5940 });
5941 });
5942
5943 const uint64_t AbsoluteDiff = std::abs(Diff);
5944 auto *VecTy = getWidenedType(ScalarTy, Sz);
5945 if (IsAnyPointerUsedOutGraph ||
5946 (AbsoluteDiff > Sz &&
5947 (Sz > Opts.slp_min_strided_loads ||
5948 (AbsoluteDiff <= Opts.slp_max_stride * Sz && AbsoluteDiff % Sz == 0 &&
5949 has_single_bit(AbsoluteDiff / Sz)))) ||
5950 Diff == -(static_cast<int64_t>(Sz) - 1)) {
5951 int64_t Stride = Diff / static_cast<int64_t>(Sz - 1);
5952 if (Diff != Stride * static_cast<int64_t>(Sz - 1))
5953 return false;
5954 if (!TTI->isLegalStridedLoadStore(VecTy, Alignment))
5955 return false;
5956 return true;
5957 }
5958 return false;
5959}
5960
5961bool BoUpSLP::isWidenedStridedLoad(const TreeEntry *E) const {
5962 if (E->State != TreeEntry::StridedVectorize ||
5963 E->getOpcode() != Instruction::Load)
5964 return false;
5965 const StridedPtrInfo &SPtrInfo = TreeEntryToStridedPtrInfoMap.at(E);
5966 return SPtrInfo.Ty->getNumElements() != E->Scalars.size();
5967}
5968
5970 const ArrayRef<Value *> PointerOps, Type *ScalarTy, Align Alignment,
5971 const SmallVectorImpl<unsigned> &SortedIndices, const int64_t Diff,
5972 Value *Ptr0, StridedPtrInfo &SPtrInfo) const {
5973 const size_t Sz = PointerOps.size();
5974 SmallVector<int64_t> SortedOffsetsFromBase(Sz);
5975 // Go through `PointerOps` in sorted order and record offsets from
5976 // PointerOps[0]. We use PointerOps[0] rather than Ptr0 because
5977 // sortPtrAccesses only validates getPointersDiff for pairs relative to
5978 // PointerOps[0]. This is safe since only offset differences are used below.
5979 for (unsigned I : seq<unsigned>(Sz)) {
5980 Value *Ptr =
5981 SortedIndices.empty() ? PointerOps[I] : PointerOps[SortedIndices[I]];
5982 std::optional<int64_t> Offset =
5983 getPointersDiff(ScalarTy, PointerOps[0], ScalarTy, Ptr, *DL, *SE);
5984 assert(Offset && "sortPtrAccesses should have validated this pointer");
5985 SortedOffsetsFromBase[I] = *Offset;
5986 }
5987
5988 // The code below checks that `SortedOffsetsFromBase` looks as follows:
5989 // ```
5990 // [
5991 // (e_{0, 0}, e_{0, 1}, ..., e_{0, GroupSize - 1}), // first group
5992 // (e_{1, 0}, e_{1, 1}, ..., e_{1, GroupSize - 1}), // secon group
5993 // ...
5994 // (e_{NumGroups - 1, 0}, e_{NumGroups - 1, 1}, ..., e_{NumGroups - 1,
5995 // GroupSize - 1}), // last group
5996 // ]
5997 // ```
5998 // The distance between consecutive elements within each group should all be
5999 // the same `StrideWithinGroup`. The distance between the first elements of
6000 // consecutive groups should all be the same `StrideBetweenGroups`.
6001
6002 int64_t StrideWithinGroup =
6003 SortedOffsetsFromBase[1] - SortedOffsetsFromBase[0];
6004 // Determine size of the first group. Later we will check that all other
6005 // groups have the same size.
6006 auto IsEndOfGroupIndex = [=, &SortedOffsetsFromBase](unsigned Idx) {
6007 return SortedOffsetsFromBase[Idx] - SortedOffsetsFromBase[Idx - 1] !=
6008 StrideWithinGroup;
6009 };
6010 auto Indices = seq<unsigned>(1, Sz);
6011 auto FoundIt = llvm::find_if(Indices, IsEndOfGroupIndex);
6012 unsigned GroupSize = FoundIt != Indices.end() ? *FoundIt : Sz;
6013
6014 unsigned VecSz = Sz;
6015 Type *NewScalarTy = ScalarTy;
6016
6017 // Quick detour: at this point we can say what the type of strided load would
6018 // be if all the checks pass. Check if this type is legal for the target.
6019 bool NeedsWidening = Sz != GroupSize;
6020 const uint64_t UnitBitWidth = DL->getTypeSizeInBits(ScalarTy).getFixedValue();
6021 if (NeedsWidening) {
6022 if (Sz % GroupSize != 0)
6023 return false;
6024
6025 if (StrideWithinGroup != 1)
6026 return false;
6027 VecSz = Sz / GroupSize;
6028 NewScalarTy = Type::getIntNTy(SE->getContext(), UnitBitWidth * GroupSize);
6029 } else if (ScalarTy->isVectorTy()) {
6030 NewScalarTy = Type::getIntNTy(SE->getContext(), UnitBitWidth);
6031 }
6032
6033 if (!isStridedLoad(PointerOps, NewScalarTy, Alignment, Diff, VecSz))
6034 return false;
6035
6036 int64_t StrideIntVal = StrideWithinGroup;
6037 if (NeedsWidening) {
6038 // Continue with checking the "shape" of `SortedOffsetsFromBase`.
6039 // Check that the strides between groups are all the same.
6040 unsigned CurrentGroupStartIdx = GroupSize;
6041 int64_t StrideBetweenGroups =
6042 SortedOffsetsFromBase[GroupSize] - SortedOffsetsFromBase[0];
6043 StrideIntVal = StrideBetweenGroups;
6044 for (; CurrentGroupStartIdx < Sz; CurrentGroupStartIdx += GroupSize) {
6045 if (SortedOffsetsFromBase[CurrentGroupStartIdx] -
6046 SortedOffsetsFromBase[CurrentGroupStartIdx - GroupSize] !=
6047 StrideBetweenGroups)
6048 return false;
6049 }
6050
6051 auto CheckGroup = [=](const unsigned StartIdx) -> bool {
6052 auto Indices = seq<unsigned>(StartIdx + 1, Sz);
6053 auto FoundIt = llvm::find_if(Indices, IsEndOfGroupIndex);
6054 unsigned GroupEndIdx = FoundIt != Indices.end() ? *FoundIt : Sz;
6055 return GroupEndIdx - StartIdx == GroupSize;
6056 };
6057 for (unsigned I = 0; I < Sz; I += GroupSize) {
6058 if (!CheckGroup(I))
6059 return false;
6060 }
6061 }
6062
6063 Type *StrideTy = DL->getIndexType(Ptr0->getType());
6064 SPtrInfo.StrideVal =
6065 ConstantInt::getSigned(StrideTy, StrideIntVal, /*ImplicitTrunc=*/true);
6066 SPtrInfo.Ty = cast<FixedVectorType>(getWidenedType(NewScalarTy, VecSz));
6067 return true;
6068}
6069
6071 Type *BaseTy, Align CommonAlignment,
6072 SmallVectorImpl<unsigned> &SortedIndices,
6073 StridedPtrInfo &SPtrInfo,
6074 bool IsLoad) const {
6075 const unsigned Sz = PointerOps.size();
6076 const unsigned MinProfitableStridedOps =
6077 IsLoad ? Opts.slp_min_strided_loads : Opts.slp_min_strided_stores;
6078 if (Sz * getNumElements(BaseTy) < MinProfitableStridedOps)
6079 return false;
6080
6081 // The element type of the strided access is fixed by the number of distinct
6082 // constant offsets the pointers fall into, which has to divide their number.
6083 auto GetStridedTy = [&](unsigned NumOffsets) -> FixedVectorType * {
6084 Type *NewScalarTy = BaseTy;
6085 if (NumOffsets > 1 || BaseTy->isVectorTy())
6086 NewScalarTy = Type::getIntNTy(
6087 SE->getContext(),
6088 DL->getTypeSizeInBits(BaseTy).getFixedValue() * NumOffsets);
6090 getWidenedType(NewScalarTy, Sz / NumOffsets));
6091 };
6092 auto IsLegalStridedTy = [&](FixedVectorType *StridedTy) {
6093 return StridedTy && TTI->isTypeLegal(StridedTy) &&
6094 TTI->isLegalStridedLoadStore(StridedTy, CommonAlignment);
6095 };
6096 // Determining the offsets below builds SCEVs for every pointer, which is
6097 // expensive. Bail out if the target does not support any strided accesses at
6098 // all.
6099 if (none_of(seq<unsigned>(1, Sz), [&](unsigned NumOffsets) {
6100 return Sz % NumOffsets == 0 &&
6101 IsLegalStridedTy(GetStridedTy(NumOffsets));
6102 }))
6103 return false;
6104
6105 // If each value in `PointerOps` is of the form `%x + Offset` where `Offset`
6106 // is constant, we partition `PointerOps` sequence into subsequences of
6107 // pointers with the same offset. For each offset we record values from
6108 // `PointerOps` and their indicies in `PointerOps`.
6110 OffsetToPointerOpIdxMap;
6111 // Track to make sure that only VecSz different stride multiples are consumed
6112 // Prevents cases such as:
6113 // 1, x + 0, x + 1, 2x + 0 from being recognized as legal RT strided as there
6114 // are 2 "0" and 2 "1" offsets and a stride of "x" between both offsets
6115 SmallDenseSet<const SCEV *> StrideMultiples;
6116 for (auto [Idx, Ptr] : enumerate(PointerOps)) {
6117 const SCEV *PtrSCEV = SE->getSCEV(Ptr);
6118 if (!PtrSCEV)
6119 return false;
6120
6121 const auto *Add = dyn_cast<SCEVAddExpr>(PtrSCEV);
6122 int64_t Offset = 0;
6123 const SCEV *StrideMultiple = PtrSCEV;
6124 if (Add) {
6125 // `Offset` is non-zero.
6126 for (int I : seq<int>(Add->getNumOperands())) {
6127 const auto *SC = dyn_cast<SCEVConstant>(Add->getOperand(I));
6128 if (!SC)
6129 continue;
6130 Offset = SC->getAPInt().getSExtValue();
6131 if (Offset >= std::numeric_limits<int64_t>::max() - 1) {
6132 Offset = 0;
6133 continue;
6134 }
6135 StrideMultiple = SE->getMinusSCEV(StrideMultiple, SC);
6136 break;
6137 }
6138 }
6139 OffsetToPointerOpIdxMap[Offset].first.push_back(Ptr);
6140 OffsetToPointerOpIdxMap[Offset].second.push_back(Idx);
6141 StrideMultiples.insert(StrideMultiple);
6142 }
6143 unsigned NumOffsets = OffsetToPointerOpIdxMap.size();
6144
6145 // Quick detour: at this point we can say what the type of strided load would
6146 // be if all the checks pass. Check if this type is legal for the target.
6147 unsigned VecSz = Sz;
6148 if (NumOffsets > 1) {
6149 if (Sz % NumOffsets != 0)
6150 return false;
6151 VecSz = Sz / NumOffsets;
6152 }
6153
6154 if (StrideMultiples.size() != VecSz)
6155 return false;
6156
6157 auto *StridedLoadTy = GetStridedTy(NumOffsets);
6158 if (!IsLegalStridedTy(StridedLoadTy))
6159 return false;
6160
6161 // Check if the offsets are contiguous and that each group has the required
6162 // size.
6163 SmallVector<int64_t> SortedOffsetsV(NumOffsets);
6164 for (auto [Idx, MapPair] : enumerate(OffsetToPointerOpIdxMap)) {
6165 if (MapPair.second.first.size() != VecSz)
6166 return false;
6167 SortedOffsetsV[Idx] = MapPair.first;
6168 }
6169 sort(SortedOffsetsV);
6170
6171 if (NumOffsets > 1) {
6172 int64_t BaseBytes = DL->getTypeStoreSize(BaseTy);
6173 for (int I : seq<int>(1, SortedOffsetsV.size())) {
6174 if (SortedOffsetsV[I] - SortedOffsetsV[I - 1] != BaseBytes)
6175 return false;
6176 }
6177 }
6178
6179 // Introduce some notation for the explanations below. Let `PointerOps_j`
6180 // denote the subsequence of `PointerOps` with offsets equal to
6181 // `SortedOffsetsV[j]`. Let `SortedIndices_j` be a such that the sequence
6182 // ```
6183 // PointerOps_j[SortedIndices_j[0]],
6184 // PointerOps_j[SortedIndices_j[1]],
6185 // PointerOps_j[SortedIndices_j[2]],
6186 // ...
6187 // ```
6188 // is sorted. Also, let `IndicesInAllPointerOps_j` be the vector
6189 // of indices of the subsequence `PointerOps_j` in all of `PointerOps`,
6190 // i.e `PointerOps_j[i] = PointerOps[IndicesInAllPointerOps_j[i]]`.
6191 // The entire sorted `PointerOps` looks like this:
6192 // ```
6193 // PointerOps_0[SortedIndices_0[0]] = PointerOps[IndicesInAllPointerOps_0[0]],
6194 // PointerOps_1[SortedIndices_1[0]] = PointerOps[IndicesInAllPointerOps_1[0]],
6195 // PointerOps_2[SortedIndices_2[0]] = PointerOps[IndicesInAllPointerOps_2[0]],
6196 // ...
6197 // PointerOps_(NumOffsets - 1)[SortedIndices_(NumOffsets - 1)[0]] =
6198 // PointerOps[IndicesInAllPointerOps_(NumOffsets - 1)[0]],
6199 //
6200 // PointerOps_0[SortedIndices_0[1]] = PointerOps[IndicesInAllPointerOps_0[1]],
6201 // PointerOps_1[SortedIndices_1[1]] = PointerOps[IndicesInAllPointerOps_1[1]],
6202 // PointerOps_2[SortedIndices_2[1]] = PointerOps[IndicesInAllPointerOps_2[1]],
6203 // ...
6204 // PointerOps_(NumOffsets - 1)[SortedIndices_(NumOffsets - 1)[1]] =
6205 // PointerOps[IndicesInAllPointerOps_(NumOffsets - 1)[1]],
6206 //
6207 // PointerOps_0[SortedIndices_0[2]] = PointerOps[IndicesInAllPointerOps_0[2]],
6208 // PointerOps_1[SortedIndices_1[2]] = PointerOps[IndicesInAllPointerOps_1[2]],
6209 // PointerOps_2[SortedIndices_2[2]] = PointerOps[IndicesInAllPointerOps_2[2]],
6210 // ...
6211 // PointerOps_(NumOffsets - 1)[SortedIndices_(NumOffsets - 1)[2]] =
6212 // PointerOps[IndicesInAllPointerOps_(NumOffsets - 1)[2]],
6213 // ...
6214 // ...
6215 // ...
6216 // PointerOps_0[SortedIndices_0[VecSz - 1]] =
6217 // PointerOps[IndicesInAllPointerOps_0[VecSz - 1]],
6218 // PointerOps_1[SortedIndices_1[VecSz - 1]] =
6219 // PointerOps[IndicesInAllPointerOps_1[VecSz - 1]],
6220 // PointerOps_2[SortedIndices_2[VecSz - 1]] =
6221 // PointerOps[IndicesInAllPointerOps_2[VecSz - 1]],
6222 // ...
6223 // PointerOps_(NumOffsets - 1)[SortedIndices_(NumOffsets - 1)[VecSz - 1]] =
6224 // PointerOps[IndicesInAllPointerOps_(NumOffsets - 1)[VecSz - 1]],
6225 // ```
6226 // In order to be able to generate a strided load, for each `PointerOps_j`
6227 // check that the distance between adjacent pointers are all equal to the same
6228 // value (stride).
6229 //
6230 // As we do that, also calculate SortedIndices. Since we should not modify
6231 // `SortedIndices` unless we know that all the checks succeed, record the
6232 // indicies into `SortedIndicesDraft`.
6233 SmallVector<unsigned> SortedIndicesDraft(Sz);
6234
6235 // Given sorted indices for a particular offset (as calculated by
6236 // calculateRtStride), update the `SortedIndicesDraft` for all of PointerOps.
6237 // Let `Offset` be `SortedOffsetsV[OffsetNum]`.
6238 // \param `OffsetNum` the index of `Offset` in `SortedOffsetsV`.
6239 // \param `IndicesInAllPointerOps` vector of indices of the
6240 // subsequence `PointerOps_OffsetNum` in `PointerOps`, i.e. using the above
6241 // notation `IndicesInAllPointerOps = IndicesInAllPointerOps_OffsetNum`.
6242 // \param `SortedIndicesForOffset = SortedIndices_OffsetNum`
6243 auto UpdateSortedIndices =
6244 [&](SmallVectorImpl<unsigned> &SortedIndicesForOffset,
6245 ArrayRef<unsigned> IndicesInAllPointerOps, const int64_t OffsetNum) {
6246 if (SortedIndicesForOffset.empty()) {
6247 SortedIndicesForOffset.resize(IndicesInAllPointerOps.size());
6248 std::iota(SortedIndicesForOffset.begin(),
6249 SortedIndicesForOffset.end(), 0);
6250 }
6251 for (const auto [Num, Idx] : enumerate(SortedIndicesForOffset)) {
6252 SortedIndicesDraft[Num * NumOffsets + OffsetNum] =
6253 IndicesInAllPointerOps[Idx];
6254 }
6255 };
6256
6257 int64_t LowestOffset = SortedOffsetsV[0];
6258 ArrayRef<Value *> PointerOps0 = OffsetToPointerOpIdxMap[LowestOffset].first;
6259
6260 SmallVector<unsigned> SortedIndicesForOffset0;
6261 const SCEV *Stride0 =
6262 calculateRtStride(PointerOps0, BaseTy, *DL, *SE, SortedIndicesForOffset0);
6263 if (!Stride0)
6264 return false;
6265
6266 ArrayRef<unsigned> IndicesInAllPointerOps0 =
6267 OffsetToPointerOpIdxMap[LowestOffset].second;
6268 UpdateSortedIndices(SortedIndicesForOffset0, IndicesInAllPointerOps0, 0);
6269
6270 // Now that we know what the common stride and coefficients has to be check
6271 // the remaining `PointerOps_j`.
6272 SmallVector<unsigned> SortedIndicesForOffset;
6273 for (int J : seq<int>(1, NumOffsets)) {
6274 SortedIndicesForOffset.clear();
6275
6276 int64_t Offset = SortedOffsetsV[J];
6277 ArrayRef<Value *> PointerOpsForOffset =
6278 OffsetToPointerOpIdxMap[Offset].first;
6279 ArrayRef<unsigned> IndicesInAllPointerOps =
6280 OffsetToPointerOpIdxMap[Offset].second;
6281 const SCEV *StrideWithinGroup = calculateRtStride(
6282 PointerOpsForOffset, BaseTy, *DL, *SE, SortedIndicesForOffset);
6283
6284 if (!StrideWithinGroup || StrideWithinGroup != Stride0)
6285 return false;
6286
6287 UpdateSortedIndices(SortedIndicesForOffset, IndicesInAllPointerOps, J);
6288 }
6289
6290 SortedIndices.clear();
6291 SortedIndices = std::move(SortedIndicesDraft);
6292 SPtrInfo.StrideSCEV = Stride0;
6293 SPtrInfo.Ty = StridedLoadTy;
6294 return true;
6295}
6296
6298 ArrayRef<Value *> VL, const Value *VL0, SmallVectorImpl<unsigned> &Order,
6299 SmallVectorImpl<Value *> &PointerOps, StridedPtrInfo &SPtrInfo,
6300 unsigned *BestVF, bool TryRecursiveCheck) const {
6301 // Check that a vectorized load would load the same memory as a scalar
6302 // load. For example, we don't want to vectorize loads that are smaller
6303 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
6304 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
6305 // from such a struct, we read/write packed bits disagreeing with the
6306 // unvectorized version.
6307 if (BestVF)
6308 *BestVF = 0;
6310 return LoadsState::Gather;
6311 Type *ScalarTy = VL0->getType();
6312
6313 if (DL->getTypeSizeInBits(ScalarTy) != DL->getTypeAllocSizeInBits(ScalarTy))
6314 return LoadsState::Gather;
6315
6316 // The undef and poison lanes are covered by a single wide load of the
6317 // consecutive loads.
6318 if (any_of(VL, IsaPred<UndefValue>))
6319 return canWidenLoadsOverUndefLanes(VL, *DL, *SE, *AC, *DT, *TLI)
6322
6323 // Make sure all loads in the bundle are simple - we can't vectorize
6324 // atomic or volatile loads.
6325 PointerOps.clear();
6326 const size_t Sz = VL.size();
6327 PointerOps.resize(Sz);
6328 auto *POIter = PointerOps.begin();
6329 for (Value *V : VL) {
6330 auto *L = dyn_cast<LoadInst>(V);
6331 if (!L || !L->isSimple())
6332 return LoadsState::Gather;
6333 *POIter = L->getPointerOperand();
6334 ++POIter;
6335 }
6336
6337 Order.clear();
6338 // Check the order of pointer operands or that all pointers are the same.
6339 bool IsSorted = Cache.sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, Order);
6340
6341 auto *VecTy = dyn_cast<VectorType>(getWidenedType(ScalarTy, Sz));
6342 if (!VecTy)
6343 return LoadsState::Gather;
6344 Align CommonAlignment = computeCommonAlignment<LoadInst>(VL);
6345 // Cache masked gather legality - both the !IsSorted path below and the
6346 // post-branch check use the same VecTy/CommonAlignment, and the underlying
6347 // TTI calls are virtual.
6348 std::optional<bool> MaskedGatherLegal;
6349 auto IsMaskedGatherLegal = [&, TTI = TTI] {
6350 if (!MaskedGatherLegal)
6351 MaskedGatherLegal =
6352 TTI->isLegalMaskedGather(VecTy, CommonAlignment) &&
6353 !TTI->forceScalarizeMaskedGather(VecTy, CommonAlignment);
6354 return *MaskedGatherLegal;
6355 };
6356 if (!IsSorted) {
6357 // Check for a group of loads, each selecting its address (directly, or
6358 // via a constant-offset GEP) between the same two candidate base
6359 // pointers - the shape if-converted, fully-unrolled loop bodies of the
6360 // form `x = cond ? A[i] : B[i]` take. If found, model it as two masked
6361 // loads (one per candidate) blended by the (vectorized) condition,
6362 // rather than falling back to a gather of the individual scalar loads.
6363 Value *TrueBase = nullptr;
6364 Value *FalseBase = nullptr;
6365 SmallVector<Value *> Conditions;
6366 if (isSelectedBaseLoad(ScalarTy, PointerOps, *DL, TrueBase, FalseBase,
6367 Conditions) &&
6368 TTI->isLegalMaskedLoad(VecTy, computeBlendedLoadBaseAlignment(VL, *DL),
6371
6372 if (analyzeRtStrideCandidate(PointerOps, ScalarTy, CommonAlignment, Order,
6373 SPtrInfo, /*isLoad=*/true))
6375
6376 if (!IsMaskedGatherLegal())
6377 return LoadsState::Gather;
6378
6379 // The gather address vector requires pointers of the same type.
6380 Value *FrontPtr = PointerOps.front();
6381 Type *PtrTy = FrontPtr->getType();
6382 if (!all_of(PointerOps,
6383 [&](Value *P) {
6384 return P->getType() == PtrTy &&
6385 arePointersCompatible(P, FrontPtr, *TLI,
6386 Opts.slp_recursion_max_depth);
6387 }) &&
6388 !isCopyableGEPAddressVector(PointerOps))
6389 return LoadsState::Gather;
6390
6391 } else {
6392 Value *Ptr0;
6393 Value *PtrN;
6394 if (Order.empty()) {
6395 Ptr0 = PointerOps.front();
6396 PtrN = PointerOps.back();
6397 } else {
6398 Ptr0 = PointerOps[Order.front()];
6399 PtrN = PointerOps[Order.back()];
6400 }
6401 // sortPtrAccesses validates getPointersDiff for all pointers relative to
6402 // PointerOps[0], so compute the span using PointerOps[0] as intermediate:
6403 // Diff = offset(PtrN) - offset(Ptr0) relative to PointerOps[0]
6404 std::optional<int64_t> Diff0 =
6405 getPointersDiff(ScalarTy, PointerOps[0], ScalarTy, Ptr0, *DL, *SE);
6406 std::optional<int64_t> DiffN =
6407 getPointersDiff(ScalarTy, PointerOps[0], ScalarTy, PtrN, *DL, *SE);
6408 assert(Diff0 && DiffN &&
6409 "sortPtrAccesses should have validated these pointers");
6410 int64_t Diff = *DiffN - *Diff0;
6411 // Check that the sorted loads are consecutive.
6412 if (static_cast<uint64_t>(Diff) == Sz - 1)
6413 return LoadsState::Vectorize;
6415 VL, PointerOps, Order, *TTI, *DL, *SE, *AC, *DT, *TLI, CostKind,
6416 [&](Value *V) {
6417 return areAllUsersVectorized(cast<Instruction>(V),
6418 UserIgnoreList);
6419 },
6420 Opts.slp_revec, Cache))
6422 // Widened strided loads must be legal for every group, not just the first
6423 // pointer, which may have a stronger alignment than the remaining loads.
6424 if (analyzeConstantStrideCandidate(PointerOps, ScalarTy, CommonAlignment,
6425 Order, Diff, Ptr0, SPtrInfo))
6427 }
6428 if (!IsMaskedGatherLegal())
6429 return LoadsState::Gather;
6430 // Correctly identify compare the cost of loads + shuffles rather than
6431 // strided/masked gather loads. Returns true if vectorized + shuffles
6432 // representation is better than just gather.
6433 auto CheckForShuffledLoads = [&, &TTI = *TTI](Align CommonAlignment,
6434 unsigned *BestVF,
6435 bool ProfitableGatherPointers) {
6436 if (BestVF)
6437 *BestVF = 0;
6438 // Compare masked gather cost and loads + insert subvector costs.
6439 auto [ScalarGEPCost, VectorGEPCost] =
6440 getGEPCosts(TTI, PointerOps, PointerOps.front(), Instruction::Load,
6441 CostKind, ScalarTy, VecTy);
6442 // Estimate the cost of masked gather GEP. If not a splat, roughly
6443 // estimate as a buildvector, otherwise estimate as splat.
6444 APInt DemandedElts = APInt::getAllOnes(Sz);
6445 Type *PtrScalarTy = PointerOps.front()->getType()->getScalarType();
6446 auto *PtrVecTy = cast<VectorType>(getWidenedType(PtrScalarTy, Sz));
6447 // Cache the underlying object of PointerOps.front() - it is invariant
6448 // across the per-V comparisons below and getUnderlyingObject walks
6449 // GEP/cast chains.
6450 const Value *FrontUO = getUnderlyingObject(PointerOps.front());
6451 // The pointers are built as a vector, not as a splat plus GEP, if they are
6452 // not GEPs of the same base. The same for all the slices below.
6453 const bool IsPtrsBuildVector =
6454 static_cast<unsigned>(count_if(
6455 PointerOps, IsaPred<GetElementPtrInst>)) < PointerOps.size() - 1 ||
6456 any_of(
6457 PointerOps,
6458 [&](Value *V) { return getUnderlyingObject(V) != FrontUO; });
6459 if (IsPtrsBuildVector)
6460 VectorGEPCost +=
6461 getScalarizationOverhead(TTI, Opts.slp_revec, PtrScalarTy, PtrVecTy,
6462 DemandedElts, /*Insert=*/true,
6463 /*Extract=*/false, CostKind);
6464 else
6465 VectorGEPCost +=
6466 getScalarizationOverhead(TTI, Opts.slp_revec, PtrScalarTy, PtrVecTy,
6467 APInt::getOneBitSet(Sz, 0),
6468 /*Insert=*/true, /*Extract=*/false,
6469 CostKind) +
6470 getShuffleCost(TTI, TTI::SK_Broadcast, PtrVecTy, CostKind);
6471 // The cost of scalar loads.
6472 InstructionCost ScalarLoadsCost =
6474 [&](InstructionCost C, Value *V) {
6475 return C + TTI.getInstructionCost(cast<Instruction>(V),
6476 CostKind);
6477 }) +
6478 ScalarGEPCost;
6479 // The cost of masked gather.
6480 InstructionCost MaskedGatherCost =
6481 TTI.getMemIntrinsicInstrCost(
6482 MemIntrinsicCostAttributes(Intrinsic::masked_gather, VecTy,
6484 /*VariableMask=*/false, CommonAlignment),
6485 CostKind) +
6486 (ProfitableGatherPointers ? 0 : VectorGEPCost);
6487 InstructionCost GatherCost =
6488 getScalarizationOverhead(TTI, Opts.slp_revec, ScalarTy, VecTy,
6489 DemandedElts,
6490 /*Insert=*/true,
6491 /*Extract=*/false, CostKind) +
6492 ScalarLoadsCost;
6493 // The list of loads is small or perform partial check already - directly
6494 // compare masked gather cost and gather cost.
6495 constexpr unsigned ListLimit = 4;
6496 if (!TryRecursiveCheck || VL.size() < ListLimit)
6497 return MaskedGatherCost - GatherCost >= -getCostThreshold();
6498
6499 unsigned Sz = DL->getTypeSizeInBits(ScalarTy);
6500 unsigned MinVF = getMinVF(2 * Sz);
6501 DemandedElts.clearAllBits();
6502 // Iterate through possible vectorization factors and check if vectorized +
6503 // shuffles is better than just gather.
6504 for (unsigned VF = getFloorFullVectorNumberOfElements(
6505 TTI, ScalarTy, VL.size() - 1, Opts.slp_revec);
6506 VF >= MinVF; VF = getFloorFullVectorNumberOfElements(
6507 TTI, ScalarTy, VF - 1, Opts.slp_revec)) {
6509 for (unsigned Cnt = 0, End = VL.size(); Cnt < End; Cnt += VF) {
6510 const unsigned SliceVF = std::min(VF, End - Cnt);
6511 ArrayRef<Value *> Slice = VL.slice(Cnt, SliceVF);
6513 SmallVector<Value *> PointerOps;
6514 LoadsState LS = canVectorizeLoads(Slice, Slice.front(), Order,
6515 PointerOps, SPtrInfo, BestVF,
6516 /*TryRecursiveCheck=*/false);
6517 // Check that the sorted loads are consecutive.
6518 if (LS == LoadsState::Gather) {
6519 if (BestVF) {
6520 DemandedElts.setAllBits();
6521 break;
6522 }
6523 DemandedElts.setBits(Cnt, Cnt + SliceVF);
6524 continue;
6525 }
6526 // If need the reorder - consider as high-cost masked gather for now.
6527 if ((LS == LoadsState::Vectorize ||
6530 !Order.empty() && !isReverseOrder(Order))
6532 States.emplace_back(Cnt, LS);
6533 }
6534 if (DemandedElts.isAllOnes())
6535 // All loads gathered - try smaller VF.
6536 continue;
6537 // Can be vectorized later as a serie of loads/insertelements.
6538 InstructionCost VecLdCost = 0;
6539 if (!DemandedElts.isZero()) {
6540 VecLdCost = getScalarizationOverhead(TTI, Opts.slp_revec, ScalarTy,
6541 VecTy, DemandedElts,
6542 /*Insert=*/true,
6543 /*Extract=*/false, CostKind) +
6544 ScalarGEPCost;
6545 for (unsigned Idx : seq<unsigned>(VL.size()))
6546 if (DemandedElts[Idx])
6547 VecLdCost +=
6548 TTI.getInstructionCost(cast<Instruction>(VL[Idx]), CostKind);
6549 }
6550 for (const auto &[SliceStart, LS] : States) {
6551 const unsigned SliceVF = std::min<unsigned>(VF, VL.size() - SliceStart);
6552 auto *SubVecTy = cast<VectorType>(getWidenedType(ScalarTy, SliceVF));
6553 auto *LI0 = cast<LoadInst>(VL[SliceStart]);
6554 InstructionCost VectorGEPCost =
6555 (LS == LoadsState::ScatterVectorize && ProfitableGatherPointers)
6556 ? 0
6557 : getGEPCosts(TTI,
6558 ArrayRef(PointerOps).slice(SliceStart, SliceVF),
6559 LI0->getPointerOperand(), Instruction::Load,
6560 CostKind, ScalarTy, SubVecTy)
6561 .second;
6562 if (LS == LoadsState::ScatterVectorize) {
6563 if (IsPtrsBuildVector)
6564 VectorGEPCost += getScalarizationOverhead(
6565 TTI, Opts.slp_revec, ScalarTy, SubVecTy,
6566 APInt::getAllOnes(SliceVF),
6567 /*Insert=*/true, /*Extract=*/false, CostKind);
6568 else
6569 VectorGEPCost +=
6571 TTI, Opts.slp_revec, ScalarTy, SubVecTy,
6572 APInt::getOneBitSet(SliceVF, 0),
6573 /*Insert=*/true, /*Extract=*/false, CostKind) +
6574 getShuffleCost(TTI, TTI::SK_Broadcast, SubVecTy, CostKind);
6575 }
6576 switch (LS) {
6578 VecLdCost += TTI.getMemoryOpCost(
6579 Instruction::Load, SubVecTy, LI0->getAlign(),
6580 LI0->getPointerAddressSpace(), CostKind,
6581 TTI::getOperandInfo(LI0->getPointerOperand())) +
6582 VectorGEPCost;
6583 break;
6585 VecLdCost += TTI.getMemIntrinsicInstrCost(
6587 Intrinsic::experimental_vp_strided_load,
6588 SubVecTy, LI0->getPointerOperand(),
6589 /*VariableMask=*/false, CommonAlignment),
6590 CostKind) +
6591 VectorGEPCost;
6592 break;
6594 VecLdCost +=
6595 TTI.getMemIntrinsicInstrCost(
6596 MemIntrinsicCostAttributes(Intrinsic::masked_load, SubVecTy,
6597 CommonAlignment,
6598 LI0->getPointerAddressSpace()),
6599 CostKind) +
6601 break;
6603 VecLdCost += TTI.getMemIntrinsicInstrCost(
6605 Intrinsic::masked_gather, SubVecTy,
6606 LI0->getPointerOperand(),
6607 /*VariableMask=*/false, CommonAlignment),
6608 CostKind) +
6609 VectorGEPCost;
6610 break;
6612 // Two masked loads (one per candidate base) plus a select; no address
6613 // vector is materialized, so VectorGEPCost is skipped.
6614 VecLdCost +=
6617 VL.slice(SliceStart, SliceVF), *DL),
6618 LI0->getPointerAddressSpace(), CostKind);
6619 break;
6620 case LoadsState::Gather:
6621 llvm_unreachable("Gathers are not added to States");
6622 }
6623 SmallVector<int> ShuffleMask(VL.size());
6624 const unsigned SliceIdx = SliceStart / VF;
6625 for (int Idx : seq<int>(VL.size()))
6626 ShuffleMask[Idx] = Idx / VF == SliceIdx ? VL.size() + Idx % VF : Idx;
6627 if (SliceStart > 0)
6628 VecLdCost +=
6629 getShuffleCost(TTI, TTI::SK_InsertSubvector, VecTy, CostKind,
6630 ShuffleMask, SliceStart, SubVecTy);
6631 }
6632 // If masked gather cost is higher - better to vectorize, so
6633 // consider it as a gather node. It will be better estimated
6634 // later.
6635 if (MaskedGatherCost >= VecLdCost &&
6636 VecLdCost - GatherCost < -getCostThreshold()) {
6637 if (BestVF)
6638 *BestVF = VF;
6639 return true;
6640 }
6641 }
6642 return MaskedGatherCost - GatherCost >= -getCostThreshold();
6643 };
6644 // TODO: need to improve analysis of the pointers, if not all of them are
6645 // GEPs or have > 2 operands, we end up with a gather node, which just
6646 // increases the cost.
6647 Loop *L = LI->getLoopFor(cast<LoadInst>(VL0)->getParent());
6648 bool ProfitableGatherPointers =
6649 L && Sz > 2 && static_cast<unsigned>(count_if(PointerOps, [L](Value *V) {
6650 return L->isLoopInvariant(V);
6651 })) <= Sz / 2;
6652 if (ProfitableGatherPointers || all_of(PointerOps, [](Value *P) {
6654 return (!GEP && doesNotNeedToBeScheduled(P)) ||
6655 (GEP && GEP->getNumOperands() == 2 &&
6656 isa<Constant, Instruction>(GEP->getOperand(1)));
6657 })) {
6658 // Check if potential masked gather can be represented as series
6659 // of loads + insertsubvectors.
6660 // If masked gather cost is higher - better to vectorize, so
6661 // consider it as a gather node. It will be better estimated
6662 // later.
6663 if (!TryRecursiveCheck || !CheckForShuffledLoads(CommonAlignment, BestVF,
6664 ProfitableGatherPointers))
6666 }
6667
6668 return LoadsState::Gather;
6669}
6670
6671std::optional<BoUpSLP::OrdersType>
6672BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
6673 assert(TE.isGather() && "Expected gather node only.");
6674 Type *ScalarTy = TE.Scalars[0]->getType();
6675
6677 Ptrs.reserve(TE.Scalars.size());
6679 BBs.reserve(TE.Scalars.size());
6680 for (Value *V : TE.Scalars) {
6681 auto *L = dyn_cast<LoadInst>(V);
6682 if (!L || !L->isSimple())
6683 return std::nullopt;
6684 Ptrs.push_back(L->getPointerOperand());
6685 BBs.push_back(L->getParent());
6686 }
6687
6688 BoUpSLP::OrdersType Order;
6689 if (!LoadEntriesToVectorize.contains(TE.Idx) &&
6690 clusterSortPtrAccesses(Ptrs, BBs, ScalarTy, *DL, *SE,
6691 Opts.slp_recursion_max_depth, Order, Cache))
6692 return std::move(Order);
6693 return std::nullopt;
6694}
6695
6696std::optional<BoUpSLP::OrdersType>
6697BoUpSLP::getReorderingData(const TreeEntry &TE, bool TopToBottom,
6698 bool IgnoreReorder) {
6699 // No need to reorder if need to shuffle reuses, still need to shuffle the
6700 // node.
6701 if (!TE.ReuseShuffleIndices.empty()) {
6702 if (isSplat(TE.Scalars))
6703 return std::nullopt;
6704 // Check if reuse shuffle indices can be improved by reordering.
6705 // For this, check that reuse mask is "clustered", i.e. each scalar values
6706 // is used once in each submask of size <number_of_scalars>.
6707 // Example: 4 scalar values.
6708 // ReuseShuffleIndices mask: 0, 1, 2, 3, 3, 2, 0, 1 - clustered.
6709 // 0, 1, 2, 3, 3, 3, 1, 0 - not clustered, because
6710 // element 3 is used twice in the second submask.
6711 unsigned Sz = TE.Scalars.size();
6712 if (TE.isGather()) {
6713 if (std::optional<OrdersType> CurrentOrder =
6714 findReusedOrderedScalars(TE, TopToBottom, IgnoreReorder)) {
6715 SmallVector<int> Mask;
6716 fixupOrderingIndices(*CurrentOrder);
6717 inversePermutation(*CurrentOrder, Mask);
6718 addMask(Mask, TE.ReuseShuffleIndices);
6719 OrdersType Res(TE.getVectorFactor(), TE.getVectorFactor());
6720 unsigned Sz = TE.Scalars.size();
6721 for (int K = 0, E = TE.getVectorFactor() / Sz; K < E; ++K) {
6722 for (auto [I, Idx] : enumerate(ArrayRef(Mask).slice(K * Sz, Sz)))
6723 if (Idx != PoisonMaskElem)
6724 Res[Idx + K * Sz] = I + K * Sz;
6725 }
6726 return std::move(Res);
6727 }
6728 }
6729 if (Sz == 2 && TE.getVectorFactor() == 4 &&
6731 getWidenedType(getValueType(TE.Scalars.front(), Opts.slp_revec),
6732 2 * TE.getVectorFactor()),
6733 getValueType(TE.Scalars.front(), Opts.slp_revec)) == 1)
6734 return std::nullopt;
6735 if (TE.ReuseShuffleIndices.size() % Sz != 0)
6736 return std::nullopt;
6737 if (!ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
6738 Sz)) {
6739 SmallVector<int> ReorderMask(Sz, PoisonMaskElem);
6740 if (TE.ReorderIndices.empty())
6741 std::iota(ReorderMask.begin(), ReorderMask.end(), 0);
6742 else
6743 inversePermutation(TE.ReorderIndices, ReorderMask);
6744 addMask(ReorderMask, TE.ReuseShuffleIndices);
6745 unsigned VF = ReorderMask.size();
6746 OrdersType ResOrder(VF, VF);
6747 unsigned NumParts = divideCeil(VF, Sz);
6748 SmallBitVector UsedVals(NumParts);
6749 for (unsigned I = 0; I < VF; I += Sz) {
6750 int Val = PoisonMaskElem;
6751 unsigned UndefCnt = 0;
6752 unsigned Limit = std::min(Sz, VF - I);
6753 if (any_of(ArrayRef(ReorderMask).slice(I, Limit),
6754 [&](int Idx) {
6755 if (Val == PoisonMaskElem && Idx != PoisonMaskElem)
6756 Val = Idx;
6757 if (Idx == PoisonMaskElem)
6758 ++UndefCnt;
6759 return Idx != PoisonMaskElem && Idx != Val;
6760 }) ||
6761 Val >= static_cast<int>(NumParts) || Val == PoisonMaskElem ||
6762 UsedVals.test(Val) || UndefCnt > Sz / 2)
6763 return std::nullopt;
6764 UsedVals.set(Val);
6765 for (unsigned K = 0; K < NumParts; ++K) {
6766 unsigned Idx = Val + Sz * K;
6767 if (Idx < VF && I + K < VF)
6768 ResOrder[Idx] = I + K;
6769 }
6770 }
6771 return std::move(ResOrder);
6772 }
6773 unsigned VF = TE.getVectorFactor();
6774 // Try build correct order for extractelement instructions.
6775 SmallVector<int> ReusedMask(TE.ReuseShuffleIndices.begin(),
6776 TE.ReuseShuffleIndices.end());
6777 if (TE.hasState() && TE.getOpcode() == Instruction::ExtractElement &&
6778 !TE.hasCopyableElements() &&
6779 all_of(make_isa_range<Instruction>(TE.Scalars), [Sz](Instruction *I) {
6780 std::optional<unsigned> Idx = getExtractIndex(I);
6781 return Idx && *Idx < Sz;
6782 })) {
6783 assert(!TE.isAltShuffle() && "Alternate instructions are only supported "
6784 "by BinaryOperator and CastInst.");
6785 SmallVector<int> ReorderMask(Sz, PoisonMaskElem);
6786 if (TE.ReorderIndices.empty())
6787 std::iota(ReorderMask.begin(), ReorderMask.end(), 0);
6788 else
6789 inversePermutation(TE.ReorderIndices, ReorderMask);
6790 for (unsigned I = 0; I < VF; ++I) {
6791 int &Idx = ReusedMask[I];
6792 if (Idx == PoisonMaskElem)
6793 continue;
6794 Value *V = TE.Scalars[ReorderMask[Idx]];
6795 std::optional<unsigned> EI = getExtractIndex(cast<Instruction>(V));
6796 Idx = std::distance(ReorderMask.begin(), find(ReorderMask, *EI));
6797 }
6798 }
6799 // Build the order of the VF size, need to reorder reuses shuffles, they are
6800 // always of VF size.
6801 OrdersType ResOrder(VF);
6802 std::iota(ResOrder.begin(), ResOrder.end(), 0);
6803 auto *It = ResOrder.begin();
6804 for (unsigned K = 0; K < VF; K += Sz) {
6805 OrdersType CurrentOrder(TE.ReorderIndices);
6806 SmallVector<int> SubMask{ArrayRef(ReusedMask).slice(K, Sz)};
6807 if (SubMask.front() == PoisonMaskElem)
6808 std::iota(SubMask.begin(), SubMask.end(), 0);
6809 reorderOrder(CurrentOrder, SubMask);
6810 transform(CurrentOrder, It, [K](unsigned Pos) { return Pos + K; });
6811 std::advance(It, Sz);
6812 }
6813 if (TE.isGather() && all_of(enumerate(ResOrder), [](const auto &Data) {
6814 return Data.index() == Data.value();
6815 }))
6816 return std::nullopt; // No need to reorder.
6817 return std::move(ResOrder);
6818 }
6819 if (TE.State == TreeEntry::StridedVectorize && !TopToBottom &&
6820 (!TE.UserTreeIndex || !TE.UserTreeIndex.UserTE->hasState() ||
6821 !Instruction::isBinaryOp(TE.UserTreeIndex.UserTE->getOpcode())) &&
6822 (TE.ReorderIndices.empty() || TE.isReverse()))
6823 return std::nullopt;
6824 if (TE.State == TreeEntry::SplitVectorize ||
6825 ((TE.State == TreeEntry::Vectorize ||
6826 TE.State == TreeEntry::StridedVectorize ||
6827 TE.State == TreeEntry::ExpandVectorize ||
6828 TE.State == TreeEntry::CompressVectorize ||
6829 TE.State == TreeEntry::BlendedLoadVectorize) &&
6832 TE.getMainOp()))))) {
6833 assert((TE.State == TreeEntry::SplitVectorize || !TE.isAltShuffle()) &&
6834 "Alternate instructions are only supported by "
6835 "BinaryOperator and CastInst.");
6836 return TE.ReorderIndices;
6837 }
6838 if (!TopToBottom && IgnoreReorder && TE.State == TreeEntry::Vectorize &&
6839 TE.isAltShuffle()) {
6840 assert(TE.ReuseShuffleIndices.empty() &&
6841 "ReuseShuffleIndices should be "
6842 "empty for alternate instructions.");
6843 SmallVector<int> Mask;
6844 TE.buildAltOpShuffleMask(
6845 [&](Instruction *I) {
6846 assert(TE.getMatchingMainOpOrAltOp(I) &&
6847 "Unexpected main/alternate opcode");
6848 return isAlternateInstruction(I, TE.getMainOp(), TE.getAltOp(), *TLI);
6849 },
6850 Mask);
6851 const int VF = TE.getVectorFactor();
6852 OrdersType ResOrder(VF, VF);
6853 for (unsigned I : seq<unsigned>(VF)) {
6854 if (Mask[I] == PoisonMaskElem)
6855 continue;
6856 ResOrder[Mask[I] % VF] = I;
6857 }
6858 return std::move(ResOrder);
6859 }
6860 if (!TE.ReorderIndices.empty())
6861 return TE.ReorderIndices;
6862 if (TE.State == TreeEntry::Vectorize && TE.getOpcode() == Instruction::PHI) {
6863 if (!TE.ReorderIndices.empty())
6864 return TE.ReorderIndices;
6865
6866 SmallVector<Instruction *> UserBVHead(TE.Scalars.size());
6867 for (auto [I, V] :
6868 make_filter_range(zip(UserBVHead, TE.Scalars), [](const auto &P) {
6869 Value *V = std::get<1>(P);
6870 return !isa<Constant>(V) && V->hasNUsesOrMore(1);
6871 })) {
6872 auto *II = dyn_cast<InsertElementInst>(*V->user_begin());
6873 if (!II)
6874 continue;
6875 Instruction *BVHead = nullptr;
6876 BasicBlock *BB = II->getParent();
6877 while (II && II->hasOneUse() && II->getParent() == BB) {
6878 BVHead = II;
6879 II = dyn_cast<InsertElementInst>(II->getOperand(0));
6880 }
6881 I = BVHead;
6882 }
6883
6884 auto CompareByBasicBlocks = [&](BasicBlock *BB1, BasicBlock *BB2) {
6885 assert(BB1 != BB2 && "Expected different basic blocks.");
6886 if (!DT->isReachableFromEntry(BB1))
6887 return false;
6888 if (!DT->isReachableFromEntry(BB2))
6889 return true;
6890 auto *NodeA = DT->getNode(BB1);
6891 auto *NodeB = DT->getNode(BB2);
6892 assert(NodeA && "Should only process reachable instructions");
6893 assert(NodeB && "Should only process reachable instructions");
6894 assert((NodeA == NodeB) ==
6895 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6896 "Different nodes should have different DFS numbers");
6897 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6898 };
6899 auto PHICompare = [&](unsigned I1, unsigned I2) {
6900 Value *V1 = TE.Scalars[I1];
6901 Value *V2 = TE.Scalars[I2];
6902 if (V1 == V2 || (V1->use_empty() && V2->use_empty()))
6903 return false;
6904 if (isa<PoisonValue>(V1))
6905 return true;
6906 if (isa<PoisonValue>(V2))
6907 return false;
6908 if (V1->getNumUses() < V2->getNumUses())
6909 return true;
6910 if (V1->getNumUses() > V2->getNumUses())
6911 return false;
6912 auto *FirstUserOfPhi1 = cast<Instruction>(*V1->user_begin());
6913 auto *FirstUserOfPhi2 = cast<Instruction>(*V2->user_begin());
6914 if (FirstUserOfPhi1->getParent() != FirstUserOfPhi2->getParent())
6915 return CompareByBasicBlocks(FirstUserOfPhi1->getParent(),
6916 FirstUserOfPhi2->getParent());
6917 auto *IE1 = dyn_cast<InsertElementInst>(FirstUserOfPhi1);
6918 auto *IE2 = dyn_cast<InsertElementInst>(FirstUserOfPhi2);
6919 auto *EE1 = dyn_cast<ExtractElementInst>(FirstUserOfPhi1);
6920 auto *EE2 = dyn_cast<ExtractElementInst>(FirstUserOfPhi2);
6921 if (IE1 && !IE2)
6922 return true;
6923 if (!IE1 && IE2)
6924 return false;
6925 if (IE1 && IE2) {
6926 if (UserBVHead[I1] && !UserBVHead[I2])
6927 return true;
6928 if (!UserBVHead[I1])
6929 return false;
6930 if (UserBVHead[I1] == UserBVHead[I2])
6931 return getElementIndex(IE1) < getElementIndex(IE2);
6932 if (UserBVHead[I1]->getParent() != UserBVHead[I2]->getParent())
6933 return CompareByBasicBlocks(UserBVHead[I1]->getParent(),
6934 UserBVHead[I2]->getParent());
6935 return UserBVHead[I1]->comesBefore(UserBVHead[I2]);
6936 }
6937 if (EE1 && !EE2)
6938 return true;
6939 if (!EE1 && EE2)
6940 return false;
6941 if (EE1 && EE2) {
6942 auto *Inst1 = dyn_cast<Instruction>(EE1->getOperand(0));
6943 auto *Inst2 = dyn_cast<Instruction>(EE2->getOperand(0));
6944 auto *P1 = dyn_cast<Argument>(EE1->getOperand(0));
6945 auto *P2 = dyn_cast<Argument>(EE2->getOperand(0));
6946 if (!Inst2 && !P2)
6947 return Inst1 || P1;
6948 if (EE1->getOperand(0) == EE2->getOperand(0))
6949 return getElementIndex(EE1) < getElementIndex(EE2);
6950 if (!Inst1 && Inst2)
6951 return false;
6952 if (Inst1 && Inst2) {
6953 if (Inst1->getParent() != Inst2->getParent())
6954 return CompareByBasicBlocks(Inst1->getParent(), Inst2->getParent());
6955 return Inst1->comesBefore(Inst2);
6956 }
6957 if (!P1 && P2)
6958 return false;
6959 assert(P1 && P2 &&
6960 "Expected either instructions or arguments vector operands.");
6961 return P1->getArgNo() < P2->getArgNo();
6962 }
6963 return false;
6964 };
6965 OrdersType Phis(TE.Scalars.size());
6966 std::iota(Phis.begin(), Phis.end(), 0);
6967 stable_sort(Phis, PHICompare);
6968 if (isIdentityOrder(Phis))
6969 return std::nullopt; // No need to reorder.
6970 return std::move(Phis);
6971 }
6972 if (TE.isGather() &&
6973 (!TE.hasState() || !TE.isAltShuffle() ||
6974 ScalarsInSplitNodes.contains(TE.getMainOp())) &&
6975 allSameType(TE.Scalars)) {
6976 // TODO: add analysis of other gather nodes with extractelement
6977 // instructions and other values/instructions, not only undefs.
6978 // Nodes with copyable lanes may mix in non-extract lanes, for which the
6979 // extract-index order is not applicable.
6980 if (((TE.hasState() && TE.getOpcode() == Instruction::ExtractElement &&
6981 !TE.hasCopyableElements()) ||
6983 any_of(TE.Scalars, IsaPred<ExtractElementInst>))) &&
6985 [](ExtractElementInst *EE) {
6986 return isa<FixedVectorType>(EE->getVectorOperandType());
6987 })) {
6988 // Check that gather of extractelements can be represented as
6989 // just a shuffle of a single vector.
6990 OrdersType CurrentOrder;
6991 bool Reuse =
6992 canReuseExtract(TE.Scalars, CurrentOrder, /*ResizeAllowed=*/true);
6993 if (Reuse || !CurrentOrder.empty())
6994 return std::move(CurrentOrder);
6995 }
6996 // If the gather node is <undef, v, .., poison> and
6997 // insertelement poison, v, 0 [+ permute]
6998 // is cheaper than
6999 // insertelement poison, v, n - try to reorder.
7000 // If rotating the whole graph, exclude the permute cost, the whole graph
7001 // might be transformed.
7002 int Sz = TE.Scalars.size();
7003 if (isSplat(TE.Scalars) && !allConstant(TE.Scalars) &&
7004 count_if(TE.Scalars, IsaPred<UndefValue>) == Sz - 1) {
7005 const auto *It = find_if_not(TE.Scalars, isConstant);
7006 if (It == TE.Scalars.begin())
7007 return OrdersType();
7008 auto *Ty =
7009 cast<VectorType>(getWidenedType(TE.Scalars.front()->getType(), Sz));
7010 if (It != TE.Scalars.end()) {
7011 OrdersType Order(Sz, Sz);
7012 unsigned Idx = std::distance(TE.Scalars.begin(), It);
7013 Order[Idx] = 0;
7014 fixupOrderingIndices(Order);
7015 SmallVector<int> Mask;
7016 inversePermutation(Order, Mask);
7017 InstructionCost PermuteCost =
7018 TopToBottom ? 0
7020 CostKind, Mask);
7021 InstructionCost InsertFirstCost =
7022 TTI->getVectorInstrCost(Instruction::InsertElement, Ty, CostKind, 0,
7023 PoisonValue::get(Ty), *It);
7024 InstructionCost InsertIdxCost =
7025 TTI->getVectorInstrCost(Instruction::InsertElement, Ty, CostKind,
7026 Idx, PoisonValue::get(Ty), *It);
7027 if (InsertFirstCost + PermuteCost < InsertIdxCost) {
7028 OrdersType Order(Sz, Sz);
7029 Order[Idx] = 0;
7030 return std::move(Order);
7031 }
7032 }
7033 }
7034 if (isSplat(TE.Scalars))
7035 return std::nullopt;
7036 if (TE.Scalars.size() >= 3)
7037 if (std::optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
7038 return Order;
7039 // Check if can include the order of vectorized loads. For masked gathers do
7040 // extra analysis later, so include such nodes into a special list.
7041 if (TE.hasState() && TE.getOpcode() == Instruction::Load) {
7042 SmallVector<Value *> PointerOps;
7043 StridedPtrInfo SPtrInfo;
7044 OrdersType CurrentOrder;
7045 LoadsState Res = canVectorizeLoads(TE.Scalars, TE.Scalars.front(),
7046 CurrentOrder, PointerOps, SPtrInfo);
7050 return std::move(CurrentOrder);
7051 }
7052 if (std::optional<OrdersType> CurrentOrder =
7053 findReusedOrderedScalars(TE, TopToBottom, IgnoreReorder))
7054 return CurrentOrder;
7055 }
7056 return std::nullopt;
7057}
7058
7059void BoUpSLP::reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const {
7060 // Reorder reuses mask.
7061 reorderReuses(TE.ReuseShuffleIndices, Mask);
7062 const unsigned Sz = TE.Scalars.size();
7063 // For vectorized and non-clustered reused no need to do anything else.
7064 if (!TE.isGather() ||
7065 !ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
7066 Sz) ||
7067 !isRepeatedNonIdentityClusteredMask(TE.ReuseShuffleIndices, Sz))
7068 return;
7069 SmallVector<int> NewMask;
7070 inversePermutation(TE.ReorderIndices, NewMask);
7071 addMask(NewMask, TE.ReuseShuffleIndices);
7072 // Clear reorder since it is going to be applied to the new mask.
7073 TE.ReorderIndices.clear();
7074 // Try to improve gathered nodes with clustered reuses, if possible.
7075 ArrayRef<int> Slice = ArrayRef(NewMask).slice(0, Sz);
7076 SmallVector<unsigned> NewOrder(Slice);
7077 inversePermutation(NewOrder, NewMask);
7078 reorderScalars(TE.Scalars, NewMask);
7079 // Fill the reuses mask with the identity submasks.
7080 for (auto *It = TE.ReuseShuffleIndices.begin(),
7081 *End = TE.ReuseShuffleIndices.end();
7082 It != End; std::advance(It, Sz))
7083 std::iota(It, std::next(It, Sz), 0);
7084}
7085
7087 if (Opts.slp_disable_tree_reorder)
7088 return false;
7089
7090 constexpr unsigned TinyVF = 2;
7091 constexpr unsigned TinyTree = 10;
7092 constexpr unsigned PhiOpsLimit = 12;
7093 constexpr unsigned GatherLoadsLimit = 2;
7094 if (VectorizableTree.size() <= TinyTree)
7095 return true;
7096 if (getRootNode().hasState() && !getRootNode().isGather() &&
7097 (getRootNode().getOpcode() == Instruction::Store ||
7098 getRootNode().getOpcode() == Instruction::PHI ||
7099 (getRootNode().getVectorFactor() <= TinyVF &&
7100 (getRootNode().getOpcode() == Instruction::PtrToInt ||
7101 getRootNode().getOpcode() == Instruction::PtrToAddr ||
7102 getRootNode().getOpcode() == Instruction::ICmp))) &&
7103 getRootNode().ReorderIndices.empty()) {
7104 // Check if the tree has only single store and single (unordered) load node,
7105 // other nodes are phis or geps/binops, combined with phis, and/or single
7106 // gather load node
7107 if (getRootNode().hasState() &&
7108 getRootNode().getOpcode() == Instruction::PHI &&
7109 getRootNodeScalars().size() == TinyVF &&
7110 getRootNode().getNumOperands() > PhiOpsLimit)
7111 return false;
7112 // Single node, which require reorder - skip.
7113 if (getRootNode().hasState() &&
7114 getRootNode().getOpcode() == Instruction::Store &&
7115 getRootNode().ReorderIndices.empty()) {
7116 const unsigned ReorderedSplitsCnt =
7117 count_if(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
7118 return TE->State == TreeEntry::SplitVectorize &&
7119 !TE->ReorderIndices.empty() && TE->UserTreeIndex.UserTE &&
7120 TE->UserTreeIndex.UserTE->State == TreeEntry::Vectorize &&
7121 isCommutative(TE->UserTreeIndex.UserTE->getMainOp());
7122 });
7123 if (ReorderedSplitsCnt <= 1 &&
7124 static_cast<unsigned>(count_if(
7125 VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
7126 return ((!TE->isGather() &&
7127 (TE->ReorderIndices.empty() ||
7128 (TE->UserTreeIndex.UserTE &&
7129 TE->UserTreeIndex.UserTE->State ==
7130 TreeEntry::Vectorize &&
7131 !TE->UserTreeIndex.UserTE->ReuseShuffleIndices
7132 .empty()))) ||
7133 (TE->isGather() && TE->ReorderIndices.empty() &&
7134 (!TE->hasState() || TE->isAltShuffle() ||
7135 TE->getOpcode() == Instruction::Load ||
7136 TE->getOpcode() == Instruction::ZExt ||
7137 TE->getOpcode() == Instruction::SExt))) &&
7138 (getRootNode().getVectorFactor() > TinyVF ||
7139 !TE->isGather() || none_of(TE->Scalars, [&](Value *V) {
7140 return !isConstant(V) && isVectorized(V);
7141 }));
7142 })) >= VectorizableTree.size() - ReorderedSplitsCnt)
7143 return false;
7144 }
7145 bool HasPhis = false;
7146 bool HasLoad = true;
7147 unsigned GatherLoads = 0;
7148 for (const std::unique_ptr<TreeEntry> &TE :
7149 ArrayRef(VectorizableTree).drop_front()) {
7150 if (TE->State == TreeEntry::SplitVectorize)
7151 continue;
7152 if (!TE->hasState()) {
7153 if (all_of(TE->Scalars, IsaPred<Constant, PHINode>) ||
7155 continue;
7156 if (getRootNodeScalars().size() == TinyVF &&
7158 continue;
7159 return true;
7160 }
7161 if (TE->getOpcode() == Instruction::Load && TE->ReorderIndices.empty()) {
7162 if (!TE->isGather()) {
7163 HasLoad = false;
7164 continue;
7165 }
7166 if (HasLoad)
7167 return true;
7168 ++GatherLoads;
7169 if (GatherLoads >= GatherLoadsLimit)
7170 return true;
7171 }
7172 if (TE->getOpcode() == Instruction::GetElementPtr ||
7173 Instruction::isBinaryOp(TE->getOpcode()))
7174 continue;
7175 if (TE->getOpcode() != Instruction::PHI &&
7176 (!TE->hasCopyableElements() ||
7177 static_cast<unsigned>(count_if(TE->Scalars, IsaPred<PHINode>)) <
7178 TE->Scalars.size() / 2))
7179 return true;
7180 if (getRootNodeScalars().size() == TinyVF &&
7181 TE->getNumOperands() > PhiOpsLimit)
7182 return false;
7183 HasPhis = true;
7184 }
7185 return !HasPhis;
7186 }
7187 return true;
7188}
7189
7190void BoUpSLP::TreeEntry::reorderSplitNode(unsigned Idx, ArrayRef<int> Mask,
7191 ArrayRef<int> MaskOrder) {
7192 assert(State == TreeEntry::SplitVectorize && "Expected split user node.");
7193 SmallVector<int> NewMask(getVectorFactor());
7194 SmallVector<int> NewMaskOrder(getVectorFactor());
7195 std::iota(NewMask.begin(), NewMask.end(), 0);
7196 std::iota(NewMaskOrder.begin(), NewMaskOrder.end(), 0);
7197 if (Idx == 0) {
7198 copy(Mask, NewMask.begin());
7199 copy(MaskOrder, NewMaskOrder.begin());
7200 } else {
7201 assert(Idx == 1 && "Expected either 0 or 1 index.");
7202 unsigned Offset = CombinedEntriesWithIndices.back().second;
7203 for (unsigned I : seq<unsigned>(Mask.size())) {
7204 NewMask[I + Offset] = Mask[I] + Offset;
7205 NewMaskOrder[I + Offset] = MaskOrder[I] + Offset;
7206 }
7207 }
7208 reorderScalars(Scalars, NewMask);
7209 reorderOrder(ReorderIndices, NewMaskOrder, /*BottomOrder=*/true);
7210 if (!ReorderIndices.empty() && BoUpSLP::isIdentityOrder(ReorderIndices))
7211 ReorderIndices.clear();
7212}
7213
7215 if (!TE.hasState())
7216 return;
7217 if (auto It = BlocksSchedules.find(TE.getMainOp()->getParent());
7218 It != BlocksSchedules.end())
7219 It->second->markCopyableDepsForRecalc(TE);
7220}
7221
7223 // Maps VF to the graph nodes.
7225 // ExtractElement gather nodes which can be vectorized and need to handle
7226 // their ordering.
7228
7229 // Phi nodes can have preferred ordering based on their result users
7231
7232 // AltShuffles can also have a preferred ordering that leads to fewer
7233 // instructions, e.g., the addsub instruction in x86.
7234 DenseMap<const TreeEntry *, OrdersType> AltShufflesToOrders;
7235
7236 // Maps a TreeEntry to the reorder indices of external users.
7238 ExternalUserReorderMap;
7239 // TODO: Reordering of struct types is not supported.
7240 if (any_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
7241 return TE->State == TreeEntry::Vectorize &&
7243 getValueType(TE->Scalars.front(), Opts.slp_revec));
7244 }))
7245 return;
7246 // Compute IgnoreReorder once - it depends only on UserIgnoreList and
7247 // getRootNode(), which do not change during this loop.
7248 const bool IgnoreReorder =
7249 !UserIgnoreList && getRootNode().hasState() &&
7250 (getRootNode().getOpcode() == Instruction::InsertElement ||
7251 getRootNode().getOpcode() == Instruction::InsertValue ||
7252 getRootNode().getOpcode() == Instruction::Store);
7253 // The operand subtrees of a blended load and of a revec shufflevector build
7254 // the masks in the lane order of the user scalars, so they are not reordered
7255 // with the graph.
7256 auto IsFixedOrderOperand = [&](const TreeEntry *TE) {
7257 for (; TE->UserTreeIndex; TE = TE->UserTreeIndex.UserTE) {
7258 const TreeEntry *UserTE = TE->UserTreeIndex.UserTE;
7259 if (UserTE->State == TreeEntry::BlendedLoadVectorize ||
7260 (Opts.slp_revec && UserTE->hasState() &&
7261 isa<ShuffleVectorInst>(UserTE->getMainOp())))
7262 return true;
7263 }
7264 return false;
7265 };
7266 // Find all reorderable nodes with the given VF.
7267 // Currently the are vectorized stores,loads,extracts + some gathering of
7268 // extracts.
7269 for_each(VectorizableTree, [&, &TTIRef = *TTI](
7270 const std::unique_ptr<TreeEntry> &TE) {
7271 if (IsFixedOrderOperand(TE.get()))
7272 return;
7273 // Look for external users that will probably be vectorized.
7274 SmallVector<OrdersType, 1> ExternalUserReorderIndices =
7275 findExternalStoreUsersReorderIndices(TE.get());
7276 if (!ExternalUserReorderIndices.empty()) {
7277 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
7278 ExternalUserReorderMap.try_emplace(TE.get(),
7279 std::move(ExternalUserReorderIndices));
7280 }
7281
7282 // Patterns like [fadd,fsub] can be combined into a single instruction in
7283 // x86. Reordering them into [fsub,fadd] blocks this pattern. So we need
7284 // to take into account their order when looking for the most used order.
7285 if (TE->hasState() && TE->isAltShuffle() &&
7286 TE->State != TreeEntry::SplitVectorize) {
7287 Type *ScalarTy = TE->Scalars[0]->getType();
7288 auto *VecTy =
7289 cast<VectorType>(getWidenedType(ScalarTy, TE->Scalars.size()));
7290 unsigned Opcode0 = TE->getOpcode();
7291 unsigned Opcode1 = TE->getAltOpcode();
7292 SmallBitVector OpcodeMask(
7293 getAltInstrMask(TE->Scalars, ScalarTy, Opcode0, Opcode1));
7294 // If this pattern is supported by the target then we consider the order.
7295 if (TTIRef.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask)) {
7296 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
7297 AltShufflesToOrders.try_emplace(TE.get(), OrdersType());
7298 }
7299 // TODO: Check the reverse order too.
7300 }
7301
7302 if (std::optional<OrdersType> CurrentOrder =
7303 getReorderingData(*TE, /*TopToBottom=*/true, IgnoreReorder)) {
7304 // Do not include ordering for nodes used in the alt opcode vectorization,
7305 // better to reorder them during bottom-to-top stage. If follow the order
7306 // here, it causes reordering of the whole graph though actually it is
7307 // profitable just to reorder the subgraph that starts from the alternate
7308 // opcode vectorization node. Such nodes already end-up with the shuffle
7309 // instruction and it is just enough to change this shuffle rather than
7310 // rotate the scalars for the whole graph.
7311 unsigned Cnt = 0;
7312 const TreeEntry *UserTE = TE.get();
7313 while (UserTE && Cnt < Opts.slp_recursion_max_depth) {
7314 if (!UserTE->UserTreeIndex)
7315 break;
7316 if (UserTE->UserTreeIndex.UserTE->State == TreeEntry::Vectorize &&
7317 UserTE->UserTreeIndex.UserTE->isAltShuffle() &&
7318 UserTE->UserTreeIndex.UserTE->Idx != 0)
7319 return;
7320 UserTE = UserTE->UserTreeIndex.UserTE;
7321 ++Cnt;
7322 }
7323 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
7324 if (!(TE->State == TreeEntry::Vectorize ||
7325 TE->State == TreeEntry::StridedVectorize ||
7326 TE->State == TreeEntry::ExpandVectorize ||
7327 TE->State == TreeEntry::SplitVectorize ||
7328 TE->State == TreeEntry::CompressVectorize ||
7329 TE->State == TreeEntry::BlendedLoadVectorize) ||
7330 !TE->ReuseShuffleIndices.empty())
7331 GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
7332 if (TE->State == TreeEntry::Vectorize &&
7333 TE->getOpcode() == Instruction::PHI)
7334 PhisToOrders.try_emplace(TE.get(), *CurrentOrder);
7335 }
7336 });
7337
7338 // Reorder the graph nodes according to their vectorization factor.
7339 for (unsigned VF = getRootNode().getVectorFactor();
7340 !VFToOrderedEntries.empty() && VF > 1; --VF) {
7341 auto It = VFToOrderedEntries.find(VF);
7342 if (It == VFToOrderedEntries.end())
7343 continue;
7344 // Try to find the most profitable order. We just are looking for the most
7345 // used order and reorder scalar elements in the nodes according to this
7346 // mostly used order.
7347 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
7348 // Delete VF entry upon exit.
7349 llvm::scope_exit Cleanup([&]() { VFToOrderedEntries.erase(It); });
7350
7351 // All operands are reordered and used only in this node - propagate the
7352 // most used order to the user node.
7355 OrdersUses;
7356 // No need to reorder this nodes, still need to extend and to use shuffle,
7357 // just need to merge reordering shuffle and the reuse shuffle.
7358 for (const TreeEntry *OpTE :
7359 make_filter_range(OrderedEntries, [&](const TreeEntry *OpTE) {
7360 return OpTE->ReuseShuffleIndices.empty() ||
7361 GathersToOrders.count(OpTE) ||
7362 OpTE->State == TreeEntry::SplitVectorize;
7363 })) {
7364 // Count number of orders uses.
7365 const auto &Order = [OpTE, &GathersToOrders, &AltShufflesToOrders,
7366 &PhisToOrders]() -> const OrdersType & {
7367 if (OpTE->isGather() || !OpTE->ReuseShuffleIndices.empty()) {
7368 auto It = GathersToOrders.find(OpTE);
7369 if (It != GathersToOrders.end())
7370 return It->second;
7371 }
7372 if (OpTE->hasState() && OpTE->isAltShuffle()) {
7373 auto It = AltShufflesToOrders.find(OpTE);
7374 if (It != AltShufflesToOrders.end())
7375 return It->second;
7376 }
7377 if (OpTE->State == TreeEntry::Vectorize &&
7378 OpTE->getOpcode() == Instruction::PHI) {
7379 auto It = PhisToOrders.find(OpTE);
7380 if (It != PhisToOrders.end())
7381 return It->second;
7382 }
7383 return OpTE->ReorderIndices;
7384 }();
7385 // First consider the order of the external scalar users.
7386 auto It = ExternalUserReorderMap.find(OpTE);
7387 if (It != ExternalUserReorderMap.end()) {
7388 const auto &ExternalUserReorderIndices = It->second;
7389 // If the OpTE vector factor != number of scalars - use natural order,
7390 // it is an attempt to reorder node with reused scalars but with
7391 // external uses.
7392 if (OpTE->getVectorFactor() != OpTE->Scalars.size()) {
7393 OrdersUses.try_emplace(OrdersType(), 0).first->second +=
7394 ExternalUserReorderIndices.size();
7395 } else {
7396 for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
7397 ++OrdersUses.try_emplace(ExtOrder, 0).first->second;
7398 }
7399 // No other useful reorder data in this entry.
7400 if (Order.empty())
7401 continue;
7402 }
7403 // Stores actually store the mask, not the order, need to invert.
7404 if (OpTE->State == TreeEntry::Vectorize &&
7405 OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
7406 assert(!OpTE->isAltShuffle() &&
7407 "Alternate instructions are only supported by BinaryOperator "
7408 "and CastInst.");
7409 SmallVector<int> Mask;
7410 inversePermutation(Order, Mask);
7411 unsigned E = Order.size();
7412 OrdersType CurrentOrder(E, E);
7413 transform(Mask, CurrentOrder.begin(), [E](int Idx) {
7414 return Idx == PoisonMaskElem ? E : static_cast<unsigned>(Idx);
7415 });
7416 fixupOrderingIndices(CurrentOrder);
7417 ++OrdersUses.try_emplace(CurrentOrder, 0).first->second;
7418 } else {
7419 ++OrdersUses.try_emplace(Order, 0).first->second;
7420 }
7421 }
7422 if (OrdersUses.empty())
7423 continue;
7424 // Choose the most used order.
7425 unsigned IdentityCnt = 0;
7426 unsigned FilledIdentityCnt = 0;
7427 OrdersType IdentityOrder(VF, VF);
7428 for (auto &Pair : OrdersUses) {
7429 if (Pair.first.empty() || isIdentityOrder(Pair.first)) {
7430 if (!Pair.first.empty())
7431 FilledIdentityCnt += Pair.second;
7432 IdentityCnt += Pair.second;
7433 combineOrders(IdentityOrder, Pair.first);
7434 }
7435 }
7436 MutableArrayRef<unsigned> BestOrder = IdentityOrder;
7437 unsigned Cnt = IdentityCnt;
7438 for (auto &Pair : OrdersUses) {
7439 // Prefer identity order. But, if filled identity found (non-empty order)
7440 // with same number of uses, as the new candidate order, we can choose
7441 // this candidate order.
7442 if (Cnt < Pair.second ||
7443 (Cnt == IdentityCnt && IdentityCnt == FilledIdentityCnt &&
7444 Cnt == Pair.second && !BestOrder.empty() &&
7445 isIdentityOrder(BestOrder))) {
7446 combineOrders(Pair.first, BestOrder);
7447 BestOrder = Pair.first;
7448 Cnt = Pair.second;
7449 } else {
7450 combineOrders(BestOrder, Pair.first);
7451 }
7452 }
7453 // Set order of the user node.
7454 if (isIdentityOrder(BestOrder))
7455 continue;
7456 fixupOrderingIndices(BestOrder);
7457 SmallVector<int> Mask;
7458 inversePermutation(BestOrder, Mask);
7459 SmallVector<int> MaskOrder(BestOrder.size(), PoisonMaskElem);
7460 unsigned E = BestOrder.size();
7461 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
7462 return I < E ? static_cast<int>(I) : PoisonMaskElem;
7463 });
7464 // Do an actual reordering, if profitable.
7465 // The splat-gather subtree load roots stay in memory order: the reusing
7466 // gathers fetch lanes by value.
7467 for (std::unique_ptr<TreeEntry> &TE : make_filter_range(
7468 VectorizableTree, [&](std::unique_ptr<TreeEntry> &TE) {
7469 return (TE->State != TreeEntry::Vectorize ||
7470 TE->getOpcode() != Instruction::Load ||
7471 !is_contained(SplatGatheredScalarsRoots, TE.get())) &&
7472 !IsFixedOrderOperand(TE.get());
7473 })) {
7474 // Just do the reordering for the nodes with the given VF.
7475 if (TE->Scalars.size() != VF) {
7476 if (TE->ReuseShuffleIndices.size() == VF &&
7477 TE->State != TreeEntry::ExpandVectorize) {
7478 assert(TE->State != TreeEntry::SplitVectorize &&
7479 "Split vectorized not expected.");
7480 // Need to reorder the reuses masks of the operands with smaller VF to
7481 // be able to find the match between the graph nodes and scalar
7482 // operands of the given node during vectorization/cost estimation.
7483 assert(
7484 (!TE->UserTreeIndex ||
7485 TE->UserTreeIndex.UserTE->Scalars.size() == VF ||
7486 TE->UserTreeIndex.UserTE->Scalars.size() == TE->Scalars.size() ||
7487 TE->UserTreeIndex.UserTE->State == TreeEntry::SplitVectorize) &&
7488 "All users must be of VF size.");
7489 // Update ordering of the operands with the smaller VF than the given
7490 // one.
7491 reorderNodeWithReuses(*TE, Mask);
7492 // Update orders in user split vectorize nodes.
7493 if (TE->UserTreeIndex &&
7494 TE->UserTreeIndex.UserTE->State == TreeEntry::SplitVectorize)
7495 TE->UserTreeIndex.UserTE->reorderSplitNode(
7496 TE->UserTreeIndex.EdgeIdx, Mask, MaskOrder);
7497 }
7498 continue;
7499 }
7500 if ((TE->State == TreeEntry::SplitVectorize &&
7501 TE->ReuseShuffleIndices.empty()) ||
7502 ((TE->State == TreeEntry::Vectorize ||
7503 TE->State == TreeEntry::StridedVectorize ||
7504 TE->State == TreeEntry::ExpandVectorize ||
7505 TE->State == TreeEntry::CompressVectorize ||
7506 TE->State == TreeEntry::BlendedLoadVectorize) &&
7508 InsertElementInst, InsertValueInst>(TE->getMainOp()) ||
7509 (Opts.slp_revec && isa<ShuffleVectorInst>(TE->getMainOp()))))) {
7510 assert(
7511 (!TE->isAltShuffle() || (TE->State == TreeEntry::SplitVectorize &&
7512 TE->ReuseShuffleIndices.empty())) &&
7513 "Alternate instructions are only supported by BinaryOperator "
7514 "and CastInst.");
7515 // Build correct orders for extract{element,value}, loads,
7516 // stores and alternate (split) nodes.
7517 reorderOrder(TE->ReorderIndices, Mask);
7519 TE->getMainOp())) {
7520 TE->reorderOperands(Mask);
7522 }
7523 } else {
7524 // Reorder the node and its operands.
7525 TE->reorderOperands(Mask);
7527 assert(TE->ReorderIndices.empty() &&
7528 "Expected empty reorder sequence.");
7529 reorderScalars(TE->Scalars, Mask);
7530 }
7531 if (!TE->ReuseShuffleIndices.empty() &&
7532 TE->State != TreeEntry::ExpandVectorize) {
7533 // Apply reversed order to keep the original ordering of the reused
7534 // elements to avoid extra reorder indices shuffling. An ExpandVectorize
7535 // store keeps its expand mask fixed and carries the reorder in
7536 // ReorderIndices, so it is excluded here.
7537 OrdersType CurrentOrder;
7538 reorderOrder(CurrentOrder, MaskOrder);
7539 SmallVector<int> NewReuses;
7540 inversePermutation(CurrentOrder, NewReuses);
7541 addMask(NewReuses, TE->ReuseShuffleIndices);
7542 TE->ReuseShuffleIndices.swap(NewReuses);
7543 } else if (TE->UserTreeIndex &&
7544 TE->UserTreeIndex.UserTE->State == TreeEntry::SplitVectorize)
7545 // Update orders in user split vectorize nodes.
7546 TE->UserTreeIndex.UserTE->reorderSplitNode(TE->UserTreeIndex.EdgeIdx,
7547 Mask, MaskOrder);
7548 }
7549 }
7550}
7551
7552void BoUpSLP::buildReorderableOperands(
7553 TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
7554 const SmallPtrSetImpl<const TreeEntry *> &ReorderableGathers,
7555 SmallVectorImpl<TreeEntry *> &GatherOps) {
7556 for (unsigned I : seq<unsigned>(UserTE->getNumOperands())) {
7557 if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
7558 return OpData.first == I &&
7559 (OpData.second->State == TreeEntry::Vectorize ||
7560 OpData.second->State == TreeEntry::StridedVectorize ||
7561 OpData.second->State == TreeEntry::ExpandVectorize ||
7562 OpData.second->State == TreeEntry::CompressVectorize ||
7563 OpData.second->State == TreeEntry::BlendedLoadVectorize ||
7564 OpData.second->State == TreeEntry::SplitVectorize);
7565 }))
7566 continue;
7567 // Do not request operands, if they do not exist.
7568 if (UserTE->hasState()) {
7569 if (UserTE->getOpcode() == Instruction::ExtractElement ||
7570 UserTE->getOpcode() == Instruction::ExtractValue)
7571 continue;
7572 if ((UserTE->getOpcode() == Instruction::InsertElement ||
7573 UserTE->getOpcode() == Instruction::InsertValue) &&
7574 I == 0)
7575 continue;
7576 if (UserTE->getOpcode() == Instruction::Store && I == 1 &&
7577 (UserTE->State == TreeEntry::Vectorize ||
7578 UserTE->State == TreeEntry::StridedVectorize ||
7579 UserTE->State == TreeEntry::ExpandVectorize))
7580 continue;
7581 if (UserTE->getOpcode() == Instruction::Load &&
7582 (UserTE->State == TreeEntry::Vectorize ||
7583 UserTE->State == TreeEntry::StridedVectorize ||
7584 UserTE->State == TreeEntry::CompressVectorize ||
7585 UserTE->State == TreeEntry::BlendedLoadVectorize))
7586 continue;
7587 }
7588 TreeEntry *TE = getOperandEntry(UserTE, I);
7589 assert(TE && "Expected operand entry.");
7590 if (!TE->isGather()) {
7591 // Add the node to the list of the ordered nodes with the identity
7592 // order.
7593 Edges.emplace_back(I, TE);
7594 // Add ScatterVectorize nodes to the list of operands, where just
7595 // reordering of the scalars is required. Similar to the gathers, so
7596 // simply add to the list of gathered ops.
7597 // If there are reused scalars, process this node as a regular vectorize
7598 // node, just reorder reuses mask.
7599 if (TE->State == TreeEntry::ScatterVectorize &&
7600 TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty())
7601 GatherOps.push_back(TE);
7602 continue;
7603 }
7604 if (ReorderableGathers.contains(TE))
7605 GatherOps.push_back(TE);
7606 }
7607}
7608
7609void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
7610 struct TreeEntryCompare {
7611 bool operator()(const TreeEntry *LHS, const TreeEntry *RHS) const {
7612 if (LHS->UserTreeIndex && RHS->UserTreeIndex)
7613 return LHS->UserTreeIndex.UserTE->Idx < RHS->UserTreeIndex.UserTE->Idx;
7614 return LHS->Idx < RHS->Idx;
7615 }
7616 };
7618 DenseSet<const TreeEntry *> GathersToOrders;
7619 // Find all reorderable leaf nodes with the given VF.
7620 // Currently the are vectorized loads,extracts without alternate operands +
7621 // some gathering of extracts.
7623 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
7624 if (TE->State != TreeEntry::Vectorize &&
7625 TE->State != TreeEntry::StridedVectorize &&
7626 TE->State != TreeEntry::ExpandVectorize &&
7627 TE->State != TreeEntry::CompressVectorize &&
7628 TE->State != TreeEntry::BlendedLoadVectorize &&
7629 TE->State != TreeEntry::SplitVectorize)
7630 NonVectorized.insert(TE.get());
7631 if (std::optional<OrdersType> CurrentOrder =
7632 getReorderingData(*TE, /*TopToBottom=*/false, IgnoreReorder)) {
7633 Queue.push(TE.get());
7634 if (!(TE->State == TreeEntry::Vectorize ||
7635 TE->State == TreeEntry::StridedVectorize ||
7636 TE->State == TreeEntry::ExpandVectorize ||
7637 TE->State == TreeEntry::CompressVectorize ||
7638 TE->State == TreeEntry::BlendedLoadVectorize ||
7639 TE->State == TreeEntry::SplitVectorize) ||
7640 !TE->ReuseShuffleIndices.empty())
7641 GathersToOrders.insert(TE.get());
7642 }
7643 }
7644
7645 // 1. Propagate order to the graph nodes, which use only reordered nodes.
7646 // I.e., if the node has operands, that are reordered, try to make at least
7647 // one operand order in the natural order and reorder others + reorder the
7648 // user node itself.
7649 SmallPtrSet<const TreeEntry *, 4> Visited, RevisitedOps;
7650 while (!Queue.empty()) {
7651 // 1. Filter out only reordered nodes.
7652 std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
7653 TreeEntry *TE = Queue.top();
7654 const TreeEntry *UserTE = TE->UserTreeIndex.UserTE;
7655 Queue.pop();
7656 SmallVector<TreeEntry *> OrderedOps(1, TE);
7657 while (!Queue.empty()) {
7658 TE = Queue.top();
7659 if (!UserTE || UserTE != TE->UserTreeIndex.UserTE)
7660 break;
7661 Queue.pop();
7662 OrderedOps.push_back(TE);
7663 }
7664 for (TreeEntry *TE : make_filter_range(OrderedOps, [&](TreeEntry *TE) {
7665 return (TE->State == TreeEntry::Vectorize ||
7666 TE->State == TreeEntry::StridedVectorize ||
7667 TE->State == TreeEntry::ExpandVectorize ||
7668 TE->State == TreeEntry::CompressVectorize ||
7669 TE->State == TreeEntry::BlendedLoadVectorize ||
7670 TE->State == TreeEntry::SplitVectorize ||
7671 (TE->isGather() && GathersToOrders.contains(TE))) &&
7672 TE->UserTreeIndex &&
7673 TE->UserTreeIndex.UserTE->State !=
7674 TreeEntry::BlendedLoadVectorize &&
7675 TE->ReuseShuffleIndices.empty() && Visited.insert(TE).second;
7676 })) {
7677 // Build a map between user nodes and their operands order to speedup
7678 // search. The graph currently does not provide this dependency directly.
7679 Users.first = TE->UserTreeIndex.UserTE;
7680 Users.second.emplace_back(TE->UserTreeIndex.EdgeIdx, TE);
7681 }
7682 if (Users.first) {
7683 auto &Data = Users;
7684 // TODO: Reordering of struct types is not supported.
7685 if (Data.first->State == TreeEntry::Vectorize &&
7687 getValueType(Data.first->Scalars.front(), Opts.slp_revec)))
7688 continue;
7689 if (Data.first->State == TreeEntry::SplitVectorize) {
7690 assert(
7691 Data.second.size() <= 2 &&
7692 "Expected not greater than 2 operands for split vectorize node.");
7693 if (any_of(Data.second,
7694 [](const auto &Op) { return !Op.second->UserTreeIndex; }))
7695 continue;
7696 // Update orders in user split vectorize nodes.
7697 assert(Data.first->CombinedEntriesWithIndices.size() == 2 &&
7698 "Expected exactly 2 entries.");
7699 for (const auto &P : Data.first->CombinedEntriesWithIndices) {
7700 TreeEntry &OpTE = *VectorizableTree[P.first];
7701 // The order of an operand that has both reordered and reused scalars
7702 // cannot be absorbed into the split node cleanly: clearing the
7703 // reorder indices while keeping the reuse mask (or vice versa)
7704 // desyncs the split node scalars from the operand effective order.
7705 // Skip reordering for such operands.
7706 if (OpTE.State != TreeEntry::SplitVectorize &&
7707 !OpTE.ReorderIndices.empty() && !OpTE.ReuseShuffleIndices.empty())
7708 continue;
7709 OrdersType Order = OpTE.ReorderIndices;
7710 if (Order.empty() || !OpTE.ReuseShuffleIndices.empty()) {
7711 if (!OpTE.isGather() && OpTE.ReuseShuffleIndices.empty())
7712 continue;
7713 const auto BestOrder =
7714 getReorderingData(OpTE, /*TopToBottom=*/false, IgnoreReorder);
7715 if (!BestOrder || BestOrder->empty() || isIdentityOrder(*BestOrder))
7716 continue;
7717 Order = *BestOrder;
7718 }
7719 fixupOrderingIndices(Order);
7720 SmallVector<int> Mask;
7721 inversePermutation(Order, Mask);
7722 const unsigned E = Order.size();
7723 SmallVector<int> MaskOrder(E, PoisonMaskElem);
7724 transform(Order, MaskOrder.begin(), [E](unsigned I) {
7725 return I < E ? static_cast<int>(I) : PoisonMaskElem;
7726 });
7727 Data.first->reorderSplitNode(P.second ? 1 : 0, Mask, MaskOrder);
7728 // Clear ordering of the operand.
7729 if (!OpTE.ReorderIndices.empty()) {
7730 OpTE.ReorderIndices.clear();
7731 } else if (!OpTE.ReuseShuffleIndices.empty()) {
7732 reorderReuses(OpTE.ReuseShuffleIndices, Mask);
7733 } else {
7734 assert(OpTE.isGather() && "Expected only gather/buildvector node.");
7735 reorderScalars(OpTE.Scalars, Mask);
7736 }
7737 }
7738 if (Data.first->ReuseShuffleIndices.empty() &&
7739 !Data.first->ReorderIndices.empty()) {
7740 // Insert user node to the list to try to sink reordering deeper in
7741 // the graph.
7742 Queue.push(Data.first);
7743 }
7744 continue;
7745 }
7746 // Do not move the operand order to the root PHI node when the root
7747 // order must be preserved: the root has no user to take over the order
7748 // and it cannot be dropped at the end of the reordering.
7749 if (!IgnoreReorder && Data.first == &getRootNode() &&
7750 !Data.first->UserTreeIndex &&
7751 Data.first->State == TreeEntry::Vectorize &&
7752 Data.first->getOpcode() == Instruction::PHI &&
7753 Data.first->ReuseShuffleIndices.empty())
7754 continue;
7755 // Check that operands are used only in the User node.
7756 SmallVector<TreeEntry *> GatherOps;
7757 buildReorderableOperands(Data.first, Data.second, NonVectorized,
7758 GatherOps);
7759 // All operands are reordered and used only in this node - propagate the
7760 // most used order to the user node.
7763 OrdersUses;
7764 // Do the analysis for each tree entry only once, otherwise the order of
7765 // the same node my be considered several times, though might be not
7766 // profitable.
7769 for (const auto &Op : Data.second) {
7770 TreeEntry *OpTE = Op.second;
7771 if (!VisitedOps.insert(OpTE).second)
7772 continue;
7773 if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
7774 continue;
7775 const auto Order = [&]() -> const OrdersType {
7776 if (OpTE->isGather() || !OpTE->ReuseShuffleIndices.empty())
7777 return getReorderingData(*OpTE, /*TopToBottom=*/false,
7778 IgnoreReorder)
7779 .value_or(OrdersType(1));
7780 return OpTE->ReorderIndices;
7781 }();
7782 // The order is partially ordered, skip it in favor of fully non-ordered
7783 // orders.
7784 if (Order.size() == 1)
7785 continue;
7786
7787 // Check that the reordering does not increase number of shuffles, i.e.
7788 // same-values-nodes has same parents or their parents has same parents.
7789 if (!Order.empty() && !isIdentityOrder(Order)) {
7790 Value *Root = OpTE->hasState()
7791 ? OpTE->getMainOp()
7792 : *find_if_not(OpTE->Scalars, isConstant);
7793 auto GetSameNodesUsers = [&](Value *Root) {
7795 for (const TreeEntry *TE : ValueToGatherNodes.lookup(Root)) {
7796 if (TE != OpTE && TE->UserTreeIndex &&
7797 TE->getVectorFactor() == OpTE->getVectorFactor() &&
7798 TE->Scalars.size() == OpTE->Scalars.size() &&
7799 ((TE->ReorderIndices.empty() && OpTE->isSame(TE->Scalars)) ||
7800 (OpTE->ReorderIndices.empty() && TE->isSame(OpTE->Scalars))))
7801 Res.insert(TE->UserTreeIndex.UserTE);
7802 }
7803 for (const TreeEntry *TE : getTreeEntries(Root)) {
7804 if (TE != OpTE && TE->UserTreeIndex &&
7805 TE->getVectorFactor() == OpTE->getVectorFactor() &&
7806 TE->Scalars.size() == OpTE->Scalars.size() &&
7807 ((TE->ReorderIndices.empty() && OpTE->isSame(TE->Scalars)) ||
7808 (OpTE->ReorderIndices.empty() && TE->isSame(OpTE->Scalars))))
7809 Res.insert(TE->UserTreeIndex.UserTE);
7810 }
7811 return Res.takeVector();
7812 };
7813 auto GetNumOperands = [](const TreeEntry *TE) {
7814 if (TE->State == TreeEntry::SplitVectorize)
7815 return TE->getNumOperands();
7816 if (auto *CI = dyn_cast<CallInst>(TE->getMainOp()); CI)
7817 return CI->arg_size();
7818 return TE->getNumOperands();
7819 };
7820 auto NodeShouldBeReorderedWithOperands = [&, TTI = TTI](
7821 const TreeEntry *TE) {
7823 if (auto *CI = dyn_cast<CallInst>(TE->getMainOp()); CI)
7824 ID = getVectorIntrinsicIDForCall(CI, TLI);
7825 for (unsigned Idx : seq<unsigned>(GetNumOperands(TE))) {
7826 if (ID != Intrinsic::not_intrinsic &&
7828 continue;
7829 const TreeEntry *Op = getOperandEntry(TE, Idx);
7830 if (Op->isGather() && Op->hasState()) {
7831 const TreeEntry *VecOp =
7832 getSameValuesTreeEntry(Op->getMainOp(), Op->Scalars);
7833 if (VecOp)
7834 Op = VecOp;
7835 }
7836 if (Op->ReorderIndices.empty() && Op->ReuseShuffleIndices.empty())
7837 return false;
7838 }
7839 return true;
7840 };
7841 SmallVector<TreeEntry *> Users = GetSameNodesUsers(Root);
7842 if (!Users.empty() && !all_of(Users, [&](TreeEntry *UTE) {
7843 if (!RevisitedOps.insert(UTE).second)
7844 return false;
7845 return UTE == Data.first || !UTE->ReorderIndices.empty() ||
7846 !UTE->ReuseShuffleIndices.empty() ||
7847 (UTE->UserTreeIndex &&
7848 UTE->UserTreeIndex.UserTE == Data.first) ||
7849 (Data.first->UserTreeIndex &&
7850 Data.first->UserTreeIndex.UserTE == UTE) ||
7851 (IgnoreReorder && UTE->UserTreeIndex &&
7852 UTE->UserTreeIndex.UserTE->Idx == 0) ||
7853 NodeShouldBeReorderedWithOperands(UTE);
7854 }))
7855 continue;
7856 for (TreeEntry *UTE : Users) {
7858 if (auto *CI = dyn_cast<CallInst>(UTE->getMainOp()); CI)
7859 ID = getVectorIntrinsicIDForCall(CI, TLI);
7860 for (unsigned Idx : seq<unsigned>(GetNumOperands(UTE))) {
7861 if (ID != Intrinsic::not_intrinsic &&
7863 continue;
7864 const TreeEntry *Op = getOperandEntry(UTE, Idx);
7865 Visited.erase(Op);
7866 Queue.push(const_cast<TreeEntry *>(Op));
7867 }
7868 }
7869 }
7870 unsigned NumOps = count_if(
7871 Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
7872 return P.second == OpTE;
7873 });
7874 // Stores actually store the mask, not the order, need to invert.
7875 if (OpTE->State == TreeEntry::Vectorize &&
7876 OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
7877 assert(!OpTE->isAltShuffle() &&
7878 "Alternate instructions are only supported by BinaryOperator "
7879 "and CastInst.");
7880 SmallVector<int> Mask;
7881 inversePermutation(Order, Mask);
7882 unsigned E = Order.size();
7883 OrdersType CurrentOrder(E, E);
7884 transform(Mask, CurrentOrder.begin(), [E](int Idx) {
7885 return Idx == PoisonMaskElem ? E : static_cast<unsigned>(Idx);
7886 });
7887 fixupOrderingIndices(CurrentOrder);
7888 OrdersUses.try_emplace(CurrentOrder, 0).first->second += NumOps;
7889 } else {
7890 OrdersUses.try_emplace(Order, 0).first->second += NumOps;
7891 }
7892 auto Res = OrdersUses.try_emplace(OrdersType(), 0);
7893 const auto AllowsReordering = [&](const TreeEntry *TE) {
7894 if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
7895 (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
7896 (IgnoreReorder && TE->Idx == 0))
7897 return true;
7898 if (TE->isGather()) {
7899 if (GathersToOrders.contains(TE))
7900 return !getReorderingData(*TE, /*TopToBottom=*/false,
7901 IgnoreReorder)
7902 .value_or(OrdersType(1))
7903 .empty();
7904 return true;
7905 }
7906 return false;
7907 };
7908 if (OpTE->UserTreeIndex) {
7909 TreeEntry *UserTE = OpTE->UserTreeIndex.UserTE;
7910 if (!VisitedUsers.insert(UserTE).second)
7911 continue;
7912 // May reorder user node if it requires reordering, has reused
7913 // scalars, is an alternate op vectorize node or its op nodes require
7914 // reordering.
7915 if (AllowsReordering(UserTE))
7916 continue;
7917 // Check if users allow reordering.
7918 // Currently look up just 1 level of operands to avoid increase of
7919 // the compile time.
7920 // Profitable to reorder if definitely more operands allow
7921 // reordering rather than those with natural order.
7923 if (static_cast<unsigned>(count_if(
7924 Ops, [UserTE, &AllowsReordering](
7925 const std::pair<unsigned, TreeEntry *> &Op) {
7926 return AllowsReordering(Op.second) &&
7927 Op.second->UserTreeIndex.UserTE == UserTE;
7928 })) <= Ops.size() / 2)
7929 ++Res.first->second;
7930 }
7931 }
7932 if (OrdersUses.empty()) {
7933 Visited.insert_range(llvm::make_second_range(Data.second));
7934 continue;
7935 }
7936 // Choose the most used order.
7937 unsigned IdentityCnt = 0;
7938 unsigned VF = Data.second.front().second->getVectorFactor();
7939 OrdersType IdentityOrder(VF, VF);
7940 for (auto &Pair : OrdersUses) {
7941 if (Pair.first.empty() || isIdentityOrder(Pair.first)) {
7942 IdentityCnt += Pair.second;
7943 combineOrders(IdentityOrder, Pair.first);
7944 }
7945 }
7946 MutableArrayRef<unsigned> BestOrder = IdentityOrder;
7947 unsigned Cnt = IdentityCnt;
7948 for (auto &Pair : OrdersUses) {
7949 // Prefer identity order. But, if filled identity found (non-empty
7950 // order) with same number of uses, as the new candidate order, we can
7951 // choose this candidate order.
7952 if (Cnt < Pair.second) {
7953 combineOrders(Pair.first, BestOrder);
7954 BestOrder = Pair.first;
7955 Cnt = Pair.second;
7956 } else {
7957 combineOrders(BestOrder, Pair.first);
7958 }
7959 }
7960 // Set order of the user node.
7961 if (isIdentityOrder(BestOrder)) {
7962 Visited.insert_range(llvm::make_second_range(Data.second));
7963 continue;
7964 }
7965 fixupOrderingIndices(BestOrder);
7966 // Erase operands from OrderedEntries list and adjust their orders.
7967 VisitedOps.clear();
7968 SmallVector<int> Mask;
7969 inversePermutation(BestOrder, Mask);
7970 SmallVector<int> MaskOrder(BestOrder.size(), PoisonMaskElem);
7971 unsigned E = BestOrder.size();
7972 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
7973 return I < E ? static_cast<int>(I) : PoisonMaskElem;
7974 });
7975 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
7976 TreeEntry *TE = Op.second;
7977 if (!VisitedOps.insert(TE).second)
7978 continue;
7979 // TODO: Reordering of struct types is not supported.
7980 if (TE->State == TreeEntry::Vectorize &&
7981 isa<StructType>(getValueType(TE->Scalars.front(), Opts.slp_revec)))
7982 continue;
7983 if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
7984 reorderNodeWithReuses(*TE, Mask);
7985 continue;
7986 }
7987 // Gathers are processed separately.
7988 if (TE->State != TreeEntry::Vectorize &&
7989 TE->State != TreeEntry::StridedVectorize &&
7990 TE->State != TreeEntry::ExpandVectorize &&
7991 TE->State != TreeEntry::CompressVectorize &&
7992 TE->State != TreeEntry::BlendedLoadVectorize &&
7993 TE->State != TreeEntry::SplitVectorize &&
7994 (TE->State != TreeEntry::ScatterVectorize ||
7995 TE->ReorderIndices.empty()))
7996 continue;
7997 assert((BestOrder.size() == TE->ReorderIndices.size() ||
7998 TE->ReorderIndices.empty()) &&
7999 "Non-matching sizes of user/operand entries.");
8000 reorderOrder(TE->ReorderIndices, Mask);
8001 if (IgnoreReorder && TE == &getRootNode())
8002 IgnoreReorder = false;
8003 }
8004 // For gathers just need to reorder its scalars.
8005 for (TreeEntry *Gather : GatherOps) {
8006 assert(Gather->ReorderIndices.empty() &&
8007 "Unexpected reordering of gathers.");
8008 if (!Gather->ReuseShuffleIndices.empty()) {
8009 // Just reorder reuses indices.
8010 reorderReuses(Gather->ReuseShuffleIndices, Mask);
8011 continue;
8012 }
8013 // A ScatterVectorize (masked gather) node is scheduled, and the
8014 // scheduler reads its operand list at the same lane where the scalar
8015 // load sits, so Scalars and the operand list must stay aligned.
8016 // Record the reorder in ReorderIndices (applied by the final shuffle)
8017 // instead of physically permuting the scalars, matching how a scatter
8018 // node with a non-empty order is reordered above.
8019 if (Gather->State == TreeEntry::ScatterVectorize) {
8020 reorderOrder(Gather->ReorderIndices, Mask);
8021 Visited.insert(Gather);
8022 continue;
8023 }
8024 reorderScalars(Gather->Scalars, Mask);
8025 Visited.insert(Gather);
8026 }
8027 // Reorder operands of the user node and set the ordering for the user
8028 // node itself.
8029 auto IsNotProfitableAltCodeNode = [](const TreeEntry &TE) {
8030 return TE.isAltShuffle() &&
8031 (!TE.ReuseShuffleIndices.empty() || TE.getVectorFactor() == 2 ||
8032 TE.ReorderIndices.empty());
8033 };
8034 if (Data.first->State != TreeEntry::Vectorize ||
8036 Data.first->getMainOp()) ||
8037 IsNotProfitableAltCodeNode(*Data.first)) {
8038 Data.first->reorderOperands(Mask);
8040 }
8042 Data.first->getMainOp()) ||
8043 IsNotProfitableAltCodeNode(*Data.first) ||
8044 Data.first->State == TreeEntry::CompressVectorize) {
8045 reorderScalars(Data.first->Scalars, Mask);
8046 reorderOrder(Data.first->ReorderIndices, MaskOrder,
8047 /*BottomOrder=*/true);
8048 if (Data.first->ReuseShuffleIndices.empty() &&
8049 !Data.first->ReorderIndices.empty() &&
8050 !IsNotProfitableAltCodeNode(*Data.first)) {
8051 // Insert user node to the list to try to sink reordering deeper in
8052 // the graph.
8053 Queue.push(Data.first);
8054 }
8055 } else {
8056 reorderOrder(Data.first->ReorderIndices, Mask);
8057 }
8058 }
8059 }
8060 // If the reordering is unnecessary, just remove the reorder.
8061 if (IgnoreReorder && !getRootNode().ReorderIndices.empty() &&
8062 getRootNode().ReuseShuffleIndices.empty())
8063 getRootNode().ReorderIndices.clear();
8064}
8065
8066Instruction *BoUpSLP::getRootEntryInstruction(const TreeEntry &Entry) const {
8067 if (Entry.hasState() &&
8068 (Entry.getOpcode() == Instruction::Store ||
8069 Entry.getOpcode() == Instruction::Load) &&
8070 Entry.State == TreeEntry::StridedVectorize && Entry.isReverse() &&
8071 !isWidenedStridedLoad(&Entry))
8072 return dyn_cast<Instruction>(Entry.Scalars[Entry.ReorderIndices.front()]);
8073 return Entry.hasState() ? Entry.getMainOp()
8074 : dyn_cast<Instruction>(Entry.Scalars.front());
8075}
8076
8078 const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
8079 const size_t NumVectScalars = ScalarToTreeEntries.size() + 1;
8080 DenseMap<Value *, unsigned> ScalarToExtUses;
8081 // Peeled scalars still claimed by the tree (gathered, listed in some
8082 // entry's scalars, or modeled as a copyable element, which is emitted as
8083 // a scalar) survive as plain code, along with the peeled scalars
8084 // in their operand chains, which no vector node can rematerialize.
8085 KeptReassocScalars.clear();
8086 SmallVector<const Value *, 8> KeptWorklist;
8087 for (const auto &[V, Owners] : ReassocScalarToTreeEntries)
8088 if ((isGathered(V) || !getTreeEntries(V).empty() ||
8089 any_of(Owners,
8090 [V = V](const TreeEntry *TE) {
8091 return TE->isCopyableElement(const_cast<Value *>(V));
8092 })) &&
8093 KeptReassocScalars.insert(V).second)
8094 KeptWorklist.push_back(V);
8095 while (!KeptWorklist.empty()) {
8096 const Value *V = KeptWorklist.pop_back_val();
8097 for (const Value *Op : cast<Instruction>(V)->operand_values())
8098 if (ReassocScalarToTreeEntries.contains(Op) &&
8099 KeptReassocScalars.insert(Op).second)
8100 KeptWorklist.push_back(Op);
8101 }
8102 // The blended loads and the loads of the extracted aggregates use the
8103 // pointers of the out-of-tree instructions. If vectorized, these pointers
8104 // get erased, so all their uses must be replaced by the extracts.
8105 SmallPtrSet<Value *, 4> VectorLoadPtrs;
8106 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
8107 if (DeletedNodes.contains(TE.get()) ||
8108 TransformedToGatherNodes.contains(TE.get()))
8109 continue;
8110 if (TE->State == TreeEntry::BlendedLoadVectorize) {
8111 SelectInst *Sel = getBlendedLoadSelect(TE->Scalars);
8112 VectorLoadPtrs.insert({Sel->getTrueValue(), Sel->getFalseValue()});
8113 } else if (TE->State == TreeEntry::Vectorize &&
8114 TE->getOpcode() == Instruction::ExtractValue &&
8115 TE->StructEVIndices.empty()) {
8116 VectorLoadPtrs.insert(
8117 cast<LoadInst>(TE->getSingleOperand(0))->getPointerOperand());
8118 }
8119 }
8120 // Collect the values that we need to extract from the tree.
8121 for (auto &TEPtr : VectorizableTree) {
8122 TreeEntry *Entry = TEPtr.get();
8123
8124 // No need to handle users of gathered values.
8125 if (Entry->isGather() || Entry->State == TreeEntry::SplitVectorize ||
8126 DeletedNodes.contains(Entry) ||
8127 TransformedToGatherNodes.contains(Entry))
8128 continue;
8129
8130 // For each lane:
8131 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
8132 Value *Scalar = Entry->Scalars[Lane];
8133 if (!isa<Instruction>(Scalar) || Entry->isCopyableElement(Scalar))
8134 continue;
8135 bool IsStructScalar = isa<StructType>(Scalar->getType());
8136
8137 // All uses must be replaced already? No need to do it again.
8138 auto It = ScalarToExtUses.find(Scalar);
8139 if (It != ScalarToExtUses.end() && !ExternalUses[It->second].User)
8140 continue;
8141
8142 if (!IsStructScalar && (VectorLoadPtrs.contains(Scalar) ||
8143 Scalar->hasNUsesOrMore(NumVectScalars))) {
8144 unsigned FoundLane = Entry->findLaneForValue(Scalar);
8145 LLVM_DEBUG(dbgs() << "SLP: Need to extract from lane " << FoundLane
8146 << " from " << *Scalar << "for many users.\n");
8147 It = ScalarToExtUses.try_emplace(Scalar, ExternalUses.size()).first;
8148 ExternalUses.emplace_back(Scalar, nullptr, *Entry, FoundLane);
8149 ExternalUsesWithNonUsers.insert(Scalar);
8150 continue;
8151 }
8152
8153 // Check if the scalar is externally used as an extra arg.
8154 const auto ExtI = ExternallyUsedValues.find(Scalar);
8155 if (ExtI != ExternallyUsedValues.end()) {
8156 unsigned FoundLane = Entry->findLaneForValue(Scalar);
8157 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
8158 << FoundLane << " from " << *Scalar << ".\n");
8159 ScalarToExtUses.try_emplace(Scalar, ExternalUses.size());
8160 ExternalUses.emplace_back(Scalar, nullptr, *Entry, FoundLane);
8161 continue;
8162 }
8163 for (User *U : Scalar->users()) {
8164 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
8165
8166 Instruction *UserInst = dyn_cast<Instruction>(U);
8167 if (!UserInst || isDeleted(UserInst))
8168 continue;
8169
8170 // Ignore users in the user ignore list.
8171 if (UserIgnoreList && UserIgnoreList->contains(UserInst))
8172 continue;
8173
8174 // Peeled reassociated scalars are subsumed by the flattened node and
8175 // erased during vectorization, not external users. Kept ones survive
8176 // and their uses of erased scalars become extracts like any other.
8177 if (isReassocScalarVectorized(UserInst) &&
8178 !KeptReassocScalars.contains(UserInst)) {
8179 LLVM_DEBUG(dbgs() << "SLP: \tInternal (reassociated) user will be "
8180 "removed:"
8181 << *U << ".\n");
8182 continue;
8183 }
8184
8185 // The wide load of the copyable loads uses the pointer of the first
8186 // load.
8187 auto CIt = CopyableLoadsToTreeEntries.find(UserInst);
8188 const bool IsCopyableBasePtr =
8189 CIt != CopyableLoadsToTreeEntries.end() &&
8190 cast<LoadInst>(UserInst)->getPointerOperand() == Scalar &&
8191 any_of(CIt->second, [&](const TreeEntry *UseEntry) {
8192 return UseEntry->getFirstLoad() == UserInst &&
8193 !DeletedNodes.contains(UseEntry) &&
8194 !TransformedToGatherNodes.contains(UseEntry);
8195 });
8196 // Skip in-tree scalars that become vectors
8197 if (ArrayRef<TreeEntry *> UseEntries = getTreeEntries(U);
8198 IsCopyableBasePtr ||
8199 any_of(UseEntries, [this](const TreeEntry *UseEntry) {
8200 return !DeletedNodes.contains(UseEntry) &&
8201 !TransformedToGatherNodes.contains(UseEntry);
8202 })) {
8203 // Some in-tree scalars will remain as scalar in vectorized
8204 // instructions. If that is the case, the one in FoundLane will
8205 // be used.
8206 if (!IsCopyableBasePtr &&
8207 (!((Scalar->getType()->getScalarType()->isPointerTy() &&
8208 isa<LoadInst, StoreInst>(UserInst)) ||
8209 isa<CallInst>(UserInst)) ||
8210 all_of(UseEntries, [&](TreeEntry *UseEntry) {
8211 if (DeletedNodes.contains(UseEntry) ||
8212 TransformedToGatherNodes.contains(UseEntry))
8213 return true;
8214 return UseEntry->State == TreeEntry::ScatterVectorize ||
8216 Scalar, getRootEntryInstruction(*UseEntry), TLI,
8217 TTI);
8218 }))) {
8219 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
8220 << ".\n");
8221 assert(none_of(UseEntries,
8222 [](TreeEntry *UseEntry) {
8223 return UseEntry->isGather();
8224 }) &&
8225 "Bad state");
8226 continue;
8227 }
8228 if (!IsStructScalar) {
8229 U = nullptr;
8230 if (It != ScalarToExtUses.end()) {
8231 ExternalUses[It->second].User = nullptr;
8232 break;
8233 }
8234 }
8235 }
8236
8237 if (U && !IsStructScalar && Scalar->hasNUsesOrMore(UsesLimit))
8238 U = nullptr;
8239 unsigned FoundLane = Entry->findLaneForValue(Scalar);
8240 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *UserInst
8241 << " from lane " << FoundLane << " from " << *Scalar
8242 << ".\n");
8243 It = ScalarToExtUses.try_emplace(Scalar, ExternalUses.size()).first;
8244 ExternalUses.emplace_back(Scalar, U, *Entry, FoundLane);
8245 ExternalUsesWithNonUsers.insert(Scalar);
8246 if (!U)
8247 break;
8248 }
8249 }
8250 }
8251
8252 // The expansion of the runtime stride may reuse an in-tree instruction with
8253 // the matching SCEV, which gets erased upon vectorization. Register an
8254 // external use for it to replace the stride operand with the extract.
8256 for (const auto &[StridedTE, SPtrInfo] : TreeEntryToStridedPtrInfoMap)
8257 if (SPtrInfo.StrideSCEV && !SPtrInfo.StrideVal &&
8258 !DeletedNodes.contains(StridedTE) &&
8259 !TransformedToGatherNodes.contains(StridedTE))
8260 Strides.emplace_back(SPtrInfo.StrideSCEV,
8261 StridedTE->getMainOp()->getParent());
8262 if (Strides.empty())
8263 return;
8264 for (const std::unique_ptr<TreeEntry> &TEPtr : VectorizableTree) {
8265 TreeEntry *Entry = TEPtr.get();
8266 if (Entry->isGather() || Entry->State == TreeEntry::SplitVectorize ||
8267 DeletedNodes.contains(Entry) ||
8268 TransformedToGatherNodes.contains(Entry))
8269 continue;
8270 for (Instruction *Scalar : make_isa_range<Instruction>(Entry->Scalars)) {
8271 if (Entry->isCopyableElement(Scalar) ||
8272 !SE->isSCEVable(Scalar->getType()))
8273 continue;
8274 const SCEV *ScalarSCEV = SE->getSCEV(Scalar);
8275 if (isa<SCEVConstant>(ScalarSCEV) ||
8276 none_of(Strides, [&](const auto &Stride) {
8277 return DT->dominates(Scalar, Stride.second->getTerminator()) &&
8278 SCEVExprContains(Stride.first, [ScalarSCEV](const SCEV *S) {
8279 return S == ScalarSCEV;
8280 });
8281 }))
8282 continue;
8283 auto It = ScalarToExtUses.find(Scalar);
8284 if (It != ScalarToExtUses.end()) {
8285 // Replace all uses: the stride operand is emitted later, during the
8286 // codegen.
8287 ExternalUses[It->second].User = nullptr;
8288 continue;
8289 }
8290 unsigned FoundLane = Entry->findLaneForValue(Scalar);
8291 LLVM_DEBUG(dbgs() << "SLP: Need to extract: strided load stride from "
8292 "lane "
8293 << FoundLane << " from " << *Scalar << ".\n");
8294 ScalarToExtUses.try_emplace(Scalar, ExternalUses.size());
8295 ExternalUses.emplace_back(Scalar, nullptr, *Entry, FoundLane);
8296 ExternalUsesWithNonUsers.insert(Scalar);
8297 }
8298 }
8299}
8300
8302BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
8305 PtrToStoresMap;
8306 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
8307 Value *V = TE->Scalars[Lane];
8308 // Don't iterate over the users of constant data.
8309 if (!isa<Instruction>(V))
8310 continue;
8311 // To save compilation time we don't visit if we have too many users.
8312 if (V->hasNUsesOrMore(UsesLimit))
8313 break;
8314
8315 // Collect stores per pointer object.
8316 for (User *U : V->users()) {
8317 auto *SI = dyn_cast<StoreInst>(U);
8318 // Test whether we can handle the store. V might be a global, which could
8319 // be used in a different function.
8320 if (SI == nullptr || !SI->isSimple() || SI->getFunction() != F ||
8321 !isValidElementType(SI->getValueOperand()->getType(), Opts.slp_revec))
8322 continue;
8323 // Skip entry if already
8324 if (isVectorized(U))
8325 continue;
8326
8327 Value *Ptr = getUnderlyingObject(SI->getPointerOperand(),
8328 Opts.slp_recursion_max_depth);
8329 auto &StoresVec = PtrToStoresMap[{SI->getParent(),
8330 SI->getValueOperand()->getType(), Ptr}];
8331 // For now just keep one store per pointer object per lane.
8332 // TODO: Extend this to support multiple stores per pointer per lane
8333 if (StoresVec.size() > Lane)
8334 continue;
8335 if (!StoresVec.empty()) {
8336 std::optional<int64_t> Diff = getPointersDiff(
8337 SI->getValueOperand()->getType(), SI->getPointerOperand(),
8338 SI->getValueOperand()->getType(),
8339 StoresVec.front()->getPointerOperand(), *DL, *SE,
8340 /*StrictCheck=*/true);
8341 // We failed to compare the pointers so just abandon this store.
8342 if (!Diff)
8343 continue;
8344 }
8345 StoresVec.push_back(SI);
8346 }
8347 }
8348 SmallVector<SmallVector<StoreInst *>> Res(PtrToStoresMap.size());
8349 unsigned I = 0;
8350 for (auto &P : PtrToStoresMap) {
8351 Res[I].swap(P.second);
8352 ++I;
8353 }
8354 return Res;
8355}
8356
8357bool BoUpSLP::canFormVector(ArrayRef<StoreInst *> StoresVec,
8358 OrdersType &ReorderIndices) const {
8359 // We check whether the stores in StoreVec can form a vector by sorting them
8360 // and checking whether they are consecutive.
8361
8362 // To avoid calling getPointersDiff() while sorting we create a vector of
8363 // pairs {store, offset from first} and sort this instead.
8365 StoreInst *S0 = StoresVec[0];
8366 StoreOffsetVec.emplace_back(0, 0);
8367 Type *S0Ty = S0->getValueOperand()->getType();
8368 Value *S0Ptr = S0->getPointerOperand();
8369 for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
8370 StoreInst *SI = StoresVec[Idx];
8371 std::optional<int64_t> Diff =
8372 getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
8373 SI->getPointerOperand(), *DL, *SE,
8374 /*StrictCheck=*/true);
8375 StoreOffsetVec.emplace_back(*Diff, Idx);
8376 }
8377
8378 // Check if the stores are consecutive by checking if their difference is 1.
8379 if (StoreOffsetVec.size() != StoresVec.size())
8380 return false;
8381 sort(StoreOffsetVec, llvm::less_first());
8382 unsigned Idx = 0;
8383 int64_t PrevDist = 0;
8384 for (const auto &P : StoreOffsetVec) {
8385 if (Idx > 0 && P.first != PrevDist + 1)
8386 return false;
8387 PrevDist = P.first;
8388 ++Idx;
8389 }
8390
8391 // Calculate the shuffle indices according to their offset against the sorted
8392 // StoreOffsetVec.
8393 ReorderIndices.assign(StoresVec.size(), 0);
8394 bool IsIdentity = true;
8395 for (auto [I, P] : enumerate(StoreOffsetVec)) {
8396 ReorderIndices[P.second] = I;
8397 IsIdentity &= P.second == I;
8398 }
8399 // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
8400 // reorderTopToBottom() and reorderBottomToTop(), so we are following the
8401 // same convention here.
8402 if (IsIdentity)
8403 ReorderIndices.clear();
8404
8405 return true;
8406}
8407
8408#ifndef NDEBUG
8410 for (unsigned Idx : Order)
8411 dbgs() << Idx << ", ";
8412 dbgs() << "\n";
8413}
8414#endif
8415
8417BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
8418 unsigned NumLanes = TE->Scalars.size();
8419
8420 SmallVector<SmallVector<StoreInst *>> Stores = collectUserStores(TE);
8421
8422 // Holds the reorder indices for each candidate store vector that is a user of
8423 // the current TreeEntry.
8424 SmallVector<OrdersType, 1> ExternalReorderIndices;
8425
8426 // Now inspect the stores collected per pointer and look for vectorization
8427 // candidates. For each candidate calculate the reorder index vector and push
8428 // it into `ExternalReorderIndices`
8429 // If we have fewer than NumLanes stores, then we can't form a vector.
8430 for (ArrayRef<StoreInst *> StoresVec :
8431 make_filter_range(Stores, [&](ArrayRef<StoreInst *> StoresVec) {
8432 return StoresVec.size() == NumLanes;
8433 })) {
8434 // If the stores are not consecutive then abandon this StoresVec.
8435 OrdersType ReorderIndices;
8436 if (!canFormVector(StoresVec, ReorderIndices))
8437 continue;
8438
8439 // We now know that the scalars in StoresVec can form a vector instruction,
8440 // so set the reorder indices.
8441 ExternalReorderIndices.push_back(ReorderIndices);
8442 }
8443 return ExternalReorderIndices;
8444}
8445
8447 const SmallDenseSet<Value *> &UserIgnoreLst) {
8448 deleteTree();
8449 assert(TreeEntryToStridedPtrInfoMap.empty() &&
8450 "TreeEntryToStridedPtrInfoMap is not cleared");
8451 UserIgnoreList = &UserIgnoreLst;
8452 if (!allSameType(Roots))
8453 return;
8454 buildTreeRec(Roots, 0, EdgeInfo());
8455 // Build splat-gather subtrees here so the reordering passes cover them too.
8456 tryToVectorizeSplatGatheredScalars();
8457}
8458
8460 deleteTree();
8461 assert(TreeEntryToStridedPtrInfoMap.empty() &&
8462 "TreeEntryToStridedPtrInfoMap is not cleared");
8463 if (!allSameType(Roots))
8464 return;
8465 buildTreeRec(Roots, 0, EdgeInfo());
8466 // Build splat-gather subtrees here so the reordering passes cover them too.
8467 tryToVectorizeSplatGatheredScalars();
8468}
8469
8470/// Tries to find subvector of loads and builds new vector of only loads if can
8471/// be profitable.
8473 const BoUpSLP &R, ArrayRef<Value *> VL, const DataLayout &DL,
8475 SmallVectorImpl<SmallVector<std::pair<LoadInst *, int64_t>>> &GatheredLoads,
8476 bool AddNew = true) {
8477 if (VL.empty())
8478 return;
8479 Type *ScalarTy = getValueType(VL.front(), R.Opts.slp_revec);
8480 if (!isValidElementType(ScalarTy, R.Opts.slp_revec))
8481 return;
8483 SmallVector<DenseMap<int64_t, LoadInst *>> ClusteredDistToLoad;
8484 for (LoadInst *LI : make_isa_range<LoadInst>(VL)) {
8485 if (R.isDeleted(LI) || R.isVectorized(LI) || !LI->isSimple())
8486 continue;
8487 bool IsFound = false;
8488 for (auto [Map, Data] : zip(ClusteredDistToLoad, ClusteredLoads)) {
8489 assert(LI->getParent() == Data.front().first->getParent() &&
8490 LI->getType() == Data.front().first->getType() &&
8491 getUnderlyingObject(LI->getPointerOperand(),
8492 R.Opts.slp_recursion_max_depth) ==
8493 getUnderlyingObject(Data.front().first->getPointerOperand(),
8494 R.Opts.slp_recursion_max_depth) &&
8495 "Expected loads with the same type, same parent and same "
8496 "underlying pointer.");
8497 std::optional<int64_t> Dist = R.getPointersDiff(
8498 LI->getType(), LI->getPointerOperand(), Data.front().first->getType(),
8499 Data.front().first->getPointerOperand(), DL, SE,
8500 /*StrictCheck=*/true);
8501 if (!Dist)
8502 continue;
8503 auto It = Map.find(*Dist);
8504 if (It != Map.end() && It->second != LI)
8505 continue;
8506 if (It == Map.end()) {
8507 Data.emplace_back(LI, *Dist);
8508 Map.try_emplace(*Dist, LI);
8509 }
8510 IsFound = true;
8511 break;
8512 }
8513 if (!IsFound) {
8514 ClusteredLoads.emplace_back().emplace_back(LI, 0);
8515 ClusteredDistToLoad.emplace_back().try_emplace(0, LI);
8516 }
8517 }
8518 auto FindMatchingLoads =
8521 &GatheredLoads,
8523 int64_t &Offset, unsigned &Start) {
8524 if (Loads.empty())
8525 return GatheredLoads.end();
8526 LoadInst *LI = Loads.front().first;
8527 auto IsFromStart = [&](const auto &P) { return P.index() >= Start; };
8528 for (auto [Idx, Data] :
8529 make_filter_range(enumerate(GatheredLoads), IsFromStart)) {
8530 ToAdd.clear();
8531 if (LI->getType() != Data.front().first->getType())
8532 continue;
8533 std::optional<int64_t> Dist =
8534 R.getPointersDiff(LI->getType(), LI->getPointerOperand(),
8535 Data.front().first->getType(),
8536 Data.front().first->getPointerOperand(), DL, SE,
8537 /*StrictCheck=*/true);
8538 if (!Dist)
8539 continue;
8540 SmallSet<int64_t, 4> DataDists;
8542 for (std::pair<LoadInst *, int64_t> P : Data) {
8543 DataDists.insert(P.second);
8544 DataLoads.insert(P.first);
8545 }
8546 // Found matching gathered loads - check if all loads are unique or
8547 // can be effectively vectorized.
8548 unsigned NumUniques = 0;
8549 for (auto [Cnt, Pair] : enumerate(Loads)) {
8550 bool Used = DataLoads.contains(Pair.first);
8551 if (!Used && !DataDists.contains(*Dist + Pair.second)) {
8552 ++NumUniques;
8553 ToAdd.insert(Cnt);
8554 } else if (Used) {
8555 Repeated.insert(Cnt);
8556 }
8557 }
8558 if (NumUniques > 0 &&
8559 (Loads.size() == NumUniques ||
8560 (Loads.size() - NumUniques >= 2 &&
8561 Loads.size() - NumUniques >= Loads.size() / 2 &&
8562 (has_single_bit(Data.size() + NumUniques) ||
8563 bit_ceil(Data.size()) <
8564 bit_ceil(Data.size() + NumUniques))))) {
8565 Offset = *Dist;
8566 Start = Idx + 1;
8567 return std::next(GatheredLoads.begin(), Idx);
8568 }
8569 }
8570 ToAdd.clear();
8571 return GatheredLoads.end();
8572 };
8573 for (ArrayRef<std::pair<LoadInst *, int64_t>> Data : ClusteredLoads) {
8574 unsigned Start = 0;
8575 SetVector<unsigned> ToAdd, LocalToAdd, Repeated;
8576 int64_t Offset = 0;
8577 auto *It = FindMatchingLoads(Data, GatheredLoads, LocalToAdd, Repeated,
8578 Offset, Start);
8579 while (It != GatheredLoads.end()) {
8580 assert(!LocalToAdd.empty() && "Expected some elements to add.");
8581 for (unsigned Idx : LocalToAdd)
8582 It->emplace_back(Data[Idx].first, Data[Idx].second + Offset);
8583 ToAdd.insert_range(LocalToAdd);
8584 It = FindMatchingLoads(Data, GatheredLoads, LocalToAdd, Repeated, Offset,
8585 Start);
8586 }
8587 if (any_of(seq<unsigned>(Data.size()), [&](unsigned Idx) {
8588 return !ToAdd.contains(Idx) && !Repeated.contains(Idx);
8589 })) {
8590 auto AddNewLoads =
8592 for (unsigned Idx : seq<unsigned>(Data.size())) {
8593 if (ToAdd.contains(Idx) || Repeated.contains(Idx))
8594 continue;
8595 Loads.push_back(Data[Idx]);
8596 }
8597 };
8598 if (!AddNew) {
8599 LoadInst *LI = Data.front().first;
8600 It = find_if(GatheredLoads,
8601 [&](ArrayRef<std::pair<LoadInst *, int64_t>> PD) {
8602 return PD.front().first->getType() == LI->getType();
8603 });
8604 while (It != GatheredLoads.end()) {
8605 AddNewLoads(*It);
8606 It = std::find_if(std::next(It), GatheredLoads.end(),
8607 [&](ArrayRef<std::pair<LoadInst *, int64_t>> PD) {
8608 return PD.front().first->getType() ==
8609 LI->getType();
8610 });
8611 }
8612 }
8613 GatheredLoads.emplace_back().append(Data.begin(), Data.end());
8614 AddNewLoads(GatheredLoads.emplace_back());
8615 }
8616 }
8617}
8618
8619void BoUpSLP::tryToVectorizeGatheredLoads(
8620 const SmallMapVector<
8621 std::tuple<BasicBlock *, Value *, Type *>,
8622 SmallVector<SmallVector<std::pair<LoadInst *, int64_t>>>, 8>
8623 &GatheredLoads) {
8624 GatheredLoadsEntriesFirst = VectorizableTree.size();
8625
8626 SmallVector<SmallPtrSet<const Value *, 4>> LoadSetsToVectorize(
8627 LoadEntriesToVectorize.size());
8628 for (auto [Idx, Set] : zip(LoadEntriesToVectorize, LoadSetsToVectorize))
8629 Set.insert_range(VectorizableTree[Idx]->Scalars);
8630
8631 // Sort loads by distance.
8632 auto LoadSorter = [](const std::pair<LoadInst *, int64_t> &L1,
8633 const std::pair<LoadInst *, int64_t> &L2) {
8634 return L1.second > L2.second;
8635 };
8636
8637 auto IsMaskedGatherSupported = [&, TTI = TTI](ArrayRef<LoadInst *> Loads) {
8638 ArrayRef<Value *> Values(reinterpret_cast<Value *const *>(Loads.begin()),
8639 Loads.size());
8641 auto *Ty = cast<VectorType>(
8642 getWidenedType(Loads.front()->getType(), Loads.size()));
8643 return TTI->isLegalMaskedGather(Ty, Alignment) &&
8644 !TTI->forceScalarizeMaskedGather(Ty, Alignment);
8645 };
8646
8647 auto GetVectorizedRanges = [this](ArrayRef<LoadInst *> Loads,
8648 BoUpSLP::ValueSet &VectorizedLoads,
8649 SmallVectorImpl<LoadInst *> &NonVectorized,
8650 bool Final, unsigned MaxVF) {
8652 unsigned StartIdx = 0;
8653 SmallVector<int> CandidateVFs;
8654 if (isAllowedNonPowerOf2VF(MaxVF, Opts.slp_vectorize_non_power_of_2))
8655 CandidateVFs.push_back(MaxVF);
8656 for (int NumElts = getFloorFullVectorNumberOfElements(
8657 *TTI, Loads.front()->getType(), MaxVF, Opts.slp_revec);
8658 NumElts > 1;
8660 *TTI, Loads.front()->getType(), NumElts - 1, Opts.slp_revec)) {
8661 CandidateVFs.push_back(NumElts);
8662 if (Opts.slp_vectorize_non_power_of_2 && NumElts > 2)
8663 CandidateVFs.push_back(NumElts - 1);
8664 }
8665
8666 if (Final && CandidateVFs.empty())
8667 return Results;
8668
8669 unsigned BestVF = Final ? CandidateVFs.back() : 0;
8670 auto IsValidVF = [&](unsigned VF) { return !Final || VF <= BestVF; };
8671 for (unsigned NumElts : make_filter_range(CandidateVFs, IsValidVF)) {
8672 SmallVector<unsigned> MaskedGatherVectorized;
8673 for (unsigned Cnt = StartIdx, E = Loads.size(); Cnt < E;
8674 ++Cnt) {
8675 ArrayRef<LoadInst *> Slice =
8676 ArrayRef(Loads).slice(Cnt, std::min(NumElts, E - Cnt));
8677 if (VectorizedLoads.count(Slice.front()) ||
8678 VectorizedLoads.count(Slice.back()) ||
8680 continue;
8681 // Check if it is profitable to try vectorizing gathered loads. It is
8682 // profitable if we have more than 3 consecutive loads or if we have
8683 // less but all users are vectorized or deleted.
8684 bool AllowToVectorize = false;
8685 // Check if it is profitable to vectorize 2-elements loads.
8686 if (NumElts == 2) {
8687 bool IsLegalBroadcastLoad = TTI->isLegalBroadcastLoad(
8688 Slice.front()->getType(), ElementCount::getFixed(NumElts));
8689 auto CheckIfAllowed = [=](ArrayRef<LoadInst *> Slice) {
8690 // If single use/user - allow to vectorize.
8691 auto IsNotSingleUse = [](LoadInst *LI) { return !LI->hasOneUse(); };
8692 for (LoadInst *LI : make_filter_range(Slice, IsNotSingleUse)) {
8693 // 1. Check if number of uses equals number of users.
8694 // 2. All users are deleted.
8695 // 3. The load broadcasts are not allowed or the load is not
8696 // broadcasted.
8697 if (static_cast<unsigned int>(std::distance(
8698 LI->user_begin(), LI->user_end())) != LI->getNumUses())
8699 return false;
8700 if (!IsLegalBroadcastLoad)
8701 continue;
8702 if (LI->hasNUsesOrMore(UsesLimit))
8703 return false;
8704 for (User *U : LI->users()) {
8705 if (auto *UI = dyn_cast<Instruction>(U); UI && isDeleted(UI))
8706 continue;
8707 for (const TreeEntry *UTE : getTreeEntries(U)) {
8708 for (int I : seq<int>(UTE->getNumOperands())) {
8709 if (all_of(UTE->getOperand(I), [LI](Value *V) {
8710 return V == LI || isa<PoisonValue>(V);
8711 }))
8712 // Found legal broadcast - do not vectorize.
8713 return false;
8714 }
8715 }
8716 }
8717 }
8718 return true;
8719 };
8720 AllowToVectorize = CheckIfAllowed(Slice);
8721 } else {
8722 AllowToVectorize =
8723 NumElts >= 3 ||
8724 any_of(ValueToGatherNodes.at(Slice.front()),
8725 [=](const TreeEntry *TE) {
8726 return TE->Scalars.size() == 2 &&
8727 ((TE->Scalars.front() == Slice.front() &&
8728 TE->Scalars.back() == Slice.back()) ||
8729 (TE->Scalars.front() == Slice.back() &&
8730 TE->Scalars.back() == Slice.front()));
8731 });
8732 }
8733 if (AllowToVectorize) {
8734 SmallVector<Value *> PointerOps;
8735 OrdersType CurrentOrder;
8736 // Try to build vector load.
8738 reinterpret_cast<Value *const *>(Slice.begin()), Slice.size());
8739 StridedPtrInfo SPtrInfo;
8740 LoadsState LS = canVectorizeLoads(Values, Slice.front(), CurrentOrder,
8741 PointerOps, SPtrInfo, &BestVF);
8742 if (LS != LoadsState::Gather ||
8743 (BestVF > 1 && static_cast<unsigned>(NumElts) == 2 * BestVF)) {
8744 if (LS == LoadsState::ScatterVectorize) {
8745 if (MaskedGatherVectorized.empty() ||
8746 Cnt >= MaskedGatherVectorized.back() + NumElts)
8747 MaskedGatherVectorized.push_back(Cnt);
8748 continue;
8749 }
8750 if (LS != LoadsState::Gather) {
8751 Results.emplace_back(Values, LS);
8752 VectorizedLoads.insert_range(Slice);
8753 // If we vectorized initial block, no need to try to vectorize it
8754 // again.
8755 if (Cnt == StartIdx)
8756 StartIdx += NumElts;
8757 }
8758 // Check if the whole array was vectorized already - exit.
8759 if (StartIdx >= Loads.size())
8760 break;
8761 // Erase last masked gather candidate, if another candidate within
8762 // the range is found to be better.
8763 if (!MaskedGatherVectorized.empty() &&
8764 Cnt < MaskedGatherVectorized.back() + NumElts)
8765 MaskedGatherVectorized.pop_back();
8766 Cnt += NumElts - 1;
8767 continue;
8768 }
8769 }
8770 if (!AllowToVectorize || BestVF == 0)
8772 }
8773 // Mark masked gathers candidates as vectorized, if any.
8774 for (unsigned Cnt : MaskedGatherVectorized) {
8775 ArrayRef<LoadInst *> Slice = ArrayRef(Loads).slice(
8776 Cnt, std::min<unsigned>(NumElts, Loads.size() - Cnt));
8778 reinterpret_cast<Value *const *>(Slice.begin()), Slice.size());
8780 VectorizedLoads.insert_range(Slice);
8781 // If we vectorized initial block, no need to try to vectorize it again.
8782 if (Cnt == StartIdx)
8783 StartIdx += NumElts;
8784 }
8785 }
8786 for (LoadInst *LI : Loads) {
8787 if (!VectorizedLoads.contains(LI))
8788 NonVectorized.push_back(LI);
8789 }
8790 return Results;
8791 };
8792 auto ProcessGatheredLoads =
8793 [&, &TTI = *TTI](
8795 bool Final = false) {
8796 SmallVector<LoadInst *> NonVectorized;
8797 for (ArrayRef<std::pair<LoadInst *, int64_t>> LoadsDists :
8798 GatheredLoads) {
8799 if (LoadsDists.size() <= 1) {
8800 NonVectorized.push_back(LoadsDists.back().first);
8801 continue;
8802 }
8804 LoadsDists);
8805 SmallVector<LoadInst *> OriginalLoads(make_first_range(LoadsDists));
8806 stable_sort(LocalLoadsDists, LoadSorter);
8808 unsigned MaxConsecutiveDistance = 0;
8809 unsigned CurrentConsecutiveDist = 1;
8810 int64_t LastDist = LocalLoadsDists.front().second;
8811 bool AllowMaskedGather = IsMaskedGatherSupported(OriginalLoads);
8812 auto IsNotVectorized = [&](const std::pair<LoadInst *, int64_t> &L) {
8813 return !isVectorized(L.first);
8814 };
8815 for (const std::pair<LoadInst *, int64_t> &L :
8816 make_filter_range(LocalLoadsDists, IsNotVectorized)) {
8817 assert(LastDist >= L.second &&
8818 "Expected first distance always not less than second");
8819 if (static_cast<uint64_t>(LastDist - L.second) ==
8820 CurrentConsecutiveDist) {
8821 ++CurrentConsecutiveDist;
8822 MaxConsecutiveDistance =
8823 std::max(MaxConsecutiveDistance, CurrentConsecutiveDist);
8824 Loads.push_back(L.first);
8825 continue;
8826 }
8827 if (!AllowMaskedGather && CurrentConsecutiveDist == 1 &&
8828 !Loads.empty())
8829 Loads.pop_back();
8830 CurrentConsecutiveDist = 1;
8831 LastDist = L.second;
8832 Loads.push_back(L.first);
8833 }
8834 if (Loads.size() <= 1)
8835 continue;
8836 if (AllowMaskedGather)
8837 MaxConsecutiveDistance = Loads.size();
8838 else if (MaxConsecutiveDistance < 2)
8839 continue;
8840 BoUpSLP::ValueSet VectorizedLoads;
8841 SmallVector<LoadInst *> SortedNonVectorized;
8843 GetVectorizedRanges(Loads, VectorizedLoads, SortedNonVectorized,
8844 Final, MaxConsecutiveDistance);
8845 if (!Results.empty() && !SortedNonVectorized.empty() &&
8846 OriginalLoads.size() == Loads.size() &&
8847 MaxConsecutiveDistance == Loads.size() &&
8849 [](const std::pair<ArrayRef<Value *>, LoadsState> &P) {
8850 return P.second == LoadsState::ScatterVectorize;
8851 })) {
8852 VectorizedLoads.clear();
8853 SmallVector<LoadInst *> UnsortedNonVectorized;
8855 UnsortedResults =
8856 GetVectorizedRanges(OriginalLoads, VectorizedLoads,
8857 UnsortedNonVectorized, Final,
8858 OriginalLoads.size());
8859 if (SortedNonVectorized.size() >= UnsortedNonVectorized.size()) {
8860 SortedNonVectorized.swap(UnsortedNonVectorized);
8861 Results.swap(UnsortedResults);
8862 }
8863 }
8865 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize gathered loads ("
8866 << Slice.size() << ")\n");
8867 if (any_of(Slice, [&](Value *V) { return isVectorized(V); })) {
8868 for (Value *L : Slice)
8869 if (!isVectorized(L))
8870 SortedNonVectorized.push_back(cast<LoadInst>(L));
8871 continue;
8872 }
8873
8874 // Select maximum VF as a maximum of user gathered nodes and
8875 // distance between scalar loads in these nodes.
8876 unsigned MaxVF = Slice.size();
8877 unsigned UserMaxVF = 0;
8878 unsigned InterleaveFactor = 0;
8879 if (MaxVF == 2) {
8880 UserMaxVF = MaxVF;
8881 } else {
8882 // Found distance between segments of the interleaved loads.
8883 std::optional<unsigned> InterleavedLoadsDistance = 0;
8884 unsigned Order = 0;
8885 std::optional<unsigned> CommonVF = 0;
8886 DenseMap<const TreeEntry *, unsigned> EntryToPosition;
8887 SmallPtrSet<const TreeEntry *, 8> DeinterleavedNodes;
8888 for (auto [Idx, V] : enumerate(Slice)) {
8889 for (const TreeEntry *E : ValueToGatherNodes.at(V)) {
8890 UserMaxVF = std::max<unsigned>(UserMaxVF, E->Scalars.size());
8891 unsigned Pos =
8892 EntryToPosition.try_emplace(E, Idx).first->second;
8893 UserMaxVF = std::max<unsigned>(UserMaxVF, Idx - Pos + 1);
8894 if (CommonVF) {
8895 if (*CommonVF == 0) {
8896 CommonVF = E->Scalars.size();
8897 continue;
8898 }
8899 if (*CommonVF != E->Scalars.size())
8900 CommonVF.reset();
8901 }
8902 // Check if the load is the part of the interleaved load.
8903 if (Pos != Idx && InterleavedLoadsDistance) {
8904 if (!DeinterleavedNodes.contains(E) &&
8905 any_of(E->Scalars, [&, Slice = Slice](Value *V) {
8906 if (isa<Constant>(V))
8907 return false;
8908 if (isVectorized(V))
8909 return true;
8910 const auto &Nodes = ValueToGatherNodes.at(V);
8911 return (Nodes.size() != 1 || !Nodes.contains(E)) &&
8912 !is_contained(Slice, V);
8913 })) {
8914 InterleavedLoadsDistance.reset();
8915 continue;
8916 }
8917 DeinterleavedNodes.insert(E);
8918 if (*InterleavedLoadsDistance == 0) {
8919 InterleavedLoadsDistance = Idx - Pos;
8920 continue;
8921 }
8922 if ((Idx - Pos) % *InterleavedLoadsDistance != 0 ||
8923 (Idx - Pos) / *InterleavedLoadsDistance < Order)
8924 InterleavedLoadsDistance.reset();
8925 Order = (Idx - Pos) / InterleavedLoadsDistance.value_or(1);
8926 }
8927 }
8928 }
8929 DeinterleavedNodes.clear();
8930 // Check if the large load represents interleaved load operation.
8931 if (InterleavedLoadsDistance.value_or(0) > 1 &&
8932 CommonVF.value_or(0) != 0) {
8933 InterleaveFactor = bit_ceil(*InterleavedLoadsDistance);
8934 unsigned VF = *CommonVF;
8935 OrdersType Order;
8936 SmallVector<Value *> PointerOps;
8937 StridedPtrInfo SPtrInfo;
8938 // Segmented load detected - vectorize at maximum vector factor.
8939 if (InterleaveFactor <= Slice.size() &&
8940 TTI.isLegalInterleavedAccessType(
8942 getWidenedType(Slice.front()->getType(), VF)),
8943 InterleaveFactor,
8944 cast<LoadInst>(Slice.front())->getAlign(),
8945 cast<LoadInst>(Slice.front())
8946 ->getPointerAddressSpace()) &&
8947 canVectorizeLoads(Slice, Slice.front(), Order, PointerOps,
8948 SPtrInfo) == LoadsState::Vectorize) {
8949 UserMaxVF = InterleaveFactor * VF;
8950 } else {
8951 InterleaveFactor = 0;
8952 }
8953 }
8954 // Cannot represent the loads as consecutive vectorizable nodes -
8955 // just exit.
8956 unsigned ConsecutiveNodesSize = 0;
8957 if (!LoadEntriesToVectorize.empty() && InterleaveFactor == 0 &&
8958 any_of(zip(LoadEntriesToVectorize, LoadSetsToVectorize),
8959 [&, Slice = Slice](const auto &P) {
8960 const auto *It = find_if(Slice, [&](Value *V) {
8961 return std::get<1>(P).contains(V);
8962 });
8963 if (It == Slice.end())
8964 return false;
8965 const TreeEntry &TE =
8966 *VectorizableTree[std::get<0>(P)];
8967 ArrayRef<Value *> VL = TE.Scalars;
8968 OrdersType Order;
8969 SmallVector<Value *> PointerOps;
8970 StridedPtrInfo SPtrInfo;
8972 VL, VL.front(), Order, PointerOps, SPtrInfo);
8973 if (State == LoadsState::ScatterVectorize ||
8976 return false;
8977 ConsecutiveNodesSize += VL.size();
8978 size_t Start = std::distance(Slice.begin(), It);
8979 size_t Sz = Slice.size() - Start;
8980 return Sz < VL.size() ||
8981 Slice.slice(Start, VL.size()) != VL;
8982 }))
8983 continue;
8984 // Try to build long masked gather loads.
8985 UserMaxVF = bit_ceil(UserMaxVF);
8986 if (InterleaveFactor == 0 &&
8987 any_of(seq<unsigned>(Slice.size() / UserMaxVF),
8988 [&, Slice = Slice](unsigned Idx) {
8989 OrdersType Order;
8990 SmallVector<Value *> PointerOps;
8991 StridedPtrInfo SPtrInfo;
8992 return canVectorizeLoads(
8993 Slice.slice(Idx * UserMaxVF, UserMaxVF),
8994 Slice[Idx * UserMaxVF], Order, PointerOps,
8995 SPtrInfo) == LoadsState::ScatterVectorize;
8996 }))
8997 UserMaxVF = MaxVF;
8998 if (Slice.size() != ConsecutiveNodesSize)
8999 MaxVF = std::min<unsigned>(MaxVF, UserMaxVF);
9000 }
9001 for (unsigned VF = MaxVF; VF >= 2; VF /= 2) {
9002 bool IsVectorized = true;
9003 for (unsigned I = 0, E = Slice.size(); I < E; I += VF) {
9004 ArrayRef<Value *> SubSlice =
9005 Slice.slice(I, std::min(VF, E - I));
9006 if (isVectorized(SubSlice.front()))
9007 continue;
9008 // Check if the subslice is to be-vectorized entry, which is not
9009 // equal to entry.
9010 if (any_of(zip(LoadEntriesToVectorize, LoadSetsToVectorize),
9011 [&](const auto &P) {
9012 return !SubSlice.equals(
9013 VectorizableTree[std::get<0>(P)]
9014 ->Scalars) &&
9015 set_is_subset(SubSlice, std::get<1>(P));
9016 }))
9017 continue;
9018 unsigned Sz = VectorizableTree.size();
9019 // A chunk smaller than InterleaveFactor cannot form an
9020 // interleave group; keep it non-interleaved instead.
9021 buildTreeRec(
9022 SubSlice, 0, EdgeInfo(),
9023 SubSlice.size() >= InterleaveFactor ? InterleaveFactor : 0);
9024 if (Sz == VectorizableTree.size()) {
9025 IsVectorized = false;
9026 // Try non-interleaved vectorization with smaller vector
9027 // factor.
9028 if (InterleaveFactor > 0) {
9029 VF = 2 * (MaxVF / InterleaveFactor);
9030 InterleaveFactor = 0;
9031 }
9032 continue;
9033 }
9034 }
9035 if (IsVectorized)
9036 break;
9037 }
9038 }
9039 NonVectorized.append(SortedNonVectorized);
9040 }
9041 return NonVectorized;
9042 };
9043 for (const auto &GLs : GatheredLoads) {
9044 const auto &Ref = GLs.second;
9045 SmallVector<LoadInst *> NonVectorized = ProcessGatheredLoads(Ref);
9046 if (!Ref.empty() && !NonVectorized.empty() &&
9047 accumulate(
9048 Ref, 0u,
9049 [](unsigned S, ArrayRef<std::pair<LoadInst *, int64_t>> LoadsDists)
9050 -> unsigned { return S + LoadsDists.size(); }) !=
9051 NonVectorized.size() &&
9052 IsMaskedGatherSupported(NonVectorized)) {
9054 FinalGatheredLoads;
9055 for (LoadInst *LI : NonVectorized) {
9056 // Reinsert non-vectorized loads to other list of loads with the same
9057 // base pointers.
9058 gatherPossiblyVectorizableLoads(*this, LI, *DL, *SE, *TTI,
9059 FinalGatheredLoads,
9060 /*AddNew=*/false);
9061 }
9062 // Final attempt to vectorize non-vectorized loads.
9063 (void)ProcessGatheredLoads(FinalGatheredLoads, /*Final=*/true);
9064 }
9065 }
9066 // Try to vectorize postponed load entries, previously marked as gathered.
9067 for (unsigned Idx : LoadEntriesToVectorize) {
9068 const TreeEntry &E = *VectorizableTree[Idx];
9069 SmallVector<Value *> GatheredScalars(E.Scalars.begin(), E.Scalars.end());
9070 // Avoid reordering, if possible.
9071 if (!E.ReorderIndices.empty()) {
9072 // Build a mask out of the reorder indices and reorder scalars per this
9073 // mask.
9074 SmallVector<int> ReorderMask;
9075 inversePermutation(E.ReorderIndices, ReorderMask);
9076 reorderScalars(GatheredScalars, ReorderMask);
9077 }
9078 buildTreeRec(GatheredScalars, 0, EdgeInfo());
9079 }
9080 // If no new entries created, consider it as no gathered loads entries must be
9081 // handled.
9082 if (static_cast<unsigned>(*GatheredLoadsEntriesFirst) ==
9083 VectorizableTree.size())
9084 GatheredLoadsEntriesFirst.reset();
9085}
9086
9087/// Generates key/subkey pair for the given value to provide effective sorting
9088/// of the values and better detection of the vectorizable values sequences. The
9089/// keys/subkeys can be used for better sorting of the values themselves (keys)
9090/// and in values subgroups (subkeys).
9091static std::pair<size_t, size_t> generateKeySubkey(
9092 Value *V, const TargetLibraryInfo *TLI,
9093 function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
9094 bool AllowAlternate) {
9095 hash_code Key = hash_value(V->getValueID() + 2);
9096 hash_code SubKey = hash_value(0);
9097 // Sort the loads by the distance between the pointers.
9098 if (auto *LI = dyn_cast<LoadInst>(V)) {
9099 Key = hash_combine(LI->getType(), hash_value(Instruction::Load), Key);
9100 if (LI->isSimple())
9101 SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
9102 else
9103 Key = SubKey = hash_value(LI);
9104 } else if (isVectorLikeInstWithConstOps(V)) {
9105 // Sort extracts by the vector operands.
9107 Key = hash_value(Value::UndefValueVal + 1);
9108 if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
9109 if (!isUndefVector(EI->getVectorOperand()).all() &&
9110 !isa<UndefValue>(EI->getIndexOperand()))
9111 SubKey = hash_value(EI->getVectorOperand());
9112 }
9113 } else if (auto *I = dyn_cast<Instruction>(V)) {
9114 // Sort other instructions just by the opcodes except for CMPInst.
9115 // For CMP also sort by the predicate kind.
9117 isValidForAlternation(I->getOpcode())) {
9118 if (AllowAlternate)
9119 Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
9120 else
9121 Key = hash_combine(hash_value(I->getOpcode()), Key);
9122 SubKey = hash_combine(
9123 hash_value(I->getOpcode()), hash_value(I->getType()),
9125 ? I->getType()
9126 : cast<CastInst>(I)->getOperand(0)->getType()));
9127 // For casts, look through the only operand to improve compile time.
9128 if (isa<CastInst>(I)) {
9129 std::pair<size_t, size_t> OpVals =
9130 generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator,
9131 /*AllowAlternate=*/true);
9132 Key = hash_combine(OpVals.first, Key);
9133 SubKey = hash_combine(OpVals.first, SubKey);
9134 }
9135 } else if (auto *CI = dyn_cast<CmpInst>(I)) {
9136 CmpInst::Predicate Pred = CI->getPredicate();
9137 if (CI->isCommutative())
9140 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
9141 hash_value(SwapPred),
9142 hash_value(CI->getOperand(0)->getType()));
9143 } else if (auto *Call = dyn_cast<CallInst>(I)) {
9145 if (isTriviallyVectorizable(ID)) {
9146 if (ID == Intrinsic::fmuladd)
9147 ID = Intrinsic::fma;
9148 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID),
9149 hash_value(I->getType()));
9150 } else if (!VFDatabase(*Call).getMappings(*Call).empty()) {
9151 SubKey = hash_combine(hash_value(I->getOpcode()),
9152 hash_value(Call->getCalledFunction()),
9153 hash_value(I->getType()));
9154 } else {
9156 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
9157 }
9158 for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
9159 SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
9160 hash_value(Op.Tag), SubKey);
9161 } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
9162 if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
9163 SubKey = hash_value(Gep->getPointerOperand());
9164 else
9165 SubKey = hash_value(Gep);
9166 } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
9167 !isa<ConstantInt>(I->getOperand(1))) {
9168 // Do not try to vectorize instructions with potentially high cost.
9169 SubKey = hash_value(I);
9170 } else {
9171 SubKey =
9172 hash_combine(hash_value(I->getOpcode()), hash_value(I->getType()));
9173 }
9174 Key = hash_combine(hash_value(I->getParent()->getNumber()), Key);
9175 }
9176 return std::make_pair(Key, SubKey);
9177}
9178
9179/// Checks if the specified instruction \p I is an main operation for the given
9180/// \p MainOp and \p AltOp instructions.
9181static bool isMainInstruction(Instruction *I, Instruction *MainOp,
9182 Instruction *AltOp, const TargetLibraryInfo &TLI);
9183
9184namespace {
9185/// Groups poor-throughput seeds for tryToVectorizeSequence.
9186struct SeedGroupKey {
9187 unsigned Opcode = 0;
9189 StringRef CalleeName;
9190
9191 bool less(const SeedGroupKey &O) const {
9192 if (Opcode != O.Opcode)
9193 return Opcode < O.Opcode;
9194 if (IntrID != O.IntrID)
9195 return IntrID < O.IntrID;
9196 return CalleeName < O.CalleeName;
9197 }
9198};
9199
9200static SeedGroupKey getSeedGroupKey(const Instruction *I,
9201 const TargetLibraryInfo &TLI) {
9202 SeedGroupKey K;
9203 K.Opcode = I->getOpcode();
9204 if (auto *CI = dyn_cast<CallInst>(I)) {
9205 K.IntrID = getVectorIntrinsicIDForCall(CI, &TLI);
9206 if (const Function *F = CI->getCalledFunction())
9207 K.CalleeName = F->getName();
9208 }
9209 return K;
9210}
9211} // namespace
9212
9213/// Get the loop nest for the given loop.
9214ArrayRef<const Loop *> BoUpSLP::getLoopNest(const Loop *L) {
9215 assert(L && "Expected valid loop");
9216 if (Opts.slp_cost_loop_trip_count == 0)
9217 return {};
9218 SmallVector<const Loop *> &Res =
9219 LoopToLoopNest.try_emplace(L).first->getSecond();
9220 if (!Res.empty())
9221 return Res;
9222 SmallVector<const Loop *> LoopNest;
9223 while (L) {
9224 LoopNest.push_back(L);
9225 L = L->getParentLoop();
9226 }
9227 Res.assign(LoopNest.rbegin(), LoopNest.rend());
9228 return Res;
9229}
9230
9232 return all_of(VL, [](Value *V) {
9233 return !isa<StructType>(V->getType()) ||
9235 });
9236}
9237
9238BoUpSLP::TreeEntry::EntryState BoUpSLP::getScalarsVectorizationState(
9239 const InstructionsState &S, ArrayRef<Value *> VL,
9240 bool IsScatterVectorizeUserTE, OrdersType &CurrentOrder,
9241 SmallVectorImpl<Value *> &PointerOps, StridedPtrInfo &SPtrInfo,
9242 SmallVectorImpl<int> &ReuseShuffleIndices) {
9243 assert(S.getMainOp() &&
9244 "Expected instructions with same/alternate opcodes only.");
9245
9246 unsigned ShuffleOrOp =
9247 S.isAltShuffle() ? (unsigned)Instruction::ShuffleVector : S.getOpcode();
9248 Instruction *VL0 = S.getMainOp();
9249 switch (ShuffleOrOp) {
9250 case Instruction::PHI: {
9251 // Too many operands - gather, most probably won't be vectorized.
9252 if (VL0->getNumOperands() > MaxPHINumOperands)
9253 return TreeEntry::NeedToGather;
9254 // Check for terminator values (e.g. invoke).
9255 for (PHINode *PHI : make_isa_range<PHINode>(VL)) {
9256 for (Instruction *Term :
9257 make_isa_range<Instruction>(PHI->incoming_values())) {
9258 if (Term->isTerminator()) {
9260 << "SLP: Need to swizzle PHINodes (terminator use).\n");
9261 return TreeEntry::NeedToGather;
9262 }
9263 }
9264 }
9265
9266 return TreeEntry::Vectorize;
9267 }
9268 case Instruction::ExtractElement:
9269 if (any_of(VL, [&](Value *V) {
9271 return false;
9272 auto *EI = dyn_cast<ExtractElementInst>(V);
9273 if (!EI)
9274 return true;
9275 Value *Op = EI->getOperand(0);
9276 if (isVectorized(Op))
9277 return true;
9278 auto *OpI = dyn_cast<Instruction>(Op);
9279 return OpI && OpI->isTerminator();
9280 }))
9281 return TreeEntry::NeedToGather;
9282 [[fallthrough]];
9283 case Instruction::ExtractValue: {
9284 bool Reuse = canReuseExtract(VL, CurrentOrder);
9285 // Copyable lanes are inserted into the reused source vector at their own
9286 // index, which is correct only for the identity extract order (empty
9287 // CurrentOrder) and without a reuse shuffle; other cases fall back to
9288 // gather.
9290 (!Reuse || !ReuseShuffleIndices.empty()))
9291 return TreeEntry::NeedToGather;
9292 if (Reuse || !CurrentOrder.empty())
9293 return TreeEntry::Vectorize;
9294 SmallVector<unsigned> Indices;
9296 if (ShuffleOrOp == Instruction::ExtractValue &&
9297 checkEVsForVecCalls(VL, S, *TLI, Indices, Calls))
9298 return TreeEntry::Vectorize;
9299 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
9300 return TreeEntry::NeedToGather;
9301 }
9302 case Instruction::InsertValue:
9303 // Handle only simple insertvalue building a homogeneous aggregate from
9304 // scalars: exactly one index and an inserted value whose type is a valid
9305 // vector element type. Vectors and aggregates (structs/arrays) are
9306 // rejected, since the inserted operand type is later widened into the
9307 // result FixedVectorType.
9308 // TODO: Support more complex insertvalues.
9310 [&](InsertValueInst *IV) {
9311 return IV->getNumIndices() != 1 ||
9312 !::isValidElementType(IV->getOperand(1)->getType(),
9313 Opts.slp_revec) ||
9314 IV->getOperand(1)->getType()->isVectorTy();
9315 }) ||
9316 none_of(make_isa_range<InsertValueInst>(VL), [](InsertValueInst *IV) {
9317 return isa<UndefValue>(IV->getAggregateOperand());
9318 }))
9319 return TreeEntry::NeedToGather;
9320 [[fallthrough]];
9321 case Instruction::InsertElement: {
9322 // Check that we have a buildvector and not a shuffle of 2 or more
9323 // different vectors.
9324 ValueSet SourceVectors;
9325 for (Value *V : VL) {
9326 if (isa<PoisonValue>(V)) {
9327 LLVM_DEBUG(
9328 dbgs()
9329 << "SLP: Gather of insertelement/insertvalue/poison vector.\n");
9330 return TreeEntry::NeedToGather;
9331 }
9332 SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
9333 assert(getElementIndex(V) != std::nullopt &&
9334 "Non-constant or undef index?");
9335 }
9336
9337 if (count_if(VL, [&SourceVectors](Value *V) {
9338 return !SourceVectors.contains(V);
9339 }) >= 2) {
9340 // Found 2nd source vector - cancel.
9341 LLVM_DEBUG(
9342 dbgs() << "SLP: Gather of insertelement/insertvalue vectors with "
9343 "different source vectors.\n");
9344 return TreeEntry::NeedToGather;
9345 }
9346
9347 if (any_of(VL, [&SourceVectors](Value *V) {
9348 // The last InsertElement/InsertValue can have multiple uses.
9349 return SourceVectors.contains(V) && !V->hasOneUse();
9350 })) {
9351 assert((Opts.slp_revec || ShuffleOrOp == Instruction::InsertValue) &&
9352 "Only supported by REVEC or InsertValue.");
9353 LLVM_DEBUG(
9354 dbgs() << "SLP: Gather of insertelement/insertvalue vectors with "
9355 "multiple uses.\n");
9356 return TreeEntry::NeedToGather;
9357 }
9358
9359 return TreeEntry::Vectorize;
9360 }
9361 case Instruction::Load: {
9362 // Check that a vectorized load would load the same memory as a scalar
9363 // load. For example, we don't want to vectorize loads that are smaller
9364 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
9365 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
9366 // from such a struct, we read/write packed bits disagreeing with the
9367 // unvectorized version.
9368 auto IsGatheredNode = [&]() {
9369 if (!GatheredLoadsEntriesFirst)
9370 return false;
9371 return all_of(VL, [&](Value *V) {
9372 if (isa<PoisonValue>(V))
9373 return true;
9374 return any_of(getTreeEntries(V), [&](const TreeEntry *TE) {
9375 return TE->Idx >= *GatheredLoadsEntriesFirst;
9376 });
9377 });
9378 };
9379 LoadsState LS =
9380 canVectorizeLoads(VL, VL0, CurrentOrder, PointerOps, SPtrInfo);
9381 // The copyable loads from the predecessor block are covered only by the
9382 // consecutive wide load in the successor block.
9383 for (auto *LI : make_isa_range<LoadInst>(VL))
9384 if (S.isCopyableElement(LI) &&
9385 (LS != LoadsState::Vectorize ||
9386 isLoadMemoryModified(LI, VL0->getParent())))
9387 return TreeEntry::NeedToGather;
9388 switch (LS) {
9390 return TreeEntry::Vectorize;
9392 if (!IsGraphTransformMode && VectorizableTree.size() > 1) {
9393 // Delay slow vectorized nodes for better vectorization attempts.
9394 LoadEntriesToVectorize.insert(VectorizableTree.size());
9395 return TreeEntry::NeedToGather;
9396 }
9397 return IsGatheredNode() ? TreeEntry::NeedToGather
9398 : TreeEntry::CompressVectorize;
9400 if (!IsGraphTransformMode && VectorizableTree.size() > 1) {
9401 // Delay slow vectorized nodes for better vectorization attempts.
9402 LoadEntriesToVectorize.insert(VectorizableTree.size());
9403 return TreeEntry::NeedToGather;
9404 }
9405 return IsGatheredNode() ? TreeEntry::NeedToGather
9406 : TreeEntry::ScatterVectorize;
9408 if (!IsGraphTransformMode && VectorizableTree.size() > 1) {
9409 // Delay slow vectorized nodes for better vectorization attempts.
9410 LoadEntriesToVectorize.insert(VectorizableTree.size());
9411 return TreeEntry::NeedToGather;
9412 }
9413 return IsGatheredNode() ? TreeEntry::NeedToGather
9414 : TreeEntry::StridedVectorize;
9416 if (!IsGraphTransformMode && VectorizableTree.size() > 1) {
9417 // Delay slow vectorized nodes for better vectorization attempts.
9418 LoadEntriesToVectorize.insert(VectorizableTree.size());
9419 return TreeEntry::NeedToGather;
9420 }
9421 return IsGatheredNode() ? TreeEntry::NeedToGather
9422 : TreeEntry::BlendedLoadVectorize;
9423 case LoadsState::Gather:
9424#ifndef NDEBUG
9425 Type *ScalarTy = VL0->getType();
9426 if (DL->getTypeSizeInBits(ScalarTy) !=
9427 DL->getTypeAllocSizeInBits(ScalarTy))
9428 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
9429 else if (any_of(VL, [](Value *V) {
9430 auto *LI = dyn_cast<LoadInst>(V);
9431 return !LI || !LI->isSimple();
9432 }))
9433 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
9434 else
9435 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
9436#endif // NDEBUG
9438 return TreeEntry::NeedToGather;
9439 }
9440 llvm_unreachable("Unexpected state of loads");
9441 }
9442 case Instruction::ZExt:
9443 case Instruction::SExt:
9444 case Instruction::FPToUI:
9445 case Instruction::FPToSI:
9446 case Instruction::FPExt:
9447 case Instruction::PtrToInt:
9448 case Instruction::PtrToAddr:
9449 case Instruction::IntToPtr:
9450 case Instruction::SIToFP:
9451 case Instruction::UIToFP:
9452 case Instruction::Trunc:
9453 case Instruction::FPTrunc:
9454 case Instruction::BitCast: {
9455 Type *SrcTy = VL0->getOperand(0)->getType();
9456 for (Instruction *I : make_isa_range<Instruction>(VL)) {
9457 Type *Ty = I->getOperand(0)->getType();
9458 if (Ty != SrcTy || !isValidElementType(Ty, Opts.slp_revec)) {
9459 LLVM_DEBUG(
9460 dbgs() << "SLP: Gathering casts with different src types.\n");
9461 return TreeEntry::NeedToGather;
9462 }
9463 }
9464 return TreeEntry::Vectorize;
9465 }
9466 case Instruction::ICmp:
9467 case Instruction::FCmp: {
9468 // Check that all of the compares have the same predicate.
9469 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
9471 Type *ComparedTy = VL0->getOperand(0)->getType();
9472 for (CmpInst *Cmp : make_isa_range<CmpInst>(VL)) {
9473 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0 &&
9475 Cmp->getOperand(0)->getType() != ComparedTy) {
9476 LLVM_DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
9477 return TreeEntry::NeedToGather;
9478 }
9479 }
9480 return TreeEntry::Vectorize;
9481 }
9482 case Instruction::Select:
9483 if (Opts.slp_revec) {
9484 SmallPtrSet<Type *, 4> CondTypes;
9485 for (Value *V : VL) {
9486 Value *Cond;
9487 if (!match(V, m_Select(m_Value(Cond), m_Value(), m_Value())) &&
9488 !match(V, m_ZExt(m_Value(Cond))))
9489 continue;
9490 CondTypes.insert(Cond->getType());
9491 }
9492 if (CondTypes.size() > 1) {
9493 LLVM_DEBUG(
9494 dbgs()
9495 << "SLP: Gathering select with different condition types.\n");
9496 return TreeEntry::NeedToGather;
9497 }
9498 }
9499 [[fallthrough]];
9500 case Instruction::FNeg:
9501 case Instruction::Add:
9502 case Instruction::FAdd:
9503 case Instruction::Sub:
9504 case Instruction::FSub:
9505 case Instruction::Mul:
9506 case Instruction::FMul:
9507 case Instruction::UDiv:
9508 case Instruction::SDiv:
9509 case Instruction::FDiv:
9510 case Instruction::URem:
9511 case Instruction::SRem:
9512 case Instruction::FRem:
9513 case Instruction::Shl:
9514 case Instruction::LShr:
9515 case Instruction::AShr:
9516 case Instruction::And:
9517 case Instruction::Or:
9518 case Instruction::Xor:
9519 case Instruction::Freeze:
9520 if (S.getMainOp()->getType()->isFloatingPointTy() &&
9521 TTI->isFPVectorizationPotentiallyUnsafe() &&
9523 [](BinaryOperator *BO) { return !BO->isFast(); }))
9524 return TreeEntry::NeedToGather;
9525 return TreeEntry::Vectorize;
9526 case Instruction::GetElementPtr: {
9527 auto IsMatchingLane = [&S](Value *V) { return !S.isCopyableElement(V); };
9528 // We don't combine GEPs with complicated (nested) indexing.
9529 for (GetElementPtrInst *GEP : make_filter_range(
9530 make_isa_range<GetElementPtrInst>(VL), IsMatchingLane)) {
9531 if (GEP->getNumOperands() != 2) {
9532 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
9533 return TreeEntry::NeedToGather;
9534 }
9535 }
9536
9537 // We can't combine several GEPs into one vector if they operate on
9538 // different types.
9539 Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
9540 for (GEPOperator *GEP :
9541 make_filter_range(make_isa_range<GEPOperator>(VL), IsMatchingLane)) {
9542 Type *CurTy = GEP->getSourceElementType();
9543 if (Ty0 != CurTy) {
9544 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
9545 return TreeEntry::NeedToGather;
9546 }
9547 }
9548
9549 // We don't combine GEPs with non-constant indexes.
9550 Type *Ty1 = VL0->getOperand(1)->getType();
9551 for (GetElementPtrInst *GEP : make_filter_range(
9552 make_isa_range<GetElementPtrInst>(VL), IsMatchingLane)) {
9553 auto *Op = GEP->getOperand(1);
9554 if ((!IsScatterVectorizeUserTE && !isa<ConstantInt>(Op)) ||
9555 (Op->getType() != Ty1 &&
9556 Op->getType()->getScalarSizeInBits() >
9557 DL->getIndexSizeInBits(
9558 GEP->getType()->getPointerAddressSpace()))) {
9559 LLVM_DEBUG(
9560 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
9561 return TreeEntry::NeedToGather;
9562 }
9563 }
9564 // The indices must be representable in a single type, the operands
9565 // builder casts the constants to it.
9567 VL, VL0,
9568 [&S](Value *V) {
9570 },
9571 *DL)) {
9572 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (mixed index types).\n");
9573 return TreeEntry::NeedToGather;
9574 }
9575
9576 return TreeEntry::Vectorize;
9577 }
9578 case Instruction::Store: {
9579 // Check if the stores are consecutive or if we need to swizzle them.
9580 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
9581 // Avoid types that are padded when being allocated as scalars, while
9582 // being packed together in a vector (such as i1).
9583 if (DL->getTypeSizeInBits(ScalarTy) !=
9584 DL->getTypeAllocSizeInBits(ScalarTy)) {
9585 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
9586 return TreeEntry::NeedToGather;
9587 }
9588 // Make sure all stores in the bundle are simple - we can't vectorize
9589 // atomic or volatile stores.
9590 for (Value *V : VL) {
9591 auto *SI = cast<StoreInst>(V);
9592 if (!SI->isSimple()) {
9593 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
9594 return TreeEntry::NeedToGather;
9595 }
9596 PointerOps.push_back(SI->getPointerOperand());
9597 }
9598
9599 // Check the order of pointer operands.
9600 if (Cache.sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
9601 Value *Ptr0;
9602 Value *PtrN;
9603 if (CurrentOrder.empty()) {
9604 Ptr0 = PointerOps.front();
9605 PtrN = PointerOps.back();
9606 } else {
9607 Ptr0 = PointerOps[CurrentOrder.front()];
9608 PtrN = PointerOps[CurrentOrder.back()];
9609 }
9610 Align CommonAlignment = computeCommonAlignment<StoreInst>(VL);
9611 std::optional<int64_t> Dist =
9612 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
9613 // Check that the sorted pointer operands are consecutive.
9614 if (static_cast<uint64_t>(*Dist) == VL.size() - 1)
9615 return TreeEntry::Vectorize;
9616 if (Opts.slp_enable_strided_stores &&
9617 analyzeConstantStrideCandidate(PointerOps, ScalarTy, CommonAlignment,
9618 CurrentOrder, *Dist, Ptr0, SPtrInfo))
9619 return TreeEntry::StridedVectorize;
9620 // If the stores are not consecutive but the target supports masked stores
9621 // for the widened type, lower them as a masked store.
9622 FixedVectorType *StoreVecTy = nullptr;
9623 if (Opts.slp_enable_masked_stores &&
9624 isMaskedStoreCompress(VL, PointerOps, CurrentOrder, *TTI, *DL, *SE,
9625 CommonAlignment, ReuseShuffleIndices,
9626 StoreVecTy, Cache)) {
9627 SPtrInfo.Ty = StoreVecTy;
9628 return TreeEntry::ExpandVectorize;
9629 }
9630 }
9631
9632 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
9633 return TreeEntry::NeedToGather;
9634 }
9635 case Instruction::Call: {
9636 if (S.getMainOp()->getType()->isFloatingPointTy() &&
9637 TTI->isFPVectorizationPotentiallyUnsafe() &&
9639 [](FPMathOperator *FPOp) { return !FPOp->isFast(); }))
9640 return TreeEntry::NeedToGather;
9641 // Check if the calls are all to the same vectorizable intrinsic or
9642 // library function.
9643 CallInst *CI = cast<CallInst>(VL0);
9645
9646 VFShape Shape = VFShape::get(
9647 CI->getFunctionType(),
9648 ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
9649 false /*HasGlobalPred*/);
9650 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
9651
9652 if (!VecFunc && !isTriviallyVectorizable(ID)) {
9653 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
9654 return TreeEntry::NeedToGather;
9655 }
9656 if (isa<StructType>(CI->getType()) &&
9658 LLVM_DEBUG(dbgs() << "SLP: Struct-returning calls have non-extractvalue "
9659 "users.\n");
9660 return TreeEntry::NeedToGather;
9661 }
9662 Function *F = CI->getCalledFunction();
9663 unsigned NumArgs = CI->arg_size();
9664 SmallVector<Value *, 4> ScalarArgs(NumArgs, nullptr);
9665 for (unsigned J = 0; J != NumArgs; ++J)
9666 if (isVectorIntrinsicWithScalarOpAtArg(ID, J, TTI))
9667 ScalarArgs[J] = CI->getArgOperand(J);
9668 // Skip copyables (idempotent stand-ins) and poisons.
9669 for (Value *V : make_filter_range(VL, [&](Value *V) {
9670 return !isa<PoisonValue>(V) && !S.isCopyableElement(V);
9671 })) {
9672 CallInst *CI2 = dyn_cast<CallInst>(V);
9673 Intrinsic::ID ID2 = CI2 ? getVectorIntrinsicIDForCall(CI2, TLI)
9675 Intrinsic::ID Equivalent = isEquivalentIntrinsicID(ID, ID2);
9676 if (!CI2 ||
9677 (CI2->getCalledFunction() != F &&
9678 isEquivalentIntrinsicID(Equivalent, Intrinsic::fmuladd) ==
9680 (ID != ID2 && Equivalent == Intrinsic::not_intrinsic) ||
9681 (VecFunc &&
9682 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
9684 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
9685 << "\n");
9686 return TreeEntry::NeedToGather;
9687 }
9688 // Some intrinsics have scalar arguments and should be same in order for
9689 // them to be vectorized.
9690 for (unsigned J = 0; J != NumArgs; ++J) {
9691 if (isVectorIntrinsicWithScalarOpAtArg(ID, J, TTI)) {
9692 Value *A1J = CI2->getArgOperand(J);
9693 if (ScalarArgs[J] != A1J) {
9695 << "SLP: mismatched arguments in call:" << *CI
9696 << " argument " << ScalarArgs[J] << "!=" << A1J << "\n");
9697 return TreeEntry::NeedToGather;
9698 }
9699 }
9700 }
9701 // Verify that the bundle operands are identical between the two calls.
9702 if (CI->hasOperandBundles() &&
9703 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
9704 CI->op_begin() + CI->getBundleOperandsEndIndex(),
9705 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
9706 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI
9707 << "!=" << *V << '\n');
9708 return TreeEntry::NeedToGather;
9709 }
9710 }
9711 SmallVector<Type *> ArgTys =
9712 buildIntrinsicArgTypes(CI, ID, VL.size(), 0, *TTI);
9713 auto *VecTy = getWidenedType(S.getMainOp()->getType(), VL.size());
9714 auto VecCallCosts =
9715 getVectorCallCosts(CI, VecTy, *TTI, *TLI, ArgTys, CostKind);
9716 if (!VecCallCosts.first.isValid() && !VecCallCosts.second.isValid())
9717 return TreeEntry::NeedToGather;
9718
9719 return TreeEntry::Vectorize;
9720 }
9721 case Instruction::ShuffleVector: {
9722 if (!S.isAltShuffle()) {
9723 // REVEC can support non alternate shuffle.
9724 if (Opts.slp_revec && getShufflevectorNumGroups(VL))
9725 return TreeEntry::Vectorize;
9726 // If this is not an alternate sequence of opcode like add-sub
9727 // then do not vectorize this instruction.
9728 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
9729 return TreeEntry::NeedToGather;
9730 }
9731
9732 return TreeEntry::Vectorize;
9733 }
9734 default:
9735 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
9736 return TreeEntry::NeedToGather;
9737 }
9738}
9739
9740namespace {
9741/// Allows to correctly handle operands of the phi nodes based on the \p Main
9742/// PHINode order of incoming basic blocks/values.
9743class PHIHandler {
9744 DominatorTree &DT;
9745 PHINode *Main = nullptr;
9748
9749public:
9750 PHIHandler() = delete;
9751 PHIHandler(DominatorTree &DT, PHINode *Main, ArrayRef<Value *> Phis)
9752 : DT(DT), Main(Main), Phis(Phis),
9753 Operands(Main->getNumIncomingValues(),
9754 SmallVector<Value *>(Phis.size(), nullptr)) {}
9755 void buildOperands() {
9756 constexpr unsigned FastLimit = 4;
9757 if (Main->getNumIncomingValues() <= FastLimit) {
9758 for (unsigned I : seq<unsigned>(0, Main->getNumIncomingValues())) {
9759 BasicBlock *InBB = Main->getIncomingBlock(I);
9760 if (!DT.isReachableFromEntry(InBB)) {
9761 Operands[I].assign(Phis.size(), PoisonValue::get(Main->getType()));
9762 continue;
9763 }
9764 // Prepare the operand vector.
9765 for (auto [Idx, V] : enumerate(Phis)) {
9766 auto *P = dyn_cast<PHINode>(V);
9767 if (!P) {
9769 "Expected isa instruction or poison value.");
9770 Operands[I][Idx] = V;
9771 continue;
9772 }
9773 if (P->getIncomingBlock(I) == InBB)
9774 Operands[I][Idx] = P->getIncomingValue(I);
9775 else
9776 Operands[I][Idx] = P->getIncomingValueForBlock(InBB);
9777 }
9778 }
9779 return;
9780 }
9781 SmallMapVector<BasicBlock *, SmallVector<unsigned>, 4>
9782 Blocks;
9783 for (unsigned I : seq<unsigned>(Main->getNumIncomingValues())) {
9784 BasicBlock *InBB = Main->getIncomingBlock(I);
9785 if (!DT.isReachableFromEntry(InBB)) {
9786 Operands[I].assign(Phis.size(), PoisonValue::get(Main->getType()));
9787 continue;
9788 }
9789 Blocks.try_emplace(InBB).first->second.push_back(I);
9790 }
9791 for (auto [Idx, V] : enumerate(Phis)) {
9792 if (isa<PoisonValue>(V)) {
9793 for (unsigned I : seq<unsigned>(Main->getNumIncomingValues()))
9794 Operands[I][Idx] = V;
9795 continue;
9796 }
9797 auto *P = cast<PHINode>(V);
9798 for (unsigned I : seq<unsigned>(P->getNumIncomingValues())) {
9799 BasicBlock *InBB = P->getIncomingBlock(I);
9800 if (InBB == Main->getIncomingBlock(I)) {
9802 continue;
9803 Operands[I][Idx] = P->getIncomingValue(I);
9804 continue;
9805 }
9806 auto *It = Blocks.find(InBB);
9807 if (It == Blocks.end())
9808 continue;
9809 Operands[It->second.front()][Idx] = P->getIncomingValue(I);
9810 }
9811 }
9812 for (const auto &P : Blocks) {
9813 ArrayRef<unsigned> IncomingValues = P.second;
9814 if (IncomingValues.size() <= 1)
9815 continue;
9816 unsigned BasicI = IncomingValues.consume_front();
9817 for (unsigned I : IncomingValues) {
9819 [&](const auto &Data) {
9820 return !Data.value() ||
9821 Data.value() == Operands[BasicI][Data.index()];
9822 }) &&
9823 "Expected empty operands list.");
9824 Operands[I] = Operands[BasicI];
9825 }
9826 }
9827 }
9828 ArrayRef<Value *> getOperands(unsigned I) const { return Operands[I]; }
9829};
9830} // namespace
9831
9832/// Checks that every instruction appears once in the list and if not, packs
9833/// them, building \p ReuseShuffleIndices mask and mutating \p VL. The list of
9834/// unique scalars is extended by poison values to the whole register size.
9835///
9836/// \returns false if \p VL could not be uniquified, in which case \p VL is
9837/// unchanged and \p ReuseShuffleIndices is empty.
9838static bool tryToFindDuplicates(const VectorizeOptions &Opts,
9840 SmallVectorImpl<int> &ReuseShuffleIndices,
9841 const TargetTransformInfo &TTI,
9842 const TargetLibraryInfo &TLI,
9843 const InstructionsState &S,
9844 const BoUpSLP::EdgeInfo &UserTreeIdx,
9845 const BoUpSLP &R, bool BuildGatherOnly = true) {
9846 // TODO: Reordering of struct types is not supported.
9847 if (isa<StructType>(getValueType(VL.front(), Opts.slp_revec))) {
9848 LLVM_DEBUG(dbgs() << "SLP: struct type in bundle.\n");
9849 ReuseShuffleIndices.clear();
9850 return true;
9851 }
9852 // Check that every instruction appears once in this bundle.
9853 SmallVector<Value *> UniqueValues;
9854 SmallDenseMap<Value *, unsigned, 16> UniquePositions(VL.size());
9855 for (Value *V : VL) {
9856 if (isConstant(V)) {
9857 // Constants are always considered distinct, even if the same constant
9858 // appears multiple times in VL.
9859 ReuseShuffleIndices.emplace_back(
9860 isa<PoisonValue>(V) ? PoisonMaskElem : UniqueValues.size());
9861 UniqueValues.emplace_back(V);
9862 continue;
9863 }
9864 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
9865 ReuseShuffleIndices.emplace_back(Res.first->second);
9866 if (Res.second)
9867 UniqueValues.emplace_back(V);
9868 }
9869 // All the values are unique and there are no tail poisons to drop.
9870 if (UniqueValues.size() == VL.size() &&
9871 !isa<PoisonValue>(UniqueValues.back())) {
9872 ReuseShuffleIndices.clear();
9873 return true;
9874 }
9875
9876 // Check if we need to schedule the scalars. If no, can keep original scalars
9877 // and avoid extra shuffles.
9878 bool RequireScheduling = S && S.getOpcode() != Instruction::PHI &&
9881 !doesNotNeedToSchedule(UniqueValues));
9882 // Compute this flag BEFORE the tail-poison erase below - it must reflect
9883 // the state of the original VL (for the InsertsCost call), not the
9884 // potentially-shrunk UniqueValues.
9885 bool AreAllValuesNonConst = UniquePositions.size() == UniqueValues.size();
9886 // Drop tail poisons, if the values can be vectorized.
9887 if (RequireScheduling) {
9888 const auto EndIt =
9889 find_if_not(make_range(UniqueValues.rbegin(), UniqueValues.rend()),
9891 assert(EndIt != UniqueValues.rend() && "Expected at least one non-poison.");
9892 UniqueValues.erase(EndIt.base(), UniqueValues.end());
9893 }
9894 unsigned NumUniqueScalarValues = UniqueValues.size();
9895 if (NumUniqueScalarValues == VL.size()) {
9896 ReuseShuffleIndices.clear();
9897 return true;
9898 }
9899
9900 // For VL=4 with 3 unique values: keep originals. A <3 x T> vector is
9901 // always widened to <4 x T> on hardware, so the packing just adds an
9902 // extra expand shuffle. Does not apply to loads (a <3 x T> load is a
9903 // single memory access) or PHIs (benefit from compact packing in loops).
9904 constexpr unsigned SmallVecWidth = 4;
9905 constexpr unsigned SmallVecUniqueThreshold = 3;
9906 if (VL.size() == SmallVecWidth &&
9907 NumUniqueScalarValues == SmallVecUniqueThreshold && !BuildGatherOnly &&
9908 !(S && (S.getOpcode() == Instruction::Load ||
9909 S.getOpcode() == Instruction::PHI))) {
9910 // Keep originals with identity reuse - no packing, no extra shuffle.
9911 ReuseShuffleIndices.clear();
9912 return true;
9913 }
9914
9915 // Checks if unique inserts + shuffle is more profitable than just inserts or
9916 // vectorized values.
9917 auto EstimatePackPlusShuffleVsInserts = [&]() {
9918 // Single instruction/argument insert - no shuffle.
9919 if (UniquePositions.size() == 1 &&
9920 (NumUniqueScalarValues == 1 ||
9922 return std::make_pair(false, false);
9923 // For large gathers with power-of-2 VL where packing would produce
9924 // non-power-of-2, reject if most scalars are constants - the packing
9925 // overhead (non-power-of-2 split + shuffles) outweighs the benefit.
9926 constexpr unsigned MinVLForConstGatherCheck = 4;
9927 if (BuildGatherOnly && VL.size() > MinVLForConstGatherCheck &&
9928 has_single_bit(static_cast<unsigned>(VL.size())) &&
9929 !has_single_bit(NumUniqueScalarValues) &&
9930 UniquePositions.size() * 2 < NumUniqueScalarValues)
9931 return std::make_pair(false, false);
9932 auto GetLoadsState = [&](ArrayRef<Value *> Loads) {
9933 assert(S && S.getOpcode() == Instruction::Load && "Expected load.");
9934 BoUpSLP::OrdersType Order;
9935 SmallVector<Value *> PointerOps;
9936 BoUpSLP::StridedPtrInfo SPtrInfo;
9937 return R.canVectorizeLoads(Loads, S.getMainOp(), Order, PointerOps,
9938 SPtrInfo);
9939 };
9940 auto CheckLoads = [&](ArrayRef<Value *> Loads, bool IncludeGather) {
9941 BoUpSLP::LoadsState Res = GetLoadsState(Loads);
9942 return (IncludeGather && Res == BoUpSLP::LoadsState::Gather) ||
9947 };
9948 // Operand of the root tree entry on the vectorize path: always pack the
9949 // scalars (PackProfitable=true). Choose between keeping the original VL
9950 // and packing the unique values:
9951 // - For loads, prefer the originals only when both the deduplicated and
9952 // the full sequence can be vectorized non-Gather, or when the reuse
9953 // mask is the identity (the shuffle is free).
9954 // - For everything else (including !S, where RequireScheduling is forced
9955 // to false above), keep originals iff no scheduling is required.
9956 bool IsRootOperand =
9957 UserTreeIdx.UserTE && UserTreeIdx.UserTE->Idx == 0 && !BuildGatherOnly;
9958 if (IsRootOperand) {
9959 if (S && S.getOpcode() == Instruction::Load) {
9960 bool UseOrig = (CheckLoads(UniqueValues, /*IncludeGather=*/true) &&
9961 CheckLoads(VL, /*IncludeGather=*/false)) ||
9963 ReuseShuffleIndices, ReuseShuffleIndices.size());
9964 return std::make_pair(true, UseOrig);
9965 }
9966 return std::make_pair(true, !RequireScheduling);
9967 }
9968 APInt DemandedElts = APInt::getZero(VL.size());
9969 for (auto [Idx, Val] : enumerate(ReuseShuffleIndices))
9970 if (Val != PoisonMaskElem && UniquePositions.contains(UniqueValues[Val]))
9971 DemandedElts.setBit(Idx);
9972 Type *ScalarTy = ::getValueType(UniqueValues.front(), Opts.slp_revec);
9973 auto *VecTy = cast<VectorType>(getWidenedType(ScalarTy, VL.size()));
9974 auto *UniquesVecTy =
9975 cast<VectorType>(getWidenedType(ScalarTy, NumUniqueScalarValues));
9976 const unsigned NumParts = R.getNumberOfParts(VecTy, ScalarTy);
9977 const unsigned UniquesNumParts = R.getNumberOfParts(UniquesVecTy, ScalarTy);
9978 // No need to schedule scalars and only single register used? Use original
9979 // scalars, do not pack.
9980 if (!RequireScheduling) {
9981 if (VL.size() / NumUniqueScalarValues == 1 &&
9983 return std::make_pair(true, true);
9984 // For PHI operands, prefer packing with reuse shuffle - the PHI
9985 // carries the vector through the loop cheaply.
9986 if (S && S.getOpcode() == Instruction::PHI && NumUniqueScalarValues > 1 &&
9987 UniquesNumParts <= NumParts)
9988 return std::make_pair(true, false);
9989 }
9990 const TTI::TargetCostKind CostKind = R.getCostKind();
9991 InstructionCost ReusesCost = getShuffleCost(
9992 TTI, TTI::SK_PermuteSingleSrc, VecTy, CostKind,
9993 NumUniqueScalarValues > VL.size() / 2 ? ArrayRef<int>()
9994 : ArrayRef(ReuseShuffleIndices),
9995 /*Index=*/0, UniquesVecTy);
9996 // For vectorizable (non-gather) nodes with low duplication, prefer keeping
9997 // the original values over packing uniques + reshuffling:
9998 // - A single duplicate (non-load) adds negligible overhead.
9999 // - When most values are already unique (>50%), or exactly half are unique
10000 // for some ops (GEPs, non-alt-shuffle casts), the reshuffle cost may
10001 // exceed the savings from a smaller packed vector - check against a
10002 // per-register-part threshold (stricter for wider vectors).
10003 if (S && !BuildGatherOnly) {
10004 bool HasOneDup = S.getOpcode() != Instruction::Load &&
10005 NumUniqueScalarValues + 1 == VL.size();
10006 bool MostlyUnique = NumUniqueScalarValues * 2 > VL.size();
10007 bool IsHalfUniqueValues =
10008 NumUniqueScalarValues * 2 == VL.size() &&
10009 (S.getOpcode() == Instruction::GetElementPtr ||
10010 (isa<CastInst>(S.getMainOp()) && !S.isAltShuffle()));
10011 InstructionCost CostThreshold =
10012 NumParts * (VL.size() > SmallVecWidth ? 1 : 2);
10013 if (HasOneDup ||
10014 ((MostlyUnique || IsHalfUniqueValues) && ReusesCost > CostThreshold))
10015 return std::make_pair(true, true);
10016 }
10017 // For loads, check if either the deduplicated or the full (with
10018 // duplicates) set can be scatter/compress-vectorized. Prefer the unique
10019 // loads (pack + reshuffle) when possible, otherwise use the originals.
10020 if (S && S.getOpcode() == Instruction::Load) {
10021 // The poison lanes are covered by a single wide load, nothing to pack.
10022 if (any_of(VL, IsaPred<PoisonValue>) &&
10023 GetLoadsState(VL) == BoUpSLP::LoadsState::Vectorize)
10024 return std::make_pair(true, true);
10025 bool UniquesVectorized =
10026 CheckLoads(UniqueValues, /*IncludeGather=*/false);
10027 if (UniquesVectorized || CheckLoads(VL, /*IncludeGather=*/false)) {
10028 bool UseOriginal = !UniquesVectorized;
10029 // The unique loads are consecutive: pack them unless the masked
10030 // gather of the originals is cheaper than the wide load + reshuffle.
10031 if (UseOriginal &&
10032 GetLoadsState(UniqueValues) == BoUpSLP::LoadsState::Vectorize) {
10033 auto *LI0 = cast<LoadInst>(S.getMainOp());
10034 InstructionCost PackCost =
10035 ReusesCost + TTI.getMemoryOpCost(
10036 Instruction::Load, UniquesVecTy, LI0->getAlign(),
10037 LI0->getPointerAddressSpace(), CostKind,
10038 TTI::getOperandInfo(LI0->getPointerOperand()));
10039 InstructionCost GatherCost = TTI.getMemIntrinsicInstrCost(
10041 Intrinsic::masked_gather, VecTy, LI0->getPointerOperand(),
10042 /*VariableMask=*/false, computeCommonAlignment<LoadInst>(VL)),
10043 CostKind);
10044 UseOriginal = GatherCost < PackCost;
10045 }
10046 return std::make_pair(true, UseOriginal);
10047 }
10048 }
10049 bool CanSkipBVCost =
10050 (!BuildGatherOnly && !RequireScheduling) || R.hasSameNode(S, VL);
10051 InstructionCost InsertsCost =
10052 CanSkipBVCost
10054 : getScalarizationOverhead(TTI, Opts.slp_revec, ScalarTy, VecTy,
10055 DemandedElts,
10056 /*Insert=*/true, /*Extract=*/false,
10057 CostKind, AreAllValuesNonConst, VL);
10058 APInt UniquesDemandedElts = APInt::getAllOnes(NumUniqueScalarValues);
10059 for (const auto [Idx, V] : enumerate(UniqueValues))
10060 if (isConstant(V))
10061 UniquesDemandedElts.clearBit(Idx);
10062 InstructionCost UniquesCost =
10063 CanSkipBVCost
10065 : getScalarizationOverhead(TTI, Opts.slp_revec, ScalarTy,
10066 UniquesVecTy, UniquesDemandedElts,
10067 /*Insert=*/true,
10068 /*Extract=*/false, CostKind,
10069 AreAllValuesNonConst, UniqueValues);
10070 UniquesCost += ReusesCost;
10071 if (UniquesCost <= InsertsCost) {
10072 // Packing to a vector that occupies the same register width as the
10073 // original only adds the reshuffle cost; keep the originals. Loads may
10074 // instead benefit from a wider contiguous load.
10075 if (S && S.getOpcode() != Instruction::Load) {
10076 unsigned EltBits =
10077 S.getMainOp()->getDataLayout().getTypeSizeInBits(ScalarTy);
10078 unsigned MinVF = R.getMinVF(EltBits);
10079 auto RegWidth = [&](unsigned N) {
10080 return std::max(
10081 getFullVectorNumberOfElements(TTI, ScalarTy, N, Opts.slp_revec),
10082 MinVF);
10083 };
10084 // Keeping the originals just moves the reshuffle to the operand
10085 // columns with duplicates; keep them only if at most one column has
10086 // duplicates, so the total number of reshuffles does not grow.
10087 auto HasExtraReshuffle = [&]() {
10088 if (BuildGatherOnly)
10089 return false;
10090 unsigned NumDupColumns = 0;
10091 for (unsigned OpIdx :
10094 auto IsNotPoison = [](Value *V) { return !isa<PoisonValue>(V); };
10095 for (Value *V : make_filter_range(VL, IsNotPoison)) {
10096 Value *Op;
10097 if (S.isCopyableElement(V)) {
10098 if (OpIdx != 0)
10099 continue;
10100 Op = V;
10101 } else {
10102 auto *I = dyn_cast<Instruction>(V);
10103 if (!I || OpIdx >= I->getNumOperands())
10104 continue;
10105 Op = I->getOperand(OpIdx);
10106 }
10107 if (!isConstant(Op) && !UniqueOps.insert(Op).second) {
10108 ++NumDupColumns;
10109 break;
10110 }
10111 }
10112 if (NumDupColumns > 1)
10113 return true;
10114 }
10115 return false;
10116 };
10117 return std::make_pair(true, RegWidth(NumUniqueScalarValues) >=
10118 RegWidth(VL.size()) &&
10119 !HasExtraReshuffle());
10120 }
10121 return std::make_pair(true, false);
10122 }
10123 InstructionCost CostDiff = UniquesCost - InsertsCost;
10124 if (CostDiff < TTI::TCC_Expensive ||
10125 (R.getTreeSize() == 0 && R.isReductionTree() &&
10126 CostDiff == TTI::TCC_Expensive))
10127 return std::make_pair(S && (!S.isAltShuffle() || !BuildGatherOnly),
10128 false);
10129 // Otherwise, use original values, if values do not require scheduling and
10130 // pass still try to vectorize them.
10131 bool KeepOriginal = !BuildGatherOnly && !RequireScheduling;
10132 return std::make_pair(KeepOriginal, KeepOriginal);
10133 };
10134
10135 const auto [PackProfitable, UseOriginal] = EstimatePackPlusShuffleVsInserts();
10136
10137 if (PackProfitable) {
10138 if (UseOriginal) {
10139 // Prefer original scalars - avoid shuffling.
10140 ReuseShuffleIndices.clear();
10141 } else {
10142 // Better to use uniques + reshuffle.
10143 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
10144 VL = std::move(UniqueValues);
10145 }
10146 return true;
10147 }
10148
10149 // Buildvector/gather of the original scalars.
10150 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
10151 ReuseShuffleIndices.clear();
10152 return false;
10153}
10154
10155/// The nodes with no more than this number of elements are not split.
10156static constexpr unsigned SmallNodeSize = 4;
10157
10159 const InstructionsState &LocalState,
10162 OrdersType &ReorderIndices) const {
10163 if (VL.size() <= SmallNodeSize || TTI->preferAlternateOpcodeVectorization() ||
10164 !Opts.slp_split_alternate_instructions)
10165 return false;
10166 // Split vectorization of struct types is not supported.
10167 if (isa<StructType>(getValueType(VL.front(), Opts.slp_revec)))
10168 return false;
10169
10170 // Check if this is a duplicate of another split entry.
10171 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *LocalState.getMainOp()
10172 << ".\n");
10173 for (TreeEntry *E : getSplitTreeEntries(LocalState.getMainOp())) {
10174 if (E->isSame(VL)) {
10175 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at "
10176 << *LocalState.getMainOp() << ".\n");
10177 return false;
10178 }
10180 if (all_of(VL, [&](Value *V) {
10181 return isa<PoisonValue>(V) || Values.contains(V);
10182 })) {
10183 LLVM_DEBUG(dbgs() << "SLP: Gathering due to full overlap.\n");
10184 return false;
10185 }
10186 }
10187
10188 ReorderIndices.assign(VL.size(), VL.size());
10189 SmallBitVector Op1Indices(VL.size());
10190 for (auto [Idx, V] : enumerate(VL)) {
10191 auto *I = dyn_cast<Instruction>(V);
10192 if (!I) {
10193 Op1.push_back(V);
10194 Op1Indices.set(Idx);
10195 continue;
10196 }
10197 if ((LocalState.getAltOpcode() != LocalState.getOpcode() &&
10198 isMainInstruction(I, LocalState.getMainOp(), LocalState.getAltOp(),
10199 *TLI)) ||
10200 (LocalState.getAltOpcode() == LocalState.getOpcode() &&
10201 !isAlternateInstruction(I, LocalState.getMainOp(),
10202 LocalState.getAltOp(), *TLI))) {
10203 Op1.push_back(V);
10204 Op1Indices.set(Idx);
10205 continue;
10206 }
10207 Op2.push_back(V);
10208 }
10209 Type *ScalarTy = getValueType(VL.front(), Opts.slp_revec);
10210 auto *VecTy = cast<VectorType>(getWidenedType(ScalarTy, VL.size()));
10211 unsigned Opcode0 = LocalState.getOpcode();
10212 unsigned Opcode1 = LocalState.getAltOpcode();
10213 SmallBitVector OpcodeMask(getAltInstrMask(VL, ScalarTy, Opcode0, Opcode1));
10214 // Enable split node, only if all nodes do not form legal alternate
10215 // instruction (like X86 addsub).
10218 if (UOp1.size() <= 1 || UOp2.size() <= 1 ||
10219 TTI->isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask))
10220 return false;
10221 unsigned Op1Cnt = 0, Op2Cnt = Op1.size();
10222 for (unsigned Idx : seq<unsigned>(VL.size())) {
10223 if (Op1Indices.test(Idx)) {
10224 ReorderIndices[Op1Cnt] = Idx;
10225 ++Op1Cnt;
10226 } else {
10227 ReorderIndices[Op2Cnt] = Idx;
10228 ++Op2Cnt;
10229 }
10230 }
10231 if (isIdentityOrder(ReorderIndices))
10232 ReorderIndices.clear();
10233 // When VL fills a power-of-2 register but the split halves do not, the
10234 // reorder shuffle makes the split unprofitable - reject.
10235 else if (hasFullVectorsOrPowerOf2(*TTI, Op1.front()->getType(), VL.size(),
10236 Opts.slp_revec) &&
10237 (!hasFullVectorsOrPowerOf2(*TTI, Op1.front()->getType(), Op1.size(),
10238 Opts.slp_revec) ||
10239 !hasFullVectorsOrPowerOf2(*TTI, Op2.front()->getType(), Op2.size(),
10240 Opts.slp_revec)))
10241 return false;
10242 SmallVector<int> Mask;
10243 if (!ReorderIndices.empty())
10244 inversePermutation(ReorderIndices, Mask);
10245 unsigned NumParts = TTI->getNumberOfParts(VecTy);
10246 auto *Op1VecTy = cast<VectorType>(getWidenedType(ScalarTy, Op1.size()));
10247 auto *Op2VecTy = cast<VectorType>(getWidenedType(ScalarTy, Op2.size()));
10248 // Check non-profitable single register ops, which better to be represented
10249 // as alternate ops.
10250 if (NumParts >= VL.size())
10251 return false;
10252 InstructionCost InsertCost = getShuffleCost(
10253 *TTI, TTI::SK_InsertSubvector, VecTy, CostKind, {}, Op1.size(), Op2VecTy);
10254 auto *SubVecTy = cast<VectorType>(
10255 getWidenedType(ScalarTy, std::max(Op1.size(), Op2.size())));
10256 InstructionCost NewShuffleCost =
10257 getShuffleCost(*TTI, TTI::SK_PermuteTwoSrc, SubVecTy, CostKind, Mask);
10258 if (!LocalState.isCmpOp() && NumParts <= 1 &&
10259 (Mask.empty() || InsertCost >= NewShuffleCost))
10260 return false;
10261 if ((LocalState.getMainOp()->isBinaryOp() &&
10262 LocalState.getAltOp()->isBinaryOp() &&
10263 (LocalState.isShiftOp() || LocalState.isBitwiseLogicOp() ||
10264 LocalState.isAddSubLikeOp() || LocalState.isMulDivLikeOp())) ||
10265 (LocalState.getMainOp()->isCast() && LocalState.getAltOp()->isCast()) ||
10266 (LocalState.getMainOp()->isUnaryOp() &&
10267 LocalState.getAltOp()->isUnaryOp())) {
10268 SmallVector<Value *> Ops0, Ops1;
10270 Ops0.push_back(I->getOperand(0));
10271 if (I->isBinaryOp())
10272 Ops1.push_back(I->getOperand(1));
10273 }
10275 TTI::OperandValueInfo Op1Info =
10277 InstructionCost OriginalVecOpsCost =
10278 TTI->getArithmeticInstrCost(Opcode0, VecTy, CostKind, Op0Info, Op1Info,
10279 {}, LocalState.getMainOp()) +
10280 TTI->getArithmeticInstrCost(Opcode1, VecTy, CostKind, Op0Info, Op1Info,
10281 {}, LocalState.getAltOp());
10282 SmallVector<int> OriginalMask(VL.size(), PoisonMaskElem);
10283 for (unsigned Idx : seq<unsigned>(VL.size())) {
10284 if (isa<PoisonValue>(VL[Idx]))
10285 continue;
10286 OriginalMask[Idx] = Idx + (Op1Indices.test(Idx) ? 0 : VL.size());
10287 }
10288 InstructionCost OriginalCost =
10289 OriginalVecOpsCost + getShuffleCost(*TTI, TTI::SK_PermuteTwoSrc, VecTy,
10290 CostKind, OriginalMask);
10291 InstructionCost NewVecOpsCost =
10292 TTI->getArithmeticInstrCost(Opcode0, Op1VecTy, CostKind, Op0Info,
10293 Op1Info, {}, LocalState.getMainOp()) +
10294 TTI->getArithmeticInstrCost(Opcode1, Op2VecTy, CostKind, Op0Info,
10295 Op1Info, {}, LocalState.getAltOp());
10296 InstructionCost NewCost =
10297 NewVecOpsCost + InsertCost +
10298 (!VectorizableTree.empty() && getRootNode().hasState() &&
10299 getRootNode().getOpcode() == Instruction::Store
10300 ? NewShuffleCost
10301 : 0);
10302 // If not profitable to split - exit.
10303 if (NewCost >= OriginalCost)
10304 return false;
10305 }
10306 return true;
10307}
10308
10309namespace {
10310/// Class accepts incoming list of values, checks if it is able to model
10311/// "copyable" values as compatible operations, and generates the list of values
10312/// for scheduling and list of operands doe the new nodes.
10313class InstructionsCompatibilityAnalysis {
10314 DominatorTree &DT;
10315 const DataLayout &DL;
10316 const TargetTransformInfo &TTI;
10317 const TargetLibraryInfo &TLI;
10318 unsigned MainOpcode = 0;
10319 Instruction *MainOp = nullptr;
10320 /// Whether every copyable in the current value list is an absorbable
10321 /// single-use fmul/fadd. Computed once per buildInstructionsState call.
10322 bool AbsorbCopyableFMulOrFAdds = false;
10323
10324 /// Checks if the opcode is supported as the main opcode for copyable
10325 /// elements.
10326 static bool isSupportedOpcode(const unsigned Opcode) {
10327 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
10328 Opcode == Instruction::Mul || Opcode == Instruction::AShr ||
10329 Opcode == Instruction::LShr || Opcode == Instruction::Shl ||
10330 Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
10331 Opcode == Instruction::And || Opcode == Instruction::Or ||
10332 Opcode == Instruction::Xor || Opcode == Instruction::FAdd ||
10333 Opcode == Instruction::FSub || Opcode == Instruction::FMul ||
10334 Opcode == Instruction::FDiv;
10335 }
10336
10337 /// Checks if \p I can be the main op for copyable analysis: a supported
10338 /// binary operator, fma/fmuladd, or an integer min/max intrinsic, the only
10339 /// call with a well-defined idempotent value (FP min/max lacks one because of
10340 /// NaNs). An extractelement with constant index from a fixed vector is also
10341 /// supported: the matching lanes reuse the source vector and the copyable
10342 /// lanes are inserted into it. A single-index scalar GEP is supported: the
10343 /// copyable lanes are modeled as zero-index GEPs of the lane values
10344 /// themselves. A scalar zext is supported: the copyable lanes are constants
10345 /// modeled as zexts of truncated constants.
10346 static bool isSupportedMainOp(Instruction *I) {
10347 return isSupportedOpcode(I->getOpcode()) || isa<MinMaxIntrinsic>(I) ||
10348 isFMAOrFMulAdd(I) ||
10350 isa<FixedVectorType>(I->getOperand(0)->getType())) ||
10351 (isa<GetElementPtrInst>(I) && I->getNumOperands() == 2 &&
10352 !I->getType()->isVectorTy()) ||
10353 (isa<ZExtInst>(I) && !I->getType()->isVectorTy() &&
10354 !isa<Constant>(I->getOperand(0)));
10355 }
10356
10357 /// Identifies the best candidate value, which represents main opcode
10358 /// operation.
10359 /// Currently the best candidate is the Add instruction with the parent
10360 /// block with the highest DFS incoming number (block, that dominates other).
10361 void findAndSetMainInstruction(ArrayRef<Value *> VL, const BoUpSLP &R) {
10362 BasicBlock *Parent = nullptr;
10363 // Checks if the instruction has supported opcode.
10364 auto IsSupportedInstruction = [&](Instruction *I, bool AnyUndef) {
10365 if (AnyUndef && (I->isIntDivRem() || I->isFPDivRem() || isa<CallInst>(I)))
10366 return false;
10367 return I && isSupportedMainOp(I) &&
10368 (!doesNotNeedToBeScheduled(I) || !R.isVectorized(I));
10369 };
10370 // Exclude operands instructions immediately to improve compile time, it
10371 // will be unable to schedule anyway.
10372 SmallDenseSet<Value *, 8> Operands;
10373 SmallMapVector<unsigned, SmallVector<Instruction *>, 4> Candidates;
10374 bool AnyUndef = false;
10375 for (Value *V : VL) {
10376 auto *I = dyn_cast<Instruction>(V);
10377 if (!I) {
10378 AnyUndef |= isa<UndefValue>(V);
10379 continue;
10380 }
10381 if (!DT.isReachableFromEntry(I->getParent()))
10382 continue;
10383 if (Candidates.empty()) {
10384 Candidates.try_emplace(I->getOpcode()).first->second.push_back(I);
10385 Parent = I->getParent();
10386 Operands.insert(I->op_begin(), I->op_end());
10387 continue;
10388 }
10389 if (Parent == I->getParent()) {
10390 Candidates.try_emplace(I->getOpcode()).first->second.push_back(I);
10391 Operands.insert(I->op_begin(), I->op_end());
10392 continue;
10393 }
10394 auto *NodeA = DT.getNode(Parent);
10395 auto *NodeB = DT.getNode(I->getParent());
10396 assert(NodeA && "Should only process reachable instructions");
10397 assert(NodeB && "Should only process reachable instructions");
10398 assert((NodeA == NodeB) ==
10399 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
10400 "Different nodes should have different DFS numbers");
10401 if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn()) {
10402 Candidates.clear();
10403 Candidates.try_emplace(I->getOpcode()).first->second.push_back(I);
10404 Parent = I->getParent();
10405 Operands.clear();
10406 Operands.insert(I->op_begin(), I->op_end());
10407 }
10408 }
10409 unsigned BestOpcodeNum = 0;
10410 MainOp = nullptr;
10411 bool UsedOutside = false;
10412 for (const auto &P : Candidates) {
10413 bool PUsedOutside = all_of(P.second, isUsedOutsideBlock);
10414 if (UsedOutside && !PUsedOutside)
10415 continue;
10416 if (!UsedOutside && PUsedOutside)
10417 BestOpcodeNum = 0;
10418 if (P.second.size() < BestOpcodeNum)
10419 continue;
10420 // If have inner dependencies - skip.
10421 if (!PUsedOutside && any_of(P.second, [&](Instruction *I) {
10422 return Operands.contains(I);
10423 }))
10424 continue;
10425 // On a tie, keep the outer binary op as MainOp rather than replacing it
10426 // with an inner op that appears as its direct operand. For example, in
10427 // (2.0f * A) + B the fadd and fmul each appear once in VL; without this
10428 // check the fmul could win and prevent vectorization of the fadd pair.
10429 if (P.second.size() == BestOpcodeNum) {
10430 auto *I = P.second.front();
10431 if (auto *MainBO = dyn_cast<BinaryOperator>(MainOp)) {
10432 auto *MainBOOp0 = dyn_cast<Instruction>(MainBO->getOperand(0));
10433 auto *MainBOOp1 = dyn_cast<Instruction>(MainBO->getOperand(1));
10434 if (MainBOOp0 && MainBOOp0->getOpcode() == I->getOpcode() &&
10435 MainBOOp0->getParent() == I->getParent())
10436 continue;
10437 if (MainBOOp1 && MainBOOp1->getOpcode() == I->getOpcode() &&
10438 MainBOOp1->getParent() == I->getParent())
10439 continue;
10440 }
10441 // Keep fmuladd over fmul/fadd on a tie only when every copyable is
10442 // an absorbed fmul/fadd.
10444 (I->getOpcode() == Instruction::FMul ||
10445 I->getOpcode() == Instruction::FAdd) &&
10446 AbsorbCopyableFMulOrFAdds)
10447 continue;
10448 // Same check when fma/fmuladd replaces fmul/fadd on a tie.
10449 if ((MainOp->getOpcode() == Instruction::FMul ||
10450 MainOp->getOpcode() == Instruction::FAdd) &&
10451 isFMAOrFMulAdd(I) && !AbsorbCopyableFMulOrFAdds)
10452 continue;
10453 }
10454 UsedOutside = PUsedOutside;
10455 if (P.first == Instruction::GetElementPtr) {
10456 // Only the GEPs of the main op shape (source element type and index
10457 // type) are matching lanes, the others are copyable. Select the most
10458 // frequent shape to minimize the number of copyable lanes.
10459 SmallDenseMap<std::pair<Type *, Type *>, unsigned, 4> ShapeCounts;
10460 auto GetShape = [](Instruction *I) {
10461 return std::make_pair(cast<GEPOperator>(I)->getSourceElementType(),
10462 I->getOperand(1)->getType());
10463 };
10464 for (Instruction *I : P.second)
10465 if (IsSupportedInstruction(I, AnyUndef))
10466 ++ShapeCounts[GetShape(I)];
10467 unsigned BestShapeNum = 0;
10468 for (Instruction *I : P.second) {
10469 if (!IsSupportedInstruction(I, AnyUndef))
10470 continue;
10471 unsigned ShapeNum = ShapeCounts.lookup(GetShape(I));
10472 if (ShapeNum > BestShapeNum) {
10473 MainOp = I;
10474 BestOpcodeNum = P.second.size();
10475 BestShapeNum = ShapeNum;
10476 }
10477 }
10478 continue;
10479 }
10480 for (Instruction *I : P.second) {
10481 if (IsSupportedInstruction(I, AnyUndef)) {
10482 MainOp = I;
10483 BestOpcodeNum = P.second.size();
10484 break;
10485 }
10486 }
10487 }
10488 if (MainOp) {
10489 // Do not match, if any copyable is a terminator from the same block as
10490 // the main operation.
10491 if (any_of(make_isa_range<Instruction>(VL), [&](Instruction *I) {
10492 return I->getParent() == MainOp->getParent() && I->isTerminator();
10493 })) {
10494 MainOp = nullptr;
10495 return;
10496 }
10497 // fma lanes match the fmuladd main op; use an fma as the main op so the
10498 // fused form is not weakened to fmuladd.
10500 auto *It = find_if(VL, [&](Value *V) {
10501 return match(V, m_Intrinsic<Intrinsic::fma>()) &&
10502 cast<Instruction>(V)->getParent() == MainOp->getParent();
10503 });
10504 if (It != VL.end())
10505 MainOp = cast<Instruction>(*It);
10506 if (doesNotNeedToBeScheduled(MainOp) && R.isVectorized(MainOp)) {
10507 MainOp = nullptr;
10508 return;
10509 }
10510 }
10511 MainOpcode = MainOp->getOpcode();
10512 }
10513 }
10514
10515 /// Returns the idempotent value for MainOp. For Add, returns 0. For Or, it
10516 /// should choose between false and the operand itself, since V or V == V.
10517 /// For the min/max intrinsics, returns the corresponding limit value (e.g. 0
10518 /// for umax, since umax(V, 0) == V). For smin and smax the type limit is
10519 /// kept when it stays same after narrowing, otherwise the limit is deduced
10520 /// from the signed width of V.
10521 Value *selectBestIdempotentValue(Value *V) const {
10522 assert(isSupportedMainOp(MainOp) && "Unsupported opcode");
10523 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(MainOp);
10524 MinMax && MinMax->isSigned() &&
10525 !isTypeLimitNeutral(V, MinMax->getIntrinsicID() == Intrinsic::smax,
10526 DL)) {
10527 // TODO: add AC to both width queries once the analysis has one.
10528 unsigned Width = ComputeMaxSignificantBits(V, DL, nullptr, nullptr, &DT);
10529 APInt Limit = MinMax->getIntrinsicID() == Intrinsic::smax
10531 : APInt::getSignedMaxValue(Width);
10533 MainOp->getType(),
10534 Limit.sext(MainOp->getType()->getScalarSizeInBits()));
10535 }
10536 return ConstantExpr::getIdentity(MainOp, MainOp->getType(),
10537 !MainOp->isCommutative());
10538 }
10539
10540 /// Returns the value and operands for the \p V, considering if it is original
10541 /// instruction and its actual operands should be returned, or it is a
10542 /// copyable element and its should be represented as idempotent instruction.
10543 /// \p SelfOp selects the op(V, V) modeling for a copyable lane instead of
10544 /// op(V, identity). \p PoisonPlaceholder selects op(V, poison) for the
10545 /// absorbing constant V.
10546 SmallVector<Value *> getOperands(const InstructionsState &S, Value *V,
10547 bool SelfOp,
10548 bool PoisonPlaceholder = false) const {
10549 if (SelfOp)
10550 return {V, V};
10551 if (isa<PoisonValue>(V)) {
10552 // Poison operands of the main op operand types: a GEP index or a cast
10553 // source has a type, different from the lane type. Excludes the
10554 // trailing callee operand of a call.
10555 auto *CI = dyn_cast<CallInst>(MainOp);
10556 return map_to_vector(
10557 seq<unsigned>(CI ? CI->arg_size() : MainOp->getNumOperands()),
10558 [&](unsigned Idx) -> Value * {
10559 return PoisonValue::get(MainOp->getOperand(Idx)->getType());
10560 });
10561 }
10562 if (!S.isCopyableElement(V))
10563 return convertTo(cast<Instruction>(V), S).second;
10564 if (isFMAOrFMulAdd(MainOp)) {
10565 Type *Ty = MainOp->getType();
10568 auto *I = cast<Instruction>(V);
10569 // fmuladd(a, b, -0.0) == fmul a, b.
10570 if (I->getOpcode() == Instruction::FMul)
10571 return {I->getOperand(0), I->getOperand(1),
10573 // fmuladd(1.0, a, b) == fadd a, b.
10574 return {ConstantFP::get(Ty, 1.0), I->getOperand(0), I->getOperand(1)};
10575 }
10576 // fmuladd(V, 1.0, -0.0) == V.
10577 if (S.getCopyableOpIdx() == 0)
10578 return {V, ConstantFP::get(Ty, 1.0), ConstantFP::getNegativeZero(Ty)};
10579 // fmuladd(0.0, -0.0, V) == V.
10581 }
10582 // gep V, 0 == V.
10583 if (MainOpcode == Instruction::GetElementPtr)
10584 return {V, ConstantInt::get(MainOp->getOperand(1)->getType(), 0)};
10585 // zext(trunc(V)) == V for the round-trippable constant lanes.
10586 if (MainOpcode == Instruction::ZExt)
10588 cast<CastInst>(MainOp)->getSrcTy())};
10589 assert(isSupportedMainOp(MainOp) && "Unsupported opcode");
10590 Type *Ty = V->getType();
10591 if (PoisonPlaceholder &&
10592 V == ConstantExpr::getBinOpAbsorber(MainOpcode, Ty))
10593 return {V, PoisonValue::get(Ty)};
10594 if (isa<UndefValue>(V) && isUndefTolerantBinOp(MainOp))
10595 return {V, V};
10596 return {V, selectBestIdempotentValue(V)};
10597 }
10598
10599 /// Checks if the lanes with the absorbing constant may use poison as the
10600 /// other operand: every other non-poison lane must be a binary operator with
10601 /// one constant operand and an undef-tolerant binary operator of a distinct
10602 /// load as the other operand.
10603 bool canUsePoisonPlaceholders(const InstructionsState &S,
10604 ArrayRef<Value *> VL) const {
10605 Constant *Absorber =
10606 ConstantExpr::getBinOpAbsorber(MainOpcode, VL.front()->getType());
10607 if (!Absorber || !is_contained(VL, Absorber))
10608 return false;
10609 SmallPtrSet<const LoadInst *, 8> Loads;
10610 return all_of(VL, [&](Value *V) {
10612 return true;
10614 return count_if(Ops, IsaPred<Constant>) == 1 &&
10615 any_of(Ops, [&](Value *Op) {
10616 const LoadInst *LI = getLoadOfUndefTolerantBinOp(Op);
10617 return LI && Loads.insert(LI).second;
10618 });
10619 });
10620 }
10621
10622 /// Returns the copyable lanes of an idempotent binop to be modeled as
10623 /// op(V, V) == V instead of op(V, identity): when the operand column the
10624 /// lane joins also holds a constant lane, the reorder would align that
10625 /// column as constants and move the lane out, breaking the opcode-peer
10626 /// node, while the symmetric form is reorder-proof. The other column must
10627 /// be an instruction node so the lane is absorbed there as a copyable
10628 /// rather than breaking a constant column. A lane is modeled this way only
10629 /// when it has a strong opcode-peer pair of its own.
10630 SmallPtrSet<const Value *, 4> findSelfOpLanes(const InstructionsState &S,
10632 const BoUpSLP &R) const {
10633 SmallPtrSet<const Value *, 4> SelfOpLanes;
10634 if (!Instruction::isIdempotent(MainOpcode) ||
10636 if (isa<PoisonValue>(V))
10637 return false;
10638 if (S.isCopyableElement(V))
10639 return isa<Constant>(V);
10640 return isa<Constant>(cast<Instruction>(V)->getOperand(0));
10641 }))
10642 return SelfOpLanes;
10643 // Index the instruction operands of the non-copyable lanes by opcode
10644 // and block, so the copyable lanes find their opcode peers without a
10645 // quadratic scan.
10646 SmallDenseMap<std::pair<unsigned, BasicBlock *>, SmallVector<Value *>>
10647 PeerOps;
10648 for (Instruction *RI : make_isa_range<Instruction>(VL)) {
10649 if (S.isCopyableElement(RI))
10650 continue;
10651 assert(RI->getNumOperands() == 2 && "Expected binary operation.");
10652 for (unsigned OpIdx : seq<unsigned>(RI->getNumOperands())) {
10653 auto *OpI = dyn_cast<Instruction>(RI->getOperand(OpIdx));
10654 if (OpI &&
10655 isa<Instruction>(RI->getOperand(RI->getNumOperands() - 1 - OpIdx)))
10656 PeerOps[{OpI->getOpcode(), OpI->getParent()}].push_back(OpI);
10657 }
10658 }
10659 for (Instruction *I : make_isa_range<Instruction>(VL)) {
10660 if (!S.isCopyableElement(I))
10661 continue;
10662 auto It = PeerOps.find({I->getOpcode(), I->getParent()});
10663 if (It == PeerOps.end())
10664 continue;
10666 for (Value *OpI : It->second)
10667 Candidates.emplace_back(I, OpI);
10668 if (R.findBestRootPair(Candidates).first)
10669 SelfOpLanes.insert(I);
10670 }
10671 return SelfOpLanes;
10672 }
10673
10674 /// Builds the index operands of a GEP node with the main op \p VL0. The
10675 /// indices of the matching GEP lanes (for which \p IsGEPLane returns true)
10676 /// are cast to the common index type, all other lanes (non-GEP pointers,
10677 /// copyable and poison lanes, modeled as gep V, 0) get a zero index of that
10678 /// type. Required to be able to find correct matches between different
10679 /// gather nodes and reuse the vectorized values rather than trying to
10680 /// gather them again. The vectorized nodes always have the common index
10681 /// type (a legality invariant); the operands built for the profitability
10682 /// analysis before that check may have none, the constants are cast to the
10683 /// pointer index type then.
10684 void buildGEPIndexOperands(ArrayRef<Value *> VL, Instruction *VL0,
10685 function_ref<bool(Value *)> IsGEPLane,
10686 BoUpSLP::ValueList &Indices) const {
10687 constexpr unsigned IndexIdx = 1;
10688 Type *Ty = getCommonGEPIndexType(VL, VL0, IsGEPLane, DL);
10689 if (!Ty)
10690 Ty = DL.getIndexType(VL0->getOperand(0)->getType()->getScalarType());
10691 for (auto [Idx, V] : enumerate(VL)) {
10692 if (!IsGEPLane(V)) {
10693 Indices[Idx] = ConstantInt::getNullValue(Ty);
10694 continue;
10695 }
10696 auto *Op = cast<GetElementPtrInst>(V)->getOperand(IndexIdx);
10697 auto *CI = dyn_cast<ConstantInt>(Op);
10698 Indices[Idx] = CI ? ConstantFoldIntegerCast(
10699 CI, Ty, CI->getValue().isSignBitSet(), DL)
10700 : Op;
10701 }
10702 }
10703
10704 /// Builds operands for the original instructions.
10705 void
10706 buildOriginalOperands(const InstructionsState &S, ArrayRef<Value *> VL,
10707 SmallVectorImpl<BoUpSLP::ValueList> &Operands) const {
10708
10709 unsigned ShuffleOrOp =
10710 S.isAltShuffle() ? (unsigned)Instruction::ShuffleVector : S.getOpcode();
10711 Instruction *VL0 = S.getMainOp();
10712
10713 switch (ShuffleOrOp) {
10714 case Instruction::PHI: {
10715 auto *PH = cast<PHINode>(VL0);
10716
10717 // Keeps the reordered operands to avoid code duplication.
10718 PHIHandler Handler(DT, PH, VL);
10719 Handler.buildOperands();
10720 Operands.assign(PH->getNumOperands(), {});
10721 for (unsigned I : seq<unsigned>(PH->getNumOperands()))
10722 Operands[I].assign(Handler.getOperands(I).begin(),
10723 Handler.getOperands(I).end());
10724 return;
10725 }
10726 case Instruction::ExtractValue: {
10727 SmallVector<unsigned> Indices;
10729 if (checkEVsForVecCalls(VL, S, TLI, Indices, Calls)) {
10730 Operands.assign(1, {});
10731 Operands[0].swap(Calls);
10732 return;
10733 }
10734 [[fallthrough]];
10735 }
10736 case Instruction::ExtractElement:
10737 // This is a special case, as it does not gather, but at the same time
10738 // we are not extending buildTree_rec() towards the operands.
10739 Operands.assign(1, {VL.size(), VL0->getOperand(0)});
10740 return;
10741 case Instruction::InsertValue:
10742 case Instruction::InsertElement:
10743 Operands.assign(2, {VL.size(), nullptr});
10744 for (auto [Idx, V] : enumerate(VL)) {
10745 auto *IE = cast<Instruction>(V);
10746 for (auto [OpIdx, Ops] : enumerate(Operands))
10747 Ops[Idx] = IE->getOperand(OpIdx);
10748 }
10749 return;
10750 case Instruction::Load:
10751 Operands.assign(
10752 1, {VL.size(),
10753 PoisonValue::get(cast<LoadInst>(VL0)->getPointerOperandType())});
10754 for (auto [V, Op] : zip(VL, Operands.back())) {
10755 auto *LI = dyn_cast<LoadInst>(V);
10756 if (!LI)
10757 continue;
10758 Op = LI->getPointerOperand();
10759 }
10760 return;
10761 case Instruction::ICmp:
10762 // With trunc X to i1 lanes the node is the bit tests of and A, B: the
10763 // compares give the operands of their ands, trunc X gives X and 1.
10764 if (any_of(VL, IsaPred<TruncInst>)) {
10765 Type *Ty = VL0->getOperand(0)->getType();
10766 Operands.assign(2, {VL.size(), PoisonValue::get(Ty)});
10767 for (auto [Idx, V] : enumerate(VL)) {
10768 if (auto *TI = dyn_cast<TruncInst>(V)) {
10769 Operands[0][Idx] = TI->getOperand(0);
10770 Operands[1][Idx] = ConstantInt::get(Ty, 1);
10771 } else if (auto *CI = dyn_cast<ICmpInst>(V)) {
10772 auto *And = cast<BinaryOperator>(CI->getOperand(0));
10773 Operands[0][Idx] = And->getOperand(0);
10774 Operands[1][Idx] = And->getOperand(1);
10775 }
10776 }
10777 return;
10778 }
10779 [[fallthrough]];
10780 case Instruction::ZExt:
10781 case Instruction::SExt:
10782 case Instruction::FPToUI:
10783 case Instruction::FPToSI:
10784 case Instruction::FPExt:
10785 case Instruction::PtrToInt:
10786 case Instruction::PtrToAddr:
10787 case Instruction::IntToPtr:
10788 case Instruction::SIToFP:
10789 case Instruction::UIToFP:
10790 case Instruction::Trunc:
10791 case Instruction::FPTrunc:
10792 case Instruction::BitCast:
10793 case Instruction::FCmp:
10794 case Instruction::FNeg:
10795 case Instruction::Add:
10796 case Instruction::FAdd:
10797 case Instruction::Sub:
10798 case Instruction::FSub:
10799 case Instruction::Mul:
10800 case Instruction::FMul:
10801 case Instruction::UDiv:
10802 case Instruction::SDiv:
10803 case Instruction::FDiv:
10804 case Instruction::URem:
10805 case Instruction::SRem:
10806 case Instruction::FRem:
10807 case Instruction::Shl:
10808 case Instruction::LShr:
10809 case Instruction::AShr:
10810 case Instruction::And:
10811 case Instruction::Or:
10812 case Instruction::Xor:
10813 case Instruction::Freeze:
10814 case Instruction::Store:
10815 case Instruction::ShuffleVector:
10816 Operands.assign(VL0->getNumOperands(), {VL.size(), nullptr});
10817 for (auto [Idx, V] : enumerate(VL)) {
10818 auto *I = dyn_cast<Instruction>(V);
10819 if (!I) {
10820 for (auto [OpIdx, Ops] : enumerate(Operands))
10821 Ops[Idx] = PoisonValue::get(VL0->getOperand(OpIdx)->getType());
10822 continue;
10823 }
10824 SmallVector<Value *> ConvertedOps = convertTo(I, S).second;
10825 for (auto [OpIdx, Ops] : enumerate(Operands))
10826 Ops[Idx] = ConvertedOps[OpIdx];
10827 }
10828 return;
10829 case Instruction::Select:
10830 Operands.assign(VL0->getNumOperands(), {VL.size(), nullptr});
10831 for (auto [Idx, V] : enumerate(VL)) {
10832 auto *I = dyn_cast<Instruction>(V);
10833 if (!I) {
10834 for (auto [OpIdx, Ops] : enumerate(Operands))
10835 Ops[Idx] = PoisonValue::get(VL0->getOperand(OpIdx)->getType());
10836 continue;
10837 }
10838 if (isa<ZExtInst>(I)) {
10839 // Special case for select + zext i1 to avoid explosion of different
10840 // types. We want to keep the condition as i1 to be able to match
10841 // different selects together and reuse the vectorized condition
10842 // rather than trying to gather it.
10843 Operands[0][Idx] = I->getOperand(0);
10844 Operands[1][Idx] = ConstantInt::get(I->getType(), 1);
10845 Operands[2][Idx] = ConstantInt::getNullValue(I->getType());
10846 continue;
10847 }
10848 SmallVector<Value *> ConvertedOps = convertTo(I, S).second;
10849 for (auto [OpIdx, Ops] : enumerate(Operands))
10850 Ops[Idx] = ConvertedOps[OpIdx];
10851 }
10852 return;
10853 case Instruction::GetElementPtr: {
10854 Operands.assign(2, {VL.size(), nullptr});
10855 for (auto [Idx, V] : enumerate(VL)) {
10857 Operands[0][Idx] = GEP ? GEP->getPointerOperand() : V;
10858 }
10859 buildGEPIndexOperands(VL, VL0, IsaPred<GetElementPtrInst>, Operands[1]);
10860 return;
10861 }
10862 case Instruction::Call: {
10863 auto *CI = cast<CallInst>(VL0);
10865 for (unsigned Idx : seq<unsigned>(CI->arg_size())) {
10867 continue;
10868 auto &Ops = Operands.emplace_back();
10869 for (Value *V : VL) {
10870 auto *I = dyn_cast<Instruction>(V);
10871 Ops.push_back(I ? I->getOperand(Idx)
10872 : PoisonValue::get(VL0->getOperand(Idx)->getType()));
10873 }
10874 }
10875 return;
10876 }
10877 default:
10878 break;
10879 }
10880 llvm_unreachable("Unexpected vectorization of the instructions.");
10881 }
10882
10883 /// Check if the specified \p VL list of values is better to represent as
10884 /// uniform with copyables, as modeled via \p CopyableS, or as alternate (or
10885 /// uniform with compatible ops), modeled via \p S.
10886 /// Performs the analysis of the operands, choosing the preferred main
10887 /// instruction and checking the matching of the operands for the main
10888 /// instruction and copyable elements.
10889 bool isCopyablePreferable(ArrayRef<Value *> VL, const BoUpSLP &R,
10890 const InstructionsState &S,
10891 const InstructionsState &CopyableS) {
10892 // If all elements are vectorized already - keep as is.
10893 if (all_of(VL, [&](Value *V) {
10894 return isa<PoisonValue>(V) || R.isVectorized(V);
10895 }))
10896 return false;
10897 Instruction *SMain = S.getMainOp();
10898 Instruction *SAlt = S.isAltShuffle() ? S.getAltOp() : nullptr;
10899 const bool IsCommutative = isCommutative(SMain);
10900 const bool IsAltCommutative =
10901 S.isAltShuffle() ? isCommutative(SAlt) : false;
10902 const bool IsMainCommutative = isCommutative(MainOp);
10904 buildOriginalOperands(S, SMain, Ops);
10905 // Support only binary operations for now.
10906 if (Ops.size() != 2)
10907 return false;
10908 // Try to find better candidate for S main instruction, which operands have
10909 // better matching.
10910 auto CheckOperands = [](Value *Op, Value *SMainOp) {
10911 auto *OpI = dyn_cast<BinaryOperator>(Op);
10912 if (!OpI)
10913 return false;
10914 auto *SMainOpI = dyn_cast<BinaryOperator>(SMainOp);
10915 if (!SMainOpI)
10916 return true;
10917 return any_of(make_isa_range<Instruction>(OpI->operands()),
10918 [&](Instruction *I) {
10919 return I->getOpcode() == SMainOpI->getOpcode();
10920 });
10921 };
10922 SmallPtrSet<Value *, 8> Operands;
10923 for (Instruction *I : make_isa_range<Instruction>(VL)) {
10924 if (I == SMain)
10925 continue;
10926 Instruction *MatchingOp = S.getMatchingMainOpOrAltOp(I);
10927 if (MatchingOp != SMain)
10928 continue;
10930 buildOriginalOperands(S, I, VOps);
10931 Operands.insert(I->op_begin(), I->op_end());
10932 assert(VOps.size() == 2 && Ops.size() == 2 &&
10933 "Expected binary operations only.");
10934 if (CheckOperands(VOps[0][0], Ops[0][0]) ||
10935 CheckOperands(VOps[1][0], Ops[1][0]) ||
10936 (IsCommutative && (CheckOperands(VOps[0][0], Ops[1][0]) ||
10937 CheckOperands(VOps[1][0], Ops[0][0])))) {
10938 SMain = I;
10939 Ops.swap(VOps);
10940 break;
10941 }
10942 }
10944 buildOriginalOperands(S, MainOp, MainOps);
10945
10946 auto BuildFirstOperandCandidates =
10947 [&](SmallVectorImpl<std::pair<Value *, Value *>> &Candidates,
10949 bool IsCommutative) {
10950 Candidates.emplace_back(Ops[0][0], Op0);
10951 if (IsCommutative)
10952 Candidates.emplace_back(Ops[0][0], Op1);
10953 };
10954
10955 auto BuildSecondOperandCandidates =
10956 [&](SmallVectorImpl<std::pair<Value *, Value *>> &Candidates,
10957 ArrayRef<BoUpSLP::ValueList> Ops, int PrevBestIdx, Value *Op0,
10958 Value *Op1, bool IsCommutative) {
10959 if (PrevBestIdx != 1)
10960 Candidates.emplace_back(Ops[1][0], Op1);
10961 if (PrevBestIdx != 0 && IsCommutative)
10962 Candidates.emplace_back(Ops[1][0], Op0);
10963 };
10964
10965 auto FindBestCandidate =
10966 [&](ArrayRef<std::pair<Value *, Value *>> Candidates, bool &IsConst,
10967 int &Score) {
10968 auto Res = R.findBestRootPair(Candidates);
10969 Score = Res.second;
10970 IsConst =
10972 isConstant(Candidates[Res.first.value_or(0)].first) &&
10973 isConstant(Candidates[Res.first.value_or(0)].second);
10974 if (IsConst) {
10975 // Check if there are splat candidates and consider them better
10976 // option.
10977 for (const auto [Idx, P] : enumerate(Candidates)) {
10978 if (!isConstant(P.first) && !isConstant(P.second) &&
10979 P.second == P.first) {
10980 Res.first = Idx;
10981 IsConst = false;
10982 Score = isa<LoadInst>(Candidates[Res.first.value_or(0)].first)
10985 break;
10986 }
10987 }
10988 }
10989 return Res.first;
10990 };
10991
10992 for (Instruction *I : make_isa_range<Instruction>(VL)) {
10993 if (I == SMain && (I == MainOp || !S.isAltShuffle()))
10994 continue;
10996 buildOriginalOperands(S, I == SMain ? MainOp : I, VOps);
10997 SmallVector<Value *> CopyableOps =
10998 getOperands(CopyableS, I == MainOp ? SMain : I, /*SelfOp=*/false);
10999 if (CopyableOps.size() == VOps.size() &&
11000 all_of(zip(CopyableOps, VOps), [&](const auto &P) {
11001 return std::get<0>(P) == std::get<1>(P)[0];
11002 }))
11003 continue;
11005 BuildFirstOperandCandidates(Candidates, MainOps, CopyableOps[0],
11006 CopyableOps[1], IsMainCommutative);
11007 const unsigned OpSize = Candidates.size();
11008 Instruction *MatchingOp =
11009 S.getMatchingMainOpOrAltOp(I) == S.getMainOp() ? SMain : SAlt;
11010 const bool IsCommutativeInst =
11011 (MatchingOp == SMain ? IsCommutative : IsAltCommutative) ||
11012 isCommutative(I, MatchingOp);
11013 if (S.isAltShuffle() && MatchingOp == SAlt &&
11014 any_of(VOps, [&](const BoUpSLP::ValueList &Ops) {
11015 auto *I = dyn_cast<BinaryOperator>(Ops[0]);
11016 return I && Operands.contains(I);
11017 }))
11018 return false;
11019 if (S.isAltShuffle() && MatchingOp == SMain)
11020 Operands.insert(I->op_begin(), I->op_end());
11021 BuildFirstOperandCandidates(Candidates, Ops, VOps[0][0], VOps[1][0],
11022 IsCommutativeInst);
11023 bool IsBestConst;
11024 int Score;
11025 std::optional<int> BestOp =
11026 FindBestCandidate(Candidates, IsBestConst, Score);
11027 const bool IsOriginalBetter =
11028 static_cast<unsigned>(BestOp.value_or(OpSize)) >= OpSize;
11029 Candidates.clear();
11030 BuildSecondOperandCandidates(
11031 Candidates, MainOps, IsOriginalBetter ? -1 : *BestOp, CopyableOps[0],
11032 CopyableOps[1], IsMainCommutative);
11033 const unsigned SecondOpSize = Candidates.size();
11034 BuildSecondOperandCandidates(
11035 Candidates, Ops,
11036 IsOriginalBetter ? BestOp.value_or(OpSize - 1) - OpSize : -1,
11037 VOps[0][0], VOps[1][0], IsCommutativeInst);
11038 bool IsSecondBestConst;
11039 int SecondScore;
11040 std::optional<int> SecondBestOp =
11041 FindBestCandidate(Candidates, IsSecondBestConst, SecondScore);
11042 // No best candidates.
11043 if (!BestOp && !SecondBestOp)
11044 return false;
11045 // Original better in both ops combinations.
11046 const bool IsSecondOriginalBetter =
11047 static_cast<unsigned>(SecondBestOp.value_or(SecondOpSize)) >=
11048 SecondOpSize;
11049 if (IsOriginalBetter && IsSecondOriginalBetter)
11050 return false;
11051 // Original is better in second combination, but in the first combination
11052 // no best candidates.
11053 if (!BestOp && IsSecondOriginalBetter)
11054 return false;
11055 // Original is better in first combination, but in the second combination
11056 // no best candidates.
11057 if (!SecondBestOp && IsOriginalBetter)
11058 return false;
11059 // Copyable is best in the first combination, but it is constant, but
11060 // original is better in second non-constant combination.
11061 if (!IsOriginalBetter && IsBestConst && IsSecondOriginalBetter &&
11062 !IsSecondBestConst)
11063 return false;
11064 // Copyable is best in the second combination, but it is constant, but
11065 // original is better in the first non-constant combination.
11066 if (BestOp && IsOriginalBetter && !IsBestConst &&
11067 !IsSecondOriginalBetter && IsSecondBestConst)
11068 return false;
11069 // Original combination score is better.
11070 if (((Score > SecondScore ||
11072 Score == SecondScore)) &&
11073 IsOriginalBetter) ||
11074 (IsSecondOriginalBetter &&
11075 (SecondScore > Score ||
11077 Score == SecondScore))))
11078 return false;
11079 }
11080 return true;
11081 }
11082
11083public:
11084 InstructionsCompatibilityAnalysis(DominatorTree &DT, const DataLayout &DL,
11085 const TargetTransformInfo &TTI,
11086 const TargetLibraryInfo &TLI)
11087 : DT(DT), DL(DL), TTI(TTI), TLI(TLI) {}
11088
11089 InstructionsState buildInstructionsState(ArrayRef<Value *> VL,
11090 const BoUpSLP &R,
11091 bool WithProfitabilityCheck = false,
11092 bool SkipSameCodeCheck = false) {
11093 InstructionsState S = (SkipSameCodeCheck || !allSameBlock(VL))
11095 : getSameOpcode(VL, TLI);
11096 // Check if series of selects + zext i1 %x to in can be combined into
11097 // selects + select %x, i32 1, i32 0.
11098 Instruction *SelectOp = nullptr;
11099 if (!S && allSameBlock(VL) && all_of(VL, [&](Value *V) {
11100 if (match(V, m_Select(m_Value(), m_Value(), m_Value()))) {
11101 if (!SelectOp)
11102 SelectOp = cast<Instruction>(V);
11103 return true;
11104 }
11105 auto *ZExt = dyn_cast<ZExtInst>(V);
11106 return (ZExt && ZExt->getSrcTy()->isIntegerTy(1)) ||
11108 })) {
11109 if (SelectOp)
11110 return InstructionsState(SelectOp, SelectOp);
11111 }
11112 // The undef lanes among the loads are the copyable elements, covered by a
11113 // single wide load.
11114 if (!S && R.Opts.slp_copyable_elements &&
11116 return isa<UndefValue>(V) && !isa<PoisonValue>(V);
11117 })) {
11119 if (Loads.size() > 1 && allSameBlock(Loads)) {
11120 auto *LI = cast<LoadInst>(Loads.front());
11121 return InstructionsState(LI, LI, /*HasCopyables=*/true);
11122 }
11123 }
11124 // The loads from the single predecessor block are the copyable elements,
11125 // covered by a single wide load in the successor block.
11126 if (!S && R.Opts.slp_copyable_elements && all_of(VL, IsaPred<LoadInst>)) {
11127 auto *LI = cast<LoadInst>(VL.front());
11128 const auto *It = find_if(VL, [&](Value *V) {
11129 return cast<LoadInst>(V)->getParent() != LI->getParent();
11130 });
11131 if (It != VL.end()) {
11132 if (LI->getParent()->getSinglePredecessor() !=
11133 cast<LoadInst>(*It)->getParent())
11134 LI = cast<LoadInst>(*It);
11135 BasicBlock *Pred = LI->getParent()->getSinglePredecessor();
11136 if (Pred && all_of(VL, [&](Value *V) {
11138 return BB == LI->getParent() || BB == Pred;
11139 }))
11140 return InstructionsState(LI, LI, /*HasCopyables=*/true);
11141 }
11142 }
11143 if (S && S.isAltShuffle()) {
11144 Type *ScalarTy = S.getMainOp()->getType();
11145 auto *VecTy = cast<VectorType>(getWidenedType(ScalarTy, VL.size()));
11146 unsigned Opcode0 = S.getOpcode();
11147 unsigned Opcode1 = S.getAltOpcode();
11148 SmallBitVector OpcodeMask(
11149 getAltInstrMask(VL, ScalarTy, Opcode0, Opcode1));
11150 // If this pattern is supported by the target then we consider the order.
11151 if (TTI.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask))
11152 return S;
11153 } else if (S &&
11154 (!R.Opts.slp_copyable_elements ||
11155 !isSupportedMainOp(S.getMainOp()) ||
11156 all_of(make_isa_range<Instruction>(VL), [&](Instruction *I) {
11157 return I->getOpcode() == S.getOpcode() ||
11158 (S.getOpcode() == Instruction::Add &&
11159 I->getOpcode() == Instruction::Shl);
11160 }))) {
11161 return S;
11162 }
11163 if (!R.Opts.slp_copyable_elements)
11164 return S;
11165 AbsorbCopyableFMulOrFAdds = hasOnlyAbsorbableCopyableFMulOrFAdds(VL);
11166 findAndSetMainInstruction(VL, R);
11167 if (!MainOp)
11168 return S;
11169 InstructionsState OrigS = S;
11170 S = InstructionsState(MainOp, MainOp, /*HasCopyables=*/true);
11171 // Cast nodes support only matching lanes from the main op block and
11172 // copyable (round-trippable constant) lanes.
11173 if (isa<CastInst>(MainOp) && any_of(VL, [&](Value *V) {
11174 auto *I = dyn_cast<Instruction>(V);
11175 return !isa<PoisonValue>(V) &&
11176 !(I && I->getOpcode() == MainOpcode &&
11177 I->getParent() == MainOp->getParent()) &&
11178 !S.isCopyableElement(V);
11179 }))
11180 return OrigS;
11181 if (OrigS && !isCopyablePreferable(VL, R, OrigS, S))
11182 return OrigS;
11183 if (!WithProfitabilityCheck)
11184 return S;
11185 // ExtractElement copyable nodes reuse the source vector and insert the
11186 // copyable lanes; the binary-operator operand heuristics below do not
11187 // apply, so defer profitability to the full tree cost.
11188 if (isa<ExtractElementInst>(MainOp)) {
11189 // A load as a copyable lane would be pulled out of the consecutive-load
11190 // vectorization; keep the original state so the node can be split.
11191 if (any_of(VL, [&](Value *V) {
11192 return S.isCopyableElement(V) && isa<LoadInst>(V);
11193 }))
11194 return OrigS;
11195 return S;
11196 }
11197 // Check if it is profitable to vectorize the instruction.
11198 unsigned CopyableNum =
11199 count_if(VL, [&](Value *V) { return S.isCopyableElement(V); });
11200 // A cast copyable node just extends the sources of the matching lanes:
11201 // the constant lanes are free in a gather of the original values, so it
11202 // cannot be better unless the matching lanes are the majority and are not
11203 // vectorized already (the gather reuses the vector otherwise).
11204 if (isa<CastInst>(MainOp) &&
11205 (CopyableNum * 2 >= VL.size() || none_of(VL, [&](Value *V) {
11206 return !S.isCopyableElement(V) && !isa<PoisonValue>(V) &&
11207 !R.isVectorized(V);
11208 })))
11209 return OrigS;
11210 // Absorb copyable single-use fmuls/fadds as fmuladd(a, b, -0.0) or
11211 // fmuladd(1.0, a, b) when every copyable is such a binop: the binops die
11212 // instead of being computed and gathered.
11214 AbsorbCopyableFMulOrFAdds)
11216 SmallVector<BoUpSLP::ValueList> Operands = buildOperands(S, VL, R);
11217 auto CheckOperand = [&](ArrayRef<Value *> Ops) {
11218 if (allConstant(Ops) || isSplat(Ops))
11219 return true;
11220 // Non-instruction operands of a call (args, constants) are always a
11221 // trivial gather, same as the constant/splat cases above.
11222 if (MainOpcode == Instruction::Call && none_of(Ops, IsaPred<Instruction>))
11223 return true;
11224 // Check if it is "almost" splat, i.e. has >= 4 elements and only single
11225 // one is different.
11226 constexpr unsigned Limit = 4;
11227 if (Operands.front().size() >= Limit) {
11228 SmallDenseMap<const Value *, unsigned> Counters;
11229 auto IsNotUndef = [](Value *V) { return !isa<UndefValue>(V); };
11230 for (Value *V : make_filter_range(Ops, IsNotUndef))
11231 ++Counters[V];
11232 if (Counters.size() == 2 &&
11233 any_of(Counters, [&](const auto &C) { return C.second == 1; }))
11234 return true;
11235 }
11236 // First operand not a constant or splat? Last attempt - check for
11237 // potential vectorization.
11238 InstructionsCompatibilityAnalysis Analysis(DT, DL, TTI, TLI);
11239 InstructionsState OpS = Analysis.buildInstructionsState(Ops, R);
11240 if (!OpS || (OpS.getOpcode() == Instruction::PHI && !allSameBlock(Ops)))
11241 return false;
11242 unsigned CopyableNum =
11243 count_if(Ops, [&](Value *V) { return OpS.isCopyableElement(V); });
11244 return CopyableNum <= VL.size() / 2;
11245 };
11246 // A copyable GEP node is a vector GEP over the base pointers of the
11247 // matching lanes and the values of the copyable lanes. It is profitable
11248 // only if that base vector is cheap (a splat, constants or vectorizable),
11249 // otherwise it is a gather not cheaper than the gather of the pointers.
11250 if (MainOpcode == Instruction::GetElementPtr &&
11251 !CheckOperand(Operands.front()))
11252 return OrigS;
11253 auto BuildCandidates =
11254 [](SmallVectorImpl<std::pair<Value *, Value *>> &Candidates, Value *V1,
11255 Value *V2) {
11256 if (V1 != V2 && isa<PHINode>(V1))
11257 return;
11258 auto *I1 = dyn_cast<Instruction>(V1);
11259 auto *I2 = dyn_cast<Instruction>(V2);
11260 if (I1 && I2 && I1->getOpcode() == I2->getOpcode() &&
11261 I1->getParent() != I2->getParent())
11262 return;
11263 Candidates.emplace_back(V1, (I1 || I2) ? V2 : V1);
11264 };
11265 if (VL.size() == 2) {
11266 // The operand-pairing heuristic below does not apply to calls, GEPs
11267 // and casts; defer to the full tree cost computation instead of
11268 // pre-rejecting here.
11269 if (MainOpcode == Instruction::Call ||
11270 MainOpcode == Instruction::GetElementPtr || isa<CastInst>(MainOp))
11271 return S;
11272 // Check if the operands allow better vectorization.
11273 SmallVector<std::pair<Value *, Value *>, 4> Candidates1, Candidates2;
11274 BuildCandidates(Candidates1, Operands[0][0], Operands[0][1]);
11275 BuildCandidates(Candidates2, Operands[1][0], Operands[1][1]);
11276 bool Res = !Candidates1.empty() && !Candidates2.empty() &&
11277 R.findBestRootPair(Candidates1).first &&
11278 R.findBestRootPair(Candidates2).first;
11279 if (!Res && isCommutative(MainOp)) {
11280 Candidates1.clear();
11281 Candidates2.clear();
11282 BuildCandidates(Candidates1, Operands[0][0], Operands[1][1]);
11283 BuildCandidates(Candidates2, Operands[1][0], Operands[0][1]);
11284 Res = !Candidates1.empty() && !Candidates2.empty() &&
11285 R.findBestRootPair(Candidates1).first &&
11286 R.findBestRootPair(Candidates2).first;
11287 }
11288 if (!Res)
11289 return OrigS;
11290 const TTI::TargetCostKind Kind = R.getCostKind();
11291 InstructionCost ScalarCost = TTI.getInstructionCost(S.getMainOp(), Kind);
11292 InstructionCost VectorCost;
11293 auto *VecTy = getWidenedType(S.getMainOp()->getType(), VL.size());
11294 switch (MainOpcode) {
11295 case Instruction::Add:
11296 case Instruction::Sub:
11297 case Instruction::Mul:
11298 case Instruction::AShr:
11299 case Instruction::LShr:
11300 case Instruction::Shl:
11301 case Instruction::SDiv:
11302 case Instruction::UDiv:
11303 case Instruction::And:
11304 case Instruction::Or:
11305 case Instruction::Xor:
11306 case Instruction::FAdd:
11307 case Instruction::FMul:
11308 case Instruction::FSub:
11309 case Instruction::FDiv:
11310 VectorCost = TTI.getArithmeticInstrCost(
11311 MainOpcode, VecTy, Kind,
11313 TTI::commonOperandInfo(Operands[1][0], Operands[1][1]), {},
11314 S.getMainOp(), &TLI);
11315 break;
11316 default:
11317 // Calls (min/max, fmuladd) return above before reaching this switch.
11318 llvm_unreachable("Unexpected instruction.");
11319 }
11320 if (VectorCost > ScalarCost)
11321 return OrigS;
11322 return S;
11323 }
11324 // Casts are the only 1-operand and fma/fmuladd are the only 3-operand
11325 // copyables.
11326 assert((Operands.size() == 2 ||
11327 (Operands.size() == 1 && isa<CastInst>(MainOp)) ||
11328 (Operands.size() == 3 && isFMAOrFMulAdd(MainOp))) &&
11329 "Unexpected number of operands!");
11330 if (CopyableNum < VL.size() / 2)
11331 return S;
11332 // Too many phi copyables - exit.
11333 const unsigned Limit = VL.size() / 24;
11334 if ((CopyableNum >= VL.size() - Limit ||
11335 (CopyableNum >= VL.size() - 1 && VL.size() > 4) ||
11336 CopyableNum >= MaxPHINumOperands) &&
11337 all_of(VL, [&](Value *V) {
11338 return isa<PHINode>(V) || !S.isCopyableElement(V);
11339 }))
11340 return OrigS;
11341 // Check profitability if number of copyables > VL.size() / 2.
11342 // 1. Reorder operands for better matching.
11343 if (Operands.size() == 2 && isCommutative(MainOp)) {
11344 Value *BestFrontOp = nullptr;
11345 for (auto [OpL, OpR] : zip(Operands.front(), Operands.back())) {
11346 // Make instructions the first operands.
11347 if (!isa<Instruction>(OpL) && isa<Instruction>(OpR)) {
11348 BestFrontOp = OpR;
11349 std::swap(OpL, OpR);
11350 continue;
11351 }
11352 // Make constants the second operands.
11353 if ((isa<Constant>(OpL) && !match(OpR, m_Zero())) ||
11354 match(OpL, m_Zero())) {
11355 if (isa<Instruction>(OpR))
11356 BestFrontOp = OpR;
11357 std::swap(OpL, OpR);
11358 continue;
11359 }
11360 if (isa<Instruction>(OpL))
11361 BestFrontOp = OpL;
11362 }
11363 // If some of the RHS operands better match most of LHS - swap such
11364 // operands to increase matching rate.
11365 if (auto *BestLHS = dyn_cast_if_present<Instruction>(BestFrontOp)) {
11366 const unsigned BestOpcode = BestLHS->getOpcode();
11367 for (auto [OpL, OpR] : zip(Operands.front(), Operands.back())) {
11368 auto *OpRI = dyn_cast<Instruction>(OpR);
11369 if (!OpRI)
11370 continue;
11371 if (OpRI->getOpcode() == BestOpcode)
11372 std::swap(OpL, OpR);
11373 }
11374 }
11375 }
11376 // 2. Check, if operands can be vectorized. Skip for fmuladd; the
11377 // copyable operand is checked below and may legitimately hold many
11378 // instructions. The instructions, built only from the first operand of the
11379 // same lane and constants, are computed from the vectorized first
11380 // operand, not gathered.
11381 if (Operands.size() == 2 &&
11382 count_if(Operands.back(), IsaPred<Instruction>) > 1 &&
11383 !all_of(zip(Operands.front(), Operands.back()), [](const auto &P) {
11384 auto *I = dyn_cast<Instruction>(std::get<1>(P));
11385 return !I || all_of(I->operands(), [&](Value *Op) {
11386 return Op == std::get<0>(P) || isConstant(Op);
11387 });
11388 }))
11389 return OrigS;
11390 // Check the operand holding the copyable values.
11391 if (!CheckOperand(Operands[S.getCopyableOpIdx()])) {
11392 if (Operands.size() == 2)
11393 return OrigS;
11394 // Retry with the copyable modeled as the first multiplicand.
11395 S.setCopyableOpIdx(0);
11396 Operands = buildOperands(S, VL, R);
11397 if (!CheckOperand(Operands[S.getCopyableOpIdx()]))
11398 return OrigS;
11399 }
11400
11401 return S;
11402 }
11403
11405 buildOperands(const InstructionsState &S, ArrayRef<Value *> VL,
11406 const BoUpSLP &R, bool AllowPoisonPlaceholders = true) {
11407 assert(S && "Invalid state!");
11410 MainOp = S.getMainOp();
11411 MainOpcode = S.getOpcode();
11412 // ExtractElement copyable nodes carry a single operand (the shared
11413 // source vector); copyable lanes are inserted during codegen and do
11414 // not contribute an operand column.
11415 if (MainOpcode == Instruction::ExtractElement) {
11416 Operands.assign(1,
11417 BoUpSLP::ValueList(VL.size(), MainOp->getOperand(0)));
11418 return Operands;
11419 }
11420 // The undef lanes of the loads have no pointer operands.
11421 if (MainOpcode == Instruction::Load) {
11422 buildOriginalOperands(S, VL, Operands);
11423 return Operands;
11424 }
11425 // Excludes the trailing callee operand (2 for min/max, 3 for fmuladd).
11426 // getNumberOfPotentiallyCommutativeOps collapses fmuladd to 2 and must
11427 // not be used here. Only the 2-operand case is commutative-normalized.
11428 auto *CI = dyn_cast<CallInst>(MainOp);
11429 const unsigned NumMainOpOperands =
11430 CI ? CI->arg_size() : MainOp->getNumOperands();
11431 const bool IsCommutative =
11432 isCommutative(MainOp) && NumMainOpOperands == 2;
11433 Operands.assign(NumMainOpOperands,
11434 BoUpSLP::ValueList(VL.size(), nullptr));
11435 SmallPtrSet<const Value *, 4> SelfOpLanes = findSelfOpLanes(S, VL, R);
11436 const bool PoisonPlaceholders =
11437 AllowPoisonPlaceholders && canUsePoisonPlaceholders(S, VL);
11438 // Populate operands for every lane.
11439 for (auto [Idx, V] : enumerate(VL)) {
11440 SmallVector<Value *> OperandsForValue =
11441 getOperands(S, V, SelfOpLanes.contains(V), PoisonPlaceholders);
11442 for (auto [OperandIdx, Operand] : enumerate(OperandsForValue))
11443 Operands[OperandIdx][Idx] = Operand;
11444 }
11445 // The copyable lanes of a GEP node are gep V, 0; cast the indices of
11446 // the matching lanes and the zeroes to the common index type.
11447 if (MainOpcode == Instruction::GetElementPtr)
11448 buildGEPIndexOperands(
11449 VL, MainOp,
11450 [&](Value *V) {
11452 },
11453 Operands[1]);
11454 // Operand-order normalization below swaps OpIdx 0 and OpIdx 1
11455 // of non-copyable lanes. That is only safe when the main op is
11456 // commutative (e.g. 0 - X is not X - 0, so `sub` must be
11457 // excluded). With absorbed fmul/fadd copyables the fmuladd
11458 // multiplicands are commutative per lane and get normalized too;
11459 // the 0/1 swaps never touch the addend column.
11460 if (IsCommutative || S.hasAbsorbedCopyableFMulOrFAdd()) {
11461 // IsCommutative can hold for MainOp (e.g. a Sub/FSub feeding only
11462 // fabs/icmp-eq-0) without every lane sharing that property, so
11463 // re-check the specific lane before swapping it. Absorbed fmul/fadd
11464 // lanes are always commutative.
11465 auto CanSwap = [&](Value *V) {
11468 return true;
11470 V);
11471 };
11472 // Absorbed fmul/fadd copyables do not vote for the majority operand
11473 // pattern (their multiplicand order is arbitrary) but take part
11474 // in the swaps.
11475 auto SwappableLane = [&](Value *V) {
11476 return !isa<PoisonValue>(V) &&
11477 (!S.isCopyableElement(V) ||
11480 };
11481 // Count (ID0, ID1) pair frequencies for operand normalization.
11482 // Pairs and their inverses are tracked under a canonical key
11483 // so that (Load, Add) and (Add, Load) contribute to the same
11484 // bucket.
11485 struct PairInfo {
11486 unsigned FwdCount = 0;
11487 unsigned RevCount = 0;
11488 };
11489 SmallMapVector<std::pair<unsigned, unsigned>, PairInfo, 8> PairCounts;
11490 SmallMapVector<unsigned, unsigned, 4> AddendIDCounts;
11491 unsigned MajID0 = 0, MajID1 = 0;
11492 for (const auto &P :
11493 make_filter_range(enumerate(VL), [&](const auto &P) {
11494 return !S.isCopyableElement(P.value()) &&
11495 !isa<PoisonValue>(P.value());
11496 })) {
11497 size_t Idx = P.index();
11498 unsigned ID0 = Operands[0][Idx]->getValueID();
11499 unsigned ID1 = Operands[1][Idx]->getValueID();
11501 ++AddendIDCounts[Operands[2][Idx]->getValueID()];
11502 if (ID0 == ID1)
11503 continue;
11504 unsigned MinID = std::min(ID0, ID1);
11505 unsigned MaxID = std::max(ID0, ID1);
11506 auto *It = PairCounts.try_emplace(std::make_pair(MinID, MaxID)).first;
11507 PairInfo &Info = It->second;
11508 if (ID0 < ID1)
11509 ++Info.FwdCount;
11510 else
11511 ++Info.RevCount;
11512 }
11513 // Find the most frequent (ID0, ID1) pair across non-copyable
11514 // lanes. Select the orientation (original or inverse) that
11515 // has more votes as the majority pattern.
11516 unsigned BestCount = 0;
11517 for (const auto &P : PairCounts) {
11518 const PairInfo &Info = P.second;
11519 unsigned Total = Info.FwdCount + Info.RevCount;
11520 if (Total > BestCount) {
11521 BestCount = Total;
11522 if (Info.FwdCount >= Info.RevCount) {
11523 MajID0 = P.first.first;
11524 MajID1 = P.first.second;
11525 } else {
11526 MajID0 = P.first.second;
11527 MajID1 = P.first.first;
11528 }
11529 }
11530 }
11531 // Absorbed fadd copyables are fmuladd(1.0, a, b): pick the
11532 // addend/multiplicand assignment matching the majority operand
11533 // kinds of the non-copyable lanes in the multiplicand (1) and
11534 // addend (2) columns.
11536 unsigned MajID2 = 0, Best2 = 0;
11537 for (const auto &P : AddendIDCounts) {
11538 if (P.second > Best2) {
11539 Best2 = P.second;
11540 MajID2 = P.first;
11541 }
11542 }
11543 for (auto [Idx, V] : enumerate(VL)) {
11544 auto *I = dyn_cast<Instruction>(V);
11545 if (!I || I->getOpcode() != Instruction::FAdd ||
11547 continue;
11548 unsigned ID1 = Operands[1][Idx]->getValueID();
11549 unsigned ID2 = Operands[2][Idx]->getValueID();
11550 unsigned Cur = (ID1 == MajID1) + (ID2 == MajID2);
11551 unsigned Swapped = (ID2 == MajID1) + (ID1 == MajID2);
11552 if (Swapped > Cur)
11553 std::swap(Operands[1][Idx], Operands[2][Idx]);
11554 }
11555 }
11556 // Normalize swappable lanes in two steps:
11557 // 1) Swap lanes whose operand types are the exact inverse of
11558 // the majority pattern, making the non-copyable lanes
11559 // consistent.
11560 // 2) Independently, if a strict majority of swappable lanes
11561 // have loads at OpIdx 1, swap those lanes to put loads at
11562 // OpIdx 0 for better downstream vectorization.
11563 unsigned LAt0 = 0, LAt1 = 0, TotalNC = 0;
11564 for (auto [Idx, V] :
11565 make_filter_range(enumerate(VL), [&](const auto &P) {
11566 return SwappableLane(P.value());
11567 })) {
11568 // Step 1: swap exact-inverse lanes.
11569 if (BestCount > 0) {
11570 unsigned ID0 = Operands[0][Idx]->getValueID();
11571 unsigned ID1 = Operands[1][Idx]->getValueID();
11572 if (ID0 == MajID1 && ID1 == MajID0 && CanSwap(V))
11573 std::swap(Operands[0][Idx], Operands[1][Idx]);
11574 }
11575 ++TotalNC;
11576 LAt0 += isa<LoadInst>(Operands[0][Idx]);
11577 LAt1 += isa<LoadInst>(Operands[1][Idx]);
11578 }
11579 // Step 2: if most non-copyable lanes have loads at OpIdx 1,
11580 // swap those lanes to put loads at OpIdx 0.
11581 if (TotalNC > 1 && LAt1 > LAt0 && LAt1 * 2 > TotalNC) {
11582 for (auto [Idx, V] :
11583 make_filter_range(enumerate(VL), [&](const auto &P) {
11584 return SwappableLane(P.value());
11585 })) {
11586 if (!isa<LoadInst>(Operands[0][Idx]) &&
11587 isa<LoadInst>(Operands[1][Idx]) && CanSwap(V))
11588 std::swap(Operands[0][Idx], Operands[1][Idx]);
11589 }
11590 }
11591 }
11592 } else {
11593 buildOriginalOperands(S, VL, Operands);
11594 }
11595 return Operands;
11596 }
11597};
11598} // namespace
11599
11600void BoUpSLP::tryToVectorizeSplatGatheredScalars() {
11601 unsigned PrevTreeSize = VectorizableTree.size();
11602 auto LoadsSubkey = [](size_t /*Key*/, LoadInst *LI) {
11603 return hash_value(getUnderlyingObject(LI->getPointerOperand()));
11604 };
11605 // The key includes the value type: the opcode-based key does not always
11606 // distinguish types (e.g. all extractvalue instructions share one key),
11607 // while the tree requires same-typed scalars.
11608 SmallMapVector<std::tuple<size_t, size_t, Type *>, SmallSetVector<Value *, 4>,
11609 4>
11610 Groups;
11611 // Only gathers with vectorized (non-gather) users can reuse the broadcast.
11612 for (const std::unique_ptr<TreeEntry> &TE : make_filter_range(
11613 VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
11614 return TE->isGather() && TE->UserTreeIndex &&
11615 !TE->UserTreeIndex.UserTE->isGather() &&
11616 isSplat(TE->Scalars);
11617 })) {
11618 auto *I = dyn_cast<Instruction>(TE->Scalars.front());
11619 // Skip shuffle-like instructions: their splat gathers are already emitted
11620 // as cheap shuffles of the source vector.
11621 if (!I ||
11623 I->getType()->isVoidTy() || isVectorized(I) || isDeleted(I) ||
11624 (UserIgnoreList && UserIgnoreList->contains(I)))
11625 continue;
11626 // Scheduling new memory bundles in a to-be-versioned tree records extra
11627 // alias-check pairs and can push the region over the versioning limits.
11628 if (isTryingRuntimeAliasChecks() && I->mayReadOrWriteMemory())
11629 continue;
11630 auto [Key, SubKey] =
11631 generateKeySubkey(I, TLI, LoadsSubkey, /*AllowAlternate=*/true);
11632 Groups[std::make_tuple(Key, SubKey, I->getType())].insert(I);
11633 }
11634 // Values left in singleton groups cannot form a bundle on their own;
11635 // regroup them by the opcode-insensitive key so alternate/copyable
11636 // bundles still form.
11637 SmallMapVector<std::pair<size_t, Type *>, SmallSetVector<Value *, 4>, 4>
11638 FallbackGroups;
11639 for (auto &[Key, Group] : make_filter_range(
11640 Groups, [](const auto &P) { return P.second.size() < 2; })) {
11641 FallbackGroups[std::make_pair(std::get<0>(Key), Group.front()->getType())]
11642 .insert(Group.front());
11643 }
11644 InstructionsCompatibilityAnalysis Analysis(*DT, *DL, *TTI, *TLI);
11645 auto BuildSubtree = [&](const auto &GroupMap) {
11646 auto IsMultiElement = [](const auto &P) { return P.second.size() >= 2; };
11647 for (const auto &Entry : make_filter_range(GroupMap, IsMultiElement)) {
11648 const auto &Group = Entry.second;
11649 // Copyable-aware check so bundles with copyable lanes are not skipped.
11650 if (!Analysis.buildInstructionsState(Group.getArrayRef(), *this))
11651 continue;
11652 unsigned PrevSize = VectorizableTree.size();
11653 buildTreeRec(Group.getArrayRef(), 0, EdgeInfo());
11654 if (PrevSize == VectorizableTree.size())
11655 continue;
11656 TreeEntry *NewRoot = VectorizableTree[PrevSize].get();
11657 if (NewRoot->isGather()) {
11658 // Failed to vectorize the bundle: drop the added gather entry, it has
11659 // no users and only adds cost.
11660 for (Value *V : NewRoot->Scalars) {
11661 auto It = ValueToGatherNodes.find(V);
11662 if (It != ValueToGatherNodes.end())
11663 It->second.remove(NewRoot);
11664 }
11665 LoadEntriesToVectorize.remove(PrevSize);
11666 VectorizableTree.pop_back();
11667 continue;
11668 }
11669 // The root has no users, the gathers reuse its lanes by value: keep the
11670 // loads in memory order instead of permuting them into the group order.
11671 if (NewRoot->State == TreeEntry::Vectorize &&
11672 NewRoot->getOpcode() == Instruction::Load)
11673 NewRoot->ReorderIndices.clear();
11674 SplatGatheredScalarsRoots.push_back(NewRoot);
11675 }
11676 };
11677 BuildSubtree(Groups);
11678 BuildSubtree(FallbackGroups);
11679 NumCanonicalSplatSubtreeEntries = VectorizableTree.size() - PrevTreeSize;
11680}
11681
11682BoUpSLP::ScalarsVectorizationLegality
11683BoUpSLP::getScalarsVectorizationLegality(ArrayRef<Value *> VL, unsigned Depth,
11684 const EdgeInfo &UserTreeIdx) const {
11685 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
11686
11687 InstructionsCompatibilityAnalysis Analysis(*DT, *DL, *TTI, *TLI);
11688 InstructionsState S = Analysis.buildInstructionsState(
11689 VL, *this, /*WithProfitabilityCheck=*/true);
11690
11691 bool AreScatterAllGEPSameBlock = false;
11692 if (!S) {
11693 SmallVector<unsigned> SortedIndices;
11694 BasicBlock *BB = nullptr;
11695 bool IsScatterVectorizeUserTE =
11696 UserTreeIdx.UserTE &&
11697 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize;
11698 AreScatterAllGEPSameBlock =
11699 (IsScatterVectorizeUserTE && VL.front()->getType()->isPointerTy() &&
11700 VL.size() > 2 &&
11701 all_of(VL,
11702 [&BB](Value *V) {
11704 if (!I)
11706 if (!BB)
11707 BB = I->getParent();
11708 return BB == I->getParent() && I->getNumOperands() == 2;
11709 }) &&
11710 BB &&
11711 sortPtrAccesses(VL, UserTreeIdx.UserTE->getMainOp()->getType(), *DL,
11712 *SE, SortedIndices));
11713 if (!AreScatterAllGEPSameBlock) {
11714 LLVM_DEBUG(dbgs() << "SLP: Try split and if failed, gathering due to "
11715 "C,S,B,O, small shuffle. \n";
11716 dbgs() << "[";
11717 interleaveComma(VL, dbgs(), [&](Value *V) { dbgs() << *V; });
11718 dbgs() << "]\n");
11719 return ScalarsVectorizationLegality(S, /*IsLegal=*/false,
11720 /*TryToFindDuplicates=*/true,
11721 /*TrySplitVectorize=*/true);
11722 }
11723 // Reset S to make it GetElementPtr kind of node.
11724 const auto *It = find_if(VL, IsaPred<GetElementPtrInst>);
11725 assert(It != VL.end() && "Expected at least one GEP.");
11726 S = getSameOpcode(*It, *TLI);
11727 }
11728 assert(S && "Must be valid.");
11729
11730 // Gather very wide PHI bundles. Wide PHIs (e.g. produced by
11731 // jump threading) are not profitable to vectorize and make this analysis
11732 // explode, so gather them to keep the compile time bounded.
11733 if (S.getOpcode() == Instruction::PHI) {
11734 unsigned NumIncomingValues =
11735 cast<PHINode>(S.getMainOp())->getNumIncomingValues();
11736 if (static_cast<uint64_t>(VL.size()) * NumIncomingValues >
11737 Opts.slp_phi_vectorization_budget) {
11738 LLVM_DEBUG(dbgs() << "SLP: Gathering due to wide PHI operand fan-out ("
11739 << VL.size() << " lanes x " << NumIncomingValues
11740 << " incoming values).\n");
11741 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11742 }
11743 }
11744
11745 // Don't handle vectors.
11746 if (!Opts.slp_revec &&
11747 getValueType(VL.front(), Opts.slp_revec)->isVectorTy()) {
11748 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
11749 // Do not try to pack to avoid extra instructions here.
11750 return ScalarsVectorizationLegality(S, /*IsLegal=*/false,
11751 /*TryToFindDuplicates=*/false);
11752 }
11753
11754 // Check that all of the users of the scalars that we want to vectorize are
11755 // schedulable.
11756 BasicBlock *BB = S.getMainOp()->getParent();
11757
11758 if (BB->isEHPad() || isa<UnreachableInst>(BB->getTerminator()) ||
11759 !DT->isReachableFromEntry(BB)) {
11760 // Don't go into unreachable blocks. They may contain instructions with
11761 // dependency cycles which confuse the final scheduling.
11762 // Do not vectorize EH and non-returning blocks, not profitable in most
11763 // cases.
11764 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
11765 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11766 }
11767
11768 // Don't go into catchswitch blocks, which can happen with PHIs.
11769 // Such blocks can only have PHIs and the catchswitch. There is no
11770 // place to insert a shuffle if we need to, so just avoid that issue.
11772 LLVM_DEBUG(dbgs() << "SLP: bundle in catchswitch block.\n");
11773 // Do not try to pack to avoid extra instructions here.
11774 return ScalarsVectorizationLegality(S, /*IsLegal=*/false,
11775 /*TryToFindDuplicates=*/false);
11776 }
11777
11778 // Don't handle scalable vectors
11779 if (S.getOpcode() == Instruction::ExtractElement &&
11781 cast<ExtractElementInst>(S.getMainOp())->getVectorOperandType())) {
11782 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
11783 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11784 }
11785
11786 // Gather if we hit the RecursionMaxDepth, unless this is a load (or z/sext of
11787 // a load), in which case peek through to include it in the tree, without
11788 // ballooning over-budget.
11789 if (Depth >= Opts.slp_recursion_max_depth &&
11790 (S.isAltShuffle() || VL.size() < 4 ||
11791 !(match(S.getMainOp(), m_Load(m_Value())) ||
11792 all_of(VL, [&S](const Value *I) {
11793 return match(I,
11795 cast<Instruction>(I)->getOpcode() == S.getOpcode();
11796 })))) {
11797 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
11798 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11799 }
11800
11801 // Check if this is a duplicate of another entry.
11802 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.getMainOp() << ".\n");
11803 // Cache invariants to avoid recomputing for every V in VL (and every E).
11804 const bool IsPHIWithLoop =
11805 S.getOpcode() == Instruction::PHI &&
11806 LI->getLoopFor(S.getMainOp()->getParent()) != nullptr;
11807 for (TreeEntry *E : getTreeEntries(S.getMainOp())) {
11808 if (E->isSame(VL)) {
11809 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.getMainOp()
11810 << ".\n");
11811 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11812 }
11813 SmallPtrSet<Value *, 8> Values(llvm::from_range, E->Scalars);
11814 if (all_of(VL, [&](Value *V) {
11815 return isa<PoisonValue>(V) || Values.contains(V) ||
11816 (IsPHIWithLoop && isa<PHINode>(V) && isVectorized(V));
11817 })) {
11818 LLVM_DEBUG(dbgs() << "SLP: Gathering due to full overlap.\n");
11819 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11820 }
11821 }
11822
11823 bool AreAllSameBlock = !AreScatterAllGEPSameBlock;
11824 bool AreAllSameInsts = AreAllSameBlock || AreScatterAllGEPSameBlock;
11825 if (!AreAllSameInsts || isSplat(VL) ||
11827 S.getMainOp()) &&
11829 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O conditions. \n";
11830 dbgs() << "[";
11831 interleaveComma(VL, dbgs(), [&](Value *V) { dbgs() << *V; });
11832 dbgs() << "]\n");
11833 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11834 }
11835
11836 // Don't vectorize ephemeral values.
11837 if (!EphValues.empty()) {
11838 for (Value *V : VL) {
11839 if (EphValues.count(V)) {
11840 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
11841 << ") is ephemeral.\n");
11842 // Do not try to pack to avoid extra instructions here.
11843 return ScalarsVectorizationLegality(S, /*IsLegal=*/false,
11844 /*TryToFindDuplicates=*/false);
11845 }
11846 }
11847 }
11848
11849 // We now know that this is a vector of instructions of the same type from
11850 // the same block.
11851
11852 // Check that none of the instructions in the bundle are already in the tree
11853 // and the node may be not profitable for the vectorization as the small
11854 // alternate node.
11855 if (S.isAltShuffle()) {
11856 auto GetNumVectorizedExtracted = [&]() {
11857 APInt Extracted = APInt::getZero(VL.size());
11858 APInt Vectorized = APInt::getAllOnes(VL.size());
11859 for (auto [Idx, V] : enumerate(VL)) {
11860 auto *I = dyn_cast<Instruction>(V);
11861 if (!I || doesNotNeedToBeScheduled(I) ||
11862 all_of(I->operands(), [&](const Use &U) {
11863 return isa<ExtractElementInst>(U.get());
11864 }))
11865 continue;
11866 if (isVectorized(I))
11867 Vectorized.clearBit(Idx);
11868 else if (!I->hasOneUser() && !areAllUsersVectorized(I, UserIgnoreList))
11869 Extracted.setBit(Idx);
11870 }
11871 return std::make_pair(Vectorized, Extracted);
11872 };
11873 auto [Vectorized, Extracted] = GetNumVectorizedExtracted();
11874 bool PreferScalarize = !Vectorized.isAllOnes() && VL.size() == 2;
11875 if (!Vectorized.isAllOnes() && !PreferScalarize) {
11876 // Rough cost estimation, if the vector code (+ potential extracts) is
11877 // more profitable than the scalar + buildvector.
11878 Type *ScalarTy = VL.front()->getType();
11879 auto *VecTy = cast<VectorType>(getWidenedType(ScalarTy, VL.size()));
11880 InstructionCost VectorizeCostEstimate =
11881 getShuffleCost(*TTI, TTI::SK_PermuteTwoSrc, VecTy, CostKind) +
11883 *TTI, Opts.slp_revec, ScalarTy, VecTy, Extracted,
11884 /*Insert=*/false, /*Extract=*/true, CostKind);
11885 InstructionCost ScalarizeCostEstimate = getScalarizationOverhead(
11886 *TTI, Opts.slp_revec, ScalarTy, VecTy, Vectorized,
11887 /*Insert=*/true, /*Extract=*/false, CostKind, /*ForPoisonSrc=*/false);
11888 PreferScalarize = VectorizeCostEstimate > ScalarizeCostEstimate;
11889 }
11890 if (PreferScalarize) {
11891 LLVM_DEBUG(dbgs() << "SLP: The instructions are in tree and alternate "
11892 "node is not profitable.\n");
11893 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11894 }
11895 }
11896
11897 // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
11898 if (UserIgnoreList && !UserIgnoreList->empty()) {
11899 for (Value *V : VL) {
11900 if (UserIgnoreList->contains(V)) {
11901 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
11902 return ScalarsVectorizationLegality(S, /*IsLegal=*/false);
11903 }
11904 }
11905 }
11906
11907 return ScalarsVectorizationLegality(S, /*IsLegal=*/true);
11908}
11909
11910/// Peel associative single-use binary chains into operand columns. Peeled
11911/// instructions go to \p ReassocScalars; sub-operands are inserted after the
11912/// peeled column so real pairs stay adjacent for flag reuse.
11913/// Poison lanes are allowed through; a lane that is not itself a matching
11914/// real instruction can still be peeled as a copyable identity leaf, as
11915/// long as some other lane anchors the opcode.
11916/// Add/sub (and fadd/fsub) chains peel together: a peeled subtract keeps
11917/// the column sign for its first operand and flips it for the second one,
11918/// recorded per column in \p NegatedColumns, so subtracted leaves stay out
11919/// of the positive total.
11921 const InstructionsState &S, DominatorTree &DT, const DataLayout &DL,
11924 SmallBitVector &NegatedColumns, SmallVectorImpl<Value *> &ReassocScalars) {
11925 assert(Operands.size() == 2 && NegatedColumns.empty() &&
11926 "Expected the initial 2 operand columns.");
11927 // The subtract family flips the sign of its second operand column.
11928 auto IsSub = [](unsigned Opcode) {
11929 return Opcode == Instruction::Sub || Opcode == Instruction::FSub;
11930 };
11931 // Signs ride with the columns so the parallel lists cannot drift apart.
11932 struct SignedColumn {
11934 bool Negated;
11935 };
11937 {std::move(Operands[0]), false},
11938 {std::move(Operands[1]), IsSub(S.getOpcode())}};
11939 InstructionsCompatibilityAnalysis Analysis(DT, DL, TTI, TLI);
11940 // The opcode family a column may peel into: subtracts flatten as adds of
11941 // a negated leaf, other opcodes peel only into their own kind.
11942 const unsigned RootFamily = getReassocCombineOpcode(S.getOpcode());
11943 // A lane whose value is itself a single-use chain link; block placement
11944 // does not matter here (buildTreeRec re-checks that later for whatever
11945 // columns end up as real leaves).
11946 auto IsRealLane = [&](Value *V) {
11947 auto *I = dyn_cast<Instruction>(V);
11948 return I && I->hasOneUse() &&
11949 getReassocCombineOpcode(I->getOpcode()) == RootFamily &&
11951 };
11952 // Builds on InstructionsCompatibilityAnalysis's own opcode matching
11953 // (rather than the more permissive getSameOpcode()) so a column that
11954 // falls back to a copyable identity leaf only ever anchors on a MainOp
11955 // that InstructionsCompatibilityAnalysis::isSupportedOpcode() accepts.
11956 auto CanPeel = [&](ArrayRef<Value *> Column) {
11957 InstructionsState ColS = Analysis.buildInstructionsState(Column, R);
11958 if (!ColS || getReassocCombineOpcode(ColS.getOpcode()) != RootFamily ||
11959 ColS.isAltShuffle())
11961 // Every lane must be poison, a genuine matching real lane, or (only for
11962 // a copyable ColS) stand in as a copyable identity leaf
11963 // (Opcode(V, identity) == V).
11964 if (!all_of(Column, [&](Value *V) {
11965 return isa<PoisonValue>(V) || IsRealLane(V) ||
11967 ColS.isCopyableElement(V));
11968 }))
11970 return ColS;
11971 };
11972 for (unsigned Idx = 0; Idx != Columns.size();) {
11973 InstructionsState ColS = CanPeel(Columns[Idx].Col);
11974 if (!ColS) {
11975 ++Idx;
11976 continue;
11977 }
11978 BoUpSLP::ValueList Column = std::move(Columns[Idx].Col);
11979 // The absorbing constants of the peeled lanes keep the identity as the
11980 // other operand: the poison operand is not frozen in the flattened node.
11981 SmallVector<BoUpSLP::ValueList> SubOperands = Analysis.buildOperands(
11982 ColS, Column, R, /*AllowPoisonPlaceholders=*/false);
11983 assert(SubOperands.size() == 2 && "Expected 2 operand columns.");
11984 // Poison and copyable lanes have no real instruction left to erase
11985 // later: a copyable V is used as-is, not subsumed by the flattened
11986 // combine.
11987 for (Value *V : Column)
11988 if (!isa<PoisonValue>(V) && !ColS.isCopyableElement(V))
11989 ReassocScalars.push_back(V);
11990 // A peeled subtract negates its second operand column.
11991 const bool Negated = Columns[Idx].Negated;
11992 const bool SubNegated = IsSub(ColS.getOpcode()) != Negated;
11993 // The identity of a copyable lane is combined with the total of the
11994 // column it lands in, so it follows the sign of that column rather than
11995 // the opcode of the peeled column.
11996 if (Negated && RootFamily == Instruction::FAdd)
11997 for (auto [V, Op] : zip(Column, SubOperands.back()))
11998 if (ColS.isCopyableElement(V))
11999 Op = getReassocIdentity(RootFamily, Op->getType(), SubNegated);
12000 Columns[Idx].Col = std::move(SubOperands.front());
12001 Columns.insert(std::next(Columns.begin(), Idx + 1),
12002 {std::move(SubOperands.back()), SubNegated});
12003 // Do not advance Idx: re-examine the column that was just placed here.
12004 }
12005 Operands.clear();
12006 for (auto &[Col, Negated] : Columns) {
12007 Operands.push_back(std::move(Col));
12008 NegatedColumns.push_back(Negated);
12009 }
12010}
12011
12012/// Realign flattened operand columns so matching value families share a
12013/// column across lanes. Lane 0 is canonical; other lanes match by key equality
12014/// only (never compare hash values). Columns sharing a key are paired by the
12015/// family of their first operand where available, so e.g. shifts fed by the
12016/// same load family land in one column instead of pairing by encounter order.
12017/// Values move between columns only within the same sign: a subtracted leaf
12018/// never lands in an added column. The sign is queried per lane and column
12019/// with \p IsNegated: alternate add/sub nodes negate only the non-leading
12020/// columns of their subtract lanes.
12023 function_ref<bool(unsigned Lane, unsigned Col)> IsNegated,
12024 const TargetLibraryInfo &TLI) {
12025 const unsigned NumCols = Operands.size();
12026 const unsigned NumLanes = Operands.front().size();
12027 auto LoadsSubkey = [](size_t /*Key*/, LoadInst *LI) {
12028 return hash_value(getUnderlyingObject(LI->getPointerOperand()));
12029 };
12030 auto GetKey = [&](Value *V) {
12031 return generateKeySubkey(V, &TLI, LoadsSubkey, /*AllowAlternate=*/false);
12032 };
12033 const std::pair<size_t, size_t> NoSecondaryKey{0, 0};
12034 // Family of the value's first operand; loads already carry their family in
12035 // the primary key.
12036 auto GetSecondaryKey = [&](Value *V) -> std::pair<size_t, size_t> {
12037 auto *I = dyn_cast<Instruction>(V);
12038 if (!I || isa<LoadInst>(I) || I->getNumOperands() == 0)
12039 return NoSecondaryKey;
12040 return GetKey(I->getOperand(0));
12041 };
12043 Operands, [&](const BoUpSLP::ValueList &Col) { return GetKey(Col[0]); });
12044 SmallVector<std::pair<size_t, size_t>> Lane0SecondaryKeys =
12045 map_to_vector(Operands, [&](const BoUpSLP::ValueList &Col) {
12046 return GetSecondaryKey(Col[0]);
12047 });
12048
12050 BoUpSLP::ValueList(NumLanes));
12051 for (unsigned Col : seq<unsigned>(NumCols))
12052 Aligned[Col][0] = Operands[Col][0];
12053
12054 for (unsigned Lane : seq<unsigned>(1, NumLanes)) {
12055 // Buckets are keyed by the value key and the column sign.
12056 using Key = std::pair<std::pair<size_t, size_t>, unsigned>;
12057 auto Sign = [&](unsigned Col) { return IsNegated(Lane, Col) ? 1U : 0U; };
12059 for (unsigned Col : seq<unsigned>(NumCols))
12060 Buckets[{GetKey(Operands[Col][Lane]), Sign(Col)}].push_back(Col);
12062 SmallVector<unsigned> SlotSrcCol(NumCols, NumCols);
12063 SmallBitVector ColClaimed(NumCols, false);
12064 for (unsigned Slot : seq<unsigned>(NumCols)) {
12065 const auto SlotKey = std::make_pair(Lane0Keys[Slot], Sign(Slot));
12066 auto BucketIt = Buckets.find(SlotKey);
12067 if (BucketIt == Buckets.end())
12068 continue;
12069 unsigned &Cursor = NextInBucket[SlotKey];
12070 if (Cursor >= BucketIt->second.size())
12071 continue;
12072 // Among the remaining same-key columns prefer the one whose operand
12073 // family matches lane 0's; no match keeps the bucket order.
12074 unsigned PickPos = Cursor;
12075 if (Lane0SecondaryKeys[Slot] != NoSecondaryKey)
12076 for (unsigned P = Cursor, E = BucketIt->second.size(); P != E; ++P)
12077 if (GetSecondaryKey(Operands[BucketIt->second[P]][Lane]) ==
12078 Lane0SecondaryKeys[Slot]) {
12079 PickPos = P;
12080 break;
12081 }
12082 std::swap(BucketIt->second[Cursor], BucketIt->second[PickPos]);
12083 unsigned SrcCol = BucketIt->second[Cursor++];
12084 SlotSrcCol[Slot] = SrcCol;
12085 ColClaimed[SrcCol] = true;
12086 }
12087 // Leftover slots take leftover columns of the same sign; per-lane sign
12088 // counts match, so every slot finds one.
12089 for (unsigned Slot : seq<unsigned>(NumCols)) {
12090 if (SlotSrcCol[Slot] != NumCols)
12091 continue;
12092 for (unsigned Col : seq<unsigned>(NumCols)) {
12093 if (!ColClaimed[Col] && IsNegated(Lane, Col) == IsNegated(Lane, Slot)) {
12094 SlotSrcCol[Slot] = Col;
12095 ColClaimed[Col] = true;
12096 break;
12097 }
12098 }
12099 }
12100 for (unsigned Slot : seq<unsigned>(NumCols))
12101 Aligned[Slot][Lane] = Operands[SlotSrcCol[Slot]][Lane];
12102 }
12103 return Aligned;
12104}
12105
12106/// Rank reassociated operand layouts by vectorizable load columns, other load
12107/// patterns, broadcast/constant columns, then fewer unique values per column.
12108/// Identity columns are scored by the opcode of the emitted combines.
12109static std::tuple<unsigned, unsigned, unsigned, int>
12111 unsigned Opcode) {
12112 unsigned NumConsecutiveLoadCols = 0;
12113 unsigned NumOtherVecLoadCols = 0;
12114 unsigned NumBroadcastOrConstCols = 0;
12115 int NumUniqueValues = 0;
12116 const unsigned CombineOpcode = getReassocCombineOpcode(Opcode);
12117 for (ArrayRef<Value *> Col : Columns) {
12118 if (all_of(Col, IsaPred<Constant>)) {
12119 ++NumBroadcastOrConstCols;
12120 continue;
12121 }
12122 // Identity constants are free beyond the base they are inserted into.
12123 SmallPtrSet<Value *, 8> UniqueValues;
12124 for (Value *V : Col)
12125 if (!isBinOpIdentityConstant(V, CombineOpcode))
12126 UniqueValues.insert(V);
12127 NumUniqueValues += UniqueValues.size();
12128 if (UniqueValues.size() <= 1) {
12129 ++NumBroadcastOrConstCols;
12130 continue;
12131 }
12132 if (all_of(Col, IsaPred<LoadInst>)) {
12133 BoUpSLP::OrdersType Order;
12134 SmallVector<Value *> PointerOps;
12135 BoUpSLP::StridedPtrInfo SPtrInfo;
12137 R.canVectorizeLoads(Col, Col.front(), Order, PointerOps, SPtrInfo);
12139 ++NumConsecutiveLoadCols;
12140 else if (LS != BoUpSLP::LoadsState::Gather)
12141 ++NumOtherVecLoadCols;
12142 }
12143 }
12144 // Greater is better; negate unique count as a tie-breaker.
12145 return std::make_tuple(NumConsecutiveLoadCols, NumOtherVecLoadCols,
12146 NumBroadcastOrConstCols, -NumUniqueValues);
12147}
12148
12149void BoUpSLP::buildTreeRec(ArrayRef<Value *> VLRef, unsigned Depth,
12150 const EdgeInfo &UserTreeIdx,
12151 unsigned InterleaveFactor) {
12152 assert((allConstant(VLRef) || allSameType(VLRef)) && "Invalid types!");
12153
12154 SmallVector<int> ReuseShuffleIndices;
12155 SmallVector<Value *> VL(VLRef);
12156
12157 // Tries to build split node.
12158 auto TrySplitNode = [&](const InstructionsState &LocalState,
12159 bool SplitInHalves = false) {
12160 SmallVector<Value *> Op1, Op2;
12161 OrdersType ReorderIndices;
12162 if (SplitInHalves) {
12163 auto *Mid = std::next(VL.begin(), VL.size() / 2);
12164 Op1.assign(VL.begin(), Mid);
12165 Op2.assign(Mid, VL.end());
12166 } else if (!canBuildSplitNode(VL, LocalState, Op1, Op2, ReorderIndices)) {
12167 return false;
12168 }
12169
12170 auto Invalid = ScheduleBundle::invalid();
12171 auto *TE = newTreeEntry(VL, TreeEntry::SplitVectorize, Invalid, LocalState,
12172 UserTreeIdx, {}, ReorderIndices);
12173 LLVM_DEBUG(dbgs() << "SLP: split alternate node.\n"; TE->dump());
12174 auto AddNode = [&](ArrayRef<Value *> Op, unsigned Idx) {
12175 InstructionsState S = getSameOpcode(Op, *TLI);
12176 if (S && (isa<LoadInst>(S.getMainOp()) ||
12177 getSameValuesTreeEntry(S.getMainOp(), Op, /*SameVF=*/true))) {
12178 // Build gather node for loads, they will be gathered later.
12179 TE->CombinedEntriesWithIndices.emplace_back(VectorizableTree.size(),
12180 Idx == 0 ? 0 : Op1.size());
12181 (void)newTreeEntry(Op, TreeEntry::NeedToGather, Invalid, S, {TE, Idx});
12182 } else {
12183 TE->CombinedEntriesWithIndices.emplace_back(VectorizableTree.size(),
12184 Idx == 0 ? 0 : Op1.size());
12185 buildTreeRec(Op, Depth, {TE, Idx});
12186 }
12187 };
12188 AddNode(Op1, 0);
12189 AddNode(Op2, 1);
12190 return true;
12191 };
12192
12193 auto AreOnlyConstsWithPHIs = [](ArrayRef<Value *> VL) {
12194 bool AreConsts = false;
12195 auto IsNotPoison = [](Value *V) { return !isa<PoisonValue>(V); };
12196 for (Value *V : make_filter_range(VL, IsNotPoison)) {
12197 if (isa<Constant>(V)) {
12198 AreConsts = true;
12199 continue;
12200 }
12201 if (!isa<PHINode>(V))
12202 return false;
12203 }
12204 return AreConsts;
12205 };
12206 if (AreOnlyConstsWithPHIs(VL)) {
12207 LLVM_DEBUG(dbgs() << "SLP: Gathering due to all constants and PHIs.\n");
12208 newGatherTreeEntry(VL, InstructionsState::invalid(), UserTreeIdx);
12209 return;
12210 }
12211
12212 ScalarsVectorizationLegality Legality =
12213 getScalarsVectorizationLegality(VL, Depth, UserTreeIdx);
12214 InstructionsState S = Legality.getInstructionsState();
12215 if (!Legality.isLegal()) {
12216 if (Legality.trySplitVectorize()) {
12217 auto [MainOp, AltOp] = getMainAltOpsNoStateVL(VL);
12218 // Last chance to try to vectorize alternate node.
12219 if (MainOp && AltOp && TrySplitNode(InstructionsState(MainOp, AltOp)))
12220 return;
12221 }
12222 if (Legality.tryToFindDuplicates())
12223 (void)tryToFindDuplicates(Opts, VL, ReuseShuffleIndices, *TTI, *TLI, S,
12224 UserTreeIdx, *this);
12225
12226 newGatherTreeEntry(VL, S, UserTreeIdx, ReuseShuffleIndices);
12227 return;
12228 }
12229
12230 if (SplitStoredValues && S && UserTreeIdx.UserTE &&
12231 UserTreeIdx.UserTE->Idx == 0 && TrySplitNode(S, /*SplitInHalves=*/true))
12232 return;
12233
12234 // FIXME: investigate if there are profitable cases for VL.size() <= 4.
12235 if (S.isAltShuffle() && TrySplitNode(S))
12236 return;
12237
12238 // Cmp nodes with interchangeable lanes (e.g. x == 0 mixed with x <u C)
12239 // try the split by the original predicates, like the alternate nodes. The
12240 // trunc X to i1 lanes have no original predicate.
12241 if (S.getOpcode() == Instruction::ICmp && !S.isAltShuffle() &&
12243 auto SameOrSwapped = [](const ICmpInst *CI, CmpInst::Predicate P) {
12244 return CI->getPredicate() == P ||
12246 };
12247 ICmpInst *MainI = cast<ICmpInst>(*find_if(VL, IsaPred<ICmpInst>));
12248 auto *AltIt = find_if(VL, [&](Value *V) {
12249 auto *CI = dyn_cast<ICmpInst>(V);
12250 return CI && !SameOrSwapped(CI, MainI->getPredicate());
12251 });
12252 ICmpInst *AltI = AltIt == VL.end() ? nullptr : cast<ICmpInst>(*AltIt);
12253 if (AltI &&
12255 [&](ICmpInst *CI) {
12256 return SameOrSwapped(CI, MainI->getPredicate()) ||
12257 SameOrSwapped(CI, AltI->getPredicate());
12258 }) &&
12259 TrySplitNode(InstructionsState(MainI, AltI)))
12260 return;
12261 }
12262
12263 // Check that every instruction appears once in this bundle.
12264 if (!tryToFindDuplicates(Opts, VL, ReuseShuffleIndices, *TTI, *TLI, S,
12265 UserTreeIdx, *this, /*BuildGatherOnly=*/false)) {
12266 newGatherTreeEntry(VL, S, UserTreeIdx, ReuseShuffleIndices);
12267 return;
12268 }
12269
12270 // Perform specific checks for each particular instruction kind.
12271 bool IsScatterVectorizeUserTE =
12272 UserTreeIdx.UserTE &&
12273 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize;
12274 OrdersType CurrentOrder;
12275 SmallVector<Value *> PointerOps;
12276 StridedPtrInfo SPtrInfo;
12277 SmallVector<int> ExpandShuffleMask;
12278 TreeEntry::EntryState State = getScalarsVectorizationState(
12279 S, VL, IsScatterVectorizeUserTE, CurrentOrder, PointerOps, SPtrInfo,
12280 ExpandShuffleMask);
12281 // The zero-extended sub-fields of the same wider integer scalar are
12282 // gathered and emitted as a bitcast to the field vector plus a permutation.
12283 // For 2 lanes the emission is not cheaper than the insertelement chain.
12284 if (State == TreeEntry::NeedToGather ||
12285 (VL.size() > 2 && ReuseShuffleIndices.empty() &&
12286 matchGatheredExtractedFields(VL, *DL))) {
12287 newGatherTreeEntry(VL, S, UserTreeIdx, ReuseShuffleIndices);
12288 return;
12289 }
12290
12291 // Check the loop nest. We need to be sure we handle a single loop nest at a
12292 // time to avoid incorrect cost estimation because of the loop aware cost
12293 // model.
12294 if (VectorizableTree.empty()) {
12295 assert(CurrentLoopNest.empty() && "Expected empty loop nest");
12296 // Process the first node? Initial fill of the loop nest.
12297 BasicBlock *Parent = S.getMainOp()->getParent();
12298 if (const Loop *L = LI->getLoopFor(Parent)) {
12300 if (L)
12301 CurrentLoopNest.assign(getLoopNest(L));
12302 }
12303 } else if (!UserTreeIdx ||
12304 UserTreeIdx.UserTE->State == TreeEntry::SplitVectorize ||
12305 UserTreeIdx.UserTE->isGather() ||
12306 UserTreeIdx.UserTE->getMainOp()->getParent() !=
12307 S.getMainOp()->getParent()) {
12308 BasicBlock *Parent = S.getMainOp()->getParent();
12309 if (const Loop *L = LI->getLoopFor(Parent)) {
12310 // Check that the new loop nest shares the same outer structure as the
12311 // tree's current loop nest. Completely disjoint nests (different
12312 // outermost loops) are forced to gather because their scales cannot be
12313 // meaningfully combined. Sibling inner loops (inside a common outer
12314 // loop or outside any loops at all) are allowed: the cost model scales
12315 // each entry by its own loop via getScaleToLoopIterations(), so a tree
12316 // that spans sibling inner loops (e.g. a PHI at their merge block) can
12317 // still be costed correctly. Contract CurrentLoopNest to the longest
12318 // common prefix with the new entry's nest so subsequent entries in yet
12319 // another sibling can also be admitted.
12321 if (L) {
12322 SmallVector<const Loop *> NewLoopNest(getLoopNest(L));
12323 unsigned CommonLen = 0;
12324 for (const auto [L1, L2] : zip(CurrentLoopNest, NewLoopNest)) {
12325 if (L1 != L2)
12326 break;
12327 ++CommonLen;
12328 }
12329 auto ValidateMergedBTCs = [&](unsigned StartDepth) -> bool {
12330 unsigned EndDepth =
12331 std::min<unsigned>(NewLoopNest.size(), MergedLoopBTCs.size());
12332 for (unsigned D = StartDepth; D < EndDepth; ++D) {
12333 const SCEV *Constraint = MergedLoopBTCs[D];
12334 if (!Constraint)
12335 continue;
12336 const SCEV *NewBTC = SE->getBackedgeTakenCount(NewLoopNest[D]);
12337 if (isa<SCEVCouldNotCompute>(NewBTC) || NewBTC != Constraint)
12338 return false;
12339 }
12340 return true;
12341 };
12342 auto BailOutToGather = [&]() {
12344 << "SLP: Sibling loops have different trip counts.\n");
12345 newGatherTreeEntry(VL, S, UserTreeIdx, ReuseShuffleIndices);
12346 };
12347 if (CurrentLoopNest.empty()) {
12348 if (!ValidateMergedBTCs(0)) {
12349 BailOutToGather();
12350 return;
12351 }
12352 CurrentLoopNest.assign(NewLoopNest);
12353 } else if (CommonLen < CurrentLoopNest.size() &&
12354 CommonLen < NewLoopNest.size()) {
12355 // Divergence below the common prefix: the tree now spans sibling
12356 // loops at depth CommonLen. Admitting them into one tree makes
12357 // the profitability decision JOINT across both siblings, so a
12358 // very hot sibling could otherwise let an unprofitable cold
12359 // sibling ride along "for free" (per-entry scaling of the cold
12360 // sibling's entries would be dwarfed by the hot one). Require
12361 // SCEV-proven equal backedge-taken counts for the diverging
12362 // siblings before joining; otherwise force gather.
12363 const Loop *SibA = CurrentLoopNest[CommonLen];
12364 const Loop *SibB = NewLoopNest[CommonLen];
12365 const SCEV *BecA = SE->getBackedgeTakenCount(SibA);
12366 const SCEV *BecB = SE->getBackedgeTakenCount(SibB);
12367 if (isa<SCEVCouldNotCompute>(BecA) || BecA != BecB) {
12368 BailOutToGather();
12369 return;
12370 }
12371 if (!ValidateMergedBTCs(CommonLen + 1)) {
12372 BailOutToGather();
12373 return;
12374 }
12375 if (MergedLoopBTCs.size() <= CommonLen)
12376 MergedLoopBTCs.resize(CommonLen + 1, nullptr);
12377 MergedLoopBTCs[CommonLen] = BecA;
12378 CurrentLoopNest.truncate(CommonLen);
12379 } else if (NewLoopNest.size() > CurrentLoopNest.size()) {
12380 if (!ValidateMergedBTCs(CurrentLoopNest.size())) {
12381 BailOutToGather();
12382 return;
12383 }
12384 CurrentLoopNest.append(
12385 std::next(NewLoopNest.begin(), CurrentLoopNest.size()),
12386 NewLoopNest.end());
12387 }
12388 // Otherwise NewLoopNest is a prefix of CurrentLoopNest: keep as-is.
12389 }
12390 }
12391 }
12392
12393 Instruction *VL0 = S.getMainOp();
12394 BasicBlock *BB = VL0->getParent();
12395 auto &BSRef = BlocksSchedules[BB];
12396 if (!BSRef)
12397 BSRef = std::make_unique<BlockScheduling>(BB, Opts.slp_schedule_budget);
12398
12399 BlockScheduling &BS = *BSRef;
12400 TreeBlocksSchedules.insert(&BS);
12401
12402 SetVector<Value *> UniqueValues(llvm::from_range, VL);
12403 std::optional<ScheduleBundle *> BundlePtr =
12404 BS.tryScheduleBundle(UniqueValues.getArrayRef(), this, S, UserTreeIdx);
12405#ifdef EXPENSIVE_CHECKS
12406 // Make sure we didn't break any internal invariants
12407 BS.verify();
12408#endif
12409 if (!BundlePtr || (*BundlePtr && !*BundlePtr.value())) {
12410 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
12411 // Last chance to try to vectorize alternate node.
12412 if (S.isAltShuffle() && ReuseShuffleIndices.empty() && TrySplitNode(S))
12413 return;
12414 // Last chance to try to vectorize copyable node.
12416 ReuseShuffleIndices.empty()) {
12417 InstructionsState AltS = getSameOpcode(VL, *TLI);
12418 if (AltS && AltS.isAltShuffle() && TrySplitNode(AltS))
12419 return;
12420 }
12421 newGatherTreeEntry(VL, S, UserTreeIdx, ReuseShuffleIndices);
12422 NonScheduledFirst.insert(VL.front());
12423 if (S.getOpcode() == Instruction::Load &&
12424 BS.ScheduleRegionSize < BS.ScheduleRegionSizeLimit)
12426 return;
12427 }
12428 InstructionsCompatibilityAnalysis Analysis(*DT, *DL, *TTI, *TLI);
12429 SmallVector<ValueList> Operands = Analysis.buildOperands(S, VL, *this);
12430 // Flatten associative binary chains into operand columns. Only the peeled
12431 // chain links are required to be single-use (they are erased); the root
12432 // being flattened may have other uses. Skip lanes that are neither chain
12433 // links nor copyable identity leaves. Alternate nodes flatten too, but
12434 // each lane keeps its own opcode on every combine level. Restricted to
12435 // BinaryOperator: isAssociative() is also true for associative intrinsics
12436 // (e.g. smax/smin/umax/umin), which are CallInst, not BinaryOperator, and
12437 // are not supported by the copyable-identity machinery used below
12438 // (ConstantExpr::getBinOpIdentity, isSupportedOpcode,
12439 // isBinOpIdentityConstant).
12440 SmallVector<Value *> ReassocScalars;
12441 // Sign of each flattened operand column (a subtracted leaf is negated).
12442 SmallBitVector NegatedColumns;
12443 // Per-lane subtract markers for flattened alternate nodes.
12444 SmallBitVector SubLanes;
12445 // Cached below (when the peel is kept) so the reorder step further down
12446 // does not need to redo the aligning/scoring work.
12447 SmallVector<ValueList> ReassocAlignedOperands;
12448 // Snapshot of the pre-flatten operand columns, used by both revert points.
12449 SmallVector<ValueList> NaturalTwoColumns;
12450 std::tuple<unsigned, unsigned, unsigned, int> ReassocPeeledQuality;
12451 if (Opts.slp_reassociate_ops && Operands.size() == 2 &&
12452 all_of(VL, [&](Value *V) {
12453 if (!S.isAltShuffle() && S.isCopyableElement(V))
12454 return true;
12455 auto *I = dyn_cast<BinaryOperator>(V);
12456 return I && isReassocChainLink(I);
12457 })) {
12458 NaturalTwoColumns = Operands;
12459 if (S.isAltShuffle()) {
12460 if (SmallVector<SmallVector<Value *>> Flattened =
12461 scanAltAssociativeOperands(S, *TLI, VL, Operands[0], Operands[1],
12462 ReassocScalars, SubLanes);
12463 !Flattened.empty()) {
12464 Operands.clear();
12465 for (auto &Col : Flattened)
12466 Operands.emplace_back(std::move(Col));
12467 }
12468 } else {
12469 scanAssociativeOperands(S, *DT, *DL, *TTI, *TLI, *this, Operands,
12470 NegatedColumns, ReassocScalars);
12471 }
12472 // Drop flattening unless realigning improves load or broadcast column
12473 // structure; an unimproved peel ties and reverts to natural columns.
12474 if (!ReassocScalars.empty()) {
12475 auto IsNegated = [&](unsigned Lane, unsigned Col) {
12476 return S.isAltShuffle() ? Col > 0 && SubLanes.test(Lane)
12477 : NegatedColumns.test(Col);
12478 };
12479 ReassocAlignedOperands =
12480 alignReassociatedOperandsByKey(Operands, IsNegated, *TLI);
12481 // Alternate nodes compare against the natural two-column form rather
12482 // than the raw peel: the natural form pays one lane-select shuffle per
12483 // level, so the flatten is worth keeping whenever the realigned
12484 // columns improve on the natural ones.
12485 ReassocPeeledQuality = getReassocColumnsQuality(
12486 S.isAltShuffle() ? NaturalTwoColumns : Operands, *this,
12487 S.getOpcode());
12488 // The unique-value count (4th field) is only a tie-break for the
12489 // later reorder-or-not decision, not for this one.
12490 auto DropUniqueCount = [](const auto &Quality) {
12491 return std::make_tuple(std::get<0>(Quality), std::get<1>(Quality),
12492 std::get<2>(Quality));
12493 };
12494 if (DropUniqueCount(getReassocColumnsQuality(ReassocAlignedOperands,
12495 *this, S.getOpcode())) <=
12496 DropUniqueCount(ReassocPeeledQuality)) {
12497 Operands = std::move(NaturalTwoColumns);
12498 ReassocScalars.clear();
12499 }
12500 }
12501 }
12502 // Registers peeled chain links on the node so they are erased with it and
12503 // their scheduling deps are released as reassociated operands.
12504 auto RegisterReassocScalars = [&](TreeEntry *TE) {
12505 for (Value *V : ReassocScalars) {
12506 TE->addReassocScalar(V);
12507 SmallVectorImpl<const TreeEntry *> &Owners =
12508 ReassocScalarToTreeEntries.try_emplace(V).first->second;
12509 if (!is_contained(Owners, TE))
12510 Owners.push_back(TE);
12511 }
12512 };
12513 // A value routed into several columns is consumed by several combines;
12514 // that distorts both the cost and the vector structure (duplicated loads,
12515 // partial masked columns), so prefer the natural two-column shape.
12516 auto HasDupColumnValues = [&]() {
12517 SmallPtrSet<const Value *, 16> ColumnValues;
12518 return any_of(Operands, [&](const ValueList &Col) {
12519 return any_of(Col, [&](const Value *V) {
12520 return !isa<Constant>(V) && !ColumnValues.insert(V).second;
12521 });
12522 });
12523 };
12524 ScheduleBundle Empty;
12525 ScheduleBundle &Bundle = BundlePtr.value() ? *BundlePtr.value() : Empty;
12526 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
12527
12528 unsigned ShuffleOrOp =
12529 S.isAltShuffle() ? (unsigned)Instruction::ShuffleVector : S.getOpcode();
12530 auto CreateOperandNodes = [&](TreeEntry *TE, const auto &Operands) {
12531 // Postpone PHI nodes creation
12532 SmallVector<unsigned> PHIOps;
12533 for (unsigned I : seq<unsigned>(Operands.size())) {
12535 if (Op.empty())
12536 continue;
12537 InstructionsState S = getSameOpcode(Op, *TLI);
12538 if ((!S || S.getOpcode() != Instruction::PHI) || S.isAltShuffle())
12539 buildTreeRec(Op, Depth + 1, {TE, I});
12540 else
12541 PHIOps.push_back(I);
12542 }
12543 for (unsigned I : PHIOps)
12544 buildTreeRec(Operands[I], Depth + 1, {TE, I});
12545 };
12546 switch (ShuffleOrOp) {
12547 case Instruction::PHI: {
12548 TreeEntry *TE =
12549 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndices);
12550 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (PHINode).\n";
12551 TE->dump());
12552
12553 TE->setOperands(Operands);
12554 CreateOperandNodes(TE, Operands);
12555 return;
12556 }
12557 case Instruction::ExtractValue:
12558 case Instruction::ExtractElement: {
12559 if (CurrentOrder.empty()) {
12560 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
12561 } else {
12562 LLVM_DEBUG({
12563 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
12564 "with order";
12565 for (unsigned Idx : CurrentOrder)
12566 dbgs() << " " << Idx;
12567 dbgs() << "\n";
12568 });
12569 fixupOrderingIndices(CurrentOrder);
12570 }
12571 // Insert new order with initial value 0, if it does not exist,
12572 // otherwise return the iterator to the existing one.
12573 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12574 ReuseShuffleIndices, CurrentOrder);
12575 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry "
12576 "(ExtractValueInst/ExtractElementInst).\n";
12577 TE->dump());
12578 // This is a special case, as it does not gather, but at the same time
12579 // we are not extending buildTreeRec() towards the operands.
12580 TE->setOperands(Operands);
12581 if (ShuffleOrOp == Instruction::ExtractValue) {
12582 SmallVector<unsigned> Indices;
12584 if (checkEVsForVecCalls(VL, S, *TLI, Indices, Calls)) {
12585 TE->StructEVIndices = std::move(Indices);
12586 buildTreeRec(Operands.front(), Depth + 1, {TE, 0});
12587 }
12588 }
12589 return;
12590 }
12591 case Instruction::InsertValue:
12592 case Instruction::InsertElement: {
12593 assert(ReuseShuffleIndices.empty() && "All inserts should be unique");
12594
12595 auto OrdCompare = [](const std::pair<int, int> &P1,
12596 const std::pair<int, int> &P2) {
12597 return P1.first > P2.first;
12598 };
12599 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
12600 decltype(OrdCompare)>
12601 Indices(OrdCompare);
12602 for (int I = 0, E = VL.size(); I < E; ++I) {
12603 unsigned Idx = *getElementIndex(VL[I]);
12604 Indices.emplace(Idx, I);
12605 }
12606 OrdersType CurrentOrder(VL.size(), VL.size());
12607 bool IsIdentity = true;
12608 for (int I = 0, E = VL.size(); I < E; ++I) {
12609 CurrentOrder[Indices.top().second] = I;
12610 IsIdentity &= Indices.top().second == I;
12611 Indices.pop();
12612 }
12613 if (IsIdentity)
12614 CurrentOrder.clear();
12615 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12616 {}, CurrentOrder);
12617 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (InsertElementInst).\n";
12618 TE->dump());
12619
12620 TE->setOperands(Operands);
12621 buildTreeRec(TE->getOperand(1), Depth + 1, {TE, 1});
12622 return;
12623 }
12624 case Instruction::Load: {
12625 // Check that a vectorized load would load the same memory as a scalar
12626 // load. For example, we don't want to vectorize loads that are smaller
12627 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
12628 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
12629 // from such a struct, we read/write packed bits disagreeing with the
12630 // unvectorized version.
12631 TreeEntry *TE = nullptr;
12632 fixupOrderingIndices(CurrentOrder);
12633 switch (State) {
12634 case TreeEntry::Vectorize:
12635 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12636 ReuseShuffleIndices, CurrentOrder, InterleaveFactor);
12637 if (CurrentOrder.empty())
12638 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (LoadInst).\n";
12639 TE->dump());
12640 else
12642 << "SLP: added a new TreeEntry (jumbled LoadInst).\n";
12643 TE->dump());
12644 break;
12645 case TreeEntry::CompressVectorize:
12646 // Vectorizing non-consecutive loads with (masked)load + compress.
12647 TE = newTreeEntry(VL, TreeEntry::CompressVectorize, Bundle, S,
12648 UserTreeIdx, ReuseShuffleIndices, CurrentOrder);
12649 LLVM_DEBUG(
12650 dbgs()
12651 << "SLP: added a new TreeEntry (masked LoadInst + compress).\n";
12652 TE->dump());
12653 break;
12654 case TreeEntry::StridedVectorize:
12655 // Vectorizing non-consecutive loads with `llvm.masked.gather`.
12656 TE = newTreeEntry(VL, TreeEntry::StridedVectorize, Bundle, S,
12657 UserTreeIdx, ReuseShuffleIndices, CurrentOrder);
12658 TreeEntryToStridedPtrInfoMap[TE] = SPtrInfo;
12659 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (strided LoadInst).\n";
12660 TE->dump());
12661 break;
12662 case TreeEntry::ScatterVectorize:
12663 // Vectorizing non-consecutive loads with `llvm.masked.gather`.
12664 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
12665 UserTreeIdx, ReuseShuffleIndices);
12666 LLVM_DEBUG(
12667 dbgs()
12668 << "SLP: added a new TreeEntry (non-consecutive LoadInst).\n";
12669 TE->dump());
12670 break;
12671 case TreeEntry::BlendedLoadVectorize: {
12672 // Two masked loads from the candidate bases, blended by the per-lane
12673 // select conditions. The conditions are added as the operand node, so
12674 // the blend mask is vectorized through the tree.
12675 TE = newTreeEntry(VL, TreeEntry::BlendedLoadVectorize, Bundle, S,
12676 UserTreeIdx, ReuseShuffleIndices);
12677 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (blended LoadInst).\n";
12678 TE->dump());
12679 Value *TrueBase = nullptr;
12680 Value *FalseBase = nullptr;
12681 SmallVector<Value *> Conditions;
12682 [[maybe_unused]] bool Found = isSelectedBaseLoad(
12683 VL0->getType(), PointerOps, *DL, TrueBase, FalseBase, Conditions);
12684 assert(Found && "Expected a valid blended-load pattern.");
12685 Operands.assign(1, ValueList(Conditions.begin(), Conditions.end()));
12686 TE->setOperands(Operands);
12687 buildTreeRec(TE->getOperand(0), Depth + 1, {TE, 0});
12688 return;
12689 }
12690 case TreeEntry::ExpandVectorize:
12691 case TreeEntry::CombinedVectorize:
12692 case TreeEntry::SplitVectorize:
12693 case TreeEntry::NeedToGather:
12694 llvm_unreachable("Unexpected loads state.");
12695 }
12696 if (!CurrentOrder.empty() && State != TreeEntry::ScatterVectorize) {
12697 assert(Operands.size() == 1 && "Expected a single operand only");
12698 SmallVector<int> Mask;
12699 inversePermutation(CurrentOrder, Mask);
12700 reorderScalars(Operands.front(), Mask);
12701 }
12702 TE->setOperands(Operands);
12703 if (State == TreeEntry::ScatterVectorize)
12704 buildTreeRec(PointerOps, Depth + 1, {TE, 0});
12705 return;
12706 }
12707 case Instruction::ZExt:
12708 case Instruction::SExt:
12709 case Instruction::FPToUI:
12710 case Instruction::FPToSI:
12711 case Instruction::FPExt:
12712 case Instruction::PtrToInt:
12713 case Instruction::PtrToAddr:
12714 case Instruction::IntToPtr:
12715 case Instruction::SIToFP:
12716 case Instruction::UIToFP:
12717 case Instruction::Trunc:
12718 case Instruction::FPTrunc:
12719 case Instruction::BitCast: {
12720 auto [PrevMaxBW, PrevMinBW] = CastMaxMinBWSizes.value_or(
12721 std::make_pair(std::numeric_limits<unsigned>::min(),
12722 std::numeric_limits<unsigned>::max()));
12723 if (ShuffleOrOp == Instruction::ZExt ||
12724 ShuffleOrOp == Instruction::SExt) {
12725 CastMaxMinBWSizes = std::make_pair(
12726 std::max<unsigned>(DL->getTypeSizeInBits(VL0->getType()),
12727 PrevMaxBW),
12728 std::min<unsigned>(
12729 DL->getTypeSizeInBits(VL0->getOperand(0)->getType()),
12730 PrevMinBW));
12731 } else if (ShuffleOrOp == Instruction::Trunc) {
12732 CastMaxMinBWSizes = std::make_pair(
12733 std::max<unsigned>(
12734 DL->getTypeSizeInBits(VL0->getOperand(0)->getType()),
12735 PrevMaxBW),
12736 std::min<unsigned>(DL->getTypeSizeInBits(VL0->getType()),
12737 PrevMinBW));
12738 }
12739 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12740 ReuseShuffleIndices);
12741 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (CastInst).\n";
12742 TE->dump());
12743
12744 TE->setOperands(Operands);
12745 for (unsigned I : seq<unsigned>(VL0->getNumOperands()))
12746 buildTreeRec(TE->getOperand(I), Depth, {TE, I});
12747 if (ShuffleOrOp == Instruction::Trunc) {
12748 ExtraBitWidthNodes.insert(getOperandEntry(TE, 0)->Idx);
12749 } else if (ShuffleOrOp == Instruction::SIToFP ||
12750 ShuffleOrOp == Instruction::UIToFP) {
12751 unsigned NumSignBits =
12752 ComputeNumSignBits(VL0->getOperand(0), *DL, AC, nullptr, DT);
12753 if (auto *OpI = dyn_cast<Instruction>(VL0->getOperand(0))) {
12754 APInt Mask = DB->getDemandedBits(OpI);
12755 NumSignBits = std::max(NumSignBits, Mask.countl_zero());
12756 }
12757 if (NumSignBits * 2 >=
12758 DL->getTypeSizeInBits(VL0->getOperand(0)->getType()))
12759 ExtraBitWidthNodes.insert(getOperandEntry(TE, 0)->Idx);
12760 }
12761 return;
12762 }
12763 case Instruction::ICmp:
12764 case Instruction::FCmp: {
12765 // Check that all of the compares have the same predicate.
12766 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
12767 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12768 ReuseShuffleIndices);
12769 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (CmpInst).\n";
12770 TE->dump());
12771 // The ands of the bit tests are peeled into the operands of the node.
12772 if (any_of(VL, IsaPred<TruncInst>)) {
12773 for (ICmpInst *CI : make_isa_range<ICmpInst>(VL))
12774 ReassocScalars.push_back(CI->getOperand(0));
12775 RegisterReassocScalars(TE);
12776 }
12777
12778 VLOperands Ops(VL, Operands, S, *this);
12779 if (cast<CmpInst>(VL0)->isCommutative()) {
12780 // Commutative predicate - collect + sort operands of the instructions
12781 // so that each side is more likely to have the same opcode.
12783 "Commutative Predicate mismatch");
12784 Ops.reorder();
12785 Operands.front() = Ops.getVL(0);
12786 Operands.back() = Ops.getVL(1);
12787 } else {
12788 // Collect operands - commute if it uses the swapped predicate.
12789 // Lanes interchangeable with P0 (e.g. x == 0 in an x <u C bundle)
12790 // already have their operands adjusted, no need to commute them.
12791 for (auto [Idx, V] :
12792 make_filter_range(enumerate(VL), [](const auto &P) {
12793 return isa<CmpInst>(P.value());
12794 })) {
12795 auto *Cmp = cast<CmpInst>(V);
12796 if (Cmp->getPredicate() != P0 &&
12798 std::swap(Operands.front()[Idx], Operands.back()[Idx]);
12799 }
12800 }
12801 TE->setOperands(Operands);
12802 buildTreeRec(Operands.front(), Depth, {TE, 0});
12803 buildTreeRec(Operands.back(), Depth, {TE, 1});
12804 if (ShuffleOrOp == Instruction::ICmp) {
12805 unsigned NumSignBits0 =
12806 ComputeNumSignBits(VL0->getOperand(0), *DL, AC, nullptr, DT);
12807 if (NumSignBits0 * 2 >=
12808 DL->getTypeSizeInBits(VL0->getOperand(0)->getType()))
12809 ExtraBitWidthNodes.insert(getOperandEntry(TE, 0)->Idx);
12810 unsigned NumSignBits1 =
12811 ComputeNumSignBits(VL0->getOperand(1), *DL, AC, nullptr, DT);
12812 if (NumSignBits1 * 2 >=
12813 DL->getTypeSizeInBits(VL0->getOperand(1)->getType()))
12814 ExtraBitWidthNodes.insert(getOperandEntry(TE, 1)->Idx);
12815 }
12816 return;
12817 }
12818 case Instruction::Select:
12819 case Instruction::FNeg:
12820 case Instruction::Add:
12821 case Instruction::FAdd:
12822 case Instruction::Sub:
12823 case Instruction::FSub:
12824 case Instruction::Mul:
12825 case Instruction::FMul:
12826 case Instruction::UDiv:
12827 case Instruction::SDiv:
12828 case Instruction::FDiv:
12829 case Instruction::URem:
12830 case Instruction::SRem:
12831 case Instruction::FRem:
12832 case Instruction::Shl:
12833 case Instruction::LShr:
12834 case Instruction::AShr:
12835 case Instruction::And:
12836 case Instruction::Or:
12837 case Instruction::Xor:
12838 case Instruction::Freeze: {
12839 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12840 ReuseShuffleIndices);
12841 LLVM_DEBUG(
12842 dbgs() << "SLP: added a new TreeEntry "
12843 "(SelectInst/UnaryOperator/BinaryOperator/FreezeInst).\n";
12844 TE->dump());
12845
12846 if (!ReassocScalars.empty()) {
12847 // Realign columns by value family (cached above as
12848 // ReassocAlignedOperands), then let VLOperands polish the order,
12849 // keeping the polish only if the column-quality score does not regress
12850 // vs the peeled order. That polish is quadratic in the column count, so
12851 // past ReassocReorderColumnLimit keep the realigned seed, which already
12852 // groups the vectorizable columns. The polish swaps values between
12853 // columns per lane, which must not mix added and subtracted leaves in
12854 // one column, so signed nodes polish each sign group separately.
12855 if (Operands.size() <= Opts.slp_reassociate_reorder_limit) {
12856 SmallVector<ValueList> Reordered = ReassocAlignedOperands;
12857 SmallVector<unsigned> GroupIds[2];
12858 for (unsigned I : seq<unsigned>(NegatedColumns.size()))
12859 GroupIds[NegatedColumns[I]].push_back(I);
12860 for (ArrayRef<unsigned> Group :
12861 make_filter_range(GroupIds, [](ArrayRef<unsigned> Group) {
12862 return Group.size() > 1;
12863 })) {
12865 Group, [&](unsigned I) { return ReassocAlignedOperands[I]; });
12866 VLOperands Ops(GroupCols, VL0->getParent(), *this);
12867 Ops.reorder();
12868 for (unsigned Pos : seq<unsigned>(Group.size()))
12869 Reordered[Group[Pos]] = Ops.getVL(Pos);
12870 }
12871 if (getReassocColumnsQuality(Reordered, *this, S.getOpcode()) >=
12872 ReassocPeeledQuality)
12873 Operands = std::move(Reordered);
12874 else
12875 LLVM_DEBUG(dbgs() << "SLP: reassociation reorder loses column "
12876 "structure, keeping the natural operand "
12877 "order.\n");
12878 } else {
12879 Operands = std::move(ReassocAlignedOperands);
12880 }
12881 if (HasDupColumnValues()) {
12882 Operands = std::move(NaturalTwoColumns);
12883 ReassocScalars.clear();
12884 }
12885 }
12886 if (!ReassocScalars.empty())
12887 RegisterReassocScalars(TE);
12888 else if (isa<BinaryOperator>(VL0) && isCommutative(VL0)) {
12889 VLOperands Ops(VL, Operands, S, *this);
12890 Ops.reorder();
12891 Operands[0] = Ops.getVL(0);
12892 Operands[1] = Ops.getVL(1);
12893 }
12894 TE->setOperands(Operands);
12895 if (!ReassocScalars.empty() && NegatedColumns.any())
12896 TE->setReassocNegatedOps(NegatedColumns);
12897 for (unsigned I : seq<unsigned>(TE->getNumOperands()))
12898 buildTreeRec(TE->getOperand(I), Depth + 1, {TE, I});
12899 return;
12900 }
12901 case Instruction::GetElementPtr: {
12902 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12903 ReuseShuffleIndices);
12904 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (GetElementPtrInst).\n";
12905 TE->dump());
12906 TE->setOperands(Operands);
12907
12908 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
12909 buildTreeRec(Operands[I], Depth + 1, {TE, I});
12910 return;
12911 }
12912 case Instruction::Store: {
12913 assert(CurrentOrder.empty() &&
12914 "Expected ordered store during tree building");
12915 if (State == TreeEntry::StridedVectorize) {
12916 TreeEntry *TE =
12917 newTreeEntry(VL, TreeEntry::StridedVectorize, Bundle, S,
12918 UserTreeIdx, ReuseShuffleIndices, CurrentOrder);
12919 TreeEntryToStridedPtrInfoMap[TE] = SPtrInfo;
12920 LLVM_DEBUG(
12921 dbgs() << "SLP: added a new TreeEntry (strided StoreInst).\n";
12922 TE->dump());
12923 TE->setOperands(Operands);
12924 buildTreeRec(TE->getOperand(0), Depth + 1, {TE, 0});
12925 return;
12926 }
12927 if (State == TreeEntry::ExpandVectorize) {
12928 assert(ReuseShuffleIndices.empty() &&
12929 "Expected no reuse shuffle for an expanded masked store.");
12930 TreeEntry *TE =
12931 newTreeEntry(VL, TreeEntry::ExpandVectorize, Bundle, S, UserTreeIdx,
12932 ExpandShuffleMask, CurrentOrder);
12933 TreeEntryToStridedPtrInfoMap[TE] = SPtrInfo;
12934 LLVM_DEBUG(
12935 dbgs()
12936 << "SLP: added a new TreeEntry (expanded masked StoreInst).\n";
12937 TE->dump());
12938 TE->setOperands(Operands);
12939 buildTreeRec(TE->getOperand(0), Depth + 1, {TE, 0});
12940 return;
12941 }
12942 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12943 ReuseShuffleIndices, CurrentOrder);
12944 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (StoreInst).\n";
12945 TE->dump());
12946 TE->setOperands(Operands);
12947 buildTreeRec(TE->getOperand(0), Depth + 1, {TE, 0});
12948 return;
12949 }
12950 case Instruction::Call: {
12951 // Check if the calls are all to the same vectorizable intrinsic or
12952 // library function.
12953 CallInst *CI = cast<CallInst>(VL0);
12955
12956 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12957 ReuseShuffleIndices);
12958 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (CallInst).\n";
12959 TE->dump());
12960 if (isCommutative(VL0)) {
12961 VLOperands Ops(VL, Operands, S, *this);
12962 Ops.reorder();
12963 Operands[0] = Ops.getVL(0);
12964 Operands[1] = Ops.getVL(1);
12965 }
12966 TE->setOperands(Operands);
12967 for (unsigned I : seq<unsigned>(CI->arg_size())) {
12968 // For scalar operands no need to create an entry since no need to
12969 // vectorize it.
12971 continue;
12972 buildTreeRec(TE->getOperand(I), Depth + 1, {TE, I});
12973 }
12974 return;
12975 }
12976 case Instruction::ShuffleVector: {
12977 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
12978 ReuseShuffleIndices);
12979 if (S.isAltShuffle()) {
12980 LLVM_DEBUG(dbgs() << "SLP: added a new TreeEntry (isAltShuffle).\n";
12981 TE->dump());
12982 } else {
12983 assert(Opts.slp_revec && "Only supported by REVEC.");
12984 LLVM_DEBUG(
12985 dbgs() << "SLP: added a new TreeEntry (ShuffleVectorInst).\n";
12986 TE->dump());
12987 }
12988
12989 // Reorder operands if reordering would enable vectorization.
12990 auto *CI = dyn_cast<CmpInst>(VL0);
12991 if (CI && any_of(make_isa_range<CmpInst>(VL),
12992 [](CmpInst *Cmp) { return !Cmp->isCommutative(); })) {
12993 auto *MainCI = cast<CmpInst>(S.getMainOp());
12994 auto *AltCI = cast<CmpInst>(S.getAltOp());
12995 CmpInst::Predicate MainP = MainCI->getPredicate();
12996 CmpInst::Predicate AltP = AltCI->getPredicate();
12997 assert(MainP != AltP &&
12998 "Expected different main/alternate predicates.");
12999 // Collect operands - commute if it uses the swapped predicate or
13000 // alternate operation.
13001 for (auto [Idx, V] :
13002 make_filter_range(enumerate(VL), [](const auto &P) {
13003 return !isa<PoisonValue>(P.value());
13004 })) {
13005 auto *Cmp = cast<CmpInst>(V);
13006
13007 if (isAlternateInstruction(Cmp, MainCI, AltCI, *TLI)) {
13008 if (AltP == CmpInst::getSwappedPredicate(Cmp->getPredicate()))
13009 std::swap(Operands.front()[Idx], Operands.back()[Idx]);
13010 } else {
13011 if (MainP == CmpInst::getSwappedPredicate(Cmp->getPredicate()))
13012 std::swap(Operands.front()[Idx], Operands.back()[Idx]);
13013 }
13014 }
13015 TE->setOperands(Operands);
13016 buildTreeRec(Operands.front(), Depth + 1, {TE, 0});
13017 buildTreeRec(Operands.back(), Depth + 1, {TE, 1});
13018 return;
13019 }
13020
13021 if (!ReassocScalars.empty()) {
13022 // Peeled alternate chains take the realigned columns; the operand
13023 // reorder below does not preserve the per-lane sign constraints.
13024 Operands = std::move(ReassocAlignedOperands);
13025 if (HasDupColumnValues()) {
13026 Operands = std::move(NaturalTwoColumns);
13027 ReassocScalars.clear();
13028 }
13029 }
13030 if (ReassocScalars.empty() && (isa<BinaryOperator>(VL0) || CI)) {
13031 VLOperands Ops(VL, Operands, S, *this);
13032 Ops.reorder();
13033 Operands[0] = Ops.getVL(0);
13034 Operands[1] = Ops.getVL(1);
13035 }
13036 if (!ReassocScalars.empty())
13037 RegisterReassocScalars(TE);
13038 TE->setOperands(Operands);
13039 for (unsigned I : seq<unsigned>(TE->getNumOperands()))
13040 buildTreeRec(TE->getOperand(I), Depth + 1, {TE, I});
13041 return;
13042 }
13043 default:
13044 break;
13045 }
13046 llvm_unreachable("Unexpected vectorization of the instructions.");
13047}
13048
13049unsigned BoUpSLP::canMapToVector(Type *T) const {
13050 unsigned N = 1;
13051 Type *EltTy = T;
13052
13054 if (EltTy->isEmptyTy())
13055 return 0;
13056 if (auto *ST = dyn_cast<StructType>(EltTy)) {
13057 // Check that struct is homogeneous.
13058 for (const auto *Ty : ST->elements())
13059 if (Ty != *ST->element_begin())
13060 return 0;
13061 N *= ST->getNumElements();
13062 EltTy = *ST->element_begin();
13063 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
13064 N *= AT->getNumElements();
13065 EltTy = AT->getElementType();
13066 } else {
13067 auto *VT = cast<FixedVectorType>(EltTy);
13068 N *= VT->getNumElements();
13069 EltTy = VT->getElementType();
13070 }
13071 }
13072
13073 if (!isValidElementType(EltTy, Opts.slp_revec))
13074 return 0;
13075 size_t VTSize = DL->getTypeStoreSizeInBits(getWidenedType(EltTy, N));
13076 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize ||
13077 VTSize != DL->getTypeStoreSizeInBits(T))
13078 return 0;
13079 return N;
13080}
13081
13082bool BoUpSLP::canVectorStoreInsertValue(const TreeEntry *E) const {
13083 if (E->getOpcode() != Instruction::InsertValue ||
13084 E->State != TreeEntry::Vectorize)
13085 return false;
13086
13087 bool HasStore = false;
13088 for (Value *V : E->Scalars) {
13089 auto *IV = dyn_cast<InsertValueInst>(V);
13090 if (!IV || isDeleted(IV))
13091 return false;
13092
13093 bool HasExternalUser = false;
13094 for (User *U : IV->users()) {
13095 if (auto *UI = dyn_cast<Instruction>(U); UI && isDeleted(UI))
13096 continue;
13097 if (is_contained(E->Scalars, U))
13098 continue;
13099 HasExternalUser = true;
13100 // Only a plain (non-volatile, non-atomic) store may consume the vector
13101 // directly. Volatile/atomic stores must keep their original aggregate
13102 // type and access semantics, so fall back to the store + load roundtrip.
13103 auto *SI = dyn_cast<StoreInst>(U);
13104 if (!SI || !SI->isSimple())
13105 return false;
13106 HasStore = true;
13107 }
13108 if (HasExternalUser && !IV->hasOneUse())
13109 return false;
13110 }
13111 return HasStore;
13112}
13113
13115 Value *VL0 = E->getMainOp();
13116 if (E->getOpcode() == Instruction::InsertElement)
13117 return cast<FixedVectorType>(VL0->getType());
13118 assert(E->getOpcode() == Instruction::InsertValue &&
13119 "Expected InsertElement or InsertValue node.");
13120 unsigned MaxIdx = E->Scalars.size() - 1;
13122 MaxIdx = std::max(MaxIdx, I->getIndices().front());
13123 return cast<FixedVectorType>(
13124 getWidenedType(getValueType(VL0, Opts.slp_revec), MaxIdx + 1));
13125}
13126
13127bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL,
13128 SmallVectorImpl<unsigned> &CurrentOrder,
13129 bool ResizeAllowed) const {
13131 assert(It != VL.end() && "Expected at least one extract instruction.");
13132 auto *E0 = cast<Instruction>(*It);
13133 // Check if all of the extracts come from the same vector and from the
13134 // correct offset.
13135 Value *Vec = E0->getOperand(0);
13136
13137 CurrentOrder.clear();
13138
13139 // We have to extract from a vector/aggregate with the same number of elements.
13140 unsigned NElts;
13141 if (E0->getOpcode() == Instruction::ExtractValue) {
13142 NElts = canMapToVector(Vec->getType());
13143 if (!NElts)
13144 return false;
13145 // Check if load can be rewritten as load of vector.
13146 LoadInst *LI = dyn_cast<LoadInst>(Vec);
13147 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
13148 return false;
13149 } else {
13150 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
13151 }
13152
13153 unsigned E = VL.size();
13154 if (!ResizeAllowed && NElts != E)
13155 return false;
13156 SmallVector<int> Indices(E, PoisonMaskElem);
13157 unsigned MinIdx = NElts, MaxIdx = 0;
13158 // Non-extract lanes (copyable elements modeled on an extract main op, or
13159 // undefs) are treated as holes.
13160 for (auto [I, V] : make_filter_range(enumerate(VL), [](const auto &P) {
13162 })) {
13163 auto *Inst = cast<Instruction>(V);
13164 if (Inst->getOperand(0) != Vec)
13165 return false;
13166 if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
13167 if (isa<UndefValue>(EE->getIndexOperand()))
13168 continue;
13169 std::optional<unsigned> Idx = getExtractIndex(Inst);
13170 if (!Idx)
13171 return false;
13172 const unsigned ExtIdx = *Idx;
13173 if (ExtIdx >= NElts)
13174 continue;
13175 Indices[I] = ExtIdx;
13176 if (MinIdx > ExtIdx)
13177 MinIdx = ExtIdx;
13178 if (MaxIdx < ExtIdx)
13179 MaxIdx = ExtIdx;
13180 }
13181 if (MaxIdx - MinIdx + 1 > E)
13182 return false;
13183 if (MaxIdx + 1 <= E)
13184 MinIdx = 0;
13185
13186 // Check that all of the indices extract from the correct offset.
13187 bool ShouldKeepOrder = true;
13188 // Assign to all items the initial value E + 1 so we can check if the extract
13189 // instruction index was used already.
13190 // Also, later we can check that all the indices are used and we have a
13191 // consecutive access in the extract instructions, by checking that no
13192 // element of CurrentOrder still has value E + 1.
13193 CurrentOrder.assign(E, E);
13194 for (unsigned I = 0; I < E; ++I) {
13195 if (Indices[I] == PoisonMaskElem)
13196 continue;
13197 const unsigned ExtIdx = Indices[I] - MinIdx;
13198 if (CurrentOrder[ExtIdx] != E) {
13199 CurrentOrder.clear();
13200 return false;
13201 }
13202 ShouldKeepOrder &= ExtIdx == I;
13203 CurrentOrder[ExtIdx] = I;
13204 }
13205 if (ShouldKeepOrder)
13206 CurrentOrder.clear();
13207
13208 return ShouldKeepOrder;
13209}
13210
13211bool BoUpSLP::areAllUsersVectorized(
13212 Instruction *I, const SmallDenseSet<Value *> *VectorizedVals) const {
13213 return (I->hasOneUse() && (!VectorizedVals || VectorizedVals->contains(I))) ||
13214 all_of(I->users(), [this](User *U) {
13215 return isVectorized(U) || isVectorLikeInstWithConstOps(U) ||
13216 (isa<ExtractElementInst>(U) && MustGather.contains(U));
13217 });
13218}
13219
13221 const InstructionsState &S,
13222 DominatorTree &DT, const DataLayout &DL,
13223 TargetTransformInfo &TTI,
13224 const TargetLibraryInfo &TLI,
13225 const BoUpSLP &R);
13226
13227/// \returns the fmul operand of the fadd/fsub \p I that the backend fuses with
13228/// \p I into an fmuladd: the first fusable one from either operand, c - a*b
13229/// included. \p I must allow contraction.
13231 const TargetTransformInfo &TTI) {
13233 m_FSub(m_Value(), m_Value())))))
13234 return nullptr;
13235 for (Value *Op : I->operands())
13237 return cast<Instruction>(Op);
13238 return nullptr;
13239}
13240
13241/// \returns the cost of the binary operator \p I, priced as not fused. No
13242/// context instruction is passed: targets that model the fmuladd fusion would
13243/// discount the unfused side of the comparison as well.
13246 const TargetLibraryInfo &TLI,
13247 TTI::TargetCostKind CostKind) {
13248 assert(match(I, m_BinOp()) && "Expected a binary operator.");
13249 TTI::OperandValueInfo Op1Info = TTI::getOperandInfo(I->getOperand(0));
13250 TTI::OperandValueInfo Op2Info = TTI::getOperandInfo(I->getOperand(1));
13251 return TTI.getArithmeticInstrCost(
13252 I->getOpcode(), I->getType(), CostKind, Op1Info, Op2Info,
13253 {I->getOperand(0), I->getOperand(1)}, /*CxtI=*/nullptr, &TLI);
13254}
13255
13256std::pair<Instruction *, InstructionCost>
13257BoUpSLP::getFMulFusingUser(Instruction *I, bool InTree) const {
13258 if (!match(I, m_OneUse(m_FMul(m_Value(), m_Value()))))
13259 return {nullptr, InstructionCost::getInvalid()};
13260 auto *U = cast<Instruction>(I->user_back());
13261 // The reduction cost accounts for the fusion of the reduced values into the
13262 // reduction operations itself. The lanes of the combined fmuladd node are
13263 // fused with its own fmul operand node, not with the other operand.
13264 if (getFusableFMulOperand(U, *TTI) != I ||
13265 (InTree && ((UserIgnoreList && UserIgnoreList->contains(U)) ||
13266 any_of(getTreeEntries(U), [](const TreeEntry *TE) {
13267 return TE->CombinedOp == TreeEntry::FMulAdd;
13268 }))))
13269 return {nullptr, InstructionCost::getInvalid()};
13270 // The target must actually prefer the fused form.
13271 InstructionCost FMACost =
13272 canConvertToFMA(U, InstructionsState(U, U), *DT, *DL, *TTI, *TLI, *this);
13273 return {FMACost.isValid() ? U : nullptr, FMACost};
13274}
13275
13276bool BoUpSLP::isFusedVectorizedFAddSub(Instruction *U) const {
13277 return any_of(getTreeEntries(U), [&](const TreeEntry *TE) {
13278 return !DeletedNodes.contains(TE) && !TransformedToGatherNodes.contains(TE);
13279 });
13280}
13281
13282InstructionCost BoUpSLP::getUnfusedFMulsPenalty(const TreeEntry &TE) const {
13283 if (!TE.hasState() || TE.isGather() ||
13284 (TE.getOpcode() != Instruction::FMul &&
13285 TE.getAltOpcode() != Instruction::FMul))
13286 return TTI::TCC_Free;
13288 for (Value *V : TE.Scalars) {
13289 Instruction *I;
13290 if (!match(V, m_Instruction(I, m_FMul(m_Value(), m_Value()))) ||
13291 (TE.hasCopyableElements() && TE.isCopyableElement(I)))
13292 continue;
13293 if (Instruction *U = getFMulFusingUser(I).first;
13294 U && isFusedVectorizedFAddSub(U))
13295 Penalty += getUnfusedBinOpCost(I, *TTI, *TLI, CostKind);
13296 }
13297 return Penalty;
13298}
13299
13300// A poor-throughput entry's real vector-vs-scalar savings (fdiv/frem/fsqrt)
13301// are already folded into TreeCost like any other entry, including all
13302// shuffle/insert/extract overhead elsewhere in the tree. So bypassing the
13303// instruction-count veto just has to trust that already-complete TreeCost
13304// instead of guessing at extra savings: heavy gather/shuffle overhead raises
13305// TreeCost too, and will still block the bypass.
13306bool BoUpSLP::bypassesInstCountCheck(InstructionCost TreeCost) const {
13307 if (!Opts.slp_vectorize_poor_throughput || TreeCost >= -getCostThreshold())
13308 return false;
13309 PoorThroughputOpCache Cache;
13310 return any_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &Ptr) {
13311 const TreeEntry &TE = *Ptr;
13312 return TE.hasState() && !DeletedNodes.contains(&TE) && !TE.isGather() &&
13313 !TransformedToGatherNodes.contains(&TE) &&
13314 TE.State != TreeEntry::CombinedVectorize &&
13315 isPoorThroughputOp(Opts.slp_revec, TE.getMainOp(), *TTI, *TLI, Cache,
13316 CostKind);
13317 });
13318}
13319
13320bool BoUpSLP::collectGatherUserOps(
13321 const TreeEntry &E, SmallVectorImpl<TTI::BuildVectorUseOp> &UserOps) const {
13322 UserOps.clear();
13323 for (const auto &TE :
13324 make_filter_range(VectorizableTree, [&](const auto &TE) {
13325 return !DeletedNodes.contains(TE.get());
13326 })) {
13327 if (!(TE->isGather() || TransformedToGatherNodes.contains(TE.get())) ||
13328 !E.isSame(TE->Scalars))
13329 continue;
13330 const TreeEntry *UserTE = TE->UserTreeIndex.UserTE;
13331 if (!UserTE || !UserTE->hasState() || UserTE->isAltShuffle() ||
13332 TransformedToGatherNodes.contains(UserTE))
13333 return false;
13334
13336 if (auto *II = dyn_cast<IntrinsicInst>(UserTE->getMainOp()))
13337 IntrinsicID = II->getIntrinsicID();
13338 UserOps.emplace_back(UserTE->getOpcode(), IntrinsicID,
13339 TE->UserTreeIndex.EdgeIdx);
13340 }
13341 return !UserOps.empty();
13342}
13343
13344uint64_t BoUpSLP::getNumScalarInsts(bool HasTreeLoop) {
13345 uint64_t Total = 0;
13346 for (const std::unique_ptr<TreeEntry> &Ptr : VectorizableTree) {
13347 const TreeEntry &TE = *Ptr;
13348 if (DeletedNodes.contains(&TE))
13349 continue;
13350 // CombinedVectorize entries (e.g. the fmul child of an FMulAdd, or the
13351 // cmp child of a MinMax select) are absorbed into the parent on both
13352 // scalar and vector sides. The backend fuses fadd+fmul -> fma and
13353 // select+cmp -> smin/smax even for scalar code, so skip to avoid
13354 // double-counting. Checked before the scale lookup below: some of
13355 // these entries started out as constant-only gather nodes and have no
13356 // valid instruction state to key the loop-nest scale off of.
13357 if (TE.State == TreeEntry::CombinedVectorize)
13358 continue;
13359 uint64_t Scale = getEntryEffectiveScale(TE);
13360 if (HasTreeLoop && Scale <= 1)
13361 continue;
13362 unsigned Count = 0;
13363 if (TE.isGather() || TransformedToGatherNodes.contains(&TE)) {
13364 // Count extractelement scalars in gathers - they exist in the scalar
13365 // code regardless of vectorization. ExtractElement instructions
13366 // become free when the vector input is used directly.
13367 for (Value *V : TE.Scalars)
13369 ++Count;
13371 continue;
13372 }
13373 // Each vectorize entry represents a bundle of scalar instructions.
13374 // Count per-entry without cross-entry deduplication, since shared
13375 // scalars across entries still represent separate work in scalar code.
13376 for (Instruction *I : make_isa_range<Instruction>(TE.Scalars)) {
13377 if (TE.hasCopyableElements() && TE.isCopyableElement(I))
13378 continue;
13379 ++Count;
13380 // Calculate calls/divs/rems twice, they may cost higher, so better to
13381 // include their count twice to mimic slightly real cost here.
13382 if (I->isIntDivRem() || I->isFPDivRem())
13383 ++Count;
13384 if (auto *CI = dyn_cast<CallInst>(I)) {
13386 if (!isTriviallyVectorizable(BaseID))
13387 ++Count;
13388 }
13389 }
13390 // Count peeled intermediates in the scalar baseline (not in Scalars).
13391 Count += TE.getReassocScalars().size();
13392 // Even when the whole node is not combined, individual scalar
13393 // instructions may be fused by the backend. Each fused pair (e.g.
13394 // fadd+fmul -> fma, select+cmp -> smin/smax) becomes a single scalar
13395 // instruction, absorbing the operand instruction. Subtract 1 for each
13396 // such match to avoid over-counting the scalar side.
13397 if (TE.CombinedOp == TreeEntry::NotCombinedOp && TE.hasState()) {
13398 unsigned Opcode = TE.getOpcode();
13399 if (Opcode == Instruction::Select) {
13400 for (Value *V : make_filter_range(TE.Scalars, [&](Value *V) {
13401 return !TE.hasCopyableElements() || !TE.isCopyableElement(V);
13402 })) {
13403 auto *SI = dyn_cast<SelectInst>(V);
13404 if (!SI)
13405 continue;
13406 auto [ID, _] = canConvertToMinOrMaxIntrinsic({V});
13407 if (ID != Intrinsic::not_intrinsic) {
13408 assert(Count > 0 && "Underflow in scalar inst count (minmax)");
13409 --Count;
13410 }
13411 }
13412 } else {
13413 for (Instruction *I : make_filter_range(
13414 make_isa_range<Instruction>(TE.Scalars), [&](Instruction *V) {
13415 return !TE.hasCopyableElements() || !TE.isCopyableElement(V);
13416 })) {
13418 m_FSub(m_Value(), m_Value())))) {
13419 if (canConvertToFMA(I, InstructionsState(I, I), *DT, *DL, *TTI,
13420 *TLI, *this)
13421 .isValid()) {
13422 assert(Count > 0 && "Underflow in scalar inst count (fma)");
13423 --Count;
13424 }
13425 } else if (match(I, m_FMul(m_Value(), m_Value()))) {
13426 // The fmul, fused into a scalar user, disappears into the user's
13427 // fmuladd. A vectorized fadd/fsub user lane already accounts for
13428 // the fusion.
13429 Instruction *U = getFMulFusingUser(I).first;
13430 if (U && !isFusedVectorizedFAddSub(U)) {
13431 assert(Count > 0 && "Underflow in scalar inst count (fma)");
13432 --Count;
13433 }
13434 }
13435 }
13436 }
13437 }
13439 }
13440 return Total;
13441}
13442
13443uint64_t BoUpSLP::getNumVectorInsts(bool HasTreeLoop, bool CountExtracts) {
13444 uint64_t Total = 0;
13445 // The alternate op, fused with the multiplication by the target, is counted
13446 // with the multiplication node, the same way as the scalar fmas.
13447 auto IsFusedAlt = [&](const TreeEntry &TE) {
13448 if (!TE.hasState() || TE.State != TreeEntry::Vectorize ||
13449 DeletedNodes.contains(&TE) || TransformedToGatherNodes.contains(&TE) ||
13450 !TE.isAltShuffle() || TE.hasReassocScalars() ||
13451 !TE.getMainOp()->getType()->isFloatingPointTy() ||
13452 !TE.getOperations().isAddSubLikeOp())
13453 return false;
13454 Type *ScalarTy = TE.getMainOp()->getType();
13455 auto *VecTy = cast<VectorType>(getWidenedType(ScalarTy, TE.Scalars.size()));
13456 SmallBitVector OpcodeMask(getAltInstrMask(
13457 TE.Scalars, ScalarTy, TE.getOpcode(), TE.getAltOpcode()));
13458 return TTI->isLegalAltInstr(VecTy, TE.getOpcode(), TE.getAltOpcode(),
13459 OpcodeMask, TE.Scalars) &&
13460 canConvertToFMA(TE.Scalars, TE.getOperations(), *DT, *DL, *TTI, *TLI,
13461 *this)
13462 .isValid();
13463 };
13464 // The scalar count already credits the fused scalars as fmas, so only a tree
13465 // with the fused alternate op is counted at the level of the machine
13466 // instructions. Doing the same for the other trees changes their VF=2
13467 // decisions.
13468 const bool HasFusedAlt =
13469 any_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &Ptr) {
13470 return IsFusedAlt(*Ptr);
13471 });
13472 // Source vector -> max scale among the gather entries sharing it, so the
13473 // combined shufflevector is still weighted like an in-loop entry below.
13474 SmallDenseMap<Value *, uint64_t, 4> GatherExtractSourceVecs;
13475 for (const std::unique_ptr<TreeEntry> &Ptr : VectorizableTree) {
13476 const TreeEntry &TE = *Ptr;
13477 if (DeletedNodes.contains(&TE))
13478 continue;
13479 if (TE.State == TreeEntry::CombinedVectorize)
13480 continue;
13481 uint64_t Scale = getEntryEffectiveScale(TE);
13482 if (HasTreeLoop && Scale <= 1)
13483 continue;
13484 unsigned Count = 0;
13485 if (TE.isGather() || TransformedToGatherNodes.contains(&TE)) {
13486 if (TE.hasState()) {
13487 if (const TreeEntry *E =
13488 getSameValuesTreeEntry(TE.getMainOp(), TE.Scalars);
13489 E && E != &TE && E->getVectorFactor() == TE.getVectorFactor())
13490 continue;
13491 SmallVector<Value *> RevScalars(TE.Scalars.rbegin(), TE.Scalars.rend());
13492 if (const TreeEntry *E =
13493 getSameValuesTreeEntry(TE.getMainOp(), RevScalars);
13494 E && E->getVectorFactor() == TE.getVectorFactor()) {
13495 Total = SaturatingAdd(Total, Scale);
13496 continue;
13497 }
13498 }
13499 // ExtractElement gathers from the same source vector become a single
13500 // shufflevector. Collect source vectors globally across all gather
13501 // entries and count once at the end.
13502 if (all_of(TE.Scalars,
13504 for (ExtractElementInst *EE :
13506 uint64_t &VecScale =
13507 GatherExtractSourceVecs.try_emplace(EE->getVectorOperand(), 0)
13508 .first->second;
13509 VecScale = std::max(VecScale, Scale);
13510 }
13511 } else {
13512 // A splat is a single broadcast. In loops, its per-lane count, scaled
13513 // by the trip count, rejects the profitable trees.
13514 if ((HasFusedAlt || HasTreeLoop) && isSplat(TE.Scalars))
13515 Count = !isConstant(TE.Scalars.front());
13516 else
13517 Count = TE.Scalars.size() - count_if(TE.Scalars, isConstant);
13518 }
13520 continue;
13521 }
13522 // InsertElement/ExtractElement vectorize entries don't produce real
13523 // vector instructions - InsertElement at root IS the result, and
13524 // ExtractElement entries reference the input vector directly.
13525 if (TE.getOpcode() == Instruction::InsertElement ||
13526 TE.getOpcode() == Instruction::ExtractElement)
13527 continue;
13528 if (TE.getOpcode() == Instruction::InsertValue) {
13529 // InsertValue materializes via store + load unless it is stored directly
13530 // as a vector.
13531 if (!canVectorStoreInsertValue(&TE))
13532 Count += 2;
13533 if (!TE.ReorderIndices.empty() || !TE.ReuseShuffleIndices.empty())
13534 ++Count;
13536 continue;
13537 }
13538 if (IsFusedAlt(TE))
13539 continue;
13540 if (TE.State == TreeEntry::SplitVectorize)
13541 Count += 2;
13542 else if (TE.hasReassocScalars())
13543 // N operand columns need N-1 binary combines.
13544 Count += TE.getNumOperands() - 1;
13545 else
13546 ++Count;
13547 if (!TE.ReorderIndices.empty() || !TE.ReuseShuffleIndices.empty())
13548 ++Count;
13550 }
13551 for (const auto &VecAndScale : GatherExtractSourceVecs)
13552 Total = SaturatingAdd(Total, VecAndScale.second);
13553 if (!CountExtracts)
13554 return Total;
13555 // Count extract instructions from ExternalUses, skipping insertelements
13556 // (those get folded into shuffles, not real extracts).
13557 SmallPtrSet<Value *, 8> CountedExtracts;
13558 for (const ExternalUser &EU :
13559 make_filter_range(ExternalUses, [](const ExternalUser &EU) {
13560 return !isa_and_nonnull<InsertElementInst>(EU.User);
13561 })) {
13562 if (EU.User && EphValues.count(EU.User))
13563 continue;
13564 // Vector-typed scalars are consumed as whole vectors, no extract
13565 // instruction is emitted for them.
13566 if (isVectorizedTy(EU.Scalar->getType()) &&
13567 (!Opts.slp_revec ||
13568 (EU.E.hasState() && EU.E.getOpcode() == Instruction::InsertElement)))
13569 continue;
13570 if (ExternalUsesAsOriginalScalar.contains(EU.Scalar))
13571 continue;
13572 if (!CountedExtracts.insert(EU.Scalar).second)
13573 continue;
13574 // The extract of the lane, which is free in the target, is not emitted.
13575 Type *ScalarTy = EU.Scalar->getType();
13576 if (HasFusedAlt && !MinBWs.contains(&EU.E) &&
13577 VectorType::isValidElementType(ScalarTy) &&
13578 TTI->getVectorInstrCost(
13579 Instruction::ExtractElement,
13580 getWidenedType(ScalarTy, EU.E.getVectorFactor()), CostKind,
13581 EU.Lane) == TTI::TCC_Free)
13582 continue;
13583 ++Total;
13584 }
13585 return Total;
13586}
13587
13588void BoUpSLP::TreeEntry::buildAltOpShuffleMask(
13589 const function_ref<bool(Instruction *)> IsAltOp, SmallVectorImpl<int> &Mask,
13590 SmallVectorImpl<Value *> *OpScalars,
13591 SmallVectorImpl<Value *> *AltScalars) const {
13592 unsigned Sz = Scalars.size();
13593 Mask.assign(Sz, PoisonMaskElem);
13594 SmallVector<int> OrderMask;
13595 if (!ReorderIndices.empty())
13596 inversePermutation(ReorderIndices, OrderMask);
13597 for (unsigned I = 0; I < Sz; ++I) {
13598 unsigned Idx = I;
13599 if (!ReorderIndices.empty())
13600 Idx = OrderMask[I];
13601 if (isa<PoisonValue>(Scalars[Idx]))
13602 continue;
13603 auto *OpInst = cast<Instruction>(Scalars[Idx]);
13604 if (IsAltOp(OpInst)) {
13605 Mask[I] = Sz + Idx;
13606 if (AltScalars)
13607 AltScalars->push_back(OpInst);
13608 } else {
13609 Mask[I] = Idx;
13610 if (OpScalars)
13611 OpScalars->push_back(OpInst);
13612 }
13613 }
13614 if (!ReuseShuffleIndices.empty()) {
13615 SmallVector<int> NewMask(ReuseShuffleIndices.size(), PoisonMaskElem);
13616 transform(ReuseShuffleIndices, NewMask.begin(), [&Mask](int Idx) {
13617 return Idx != PoisonMaskElem ? Mask[Idx] : PoisonMaskElem;
13618 });
13619 Mask.swap(NewMask);
13620 }
13621}
13622
13624 Instruction *AltOp,
13625 const TargetLibraryInfo &TLI) {
13626 return InstructionsState(MainOp, AltOp).getMatchingMainOpOrAltOp(I) == MainOp;
13627}
13628
13629void BoUpSLP::reorderGatherNode(TreeEntry &TE) {
13630 assert(TE.isGather() && TE.ReorderIndices.empty() &&
13631 "Expected gather node without reordering.");
13632 DenseMap<std::pair<size_t, Value *>, SmallVector<LoadInst *>> LoadsMap;
13633 SmallSet<size_t, 2> LoadKeyUsed;
13634
13635 // Do not reorder nodes if it small (just 2 elements), all-constant or all
13636 // instructions have same opcode already.
13637 if (TE.Scalars.size() == 2 || (TE.hasState() && !TE.isAltShuffle()) ||
13638 all_of(TE.Scalars, isConstant))
13639 return;
13640
13641 if (any_of(seq<unsigned>(TE.Idx), [&](unsigned Idx) {
13642 return VectorizableTree[Idx]->isSame(TE.Scalars);
13643 }))
13644 return;
13645
13646 auto GenerateLoadsSubkey = [&](size_t Key, LoadInst *LI) {
13647 Key = hash_combine(hash_value(LI->getParent()->getNumber()), Key);
13648 Value *Ptr = getUnderlyingObject(LI->getPointerOperand(),
13649 Opts.slp_recursion_max_depth);
13650 if (LoadKeyUsed.contains(Key)) {
13651 auto LIt = LoadsMap.find(std::make_pair(Key, Ptr));
13652 if (LIt != LoadsMap.end()) {
13653 for (LoadInst *RLI : LIt->second) {
13654 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
13655 LI->getType(), LI->getPointerOperand(), *DL, *SE,
13656 /*StrictCheck=*/true))
13657 return hash_value(RLI->getPointerOperand());
13658 }
13659 for (LoadInst *RLI : LIt->second) {
13661 LI->getPointerOperand(), *TLI,
13662 Opts.slp_recursion_max_depth)) {
13663 hash_code SubKey = hash_value(RLI->getPointerOperand());
13664 return SubKey;
13665 }
13666 }
13667 if (LIt->second.size() > 2) {
13668 hash_code SubKey =
13669 hash_value(LIt->second.back()->getPointerOperand());
13670 return SubKey;
13671 }
13672 }
13673 }
13674 LoadKeyUsed.insert(Key);
13675 LoadsMap.try_emplace(std::make_pair(Key, Ptr)).first->second.push_back(LI);
13676 return hash_value(LI->getPointerOperand());
13677 };
13678 MapVector<size_t, MapVector<size_t, SmallVector<Value *>>> SortedValues;
13679 SmallDenseMap<Value *, SmallVector<unsigned>, 8> KeyToIndex;
13680 bool IsOrdered = true;
13681 unsigned NumInstructions = 0;
13682 // Try to "cluster" scalar instructions, to be able to build extra vectorized
13683 // nodes.
13684 for (auto [I, V] : enumerate(TE.Scalars)) {
13685 size_t Key = 1, Idx = 1;
13686 if (auto *Inst = dyn_cast<Instruction>(V);
13688 !isDeleted(Inst) && !isVectorized(V)) {
13689 std::tie(Key, Idx) = generateKeySubkey(V, TLI, GenerateLoadsSubkey,
13690 /*AllowAlternate=*/false);
13691 ++NumInstructions;
13692 }
13693 auto &Container = SortedValues[Key];
13694 if (IsOrdered && !KeyToIndex.contains(V) &&
13697 ((Container.contains(Idx) &&
13698 KeyToIndex.at(Container[Idx].back()).back() != I - 1) ||
13699 (!Container.empty() && !Container.contains(Idx) &&
13700 KeyToIndex.at(Container.back().second.back()).back() != I - 1)))
13701 IsOrdered = false;
13702 auto &KTI = KeyToIndex[V];
13703 if (KTI.empty())
13704 Container[Idx].push_back(V);
13705 KTI.push_back(I);
13706 }
13708 APInt DemandedElts = APInt::getAllOnes(TE.Scalars.size());
13709 if (!IsOrdered && NumInstructions > 1) {
13710 unsigned Cnt = 0;
13711 TE.ReorderIndices.resize(TE.Scalars.size(), TE.Scalars.size());
13712 for (const auto &D : SortedValues) {
13713 for (const auto &P : D.second) {
13714 unsigned Sz = 0;
13715 for (Value *V : P.second) {
13716 ArrayRef<unsigned> Indices = KeyToIndex.at(V);
13717 for (auto [K, Idx] : enumerate(Indices)) {
13718 TE.ReorderIndices[Cnt + K] = Idx;
13719 TE.Scalars[Cnt + K] = V;
13720 }
13721 Sz += Indices.size();
13722 Cnt += Indices.size();
13723 }
13724 if (Sz > 1 && isa<Instruction>(P.second.front())) {
13725 const unsigned SubVF = getFloorFullVectorNumberOfElements(
13726 *TTI, TE.Scalars.front()->getType(), Sz, Opts.slp_revec);
13727 SubVectors.emplace_back(Cnt - Sz, SubVF);
13728 for (unsigned I : seq<unsigned>(Cnt - Sz, Cnt - Sz + SubVF))
13729 DemandedElts.clearBit(I);
13730 } else if (!P.second.empty() && isConstant(P.second.front())) {
13731 for (unsigned I : seq<unsigned>(Cnt - Sz, Cnt))
13732 DemandedElts.clearBit(I);
13733 }
13734 }
13735 }
13736 }
13737 // Reuses always require shuffles, so consider it as profitable.
13738 if (!TE.ReuseShuffleIndices.empty() || TE.ReorderIndices.empty())
13739 return;
13740 // Do simple cost estimation.
13742 auto *ScalarTy = TE.Scalars.front()->getType();
13743 auto *VecTy = cast<VectorType>(getWidenedType(ScalarTy, TE.Scalars.size()));
13744 for (auto [Idx, Sz] : SubVectors) {
13745 Cost += getShuffleCost(*TTI, TTI::SK_InsertSubvector, VecTy, CostKind, {},
13746 Idx, cast<VectorType>(getWidenedType(ScalarTy, Sz)));
13747 }
13748 Cost += getScalarizationOverhead(*TTI, Opts.slp_revec, ScalarTy, VecTy,
13749 DemandedElts,
13750 /*Insert=*/true,
13751 /*Extract=*/false, CostKind);
13752 int Sz = TE.Scalars.size();
13753 SmallVector<int> ReorderMask(TE.ReorderIndices.begin(),
13754 TE.ReorderIndices.end());
13755 for (unsigned I : seq<unsigned>(Sz)) {
13756 Value *V = TE.getOrdered(I);
13757 if (isa<PoisonValue>(V)) {
13758 ReorderMask[I] = PoisonMaskElem;
13759 } else if (isConstant(V) || DemandedElts[I]) {
13760 ReorderMask[I] = I + TE.ReorderIndices.size();
13761 }
13762 }
13763 Cost += getShuffleCost(*TTI,
13764 any_of(ReorderMask, [&](int I) { return I >= Sz; })
13767 VecTy, CostKind, ReorderMask);
13768 DemandedElts = APInt::getAllOnes(TE.Scalars.size());
13769 ReorderMask.assign(Sz, PoisonMaskElem);
13770 for (unsigned I : seq<unsigned>(Sz)) {
13771 Value *V = TE.getOrdered(I);
13772 if (isConstant(V)) {
13773 DemandedElts.clearBit(I);
13774 if (!isa<PoisonValue>(V))
13775 ReorderMask[I] = I;
13776 } else {
13777 ReorderMask[I] = I + Sz;
13778 }
13779 }
13781 *TTI, Opts.slp_revec, ScalarTy, VecTy, DemandedElts,
13782 /*Insert=*/true, /*Extract=*/false, CostKind);
13783 if (!DemandedElts.isAllOnes())
13784 BVCost += getShuffleCost(*TTI, TTI::SK_PermuteTwoSrc, VecTy, CostKind,
13785 ReorderMask);
13786 if (Cost >= BVCost) {
13787 SmallVector<int> Mask(TE.ReorderIndices.begin(), TE.ReorderIndices.end());
13788 reorderScalars(TE.Scalars, Mask);
13789 TE.ReorderIndices.clear();
13790 }
13791}
13792
13793/// Check if we can convert fadd/fsub sequence to FMAD.
13794/// \returns Cost of the FMAD, if conversion is possible, invalid cost
13795/// otherwise.
13797 const InstructionsState &S,
13798 DominatorTree &DT, const DataLayout &DL,
13800 const TargetLibraryInfo &TLI,
13801 const BoUpSLP &R) {
13802 assert(all_of(VL,
13803 [](Value *V) {
13804 return V->getType()->getScalarType()->isFloatingPointTy();
13805 }) &&
13806 "Can only convert to FMA for floating point types");
13808 "Can only convert to FMA for add/sub or fneg chain links");
13809 const TTI::TargetCostKind CostKind = R.getCostKind();
13810
13811 auto CheckForContractable = [](ArrayRef<Value *> VL,
13812 const InstructionsState &S) {
13813 FastMathFlags FMF;
13814 FMF.set();
13816 if (S.isCopyableElement(I))
13817 continue;
13818 Instruction *MatchingI = S.getMatchingMainOpOrAltOp(I);
13819 if (S.getMainOp() != MatchingI && S.getAltOp() != MatchingI)
13820 continue;
13821 if (auto *FPCI = dyn_cast<FPMathOperator>(I))
13822 FMF &= FPCI->getFastMathFlags();
13823 }
13824 return FMF.allowContract();
13825 };
13826 if (!CheckForContractable(VL, S))
13828 // fmul also should be contractable
13829 InstructionsCompatibilityAnalysis Analysis(DT, DL, TTI, TLI);
13830 SmallVector<BoUpSLP::ValueList> Operands = Analysis.buildOperands(S, VL, R);
13831 // The operands follow the majority pattern of the lanes, while the backend
13832 // fuses the fmul from either operand (c - a*b included); move it to the
13833 // first column.
13834 if (Operands.size() == 2) {
13835 for (auto [Idx, V] : enumerate(VL)) {
13836 auto *I = dyn_cast<Instruction>(V);
13837 if (!I || S.isCopyableElement(I))
13838 continue;
13840 FMul && Operands[1][Idx] == FMul)
13841 std::swap(Operands[0][Idx], Operands[1][Idx]);
13842 }
13843 }
13844
13845 // The lanes without the fmul, e.g. the constant lanes of the copyable nodes,
13846 // are the copyable lanes of the fmul column.
13847 InstructionsState OpS = Analysis.buildInstructionsState(Operands.front(), R);
13848 if (!OpS.valid())
13850
13851 if (OpS.isAltShuffle() || OpS.getOpcode() != Instruction::FMul)
13853 if (!CheckForContractable(Operands.front(), OpS))
13855 // Compare the costs.
13856 InstructionCost FMulPlusFAddCost = 0;
13857 InstructionCost FMACost = 0;
13858 FastMathFlags FMF;
13859 FMF.set();
13860 const bool IsArithmeticState = S.isAddSubLikeOp() || S.isMulDivLikeOp() ||
13861 S.isShiftOp() || S.isBitwiseLogicOp();
13862 // A dropped fneg link stands in for the sign-flipped combine its operand
13863 // joins and is costed as an fadd plus the fneg itself (both are removed).
13864 auto GetLinkCost = [&](Instruction *I, bool IsCopyable = false) {
13865 if (S.getOpcode() != Instruction::FNeg) {
13866 if (IsCopyable || !IsArithmeticState ||
13867 (I->getOpcode() != S.getOpcode() &&
13868 I->getOpcode() != S.getAltOpcode()))
13869 return TTI.getInstructionCost(I, CostKind);
13870 return getUnfusedBinOpCost(I, TTI, TLI, CostKind);
13871 }
13872 return TTI.getArithmeticInstrCost(Instruction::FAdd, I->getType(), CostKind,
13873 {},
13874 TTI::getOperandInfo(I->getOperand(0))) +
13875 TTI.getArithmeticInstrCost(Instruction::FNeg, I->getType(), CostKind,
13876 TTI::getOperandInfo(I->getOperand(0)));
13877 };
13879 const bool IsCopyable = S.isCopyableElement(I);
13880 if (!IsCopyable)
13881 if (auto *FPCI = dyn_cast<FPMathOperator>(I))
13882 FMF &= FPCI->getFastMathFlags();
13883 FMulPlusFAddCost += GetLinkCost(I, IsCopyable);
13884 }
13885 unsigned NumOps = 0;
13886 for (auto [V, Op] :
13887 make_filter_range(zip(VL, Operands.front()), [&](const auto &P) {
13888 return !S.isCopyableElement(std::get<0>(P));
13889 })) {
13890 auto *I = dyn_cast<Instruction>(Op);
13891 if (!I || OpS.isCopyableElement(I) ||
13893 if (auto *OpI = dyn_cast<Instruction>(V))
13894 FMACost += GetLinkCost(OpI);
13895 if (I)
13896 FMACost += TTI.getInstructionCost(I, CostKind);
13897 continue;
13898 }
13899 ++NumOps;
13900 if (auto *FPCI = dyn_cast<FPMathOperator>(I))
13901 FMF &= FPCI->getFastMathFlags();
13902 FMulPlusFAddCost += getUnfusedBinOpCost(I, TTI, TLI, CostKind);
13903 }
13904 Type *Ty = VL.front()->getType();
13905 IntrinsicCostAttributes ICA(Intrinsic::fmuladd, Ty, {Ty, Ty, Ty}, FMF);
13906 FMACost += NumOps * TTI.getIntrinsicInstrCost(ICA, CostKind);
13907 return FMACost < FMulPlusFAddCost ? FMACost : InstructionCost::getInvalid();
13908}
13909
13910bool BoUpSLP::matchesShlZExt(const TreeEntry &TE, OrdersType &Order,
13911 bool &IsBSwap, bool &ForLoads) const {
13912 assert(TE.hasState() && TE.getOpcode() == Instruction::Shl &&
13913 "Expected Shl node.");
13914 IsBSwap = false;
13915 ForLoads = false;
13916 if (TE.State != TreeEntry::Vectorize || TE.isAltShuffle() ||
13917 !TE.ReorderIndices.empty() || !TE.ReuseShuffleIndices.empty() ||
13918 MinBWs.contains(&TE) ||
13919 any_of(TE.Scalars, [](Value *V) { return !V->hasOneUse(); }))
13920 return false;
13921 Type *ScalarTy = TE.getMainOp()->getType();
13922 // TODO: Check if same can be done for the vector types.
13923 if (!ScalarTy->isIntegerTy())
13924 return false;
13925 if (ScalarTy->isVectorTy())
13926 return false;
13927 const unsigned Sz = DL->getTypeSizeInBits(ScalarTy);
13928 const TreeEntry *LhsTE = getOperandEntry(&TE, /*Idx=*/0);
13929 const TreeEntry *RhsTE = getOperandEntry(&TE, /*Idx=*/1);
13930 // Lhs should be zext i<stride> to I<sz>.
13931 if (!(LhsTE->State == TreeEntry::Vectorize &&
13932 LhsTE->getOpcode() == Instruction::ZExt && !LhsTE->isAltShuffle() &&
13933 LhsTE->ReorderIndices.empty() && LhsTE->ReuseShuffleIndices.empty() &&
13934 !MinBWs.contains(LhsTE) &&
13935 all_of(LhsTE->Scalars, [](Value *V) { return V->hasOneUse(); })))
13936 return false;
13937 Type *SrcScalarTy = cast<ZExtInst>(LhsTE->getMainOp())->getSrcTy();
13938 unsigned Stride = DL->getTypeSizeInBits(SrcScalarTy);
13939 if (!isPowerOf2_64(Stride) || Stride >= Sz || Sz % Stride != 0 ||
13940 !isPowerOf2_64(LhsTE->getVectorFactor()))
13941 return false;
13942 if (!(RhsTE->isGather() && RhsTE->ReorderIndices.empty() &&
13943 RhsTE->ReuseShuffleIndices.empty() && !MinBWs.contains(RhsTE)))
13944 return false;
13945 Order.clear();
13946 unsigned CurrentValue = 0;
13947 // Rhs should be (0, Stride, 2 * Stride, ..., N-Stride), where N <= Sz.
13948 if (all_of(RhsTE->Scalars,
13949 [&](Value *V) {
13950 CurrentValue += Stride;
13951 if (isa<UndefValue>(V))
13952 return true;
13953 auto *C = dyn_cast<Constant>(V);
13954 if (!C)
13955 return false;
13956 return C->getUniqueInteger() == CurrentValue - Stride;
13957 }) &&
13958 CurrentValue <= Sz) {
13959 Order.clear();
13960 } else {
13961 const unsigned VF = RhsTE->getVectorFactor();
13962 Order.assign(VF, VF);
13963 // Track which logical positions we've seen; reject duplicate shift amounts.
13964 SmallBitVector SeenPositions(VF);
13965 // Check if need to reorder Rhs to make it in form (0, Stride, 2 * Stride,
13966 // ..., N-Stride), where N <= Sz.
13967 if (VF * Stride > Sz)
13968 return false;
13969 for (const auto [Idx, V] :
13970 make_filter_range(enumerate(RhsTE->Scalars), [](const auto &P) {
13971 return !isa<UndefValue>(P.value());
13972 })) {
13973 auto *C = dyn_cast<Constant>(V);
13974 if (!C)
13975 return false;
13976 const APInt &Val = C->getUniqueInteger();
13977 if (Val.isNegative() || Val.uge(Sz) || Val.getZExtValue() % Stride != 0)
13978 return false;
13979 unsigned Pos = Val.getZExtValue() / Stride;
13980 // TODO: Support Pos >= VF, in this case need to shift the final value.
13981 if (Order[Idx] != VF || Pos >= VF)
13982 return false;
13983 if (SeenPositions.test(Pos))
13984 return false;
13985 SeenPositions.set(Pos);
13986 Order[Idx] = Pos;
13987 }
13988 // One of the indices not set - exit.
13989 if (is_contained(Order, VF))
13990 return false;
13991 }
13992 auto *SrcType = IntegerType::getIntNTy(ScalarTy->getContext(),
13993 Stride * LhsTE->getVectorFactor());
13994 FastMathFlags FMF;
13995 auto *VecTy =
13996 cast<VectorType>(getWidenedType(ScalarTy, TE.getVectorFactor()));
13997 auto *SrcVecTy =
13998 cast<VectorType>(getWidenedType(SrcScalarTy, LhsTE->getVectorFactor()));
13999 TTI::CastContextHint CastCtx =
14000 getCastContextHint(*getOperandEntry(LhsTE, /*Idx=*/0));
14001 InstructionCost VecCost =
14002 TTI->getArithmeticReductionCost(Instruction::Or, VecTy, FMF, CostKind) +
14003 TTI->getArithmeticInstrCost(Instruction::Shl, VecTy, CostKind,
14004 TTI::getOperandInfo(LhsTE->Scalars),
14005 TTI::getOperandInfo(RhsTE->Scalars), {},
14006 TE.getMainOp()) +
14007 TTI->getCastInstrCost(
14008 Instruction::ZExt, VecTy,
14009 getWidenedType(SrcScalarTy, LhsTE->getVectorFactor()), CastCtx,
14010 CostKind, LhsTE->getMainOp());
14011 InstructionCost BitcastCost = TTI->getCastInstrCost(
14012 Instruction::BitCast, SrcType, SrcVecTy, CastCtx, CostKind);
14013 if (!Order.empty()) {
14014 fixupOrderingIndices(Order);
14015 SmallVector<int> Mask;
14016 inversePermutation(Order, Mask);
14017 BitcastCost += getShuffleCost(*TTI, TTI::SK_PermuteSingleSrc, SrcVecTy,
14018 CostKind, Mask);
14019 }
14020 // Check if the combination can be modeled as a bitcast+byteswap operation.
14021 constexpr unsigned ByteSize = 8;
14022 if (!Order.empty() && isReverseOrder(Order) &&
14023 DL->getTypeSizeInBits(SrcScalarTy) == ByteSize) {
14024 IntrinsicCostAttributes CostAttrs(Intrinsic::bswap, SrcType, {SrcType});
14025 InstructionCost BSwapCost =
14026 TTI->getCastInstrCost(Instruction::BitCast, SrcType, SrcVecTy, CastCtx,
14027 CostKind) +
14028 TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
14029 if (BSwapCost <= BitcastCost) {
14030 BitcastCost = BSwapCost;
14031 IsBSwap = true;
14032 Order.clear();
14033 // Check for loads in the ZExt node.
14034 const TreeEntry *SrcTE = getOperandEntry(LhsTE, /*Idx=*/0);
14035 if (SrcTE->State == TreeEntry::Vectorize &&
14036 SrcTE->ReorderIndices.empty() && SrcTE->ReuseShuffleIndices.empty() &&
14037 SrcTE->getOpcode() == Instruction::Load && !SrcTE->isAltShuffle() &&
14038 all_of(SrcTE->Scalars, [](Value *V) { return V->hasOneUse(); })) {
14039 LoadInst *LI = SrcTE->getFirstLoad();
14040 IntrinsicCostAttributes CostAttrs(Intrinsic::bswap, SrcType, {SrcType});
14041 InstructionCost BSwapCost =
14042 TTI->getMemoryOpCost(Instruction::Load, SrcType, LI->getAlign(),
14043 LI->getPointerAddressSpace(), CostKind,
14044 TTI::getOperandInfo(LI->getPointerOperand())) +
14045 TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
14046 if (BSwapCost <= BitcastCost) {
14047 VecCost += TTI->getMemoryOpCost(
14048 Instruction::Load, SrcVecTy, LI->getAlign(),
14049 LI->getPointerAddressSpace(), CostKind,
14050 TTI::getOperandInfo(LI->getPointerOperand()));
14051 BitcastCost = BSwapCost;
14052 ForLoads = true;
14053 }
14054 }
14055 }
14056 } else if (Order.empty() && DL->getTypeSizeInBits(SrcScalarTy) == ByteSize) {
14057 // Check for loads in the ZExt node.
14058 const TreeEntry *SrcTE = getOperandEntry(LhsTE, /*Idx=*/0);
14059 if (SrcTE->State == TreeEntry::Vectorize && SrcTE->ReorderIndices.empty() &&
14060 SrcTE->ReuseShuffleIndices.empty() &&
14061 SrcTE->getOpcode() == Instruction::Load && !SrcTE->isAltShuffle() &&
14062 all_of(SrcTE->Scalars, [](Value *V) { return V->hasOneUse(); })) {
14063 LoadInst *LI = SrcTE->getFirstLoad();
14064 BitcastCost =
14065 TTI->getMemoryOpCost(Instruction::Load, SrcType, LI->getAlign(),
14066 LI->getPointerAddressSpace(), CostKind,
14067 TTI::getOperandInfo(LI->getPointerOperand()));
14068 VecCost +=
14069 TTI->getMemoryOpCost(Instruction::Load, SrcVecTy, LI->getAlign(),
14070 LI->getPointerAddressSpace(), CostKind,
14071 TTI::getOperandInfo(LI->getPointerOperand()));
14072 ForLoads = true;
14073 }
14074 }
14075 if (SrcType != ScalarTy) {
14076 BitcastCost += TTI->getCastInstrCost(Instruction::ZExt, ScalarTy, SrcType,
14077 CastCtx, CostKind);
14078 }
14079 return BitcastCost < VecCost;
14080}
14081
14082std::optional<BitPackInfo>
14083BoUpSLP::computeBitPackLayout(const TreeEntry &TE) const {
14084 assert(TE.hasState() &&
14085 (TE.getOpcode() == Instruction::And ||
14086 TE.getOpcode() == Instruction::Shl) &&
14087 "Expected And or Shl node.");
14088 const unsigned BitWidth = DL->getTypeSizeInBits(TE.getMainOp()->getType());
14089 const TreeEntry *ShlTE = &TE;
14090 const TreeEntry *MaskTE = nullptr;
14091 if (TE.getOpcode() == Instruction::And) {
14092 MaskTE = getOperandEntry(&TE, 1);
14093 ShlTE = getOperandEntry(&TE, 0);
14094 }
14095 const TreeEntry *ShiftTE = getOperandEntry(ShlTE, 1);
14096 const TreeEntry *LhsTE = getOperandEntry(ShlTE, 0);
14097
14098 const unsigned VF = TE.getVectorFactor();
14099 SmallVector<APInt> PossibleBits(VF), Masks(VF);
14100 SmallVector<uint64_t> ShlAmts(VF);
14101 auto IsCopyable = [](const TreeEntry *TE, unsigned Idx) {
14102 return TE->hasCopyableElements() && TE->isCopyableElement(TE->Scalars[Idx]);
14103 };
14104 for (unsigned Idx : seq(VF)) {
14105 uint64_t ShlAmt = 0;
14106 const APInt *C;
14107 if (!IsCopyable(ShlTE, Idx)) {
14108 if (!match(ShiftTE->Scalars[Idx], m_APInt(C)) || C->uge(BitWidth))
14109 return std::nullopt;
14110 ShlAmt = C->getZExtValue();
14111 }
14113 if (MaskTE && !IsCopyable(&TE, Idx)) {
14114 if (!match(MaskTE->Scalars[Idx], m_APInt(C)))
14115 return std::nullopt;
14116 Mask = *C;
14117 }
14118 Value *X = LhsTE->Scalars[Idx];
14119 if (isa<PoisonValue>(X)) {
14120 PossibleBits[Idx] = APInt(BitWidth, 0);
14121 } else {
14122 PossibleBits[Idx] =
14124 ~computeKnownBits(X, SimplifyQuery(*DL)).Zero;
14125 }
14126 ShlAmts[Idx] = ShlAmt;
14127 Masks[Idx] = Mask;
14128 }
14129 return computeBitPackInfo(BitWidth, PossibleBits, ShlAmts, Masks);
14130}
14131
14132const BoUpSLP::TreeEntry *BoUpSLP::getBitPackSource(const TreeEntry &LhsTE,
14133 BitPackInfo &Info) const {
14134 // The chain nodes are checked both before and after being combined into the
14135 // root.
14136 auto IsChainNode = [](const TreeEntry &TE) {
14137 return (TE.State == TreeEntry::Vectorize ||
14138 TE.CombinedOp == TreeEntry::ReducedBitPack) &&
14139 TE.ReorderIndices.empty() && TE.ReuseShuffleIndices.empty() &&
14140 !TE.hasCopyableElements() &&
14141 all_of(TE.Scalars, [](Value *V) { return V->hasOneUse(); });
14142 };
14143 const TreeEntry *AndTE = &LhsTE;
14144 if (AndTE->hasState() && AndTE->getOpcode() == Instruction::ZExt &&
14145 IsChainNode(*AndTE))
14146 AndTE = getOperandEntry(AndTE, /*Idx=*/0);
14147 if (!AndTE->hasState() || AndTE->getOpcode() != Instruction::And ||
14148 !IsChainNode(*AndTE))
14149 return &LhsTE;
14150 const TreeEntry *ShiftTE = getOperandEntry(AndTE, /*Idx=*/0);
14151 if (!ShiftTE->hasState() ||
14152 (ShiftTE->getOpcode() != Instruction::LShr &&
14153 ShiftTE->getOpcode() != Instruction::Shl) ||
14154 !IsChainNode(*ShiftTE))
14155 return &LhsTE;
14156 const TreeEntry *SrcTE = getOperandEntry(ShiftTE, /*Idx=*/0);
14157 if (SrcTE->State != TreeEntry::Vectorize || !SrcTE->ReorderIndices.empty() ||
14158 !SrcTE->ReuseShuffleIndices.empty())
14159 return &LhsTE;
14160 const unsigned SrcBW = SrcTE->getMainOp()->getType()->getScalarSizeInBits();
14161 const unsigned FieldWidth = Info.FieldWidth;
14162 std::optional<uint64_t> UniformOff;
14163 for (auto [Idx, FieldOff] : enumerate(Info.LShrAmts)) {
14164 // The and-mask keeps the field bits, which are shifted from the same bits
14165 // of every source lane.
14166 Value *Sh;
14167 const APInt *Mask, *Amt;
14168 if (FieldOff + FieldWidth > SrcBW ||
14169 !match(AndTE->Scalars[Idx], m_c_And(m_Value(Sh), m_APInt(Mask))) ||
14170 !Mask->extractBits(FieldWidth, FieldOff).isAllOnes())
14171 return &LhsTE;
14172 uint64_t Off = FieldOff;
14173 if (match(Sh, m_LShr(m_Specific(SrcTE->Scalars[Idx]), m_APInt(Amt))))
14174 Off += Amt->getZExtValue();
14175 else if (match(Sh, m_Shl(m_Specific(SrcTE->Scalars[Idx]), m_APInt(Amt))) &&
14176 Amt->ule(FieldOff))
14177 Off -= Amt->getZExtValue();
14178 else
14179 return &LhsTE;
14180 if (Off + FieldWidth > SrcBW || (UniformOff && *UniformOff != Off))
14181 return &LhsTE;
14182 UniformOff = Off;
14183 }
14184 fill(Info.LShrAmts, *UniformOff);
14185 return SrcTE;
14186}
14187
14188unsigned BoUpSLP::getZExtSrcWidth(const TreeEntry &TE) const {
14189 if (!TE.hasState() || TE.hasCopyableElements() ||
14190 TE.getOpcode() != Instruction::ZExt)
14191 return 0;
14192 return cast<ZExtInst>(TE.getMainOp())->getSrcTy()->getScalarSizeInBits();
14193}
14194
14195bool BoUpSLP::matchesBitPack(const TreeEntry &TE) const {
14196 assert(TE.hasState() &&
14197 (TE.getOpcode() == Instruction::And ||
14198 TE.getOpcode() == Instruction::Shl) &&
14199 "Expected And or Shl node.");
14200 auto IsVectorizedOneUseNode = [&](const TreeEntry *N) {
14201 return N->State == TreeEntry::Vectorize && !N->isAltShuffle() &&
14202 N->ReorderIndices.empty() && N->ReuseShuffleIndices.empty() &&
14203 !MinBWs.contains(N) && all_of(N->Scalars, [&](Value *V) {
14204 return (N->hasCopyableElements() && N->isCopyableElement(V)) ||
14205 V->hasOneUse();
14206 });
14207 };
14208 if (!IsVectorizedOneUseNode(&TE))
14209 return false;
14210 Type *ScalarTy = TE.getMainOp()->getType();
14211 if (!ScalarTy->isIntegerTy())
14212 return false;
14213 const unsigned BitWidth = DL->getTypeSizeInBits(ScalarTy);
14214 if (!isPowerOf2_64(BitWidth))
14215 return false;
14216
14217 const TreeEntry *ShlTE = &TE;
14218 const TreeEntry *MaskTE = nullptr;
14219 if (TE.getOpcode() == Instruction::And) {
14220 MaskTE = getOperandEntry(&TE, 1);
14221 ShlTE = getOperandEntry(&TE, 0);
14222 if (!ShlTE->hasState() || ShlTE->getOpcode() != Instruction::Shl)
14223 return false;
14224 }
14225 if (!IsVectorizedOneUseNode(ShlTE))
14226 return false;
14227 const TreeEntry *ShiftTE = getOperandEntry(ShlTE, 1);
14228 const TreeEntry *LhsTE = getOperandEntry(ShlTE, 0);
14229 if (!ShiftTE->isGather() || (MaskTE && !MaskTE->isGather()))
14230 return false;
14231 // The operand must be emitted as a plain vector in lane order: a vectorized
14232 // node or a simple gather.
14233 if ((!LhsTE->isGather() && LhsTE->State != TreeEntry::Vectorize) ||
14234 (LhsTE->hasState() && LhsTE->isAltShuffle()) ||
14235 !LhsTE->ReorderIndices.empty() || !LhsTE->ReuseShuffleIndices.empty() ||
14236 MinBWs.contains(LhsTE))
14237 return false;
14238 std::optional<BitPackInfo> Info = computeBitPackLayout(TE);
14239 if (!Info)
14240 return false;
14241 auto *VecTy =
14242 cast<FixedVectorType>(getWidenedType(ScalarTy, TE.getVectorFactor()));
14243 FastMathFlags FMF;
14244 InstructionCost VecCost =
14245 TTI->getArithmeticReductionCost(Instruction::Or, VecTy, FMF, CostKind) +
14246 TTI->getArithmeticInstrCost(Instruction::Shl, VecTy, CostKind,
14247 TTI::getOperandInfo(LhsTE->Scalars),
14248 TTI::getOperandInfo(ShiftTE->Scalars),
14249 /*Args=*/{}, ShlTE->getMainOp(), TLI);
14250 if (TE.getOpcode() == Instruction::And)
14251 VecCost += TTI->getArithmeticInstrCost(
14252 Instruction::And, VecTy, CostKind, TTI::getOperandInfo(ShlTE->Scalars),
14253 TTI::getOperandInfo(MaskTE->Scalars), /*Args=*/{}, TE.getMainOp(), TLI);
14254 const TreeEntry *SrcTE = getBitPackSource(*LhsTE, *Info);
14255 auto *SrcTy = cast<FixedVectorType>(
14256 getWidenedType(SrcTE->Scalars.front()->getType(), TE.getVectorFactor()));
14257 unsigned ShiftWidth;
14259 *TTI, SrcTy, ScalarTy, *Info, getZExtSrcWidth(*SrcTE),
14260 getCastContextHint(*SrcTE), CostKind, TLI, TE.getMainOp(), ShiftWidth);
14261 return PackCost.isValid() && PackCost <= VecCost;
14262}
14263
14264bool BoUpSLP::matchesInversedZExtSelect(
14265 const TreeEntry &SelectTE,
14266 SmallVectorImpl<unsigned> &InversedCmpsIndices) const {
14267 assert(SelectTE.hasState() && SelectTE.getOpcode() == Instruction::Select &&
14268 "Expected select node.");
14270 for (auto [Idx, V] : enumerate(SelectTE.Scalars)) {
14271 auto *Inst = dyn_cast<Instruction>(V);
14272 if (!Inst || Inst->getOpcode() != Instruction::ZExt)
14273 continue;
14274 ZExts.emplace_back(Inst, Idx);
14275 }
14276 if (ZExts.empty())
14277 return false;
14278 const auto *CmpTE = getOperandEntry(&SelectTE, 0);
14279 const auto *Op1TE = getOperandEntry(&SelectTE, 1);
14280 const auto *Op2TE = getOperandEntry(&SelectTE, 2);
14281 // Compares must be alternate vectorized, and other operands must be gathers
14282 // or copyables.
14283 // TODO: investigate opportunity for reordered/reused nodes.
14284 if (CmpTE->State != TreeEntry::Vectorize || !CmpTE->isAltShuffle() ||
14285 (CmpTE->getOpcode() != Instruction::ICmp &&
14286 CmpTE->getOpcode() != Instruction::FCmp) ||
14287 !CmpTE->ReorderIndices.empty() || !CmpTE->ReuseShuffleIndices.empty() ||
14288 !Op1TE->ReorderIndices.empty() || !Op1TE->ReuseShuffleIndices.empty() ||
14289 !Op2TE->ReorderIndices.empty() || !Op2TE->ReuseShuffleIndices.empty())
14290 return false;
14291 // The operands must be buildvectors/copyables.
14292 if (!Op1TE->isGather() || !Op2TE->isGather())
14293 return false;
14294 // TODO: investigate opportunity for the vector nodes with copyables.
14295 auto *Cmp = CmpTE->getMainOp();
14296 CmpPredicate Pred;
14297 auto MatchCmp = m_Cmp(Pred, m_Value(), m_Value());
14298 if (!match(Cmp, MatchCmp))
14299 return false;
14300 // The vector compare keeps the main predicate, so only the lanes with
14301 // samesign may match it with the flipped signedness.
14302 CmpPredicate MainPred = Pred.dropSameSign();
14303 CmpPredicate InversedPred = CmpInst::getInversePredicate(Pred);
14304 for (const auto [Idx, V] :
14305 make_filter_range(enumerate(CmpTE->Scalars), [&](const auto &P) {
14306 return match(P.value(), MatchCmp);
14307 })) {
14308 if (CmpPredicate::getMatching(MainPred, Pred))
14309 continue;
14310 if (!CmpPredicate::getMatching(InversedPred, Pred))
14311 return false;
14312 if (!V->hasOneUse())
14313 return false;
14314 InversedCmpsIndices.push_back(Idx);
14315 }
14316
14317 if (InversedCmpsIndices.empty())
14318 return false;
14319 Type *VecTy =
14320 getWidenedType(Cmp->getOperand(0)->getType(), CmpTE->getVectorFactor());
14321 Type *CmpTy = CmpInst::makeCmpResultType(VecTy);
14322
14323 InstructionCost VecCost = TTI->getCmpSelInstrCost(
14324 CmpTE->getOpcode(), VecTy, CmpTy, MainPred, CostKind,
14325 TTI::getOperandInfo(CmpTE->getOperand(0)),
14326 TTI::getOperandInfo(CmpTE->getOperand(1)), CmpTE->getMainOp());
14328 *TTI, Opts.slp_revec, Cmp->getType(), cast<VectorType>(CmpTy),
14329 APInt::getAllOnes(CmpTE->getVectorFactor()),
14330 /*Insert=*/true, /*Extract=*/false, CostKind);
14331 for (Instruction *I : make_isa_range<Instruction>(CmpTE->Scalars))
14332 BVCost += TTI->getInstructionCost(I, CostKind);
14333 return VecCost < BVCost;
14334}
14335
14336bool BoUpSLP::matchesSelectOfBits(const TreeEntry &SelectTE) const {
14337 assert(SelectTE.hasState() && SelectTE.getOpcode() == Instruction::Select &&
14338 "Expected select node.");
14339 if (DL->isBigEndian())
14340 return false;
14341 if (!SelectTE.ReorderIndices.empty() || !SelectTE.ReuseShuffleIndices.empty())
14342 return false;
14343 if (!UserIgnoreList || SelectTE.Idx != 0)
14344 return false;
14345 if (any_of(SelectTE.Scalars, [](Value *V) { return !V->hasOneUse(); }))
14346 return false;
14347 // Check that all reduction operands are or instructions.
14348 if (any_of(*UserIgnoreList,
14349 [](Value *V) { return !match(V, m_Or(m_Value(), m_Value())); }))
14350 return false;
14351 const TreeEntry *Op1TE = getOperandEntry(&SelectTE, 1);
14352 const TreeEntry *Op2TE = getOperandEntry(&SelectTE, 2);
14353 if (!Op1TE->isGather() || !Op2TE->isGather())
14354 return false;
14355 // No need to check for zeroes reordering.
14356 if (!Op1TE->ReorderIndices.empty() || !Op1TE->ReuseShuffleIndices.empty() ||
14357 !Op2TE->ReuseShuffleIndices.empty())
14358 return false;
14359 Type *ScalarTy = Op1TE->Scalars.front()->getType();
14360 if (!ScalarTy->isIntegerTy())
14361 return false;
14362 // Check that second operand is all zeroes.
14363 if (any_of(Op2TE->Scalars, [](Value *V) { return !match(V, m_ZeroInt()); }))
14364 return false;
14365 // Check that first operand is 1,2,4,...
14366 if (any_of(enumerate(Op1TE->Scalars), [](const auto &P) {
14367 uint64_t V;
14368 return !(match(P.value(), m_ConstantInt(V)) && isPowerOf2_64(V) &&
14369 Log2_64(V) == P.index());
14370 }))
14371 return false;
14372 // Check if bitcast is cheaper than select.
14373 auto *DstTy = IntegerType::getIntNTy(ScalarTy->getContext(),
14374 SelectTE.getVectorFactor());
14375 Type *OpTy = getWidenedType(DstTy, SelectTE.getVectorFactor());
14376 Type *CmpTy = CmpInst::makeCmpResultType(OpTy);
14377 auto *VecTy =
14378 cast<VectorType>(getWidenedType(ScalarTy, SelectTE.getVectorFactor()));
14379 auto It = MinBWs.find(&SelectTE);
14380 if (It != MinBWs.end()) {
14381 auto *EffectiveScalarTy =
14382 IntegerType::get(F->getContext(), It->second.first);
14383 VecTy = cast<VectorType>(
14384 getWidenedType(EffectiveScalarTy, SelectTE.getVectorFactor()));
14385 }
14386 InstructionCost BitcastCost = TTI->getCastInstrCost(
14387 Instruction::BitCast, DstTy, CmpTy, TTI::CastContextHint::None, CostKind);
14388 if (DstTy != ScalarTy) {
14389 BitcastCost += TTI->getCastInstrCost(Instruction::ZExt, ScalarTy, DstTy,
14390 TTI::CastContextHint::None, CostKind);
14391 }
14392 // Use the condition predicate shared by all lanes, if there is one.
14393 CmpPredicate SelPred = CmpInst::BAD_ICMP_PREDICATE;
14394 CmpPredicate P;
14395 if (match(SelectTE.getMainOp(),
14396 m_Select(m_ICmp(P, m_Value(), m_Value()), m_Value(), m_Value())) &&
14397 all_of(SelectTE.Scalars, [&](Value *V) {
14398 CmpPredicate LaneP;
14399 return match(V, m_Select(m_ICmp(LaneP, m_Value(), m_Value()), m_Value(),
14400 m_Value())) &&
14401 LaneP == P.dropSameSign();
14402 }))
14403 SelPred = P;
14404
14405 FastMathFlags FMF;
14406 InstructionCost SelectCost =
14407 TTI->getCmpSelInstrCost(Instruction::Select, VecTy, CmpTy, SelPred,
14408 CostKind, TTI::getOperandInfo(Op1TE->Scalars),
14409 TTI::getOperandInfo(Op2TE->Scalars),
14410 SelectTE.getMainOp()) +
14411 TTI->getArithmeticReductionCost(Instruction::Or, VecTy, FMF, CostKind);
14412 return BitcastCost <= SelectCost;
14413}
14414
14416 BaseGraphSize = VectorizableTree.size();
14417 // Turn graph transforming mode on and off, when done.
14418 class GraphTransformModeRAAI {
14419 bool &SavedIsGraphTransformMode;
14420
14421 public:
14422 GraphTransformModeRAAI(bool &IsGraphTransformMode)
14423 : SavedIsGraphTransformMode(IsGraphTransformMode) {
14424 IsGraphTransformMode = true;
14425 }
14426 ~GraphTransformModeRAAI() { SavedIsGraphTransformMode = false; }
14427 } TransformContext(IsGraphTransformMode);
14428 // Operands are profitable if they are:
14429 // 1. At least one constant
14430 // or
14431 // 2. Splats
14432 // or
14433 // 3. Results in good vectorization opportunity, i.e. may generate vector
14434 // nodes and reduce cost of the graph.
14435 auto CheckOperandsProfitability = [this](Instruction *I1, Instruction *I2,
14436 const InstructionsState &S) {
14438 for (unsigned Op : seq<unsigned>(S.getMainOp()->getNumOperands()))
14439 Candidates.emplace_back().emplace_back(I1->getOperand(Op),
14440 I2->getOperand(Op));
14441 return all_of(Candidates, [this](
14442 ArrayRef<std::pair<Value *, Value *>> Cand) {
14443 return all_of(Cand,
14444 [](const std::pair<Value *, Value *> &P) {
14445 return isa<Constant>(P.first) ||
14446 isa<Constant>(P.second) || P.first == P.second;
14447 }) ||
14449 });
14450 };
14451
14452 // The reduction root gather feeds only the commutative reduction, which
14453 // maps the reduced values to the lanes by the root scalars. Put the distinct
14454 // sub-fields of the same wider scalar in the natural order to emit them
14455 // without a permutation.
14456 if (UserIgnoreList && getRootNode().isGather() &&
14457 getRootNode().ReuseShuffleIndices.empty())
14458 if (std::optional<std::tuple<Value *, unsigned, SmallVector<int>>> Fields =
14459 matchGatheredExtractedFields(getRootNode().Scalars, *DL)) {
14460 auto &[Src, FieldWidth, Mask] = *Fields;
14461 SmallVector<int> SortedMask(Mask);
14462 sort(SortedMask);
14463 if (equal(SortedMask,
14464 seq<int>(Src->getType()->getIntegerBitWidth() / FieldWidth)))
14465 reorderScalars(getRootNode().Scalars, Mask);
14466 }
14467
14468 // Try to reorder gather nodes for better vectorization opportunities.
14469 for (unsigned Idx : seq<unsigned>(BaseGraphSize)) {
14470 TreeEntry &E = *VectorizableTree[Idx];
14471 if (E.isGather())
14472 reorderGatherNode(E);
14473 }
14474
14475 // Better to use full gathered loads analysis, if there are only 2 loads
14476 // gathered nodes each having less than 16 elements.
14477 constexpr unsigned VFLimit = 16;
14478 bool ForceLoadGather =
14479 count_if(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
14480 return TE->isGather() && TE->hasState() &&
14481 TE->getOpcode() == Instruction::Load &&
14482 TE->getVectorFactor() < VFLimit;
14483 }) == 2;
14484
14485 // Checks if the scalars are used in other node.
14486 auto AreReusedScalars = [&](const TreeEntry *TE, ArrayRef<Value *> VL,
14487 function_ref<bool(Value *)> CheckContainer) {
14488 return TE->isSame(VL) || all_of(VL, [&](Value *V) {
14489 if (isa<PoisonValue>(V))
14490 return true;
14491 auto *I = dyn_cast<Instruction>(V);
14492 if (!I)
14493 return false;
14494 return is_contained(TE->Scalars, I) || CheckContainer(I);
14495 });
14496 };
14497 auto CheckForSameVectorNodes = [&](const TreeEntry &E) {
14498 if (E.hasState()) {
14499 if (ArrayRef<TreeEntry *> TEs = getTreeEntries(E.getMainOp());
14500 !TEs.empty() && any_of(TEs, [&](const TreeEntry *TE) {
14501 return AreReusedScalars(TE, E.Scalars, [&](Value *V) {
14502 ArrayRef<TreeEntry *> VTEs = getTreeEntries(V);
14503 return !VTEs.empty() && any_of(VTEs, [&](const TreeEntry *TE) {
14504 return is_contained(TEs, TE);
14505 });
14506 });
14507 }))
14508 return true;
14509 ;
14510 if (ArrayRef<TreeEntry *> TEs = getSplitTreeEntries(E.getMainOp());
14511 !TEs.empty() && any_of(TEs, [&](const TreeEntry *TE) {
14512 return AreReusedScalars(TE, E.Scalars, [&](Value *V) {
14513 ArrayRef<TreeEntry *> VTEs = getSplitTreeEntries(V);
14514 return !VTEs.empty() && any_of(VTEs, [&](const TreeEntry *TE) {
14515 return is_contained(TEs, TE);
14516 });
14517 });
14518 }))
14519 return true;
14520 } else {
14521 // Check if the gather node full copy of split node.
14522 auto *It = find_if(E.Scalars, IsaPred<Instruction>);
14523 if (It != E.Scalars.end()) {
14524 if (ArrayRef<TreeEntry *> TEs = getSplitTreeEntries(*It);
14525 !TEs.empty() && any_of(TEs, [&](const TreeEntry *TE) {
14526 return AreReusedScalars(TE, E.Scalars, [&](Value *V) {
14527 ArrayRef<TreeEntry *> VTEs = getSplitTreeEntries(V);
14528 return !VTEs.empty() && any_of(VTEs, [&](const TreeEntry *TE) {
14529 return is_contained(TEs, TE);
14530 });
14531 });
14532 }))
14533 return true;
14534 }
14535 }
14536 return false;
14537 };
14538 // Marks the fadd/fsub node \p E as fmuladd, if its fmul operand is fused
14539 // into it.
14540 auto CombineFMulAdd = [&](TreeEntry &E) {
14541 // Check if possible to convert (a*b)+c to fma; fma takes exactly two
14542 // operands, so bail out on reassociated (>2-operand) nodes.
14543 if (E.State != TreeEntry::Vectorize ||
14544 !E.getOperations().isAddSubLikeOp() ||
14545 E.getOperations().isAltShuffle() || E.getNumOperands() != 2)
14546 return;
14547 const TreeEntry *LHS = getOperandEntry(&E, 0);
14548 const TreeEntry *RHS = getOperandEntry(&E, 1);
14549 auto IsOneUseVectorFMulOperand = [](const TreeEntry *TE) {
14550 return TE->State == TreeEntry::Vectorize && TE->ReorderIndices.empty() &&
14551 TE->ReuseShuffleIndices.empty() &&
14552 TE->getOpcode() == Instruction::FMul && !TE->isAltShuffle() &&
14553 all_of(TE->Scalars, [&](Value *V) {
14554 return (TE->hasCopyableElements() && TE->isCopyableElement(V)) ||
14555 V->hasOneUse();
14556 });
14557 };
14558 // Both a*b - c and c - a*b are fused.
14559 const bool IsLHSFMul = IsOneUseVectorFMulOperand(LHS);
14560 if (!IsLHSFMul && !IsOneUseVectorFMulOperand(RHS))
14561 return;
14562 if (!canConvertToFMA(E.Scalars, E.getOperations(), *DT, *DL, *TTI, *TLI,
14563 *this)
14564 .isValid())
14565 return;
14566 // This node is a fmuladd node.
14567 E.CombinedOp = TreeEntry::FMulAdd;
14568 TreeEntry *FMulEntry = getOperandEntry(&E, IsLHSFMul ? 0 : 1);
14569 if (FMulEntry->UserTreeIndex && FMulEntry->State == TreeEntry::Vectorize) {
14570 // The FMul node is part of the combined fmuladd node.
14571 FMulEntry->State = TreeEntry::CombinedVectorize;
14572 }
14573 };
14574 // The tree may grow here, so iterate over nodes, built before.
14575 for (unsigned Idx : seq<unsigned>(BaseGraphSize)) {
14576 TreeEntry &E = *VectorizableTree[Idx];
14577 if (E.isGather()) {
14578 ArrayRef<Value *> VL = E.Scalars;
14579 const unsigned Sz = getVectorElementSize(VL.front());
14580 unsigned MinVF = getMinVF(2 * Sz);
14581 // Do not try partial vectorization for small nodes (<= 2), nodes with the
14582 // same opcode and same parent block or all constants.
14583 if (VL.size() <= 2 || LoadEntriesToVectorize.contains(Idx) ||
14584 !(!E.hasState() || E.getOpcode() == Instruction::Load ||
14585 // We use allSameOpcode instead of isAltShuffle because we don't
14586 // want to use interchangeable instruction here.
14587 !allSameOpcode(VL) || !allSameBlock(VL)) ||
14588 allConstant(VL) || isSplat(VL) ||
14589 (E.ReuseShuffleIndices.empty() &&
14591 continue;
14592 if (ForceLoadGather && E.hasState() && E.getOpcode() == Instruction::Load)
14593 continue;
14594 // Check if the node is a copy of other vector nodes.
14595 if (CheckForSameVectorNodes(E))
14596 continue;
14597 // Try to find vectorizable sequences and transform them into a series of
14598 // insertvector instructions.
14599 unsigned StartIdx = 0;
14600 unsigned End = VL.size();
14601 SmallBitVector Processed(End);
14602 for (unsigned VF = getFloorFullVectorNumberOfElements(
14603 *TTI, VL.front()->getType(), VL.size() - 1, Opts.slp_revec);
14604 VF >= MinVF;
14605 VF = getFloorFullVectorNumberOfElements(*TTI, VL.front()->getType(),
14606 VF - 1, Opts.slp_revec)) {
14607 if (StartIdx + VF > End)
14608 continue;
14610 bool AllStrided = true;
14611 // Walk the range in steps of VF, but allow the trailing slice to be
14612 // shorter (SliceVF < VF) so non-power-of-2 tails can be vectorized.
14613 // Processed only records slice starts (Cnt), and downstream consumers
14614 // (test(Cnt), AddCombinedNode's range set/StartIdx update) operate on
14615 // start positions, so partial coverage is consistent.
14616 for (unsigned Cnt = StartIdx; Cnt < End; Cnt += VF) {
14617 const unsigned SliceVF = std::min(VF, End - Cnt);
14618 if (SliceVF <= 1)
14619 continue;
14620 ArrayRef<Value *> Slice = VL.slice(Cnt, SliceVF);
14621 // If any instruction is vectorized already - do not try again.
14622 // Reuse the existing node, if it fully matches the slice.
14623 if ((Processed.test(Cnt) || isVectorized(Slice.front())) &&
14624 !getSameValuesTreeEntry(Slice.front(), Slice, /*SameVF=*/true))
14625 continue;
14626 // Constant already handled effectively - skip.
14627 if (allConstant(Slice))
14628 continue;
14629 // Do not try to vectorize small splats (less than vector register and
14630 // only with the single non-undef element).
14631 bool IsSplat = isSplat(Slice);
14632 bool IsTwoRegisterSplat = true;
14633 if (IsSplat && VF == 2) {
14634 unsigned NumRegs2VF = getNumberOfParts(
14635 getWidenedType(getValueType(Slice.front(), Opts.slp_revec),
14636 2 * VF),
14637 getValueType(Slice.front(), Opts.slp_revec));
14638 IsTwoRegisterSplat = NumRegs2VF == 2;
14639 }
14640 if (Slices.empty() || !IsSplat || !IsTwoRegisterSplat ||
14641 count(Slice, Slice.front()) ==
14642 static_cast<long>(isa<UndefValue>(Slice.front()) ? SliceVF - 1
14643 : 1)) {
14644 if (IsSplat)
14645 continue;
14646 InstructionsState S = getSameOpcode(Slice, *TLI);
14647 if (!S || !allSameOpcode(Slice) || !allSameBlock(Slice) ||
14648 (S.getOpcode() == Instruction::Load &&
14650 continue;
14651 if (VF == 2) {
14652 // Cache the cost check lazily - both branches below may need it.
14653 std::optional<bool> MainOpIsCheap;
14654 auto IsMainOpCheap = [&, TTI = TTI] {
14655 if (!MainOpIsCheap)
14656 MainOpIsCheap =
14657 TTI->getInstructionCost(S.getMainOp(), CostKind) <
14659 return *MainOpIsCheap;
14660 };
14661 // Try to vectorize reduced values or if all users are vectorized.
14662 // For expensive instructions extra extracts might be profitable.
14663 if ((!UserIgnoreList || E.Idx != 0) && IsMainOpCheap() &&
14665 [&](Instruction *I) {
14666 return areAllUsersVectorized(I, UserIgnoreList);
14667 }))
14668 continue;
14669 if (S.getOpcode() == Instruction::Load) {
14670 OrdersType Order;
14671 SmallVector<Value *> PointerOps;
14672 StridedPtrInfo SPtrInfo;
14673 LoadsState Res = canVectorizeLoads(Slice, Slice.front(), Order,
14674 PointerOps, SPtrInfo);
14675 AllStrided &= Res == LoadsState::StridedVectorize ||
14677 Res == LoadsState::Gather;
14678 // Do not vectorize gathers.
14679 if (Res == LoadsState::ScatterVectorize ||
14680 Res == LoadsState::Gather) {
14681 if (Res == LoadsState::Gather) {
14683 // If reductions and the scalars from the root node are
14684 // analyzed - mark as non-vectorizable reduction.
14685 if (UserIgnoreList && E.Idx == 0)
14686 analyzedReductionVals(Slice);
14687 }
14688 continue;
14689 }
14690 } else if (S.getOpcode() == Instruction::ExtractElement ||
14691 (IsMainOpCheap() &&
14692 !CheckOperandsProfitability(
14693 S.getMainOp(),
14696 S))) {
14697 // Do not vectorize extractelements (handled effectively
14698 // alread). Do not vectorize non-profitable instructions (with
14699 // low cost and non-vectorizable operands.)
14700 continue;
14701 }
14702 }
14703 }
14704 Slices.emplace_back(Cnt, Slice.size());
14705 }
14706 // Do not try to vectorize if all slides are strided or gathered with
14707 // vector factor 2 and there are more than 2 slices. Better to handle
14708 // them in gathered loads analysis, may result in better vectorization.
14709 if (VF == 2 && AllStrided && Slices.size() > 2)
14710 continue;
14711 auto AddCombinedNode = [&](unsigned Idx, unsigned Cnt, unsigned Sz) {
14712 E.CombinedEntriesWithIndices.emplace_back(Idx, Cnt);
14713 Processed.set(Cnt, Cnt + Sz);
14714 if (StartIdx == Cnt)
14715 StartIdx = Cnt + Sz;
14716 if (End == Cnt + Sz)
14717 End = Cnt;
14718 };
14719 for (auto [Cnt, Sz] : Slices) {
14720 ArrayRef<Value *> Slice = VL.slice(Cnt, Sz);
14721 const TreeEntry *SameTE = nullptr;
14722 if (const auto *It = find_if(Slice, IsaPred<Instruction>);
14723 It != Slice.end()) {
14724 // If any instruction is vectorized already - do not try again.
14725 SameTE = getSameValuesTreeEntry(*It, Slice);
14726 }
14727 unsigned PrevSize = VectorizableTree.size();
14728 [[maybe_unused]] unsigned PrevEntriesSize =
14729 LoadEntriesToVectorize.size();
14730 buildTreeRec(Slice, 0, EdgeInfo(&E, UINT_MAX));
14731 if (PrevSize + 1 == VectorizableTree.size() && !SameTE &&
14732 VectorizableTree[PrevSize]->isGather() &&
14733 VectorizableTree[PrevSize]->hasState() &&
14734 VectorizableTree[PrevSize]->getOpcode() !=
14735 Instruction::ExtractElement &&
14736 !isSplat(Slice)) {
14737 if (UserIgnoreList && E.Idx == 0 && VF == 2)
14738 analyzedReductionVals(Slice);
14739 VectorizableTree.pop_back();
14740 assert(PrevEntriesSize == LoadEntriesToVectorize.size() &&
14741 "LoadEntriesToVectorize expected to remain the same");
14742 continue;
14743 }
14744 AddCombinedNode(PrevSize, Cnt, Sz);
14745 }
14746 }
14747 // Restore ordering, if no extra vectorization happened.
14748 if (E.CombinedEntriesWithIndices.empty() && !E.ReorderIndices.empty()) {
14749 SmallVector<int> Mask(E.ReorderIndices.begin(), E.ReorderIndices.end());
14750 reorderScalars(E.Scalars, Mask);
14751 E.ReorderIndices.clear();
14752 }
14753 }
14754 if (!E.hasState())
14755 continue;
14756 switch (E.getOpcode()) {
14757 case Instruction::Load: {
14758 // No need to reorder masked gather loads, just reorder the scalar
14759 // operands.
14760 // Lanes without a load would break the common alignment below.
14761 if (E.State != TreeEntry::Vectorize ||
14762 any_of(E.Scalars, IsaPred<UndefValue>))
14763 break;
14764 Type *ScalarTy = E.getMainOp()->getType();
14765 auto *VecTy =
14766 cast<FixedVectorType>(getWidenedType(ScalarTy, E.Scalars.size()));
14767 Align CommonAlignment = computeCommonAlignment<LoadInst>(E.Scalars);
14768 // Check if profitable to represent consecutive load + reverse as strided
14769 // load with stride -1.
14770 if (E.isReverse() &&
14771 TTI->isLegalStridedLoadStore(VecTy, CommonAlignment)) {
14772 SmallVector<int> Mask;
14773 inversePermutation(E.ReorderIndices, Mask);
14774 auto *BaseLI = cast<LoadInst>(E.Scalars.back());
14775 InstructionCost OriginalVecCost =
14776 TTI->getMemoryOpCost(
14777 Instruction::Load, VecTy, BaseLI->getAlign(),
14778 BaseLI->getPointerAddressSpace(), CostKind,
14779 TTI::getOperandInfo(BaseLI->getPointerOperand())) +
14780 getShuffleCost(*TTI, TTI::SK_Reverse, VecTy, CostKind, Mask);
14781 Type *StrideTy = DL->getIndexType(BaseLI->getPointerOperandType());
14782 InstructionCost StridedCost = TTI->getMemIntrinsicInstrCost(
14783 MemIntrinsicCostAttributes(
14784 Intrinsic::experimental_vp_strided_load, VecTy,
14785 BaseLI->getPointerOperand(),
14786 /*VariableMask=*/false, CommonAlignment, BaseLI,
14788 StrideTy,
14789 -static_cast<int64_t>(DL->getTypeAllocSize(ScalarTy)))),
14790 CostKind);
14791 if (StridedCost < OriginalVecCost || Opts.slp_force_strided_loads) {
14792 // Strided load is more profitable than consecutive load + reverse -
14793 // transform the node to strided load.
14794 StridedPtrInfo SPtrInfo;
14795 SPtrInfo.StrideVal = ConstantInt::get(StrideTy, 1);
14796 SPtrInfo.Ty = VecTy;
14797 TreeEntryToStridedPtrInfoMap[&E] = SPtrInfo;
14798 E.State = TreeEntry::StridedVectorize;
14799 }
14800 }
14801 break;
14802 }
14803 case Instruction::Store: {
14804 if (E.State == TreeEntry::ExpandVectorize)
14805 break;
14806 Type *ScalarTy =
14807 cast<StoreInst>(E.getMainOp())->getValueOperand()->getType();
14808 auto *VecTy =
14809 cast<FixedVectorType>(getWidenedType(ScalarTy, E.Scalars.size()));
14810 Align CommonAlignment = computeCommonAlignment<StoreInst>(E.Scalars);
14811 // Check if profitable to represent consecutive load + reverse as strided
14812 // load with stride -1.
14813 if (E.isReverse() &&
14814 TTI->isLegalStridedLoadStore(VecTy, CommonAlignment)) {
14815 SmallVector<int> Mask;
14816 inversePermutation(E.ReorderIndices, Mask);
14817 auto *BaseSI = cast<StoreInst>(E.Scalars.back());
14818 InstructionCost OriginalVecCost =
14819 TTI->getMemoryOpCost(Instruction::Store, VecTy, BaseSI->getAlign(),
14820 BaseSI->getPointerAddressSpace(), CostKind,
14821 TTI::getOperandInfo(E.getOperand(0))) +
14822 getShuffleCost(*TTI, TTI::SK_Reverse, VecTy, CostKind, Mask);
14823 Type *StrideTy = DL->getIndexType(BaseSI->getPointerOperandType());
14824 InstructionCost StridedCost = TTI->getMemIntrinsicInstrCost(
14825 MemIntrinsicCostAttributes(
14826 Intrinsic::experimental_vp_strided_store, VecTy,
14827 BaseSI->getPointerOperand(),
14828 /*VariableMask=*/false, CommonAlignment, BaseSI,
14830 StrideTy,
14831 -static_cast<int64_t>(DL->getTypeAllocSize(ScalarTy)))),
14832 CostKind);
14833 if (StridedCost < OriginalVecCost) {
14834 // Strided store is more profitable than reverse + consecutive store -
14835 // transform the node to strided store.
14836 E.State = TreeEntry::StridedVectorize;
14837 StridedPtrInfo SPtrInfo;
14838 SPtrInfo.StrideVal = ConstantInt::getSigned(StrideTy, -1);
14839 SPtrInfo.Ty = VecTy;
14840 TreeEntryToStridedPtrInfoMap[&E] = SPtrInfo;
14841 }
14842 } else if (!E.ReorderIndices.empty()) {
14843 // Check for interleaved stores.
14844 auto IsInterleaveMask = [&, &TTI = *TTI](ArrayRef<int> Mask) {
14845 auto *BaseSI = cast<StoreInst>(E.Scalars.front());
14846 assert(Mask.size() > 1 && "Expected mask greater than 1 element.");
14847 if (Mask.size() < 4)
14848 return 0u;
14849 for (unsigned Factor : seq<unsigned>(2, Mask.size() / 2 + 1)) {
14851 Mask, Factor, VecTy->getElementCount().getFixedValue()) &&
14852 TTI.isLegalInterleavedAccessType(
14853 VecTy, Factor, BaseSI->getAlign(),
14854 BaseSI->getPointerAddressSpace()))
14855 return Factor;
14856 }
14857
14858 return 0u;
14859 };
14860 SmallVector<int> Mask(E.ReorderIndices.begin(), E.ReorderIndices.end());
14861 unsigned InterleaveFactor = IsInterleaveMask(Mask);
14862 if (InterleaveFactor != 0)
14863 E.setInterleave(InterleaveFactor);
14864 }
14865 break;
14866 }
14867 case Instruction::Select: {
14868 if (E.State != TreeEntry::Vectorize)
14869 break;
14870 auto [MinMaxID, SelectOnly] = canConvertToMinOrMaxIntrinsic(E.Scalars);
14871 if (MinMaxID != Intrinsic::not_intrinsic) {
14872 // This node is a minmax node.
14873 E.CombinedOp = TreeEntry::MinMax;
14874 TreeEntry *CondEntry = getOperandEntry(&E, 0);
14875 if (SelectOnly && CondEntry->UserTreeIndex &&
14876 CondEntry->State == TreeEntry::Vectorize) {
14877 // The condition node is part of the combined minmax node.
14878 CondEntry->State = TreeEntry::CombinedVectorize;
14879 }
14880 break;
14881 }
14882 // Check for zext + selects, which can be reordered.
14883 SmallVector<unsigned> InversedCmpsIndices;
14884 if (matchesInversedZExtSelect(E, InversedCmpsIndices)) {
14885 auto *CmpTE = getOperandEntry(&E, 0);
14886 auto *Op1TE = getOperandEntry(&E, 1);
14887 auto *Op2TE = getOperandEntry(&E, 2);
14888 // State now is uniform, not alternate opcode.
14889 CmpTE->setOperations(
14890 InstructionsState(CmpTE->getMainOp(), CmpTE->getMainOp()));
14891 // Update mapping between the swapped values and their internal matching
14892 // nodes.
14893 auto UpdateGatherEntry = [&](TreeEntry *OldTE, TreeEntry *NewTE,
14894 Value *V) {
14895 if (isConstant(V))
14896 return;
14897 auto It = ValueToGatherNodes.find(V);
14898 assert(It != ValueToGatherNodes.end() &&
14899 "Expected to find the value in the map.");
14900 auto &C = It->getSecond();
14901 if (!is_contained(OldTE->Scalars, V))
14902 C.remove(OldTE);
14903 C.insert(NewTE);
14904 };
14905 ValueList &Op1 = E.getOperand(1);
14906 ValueList &Op2 = E.getOperand(2);
14907 for (const unsigned Idx : InversedCmpsIndices) {
14908 Value *V1 = Op1TE->Scalars[Idx];
14909 Value *V2 = Op2TE->Scalars[Idx];
14910 std::swap(Op1TE->Scalars[Idx], Op2TE->Scalars[Idx]);
14911 std::swap(Op1[Idx], Op2[Idx]);
14912 UpdateGatherEntry(Op1TE, Op2TE, V1);
14913 UpdateGatherEntry(Op2TE, Op1TE, V2);
14914 }
14915 OperandsToTreeEntry.emplace_or_assign(std::make_pair(&E, 1), Op1TE);
14916 OperandsToTreeEntry.emplace_or_assign(std::make_pair(&E, 2), Op2TE);
14917 // NB: Fallback to check if select can be converted to cmp bitcast.
14918 }
14919 if (matchesSelectOfBits(E)) {
14920 // This node is a (reduced or) cmp bitcast node.
14921 const TreeEntry::CombinedOpcode Code = TreeEntry::ReducedCmpBitcast;
14922 E.CombinedOp = Code;
14923 auto *Op1TE = getOperandEntry(&E, 1);
14924 auto *Op2TE = getOperandEntry(&E, 2);
14925 Op1TE->State = TreeEntry::CombinedVectorize;
14926 Op1TE->CombinedOp = Code;
14927 Op2TE->State = TreeEntry::CombinedVectorize;
14928 Op2TE->CombinedOp = Code;
14929 break;
14930 }
14931 break;
14932 }
14933 case Instruction::FSub:
14934 case Instruction::FAdd:
14935 CombineFMulAdd(E);
14936 break;
14937 case Instruction::Shl:
14938 case Instruction::And: {
14939 // Shl/And are not reassociated; guard since this case indexes operands
14940 // 0/1.
14941 if (E.getNumOperands() != 2)
14942 break;
14943 if (E.Idx != 0 || DL->isBigEndian())
14944 break;
14945 if (!UserIgnoreList)
14946 break;
14947 // Check that all reduction operands are disjoint or instructions.
14948 if (E.getOpcode() == Instruction::Shl &&
14949 all_of(*UserIgnoreList, [](Value *V) {
14950 return match(V, m_DisjointOr(m_Value(), m_Value()));
14951 })) {
14952 OrdersType Order;
14953 bool IsBSwap;
14954 bool ForLoads;
14955 if (matchesShlZExt(E, Order, IsBSwap, ForLoads)) {
14956 // This node is a (reduced disjoint or) bitcast node.
14957 TreeEntry::CombinedOpcode Code =
14958 IsBSwap ? (ForLoads ? TreeEntry::ReducedBitcastBSwapLoads
14959 : TreeEntry::ReducedBitcastBSwap)
14960 : (ForLoads ? TreeEntry::ReducedBitcastLoads
14961 : TreeEntry::ReducedBitcast);
14962 E.CombinedOp = Code;
14963 E.ReorderIndices = std::move(Order);
14964 TreeEntry *ZExtEntry = getOperandEntry(&E, 0);
14965 assert(ZExtEntry->UserTreeIndex &&
14966 ZExtEntry->State == TreeEntry::Vectorize &&
14967 ZExtEntry->getOpcode() == Instruction::ZExt &&
14968 "Expected ZExt node.");
14969 // The ZExt node is part of the combined node.
14970 ZExtEntry->State = TreeEntry::CombinedVectorize;
14971 ZExtEntry->CombinedOp = Code;
14972 if (ForLoads) {
14973 TreeEntry *LoadsEntry = getOperandEntry(ZExtEntry, 0);
14974 assert(LoadsEntry->UserTreeIndex &&
14975 LoadsEntry->State == TreeEntry::Vectorize &&
14976 LoadsEntry->getOpcode() == Instruction::Load &&
14977 "Expected Load node.");
14978 // The Load node is part of the combined node.
14979 LoadsEntry->State = TreeEntry::CombinedVectorize;
14980 LoadsEntry->CombinedOp = Code;
14981 }
14982 TreeEntry *ConstEntry = getOperandEntry(&E, 1);
14983 assert(ConstEntry->UserTreeIndex && ConstEntry->isGather() &&
14984 "Expected constants only.");
14985 // The ConstNode node is part of the combined node.
14986 ConstEntry->State = TreeEntry::CombinedVectorize;
14987 ConstEntry->CombinedOp = Code;
14988 break;
14989 }
14990 }
14991 // Check that all reduction operands are or instructions.
14992 if (any_of(*UserIgnoreList, [](Value *V) {
14993 return !match(V, m_Or(m_Value(), m_Value()));
14994 }))
14995 break;
14996 if (!matchesBitPack(E))
14997 break;
14998 // This node is a (reduced or) bit pack node.
14999 E.CombinedOp = TreeEntry::ReducedBitPack;
15000 TreeEntry *ShlEntry = &E;
15001 if (E.getOpcode() == Instruction::And) {
15002 ShlEntry = getOperandEntry(&E, 0);
15003 assert(ShlEntry->UserTreeIndex &&
15004 ShlEntry->State == TreeEntry::Vectorize &&
15005 ShlEntry->getOpcode() == Instruction::Shl &&
15006 "Expected Shl node.");
15007 // The Shl node is part of the combined node.
15008 ShlEntry->State = TreeEntry::CombinedVectorize;
15009 ShlEntry->CombinedOp = TreeEntry::ReducedBitPack;
15010 TreeEntry *MaskEntry = getOperandEntry(&E, 1);
15011 assert(MaskEntry->UserTreeIndex && MaskEntry->isGather() &&
15012 "Expected constants only.");
15013 MaskEntry->State = TreeEntry::CombinedVectorize;
15014 MaskEntry->CombinedOp = TreeEntry::ReducedBitPack;
15015 }
15016 TreeEntry *ShiftEntry = getOperandEntry(ShlEntry, 1);
15017 assert(ShiftEntry->UserTreeIndex && ShiftEntry->isGather() &&
15018 "Expected constants only.");
15019 ShiftEntry->State = TreeEntry::CombinedVectorize;
15020 ShiftEntry->CombinedOp = TreeEntry::ReducedBitPack;
15021 // The chain of a uniform field extract and its constant operands are
15022 // part of the combined node.
15023 std::optional<BitPackInfo> Info = computeBitPackLayout(E);
15024 TreeEntry *LhsTE = getOperandEntry(ShlEntry, /*Idx=*/0);
15025 const TreeEntry *SrcTE = getBitPackSource(*LhsTE, *Info);
15026 for (TreeEntry *ChainTE = LhsTE; ChainTE != SrcTE;
15027 ChainTE = getOperandEntry(ChainTE, /*Idx=*/0)) {
15028 ChainTE->State = TreeEntry::CombinedVectorize;
15029 ChainTE->CombinedOp = TreeEntry::ReducedBitPack;
15030 for (unsigned Idx : seq<unsigned>(1, ChainTE->getNumOperands())) {
15031 TreeEntry *ConstTE = getOperandEntry(ChainTE, Idx);
15032 ConstTE->State = TreeEntry::CombinedVectorize;
15033 ConstTE->CombinedOp = TreeEntry::ReducedBitPack;
15034 }
15035 }
15036 break;
15037 }
15038 default:
15039 break;
15040 }
15041 }
15042 // The nodes, built for the slices of the gathered nodes, are fused with their
15043 // fmul operands in the vector code too.
15044 for (std::unique_ptr<TreeEntry> &TE :
15045 drop_begin(VectorizableTree, BaseGraphSize))
15046 if (TE->hasState() &&
15047 is_contained({Instruction::FAdd, Instruction::FSub}, TE->getOpcode()))
15048 CombineFMulAdd(*TE);
15049
15050 // The gathers of the fully reversed bytes of a scalar are emitted as a byte
15051 // swap of the scalar, if profitable.
15052 SmallVector<TreeEntry *> GatherNodes;
15053 SmallVector<SmallVector<Value *>> GatheredScalars;
15054 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
15055 if (!TE->isGather() || !TE->ReuseShuffleIndices.empty() ||
15056 !TE->CombinedEntriesWithIndices.empty())
15057 continue;
15058 GatherNodes.push_back(TE.get());
15060 GatheredScalars.emplace_back(TE->Scalars.begin(), TE->Scalars.end());
15061 SmallVector<int> ReorderMask(TE->ReorderIndices.begin(),
15062 TE->ReorderIndices.end());
15063 if (!ReorderMask.empty())
15064 reorderScalars(VL, ReorderMask);
15065 }
15066 SmallBitVector BSwapGathers = selectBSwapGathers(
15067 GatheredScalars, *DL, *TTI, Opts.slp_revec, CostKind,
15068 [&](Value *Src)
15069 -> std::optional<
15070 std::tuple<const void *, FixedVectorType *, unsigned>> {
15071 ArrayRef<TreeEntry *> TEs = getTreeEntries(Src);
15072 const auto *It = find_if_not(TEs, [&](const TreeEntry *TE) {
15073 return TransformedToGatherNodes.contains(TE) ||
15074 DeletedNodes.contains(TE);
15075 });
15076 if (It == TEs.end())
15077 return std::nullopt;
15078 return std::make_tuple(*It,
15080 Src->getType(), (*It)->getVectorFactor())),
15081 (*It)->findLaneForValue(Src));
15082 });
15083 for (unsigned Idx : BSwapGathers.set_bits())
15084 GatherNodes[Idx]->CombinedOp = TreeEntry::ExtractedFieldsBSwap;
15085
15086 if (LoadEntriesToVectorize.empty()) {
15087 // Single load node - exit.
15088 if (VectorizableTree.size() <= 1 && getRootNode().hasState() &&
15089 getRootNode().getOpcode() == Instruction::Load)
15090 return;
15091 // Small graph with small VF - exit.
15092 constexpr unsigned SmallTree = 3;
15093 constexpr unsigned SmallVF = 2;
15094 if ((VectorizableTree.size() <= SmallTree &&
15095 getRootNodeScalars().size() == SmallVF) ||
15096 (VectorizableTree.size() <= 2 && UserIgnoreList))
15097 return;
15098
15099 if (getRootNode().isNonPowOf2Vec() &&
15100 getCanonicalGraphSize() != getTreeSize() && UserIgnoreList &&
15101 getCanonicalGraphSize() <= SmallTree &&
15102 count_if(ArrayRef(VectorizableTree).drop_front(getCanonicalGraphSize()),
15103 [](const std::unique_ptr<TreeEntry> &TE) {
15104 return TE->isGather() && TE->hasState() &&
15105 TE->getOpcode() == Instruction::Load &&
15106 !allSameBlock(TE->Scalars);
15107 }) == 1)
15108 return;
15109 }
15110
15111 // A list of loads to be gathered during the vectorization process. We can
15112 // try to vectorize them at the end, if profitable.
15113 SmallMapVector<std::tuple<BasicBlock *, Value *, Type *>,
15115 GatheredLoads;
15116
15117 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
15118 TreeEntry &E = *TE;
15119 if (E.isGather() &&
15120 ((E.hasState() && E.getOpcode() == Instruction::Load) ||
15121 (!E.hasState() && any_of(make_isa_range<LoadInst>(E.Scalars),
15122 [&](LoadInst *LI) {
15123 return !isVectorized(LI) && !isDeleted(LI);
15124 }))) &&
15125 !isSplat(E.Scalars)) {
15126 // The loads from the single predecessor block are gathered with the
15127 // loads from the block of the user node, if the wide load there may
15128 // cover them.
15129 BasicBlock *UserBB =
15130 E.UserTreeIndex && E.UserTreeIndex.UserTE->hasState()
15131 ? E.UserTreeIndex.UserTE->getMainOp()->getParent()
15132 : nullptr;
15133 for (Value *V : E.Scalars) {
15134 auto *LI = dyn_cast<LoadInst>(V);
15135 if (!LI)
15136 continue;
15137 if (isDeleted(LI) || isVectorized(LI) || !LI->isSimple())
15138 continue;
15139 BasicBlock *BB = LI->getParent();
15140 if (UserBB && UserBB->getSinglePredecessor() == BB &&
15141 !isLoadMemoryModified(LI, UserBB))
15142 BB = UserBB;
15144 *this, V, *DL, *SE, *TTI,
15145 GatheredLoads[std::make_tuple(
15146 BB,
15147 getUnderlyingObject(LI->getPointerOperand(),
15148 Opts.slp_recursion_max_depth),
15149 LI->getType())]);
15150 }
15151 }
15152 }
15153 // Try to vectorize gathered loads if this is not just a gather of loads.
15154 if (!GatheredLoads.empty())
15155 tryToVectorizeGatheredLoads(GatheredLoads);
15156}
15157
15158/// Merges shuffle masks and emits final shuffle instruction, if required. It
15159/// supports shuffling of 2 input vectors. It implements lazy shuffles emission,
15160/// when the actual shuffle instruction is generated only if this is actually
15161/// required. Otherwise, the shuffle instruction emission is delayed till the
15162/// end of the process, to reduce the number of emitted instructions and further
15163/// analysis/transformations.
15165 bool IsFinalized = false;
15166 SmallVector<int> CommonMask;
15167
15168 // Each input vector can be tagged with extra context information
15169 struct InVector {
15172 TargetTransformInfo::VectorInstrContext::None;
15173
15175 TargetTransformInfo::VectorInstrContext::None)
15176 : Vec(Vec), Ctx(Ctx) {}
15177 InVector(const TreeEntry *Vec,
15179 TargetTransformInfo::VectorInstrContext::None)
15180 : Vec(Vec), Ctx(Ctx) {}
15181 };
15182 SmallVector<InVector, 2> InVectors;
15183 /// Captures the original scalar VL of a single, "clean" gather() call so
15184 /// the values can be forwarded as the Args operand to getShuffleCost() for
15185 /// the final permutation in finalize(). This lets the target cost model
15186 /// recognize patterns such as broadcast-of-load (e.g. on X86,
15187 /// vbroadcast{ss,sd} folds the broadcast and the load into one instruction
15188 /// under AVX/AVX2 and is reported as TCC_Free by getShuffleCost). The
15189 /// state machine is:
15190 /// * engaged + empty: tracking active, no qualifying gather seen yet.
15191 /// * engaged + non-empty: exactly one qualifying gather observed and its
15192 /// VL still corresponds to InVectors.front().
15193 /// * disengaged: the cached VL is no longer trustworthy (multiple
15194 /// gather() calls, or a state-mutating add() happened).
15195 std::optional<SmallVector<Value *>> BVValues = SmallVector<Value *>();
15196 const TargetTransformInfo &TTI;
15197 InstructionCost Cost = 0;
15198 SmallDenseSet<Value *> VectorizedVals;
15199 BoUpSLP &R;
15200 SmallPtrSetImpl<Value *> &CheckedExtracts;
15201 const TTI::TargetCostKind CostKind;
15202 /// While set, still trying to estimate the cost for the same nodes and we
15203 /// can delay actual cost estimation (virtual shuffle instruction emission).
15204 /// May help better estimate the cost if same nodes must be permuted + allows
15205 /// to move most of the long shuffles cost estimation to TTI.
15206 bool SameNodesEstimated = true;
15207
15208 static Constant *getAllOnesValue(const DataLayout &DL, Type *Ty) {
15209 if (Ty->getScalarType()->isPointerTy()) {
15212 IntegerType::get(Ty->getContext(),
15213 DL.getTypeStoreSizeInBits(Ty->getScalarType()))),
15214 Ty->getScalarType());
15215 if (auto *VTy = dyn_cast<VectorType>(Ty))
15216 Res = ConstantVector::getSplat(VTy->getElementCount(), Res);
15217 return Res;
15218 }
15219 return Constant::getAllOnesValue(Ty);
15220 }
15221
15222 InstructionCost getBuildVectorCost(ArrayRef<Value *> VL, Value *Root,
15223 TTI::VectorInstrContext ContextHint) {
15224 if ((!Root && allConstant(VL)) || all_of(VL, IsaPred<UndefValue>))
15225 return TTI::TCC_Free;
15226 auto *VecTy = cast<VectorType>(getWidenedType(ScalarTy, VL.size()));
15227 InstructionCost GatherCost = 0;
15228 if (!Root && isSplat(VL)) {
15229 // Found the broadcasting of the single scalar, calculate the cost as
15230 // the broadcast.
15231 const auto *It = find_if_not(VL, IsaPred<UndefValue>);
15232 assert(It != VL.end() && "Expected at least one non-undef value.");
15233 // Add broadcast for non-identity shuffle only.
15234 bool NeedShuffle =
15235 count(VL, *It) > 1 &&
15236 (VL.front() != *It || !all_of(VL.drop_front(), IsaPred<UndefValue>));
15237 if (!NeedShuffle) {
15239 assert(R.Opts.slp_revec && "FixedVectorType is not expected.");
15240 return TTI.getShuffleCost(
15241 TTI::SK_InsertSubvector, VecTy, VecTy, CostKind, {},
15242 std::distance(VL.begin(), It) * getNumElements(ScalarTy),
15244 }
15245 return TTI.getVectorInstrCost(Instruction::InsertElement, VecTy,
15246 CostKind, std::distance(VL.begin(), It),
15247 PoisonValue::get(VecTy), *It,
15248 ContextHint);
15249 }
15250
15251 SmallVector<int> ShuffleMask(VL.size(), PoisonMaskElem);
15252 transform(VL, ShuffleMask.begin(), [](Value *V) {
15253 return isa<PoisonValue>(V) ? PoisonMaskElem : 0;
15254 });
15255 InstructionCost InsertCost =
15256 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind, 0,
15257 PoisonValue::get(VecTy), *It, ContextHint);
15258 return InsertCost + getShuffleCost(TTI, TargetTransformInfo::SK_Broadcast,
15259 VecTy, CostKind, ShuffleMask,
15260 /*Index=*/0, /*SubTp=*/nullptr,
15261 /*Args=*/*It, ContextHint);
15262 }
15263 assert(ContextHint != TTI::VectorInstrContext::SplatOpFolded &&
15264 "Expected SplatOpFolded to be a splat");
15265 return GatherCost + (all_of(VL, IsaPred<UndefValue>)
15267 : R.getGatherCost(VL, !Root, ScalarTy));
15268 };
15269
15270 /// Compute the cost of creating a vector containing the extracted values from
15271 /// \p VL.
15273 computeExtractCost(ArrayRef<Value *> VL, ArrayRef<int> Mask,
15274 ArrayRef<std::optional<TTI::ShuffleKind>> ShuffleKinds,
15275 unsigned NumParts) {
15276 assert(VL.size() > NumParts && "Unexpected scalarized shuffle.");
15277 unsigned NumElts = accumulate(VL, 0, [](unsigned Sz, Value *V) {
15278 auto *EE = dyn_cast<ExtractElementInst>(V);
15279 if (!EE)
15280 return Sz;
15281 auto *VecTy = dyn_cast<FixedVectorType>(EE->getVectorOperandType());
15282 if (!VecTy)
15283 return Sz;
15284 return std::max(Sz, VecTy->getNumElements());
15285 });
15286 // FIXME: this must be moved to TTI for better estimation.
15287 unsigned EltsPerVector = getPartNumElems(VL.size(), NumParts);
15288 auto CheckPerRegistersShuffle = [&](MutableArrayRef<int> Mask,
15290 SmallVectorImpl<unsigned> &SubVecSizes)
15291 -> std::optional<TTI::ShuffleKind> {
15292 if (NumElts <= EltsPerVector)
15293 return std::nullopt;
15294 int OffsetReg0 = alignDown(accumulate(Mask, INT_MAX,
15295 [](int S, int I) {
15296 if (I == PoisonMaskElem)
15297 return S;
15298 return std::min(S, I);
15299 }),
15300 EltsPerVector);
15301 int OffsetReg1 = OffsetReg0;
15302 DenseSet<int> RegIndices;
15303 // Check that if trying to permute same single/2 input vectors.
15305 int FirstRegId = -1;
15306 Indices.assign(1, OffsetReg0);
15307 auto HasLane = [](const auto &P) { return P.value() != PoisonMaskElem; };
15308 for (auto [Pos, I] : make_filter_range(enumerate(Mask), HasLane)) {
15309 int Idx = I - OffsetReg0;
15310 int RegId =
15311 (Idx / NumElts) * NumParts + (Idx % NumElts) / EltsPerVector;
15312 if (FirstRegId < 0)
15313 FirstRegId = RegId;
15314 RegIndices.insert(RegId);
15315 if (RegIndices.size() > 2)
15316 return std::nullopt;
15317 if (RegIndices.size() == 2) {
15318 ShuffleKind = TTI::SK_PermuteTwoSrc;
15319 if (Indices.size() == 1) {
15320 OffsetReg1 = alignDown(
15321 std::accumulate(
15322 std::next(Mask.begin(), Pos), Mask.end(), INT_MAX,
15323 [&](int S, int I) {
15324 if (I == PoisonMaskElem)
15325 return S;
15326 int RegId = ((I - OffsetReg0) / NumElts) * NumParts +
15327 ((I - OffsetReg0) % NumElts) / EltsPerVector;
15328 if (RegId == FirstRegId)
15329 return S;
15330 return std::min(S, I);
15331 }),
15332 EltsPerVector);
15333 unsigned Index = OffsetReg1 % NumElts;
15334 Indices.push_back(Index);
15335 SubVecSizes.push_back(std::min(NumElts - Index, EltsPerVector));
15336 }
15337 Idx = I - OffsetReg1;
15338 }
15339 I = (Idx % NumElts) % EltsPerVector +
15340 (RegId == FirstRegId ? 0 : EltsPerVector);
15341 }
15342 return ShuffleKind;
15343 };
15344 InstructionCost Cost = 0;
15345
15346 // Process extracts in blocks of EltsPerVector to check if the source vector
15347 // operand can be re-used directly. If not, add the cost of creating a
15348 // shuffle to extract the values into a vector register.
15349 for (unsigned Part : seq<unsigned>(NumParts)) {
15350 if (!ShuffleKinds[Part])
15351 continue;
15352 ArrayRef<int> MaskSlice = Mask.slice(
15353 Part * EltsPerVector, getNumElems(Mask.size(), EltsPerVector, Part));
15354 SmallVector<int> SubMask(EltsPerVector, PoisonMaskElem);
15355 copy(MaskSlice, SubMask.begin());
15357 SmallVector<unsigned, 2> SubVecSizes;
15358 std::optional<TTI::ShuffleKind> RegShuffleKind =
15359 CheckPerRegistersShuffle(SubMask, Indices, SubVecSizes);
15360 if (!RegShuffleKind) {
15361 if (*ShuffleKinds[Part] != TTI::SK_PermuteSingleSrc ||
15363 MaskSlice, std::max<unsigned>(NumElts, MaskSlice.size())))
15364 Cost += getShuffleCost(
15365 TTI, *ShuffleKinds[Part],
15366 cast<VectorType>(getWidenedType(ScalarTy, NumElts)), CostKind,
15367 MaskSlice);
15368 continue;
15369 }
15370 if (*RegShuffleKind != TTI::SK_PermuteSingleSrc ||
15371 !ShuffleVectorInst::isIdentityMask(SubMask, EltsPerVector)) {
15372 Cost += getShuffleCost(
15373 TTI, *RegShuffleKind,
15374 cast<VectorType>(getWidenedType(ScalarTy, EltsPerVector)), CostKind,
15375 SubMask);
15376 }
15377 const unsigned BaseVF = getFullVectorNumberOfElements(
15378 *R.TTI, VL.front()->getType(), alignTo(NumElts, EltsPerVector),
15379 R.Opts.slp_revec);
15380 for (const auto [Idx, SubVecSize] : zip(Indices, SubVecSizes)) {
15381 assert((Idx + SubVecSize) <= BaseVF &&
15382 "SK_ExtractSubvector index out of range");
15383 Cost += getShuffleCost(
15385 cast<VectorType>(getWidenedType(ScalarTy, BaseVF)), CostKind, {},
15386 Idx, cast<VectorType>(getWidenedType(ScalarTy, SubVecSize)));
15387 }
15388 // Second attempt to check, if just a permute is better estimated than
15389 // subvector extract.
15390 SubMask.assign(NumElts, PoisonMaskElem);
15391 copy(MaskSlice, SubMask.begin());
15392 InstructionCost OriginalCost =
15393 getShuffleCost(TTI, *ShuffleKinds[Part],
15395 CostKind, SubMask);
15396 if (OriginalCost < Cost)
15397 Cost = OriginalCost;
15398 }
15399 return Cost;
15400 }
15401 /// Adds the cost of reshuffling \p E1 and \p E2 (if present), using given
15402 /// mask \p Mask, register number \p Part, that includes \p SliceSize
15403 /// elements.
15404 void estimateNodesPermuteCost(const TreeEntry &E1, const TreeEntry *E2,
15405 ArrayRef<int> Mask, unsigned Part,
15406 unsigned SliceSize) {
15407 if (SameNodesEstimated) {
15408 // Delay the cost estimation if the same nodes are reshuffling.
15409 // If we already requested the cost of reshuffling of E1 and E2 before, no
15410 // need to estimate another cost with the sub-Mask, instead include this
15411 // sub-Mask into the CommonMask to estimate it later and avoid double cost
15412 // estimation.
15413 if ((InVectors.size() == 2 &&
15414 cast<const TreeEntry *>(InVectors.front().Vec) == &E1 &&
15415 cast<const TreeEntry *>(InVectors.back().Vec) == E2) ||
15416 (!E2 && cast<const TreeEntry *>(InVectors.front().Vec) == &E1)) {
15417 unsigned Limit = getNumElems(Mask.size(), SliceSize, Part);
15418 assert(all_of(ArrayRef(CommonMask).slice(Part * SliceSize, Limit),
15419 [](int Idx) { return Idx == PoisonMaskElem; }) &&
15420 "Expected all poisoned elements.");
15421 ArrayRef<int> SubMask = ArrayRef(Mask).slice(Part * SliceSize, Limit);
15422 copy(SubMask, std::next(CommonMask.begin(), SliceSize * Part));
15423 return;
15424 }
15425 // Found non-matching nodes - need to estimate the cost for the matched
15426 // and transform mask.
15427 if (InVectors.size() == 1)
15428 Cost += createShuffle(InVectors.front().Vec, nullptr, CommonMask, {},
15429 InVectors.front().Ctx);
15430 else
15431 Cost += createShuffle(InVectors.front().Vec, InVectors.back().Vec,
15432 CommonMask, {}, InVectors.front().Ctx,
15433 InVectors.back().Ctx);
15434 transformMaskAfterShuffle(CommonMask, CommonMask);
15435 } else if (InVectors.size() == 2) {
15436 Cost +=
15437 createShuffle(InVectors.front().Vec, InVectors.back().Vec, CommonMask,
15438 {}, InVectors.front().Ctx, InVectors.back().Ctx);
15439 transformMaskAfterShuffle(CommonMask, CommonMask);
15440 }
15441 SameNodesEstimated = false;
15442 if (!E2 && InVectors.size() == 1) {
15443 unsigned VF = E1.getVectorFactor();
15444 if (Value *V1 = dyn_cast<Value *>(InVectors.front().Vec)) {
15445 VF = std::max(VF, getVF(V1));
15446 } else {
15447 const auto *E = cast<const TreeEntry *>(InVectors.front().Vec);
15448 VF = std::max(VF, E->getVectorFactor());
15449 }
15450 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
15451 if (Mask[Idx] != PoisonMaskElem && CommonMask[Idx] == PoisonMaskElem)
15452 CommonMask[Idx] = Mask[Idx] + VF;
15453 Cost += createShuffle(InVectors.front().Vec, &E1, CommonMask, {},
15454 InVectors.front().Ctx);
15455 transformMaskAfterShuffle(CommonMask, CommonMask);
15456 } else {
15457 auto P = InVectors.front();
15458 Cost += createShuffle(&E1, E2, Mask, {}, TTI::VectorInstrContext::None);
15459 unsigned VF = Mask.size();
15460 if (Value *V1 = dyn_cast<Value *>(P.Vec)) {
15461 VF = std::max(VF,
15462 getNumElements(V1->getType()));
15463 } else {
15464 const auto *E = cast<const TreeEntry *>(P.Vec);
15465 VF = std::max(VF, E->getVectorFactor());
15466 }
15467 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
15468 if (Mask[Idx] != PoisonMaskElem)
15469 CommonMask[Idx] = Idx + (InVectors.empty() ? 0 : VF);
15470 Cost += createShuffle(P.Vec, InVectors.front().Vec, CommonMask, {}, P.Ctx,
15471 InVectors.front().Ctx);
15472 transformMaskAfterShuffle(CommonMask, CommonMask);
15473 }
15474 }
15475
15476 class ShuffleCostBuilder {
15477 const TargetTransformInfo &TTI;
15478 const TTI::TargetCostKind CostKind;
15479
15480 static bool isEmptyOrIdentity(ArrayRef<int> Mask, unsigned VF) {
15481 int Index = -1;
15482 return Mask.empty() ||
15483 (VF == Mask.size() &&
15486 Index == 0);
15487 }
15488
15489 public:
15490 ShuffleCostBuilder(const TargetTransformInfo &TTI,
15491 const TTI::TargetCostKind CostKind)
15492 : TTI(TTI), CostKind(CostKind) {}
15493 ~ShuffleCostBuilder() = default;
15494 InstructionCost createShuffleVector(Value *V1, Value *,
15495 ArrayRef<int> Mask) const {
15496 // Empty mask or identity mask are free.
15497 unsigned VF =
15498 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
15499 if (isEmptyOrIdentity(Mask, VF))
15500 return TTI::TCC_Free;
15502 cast<VectorType>(V1->getType()), CostKind, Mask);
15503 }
15505 createShuffleVector(Value *V1, ArrayRef<int> Mask, ArrayRef<Value *> VL,
15506 TTI::VectorInstrContext ContextHint =
15508 // Empty mask or identity mask are free.
15509 unsigned VF =
15510 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
15511 if (isEmptyOrIdentity(Mask, VF))
15512 return TTI::TCC_Free;
15514 cast<VectorType>(V1->getType()), CostKind, Mask,
15515 /*Index=*/0, /*SubTp=*/nullptr, VL, ContextHint);
15516 }
15517 InstructionCost createIdentity(Value *) const { return TTI::TCC_Free; }
15518 InstructionCost createPoison(Type *Ty, unsigned VF) const {
15519 return TTI::TCC_Free;
15520 }
15521 void resizeToMatch(Value *&, Value *&) const {}
15522 };
15523
15524 /// Smart shuffle instruction emission, walks through shuffles trees and
15525 /// tries to find the best matching vector for the actual shuffle
15526 /// instruction.
15528 createShuffle(const PointerUnion<Value *, const TreeEntry *> &P1,
15530 ArrayRef<int> Mask, ArrayRef<Value *> VL = {},
15533 ShuffleCostBuilder Builder(TTI, CostKind);
15534 SmallVector<int> CommonMask(Mask);
15536 unsigned CommonVF = Mask.size();
15537 InstructionCost ExtraCost = 0;
15538 auto GetNodeMinBWAffectedCost = [&](const TreeEntry &E,
15539 unsigned VF) -> InstructionCost {
15540 if (E.isGather() && allConstant(E.Scalars))
15541 return TTI::TCC_Free;
15542 Type *EScalarTy = E.Scalars.front()->getType();
15543 bool IsSigned = true;
15544 if (auto It = R.MinBWs.find(&E); It != R.MinBWs.end()) {
15545 EScalarTy = IntegerType::get(EScalarTy->getContext(), It->second.first);
15546 IsSigned = It->second.second;
15547 }
15548 if (EScalarTy != ScalarTy) {
15549 unsigned CastOpcode = Instruction::Trunc;
15550 unsigned DstSz = R.DL->getTypeSizeInBits(ScalarTy);
15551 unsigned SrcSz = R.DL->getTypeSizeInBits(EScalarTy);
15552 if (DstSz > SrcSz)
15553 CastOpcode = IsSigned ? Instruction::SExt : Instruction::ZExt;
15554 return TTI.getCastInstrCost(CastOpcode, getWidenedType(ScalarTy, VF),
15555 getWidenedType(EScalarTy, VF),
15556 R.getCastContextHint(E), CostKind);
15557 }
15558 return TTI::TCC_Free;
15559 };
15560 auto GetValueMinBWAffectedCost = [&](const Value *V) -> InstructionCost {
15561 if (isa<Constant>(V))
15562 return TTI::TCC_Free;
15563 auto *VecTy = cast<VectorType>(V->getType());
15564 Type *EScalarTy = VecTy->getElementType();
15565 if (EScalarTy != ScalarTy) {
15566 bool IsSigned = !isKnownNonNegative(V, SimplifyQuery(*R.DL));
15567 unsigned CastOpcode = Instruction::Trunc;
15568 unsigned DstSz = R.DL->getTypeSizeInBits(ScalarTy);
15569 unsigned SrcSz = R.DL->getTypeSizeInBits(EScalarTy);
15570 if (DstSz > SrcSz)
15571 CastOpcode = IsSigned ? Instruction::SExt : Instruction::ZExt;
15573 if (ArrayRef<TreeEntry *> TEs = R.getTreeEntries(V); TEs.size() == 1)
15574 CCH = R.getCastContextHint(*TEs.front());
15575 return TTI.getCastInstrCost(
15576 CastOpcode, VectorType::get(ScalarTy, VecTy->getElementCount()),
15577 VecTy, CCH, CostKind);
15578 }
15579 return TTI::TCC_Free;
15580 };
15581 if (!V1 && !V2 && !P2.isNull()) {
15582 // Shuffle 2 entry nodes.
15583 const TreeEntry *E = cast<const TreeEntry *>(P1);
15584 unsigned VF = E->getVectorFactor();
15585 const TreeEntry *E2 = cast<const TreeEntry *>(P2);
15586 CommonVF = std::max(VF, E2->getVectorFactor());
15587 assert(all_of(Mask,
15588 [=](int Idx) {
15589 return Idx < 2 * static_cast<int>(CommonVF);
15590 }) &&
15591 "All elements in mask must be less than 2 * CommonVF.");
15592 if (E->Scalars.size() == E2->Scalars.size()) {
15593 SmallVector<int> EMask = E->getCommonMask();
15594 SmallVector<int> E2Mask = E2->getCommonMask();
15595 if (!EMask.empty() || !E2Mask.empty()) {
15596 for (int &Idx : make_filter_range(
15597 CommonMask, [](int Idx) { return Idx != PoisonMaskElem; })) {
15598 if (Idx < static_cast<int>(CommonVF) && !EMask.empty())
15599 Idx = EMask[Idx];
15600 else if (Idx >= static_cast<int>(CommonVF))
15601 Idx = (E2Mask.empty() ? Idx - CommonVF : E2Mask[Idx - CommonVF]) +
15602 E->Scalars.size();
15603 }
15604 }
15605 CommonVF = E->Scalars.size();
15606 ExtraCost += GetNodeMinBWAffectedCost(*E, CommonVF) +
15607 GetNodeMinBWAffectedCost(*E2, CommonVF);
15608 } else {
15609 ExtraCost += GetNodeMinBWAffectedCost(*E, E->getVectorFactor()) +
15610 GetNodeMinBWAffectedCost(*E2, E2->getVectorFactor());
15611 }
15613 V2 = getAllOnesValue(*R.DL, getWidenedType(ScalarTy, CommonVF));
15614 } else if (!V1 && P2.isNull()) {
15615 // Shuffle single entry node.
15616 const TreeEntry *E = cast<const TreeEntry *>(P1);
15617 unsigned VF = E->getVectorFactor();
15618 CommonVF = VF;
15619 assert(
15620 all_of(Mask,
15621 [=](int Idx) { return Idx < static_cast<int>(CommonVF); }) &&
15622 "All elements in mask must be less than CommonVF.");
15623 if (E->Scalars.size() == Mask.size() && VF != Mask.size()) {
15624 SmallVector<int> EMask = E->getCommonMask();
15625 assert(!EMask.empty() && "Expected non-empty common mask.");
15626 for (int &Idx : CommonMask) {
15627 if (Idx != PoisonMaskElem)
15628 Idx = EMask[Idx];
15629 }
15630 CommonVF = E->Scalars.size();
15631 } else if (unsigned Factor = E->getInterleaveFactor();
15632 Factor > 0 && E->Scalars.size() != Mask.size() &&
15634 Factor)) {
15635 // Deinterleaved nodes are free.
15636 std::iota(CommonMask.begin(), CommonMask.end(), 0);
15637 }
15638 ExtraCost += GetNodeMinBWAffectedCost(*E, CommonVF);
15640 // Not identity/broadcast? Try to see if the original vector is better.
15641 if (!E->ReorderIndices.empty() && CommonVF == E->ReorderIndices.size() &&
15642 CommonVF == CommonMask.size() &&
15643 any_of(enumerate(CommonMask),
15644 [](const auto &&P) {
15645 return P.value() != PoisonMaskElem &&
15646 static_cast<unsigned>(P.value()) != P.index();
15647 }) &&
15648 any_of(CommonMask,
15649 [](int Idx) { return Idx != PoisonMaskElem && Idx != 0; })) {
15650 SmallVector<int> ReorderMask;
15651 inversePermutation(E->ReorderIndices, ReorderMask);
15652 addMask(CommonMask, ReorderMask);
15653 }
15654 } else if (V1 && P2.isNull()) {
15655 // Shuffle single vector.
15656 ExtraCost += GetValueMinBWAffectedCost(V1);
15657 CommonVF = getVF(V1);
15658 assert(
15659 all_of(Mask,
15660 [=](int Idx) { return Idx < static_cast<int>(CommonVF); }) &&
15661 "All elements in mask must be less than CommonVF.");
15662 } else if (V1 && !V2) {
15663 // Shuffle vector and tree node.
15664 unsigned VF = getVF(V1);
15665 const TreeEntry *E2 = cast<const TreeEntry *>(P2);
15666 CommonVF = std::max(VF, E2->getVectorFactor());
15667 assert(all_of(Mask,
15668 [=](int Idx) {
15669 return Idx < 2 * static_cast<int>(CommonVF);
15670 }) &&
15671 "All elements in mask must be less than 2 * CommonVF.");
15672 if (E2->Scalars.size() == VF && VF != CommonVF) {
15673 SmallVector<int> E2Mask = E2->getCommonMask();
15674 assert(!E2Mask.empty() && "Expected non-empty common mask.");
15675 for (int &Idx : make_filter_range(
15676 CommonMask, [](int Idx) { return Idx != PoisonMaskElem; })) {
15677 if (Idx >= static_cast<int>(CommonVF))
15678 Idx = E2Mask[Idx - CommonVF] + VF;
15679 }
15680 CommonVF = VF;
15681 }
15682 ExtraCost += GetValueMinBWAffectedCost(V1);
15684 ExtraCost += GetNodeMinBWAffectedCost(
15685 *E2, std::min(CommonVF, E2->getVectorFactor()));
15686 V2 = getAllOnesValue(*R.DL, getWidenedType(ScalarTy, CommonVF));
15687 } else if (!V1 && V2) {
15688 // Shuffle vector and tree node.
15689 unsigned VF = getVF(V2);
15690 const TreeEntry *E1 = cast<const TreeEntry *>(P1);
15691 CommonVF = std::max(VF, E1->getVectorFactor());
15692 assert(all_of(Mask,
15693 [=](int Idx) {
15694 return Idx < 2 * static_cast<int>(CommonVF);
15695 }) &&
15696 "All elements in mask must be less than 2 * CommonVF.");
15697 if (E1->Scalars.size() == VF && VF != CommonVF) {
15698 SmallVector<int> E1Mask = E1->getCommonMask();
15699 assert(!E1Mask.empty() && "Expected non-empty common mask.");
15700 for (int &Idx : make_filter_range(
15701 CommonMask, [](int Idx) { return Idx != PoisonMaskElem; })) {
15702 if (Idx >= static_cast<int>(CommonVF))
15703 Idx = E1Mask[Idx - CommonVF] + VF;
15704 else
15705 Idx = E1Mask[Idx];
15706 }
15707 CommonVF = VF;
15708 }
15709 ExtraCost += GetNodeMinBWAffectedCost(
15710 *E1, std::min(CommonVF, E1->getVectorFactor()));
15712 ExtraCost += GetValueMinBWAffectedCost(V2);
15713 V2 = getAllOnesValue(*R.DL, getWidenedType(ScalarTy, CommonVF));
15714 } else {
15715 assert(V1 && V2 && "Expected both vectors.");
15716 unsigned VF = getVF(V1);
15717 CommonVF = std::max(VF, getVF(V2));
15718 assert(all_of(Mask,
15719 [=](int Idx) {
15720 return Idx < 2 * static_cast<int>(CommonVF);
15721 }) &&
15722 "All elements in mask must be less than 2 * CommonVF.");
15723 ExtraCost +=
15724 GetValueMinBWAffectedCost(V1) + GetValueMinBWAffectedCost(V2);
15725 if (V1->getType() != V2->getType()) {
15727 V2 = getAllOnesValue(*R.DL, getWidenedType(ScalarTy, CommonVF));
15728 } else {
15729 if (cast<VectorType>(V1->getType())->getElementType() != ScalarTy)
15731 if (cast<VectorType>(V2->getType())->getElementType() != ScalarTy)
15732 V2 = getAllOnesValue(*R.DL, getWidenedType(ScalarTy, CommonVF));
15733 }
15734 }
15735 InVectors.front() =
15736 Constant::getNullValue(getWidenedType(ScalarTy, CommonMask.size()));
15737 if (InVectors.size() == 2)
15738 InVectors.pop_back();
15740 P2.isNull() ? Ctx1 : TTI::combineVectorInstrContexts(Ctx1, Ctx2);
15742 V1, V2, CommonMask, Builder, ScalarTy,
15743 R.Opts.slp_revec, VL, Ctx);
15744 }
15745
15746public:
15748 ArrayRef<Value *> VectorizedVals, BoUpSLP &R,
15749 SmallPtrSetImpl<Value *> &CheckedExtracts)
15750 : BaseShuffleAnalysis(ScalarTy), TTI(TTI),
15751 VectorizedVals(VectorizedVals.begin(), VectorizedVals.end()), R(R),
15752 CheckedExtracts(CheckedExtracts), CostKind(R.getCostKind()) {}
15753 Value *adjustExtracts(const TreeEntry *E, MutableArrayRef<int> Mask,
15754 ArrayRef<std::optional<TTI::ShuffleKind>> ShuffleKinds,
15755 unsigned NumParts, bool &UseVecBaseAsInput) {
15756 UseVecBaseAsInput = false;
15757 if (Mask.empty())
15758 return nullptr;
15759 Value *VecBase = nullptr;
15760 SmallVector<Value *> VL(E->Scalars.begin(), E->Scalars.end());
15761 if (!E->ReorderIndices.empty()) {
15762 SmallVector<int> ReorderMask(E->ReorderIndices.begin(),
15763 E->ReorderIndices.end());
15764 reorderScalars(VL, ReorderMask);
15765 }
15766 // Check if it can be considered reused if same extractelements were
15767 // vectorized already.
15768 bool PrevNodeFound = any_of(
15769 ArrayRef(R.VectorizableTree).take_front(E->Idx),
15770 [&](const std::unique_ptr<TreeEntry> &TE) {
15771 return ((TE->hasState() && !TE->isAltShuffle() &&
15772 TE->getOpcode() == Instruction::ExtractElement) ||
15773 TE->isGather()) &&
15774 all_of(enumerate(TE->Scalars), [&](auto &&Data) {
15775 return VL.size() > Data.index() &&
15776 (Mask[Data.index()] == PoisonMaskElem ||
15777 isa<UndefValue>(VL[Data.index()]) ||
15778 Data.value() == VL[Data.index()]);
15779 });
15780 });
15781 SmallPtrSet<Value *, 4> UniqueBases;
15782 unsigned SliceSize = getPartNumElems(VL.size(), NumParts);
15783 SmallDenseMap<Value *, APInt, 4> VectorOpsToExtracts;
15784 for (unsigned Part : seq<unsigned>(NumParts)) {
15785 unsigned Limit = getNumElems(VL.size(), SliceSize, Part);
15786 ArrayRef<int> SubMask = Mask.slice(Part * SliceSize, Limit);
15787 for (auto [I, V] :
15788 enumerate(ArrayRef(VL).slice(Part * SliceSize, Limit))) {
15789 // Ignore non-extractelement scalars.
15790 if (isa<UndefValue>(V) ||
15791 (!SubMask.empty() && SubMask[I] == PoisonMaskElem))
15792 continue;
15793 // If all users of instruction are going to be vectorized and this
15794 // instruction itself is not going to be vectorized, consider this
15795 // instruction as dead and remove its cost from the final cost of the
15796 // vectorized tree.
15797 // Also, avoid adjusting the cost for extractelements with multiple uses
15798 // in different graph entries.
15799 auto *EE = cast<ExtractElementInst>(V);
15800 VecBase = EE->getVectorOperand();
15801 UniqueBases.insert(VecBase);
15802 ArrayRef<TreeEntry *> VEs = R.getTreeEntries(V);
15803 if (!CheckedExtracts.insert(V).second ||
15804 !R.areAllUsersVectorized(cast<Instruction>(V), &VectorizedVals) ||
15805 any_of(VEs,
15806 [&](const TreeEntry *TE) {
15807 return R.DeletedNodes.contains(TE) ||
15808 R.TransformedToGatherNodes.contains(TE);
15809 }) ||
15810 (E->UserTreeIndex && E->UserTreeIndex.EdgeIdx == UINT_MAX &&
15811 !R.isVectorized(EE) &&
15812 count_if(E->Scalars, [&](Value *V) { return V == EE; }) !=
15813 count_if(E->UserTreeIndex.UserTE->Scalars,
15814 [&](Value *V) { return V == EE; })) ||
15815 any_of(EE->users(),
15816 [&](User *U) {
15817 return isa<GetElementPtrInst>(U) &&
15818 !R.areAllUsersVectorized(cast<Instruction>(U),
15819 &VectorizedVals);
15820 }) ||
15821 (!VEs.empty() && !is_contained(VEs, E)))
15822 continue;
15823 std::optional<unsigned> EEIdx = getExtractIndex(EE);
15824 if (!EEIdx)
15825 continue;
15826 unsigned Idx = *EEIdx;
15827 // Take credit for instruction that will become dead.
15828 if (EE->hasOneUse() || !PrevNodeFound) {
15829 Instruction *Ext = EE->user_back();
15830 if (isa<SExtInst, ZExtInst>(Ext) &&
15832 // Use getExtractWithExtendCost() to calculate the cost of
15833 // extractelement/ext pair.
15834 Cost -= TTI.getExtractWithExtendCost(
15835 Ext->getOpcode(), Ext->getType(), EE->getVectorOperandType(),
15836 Idx, CostKind);
15837 // Add back the cost of s|zext which is subtracted separately.
15838 Cost += TTI.getCastInstrCost(
15839 Ext->getOpcode(), Ext->getType(), EE->getType(),
15840 TTI::getCastContextHint(Ext), CostKind, Ext);
15841 continue;
15842 }
15843 }
15844 APInt &DemandedElts =
15845 VectorOpsToExtracts
15846 .try_emplace(VecBase,
15847 APInt::getZero(getNumElements(VecBase->getType())))
15848 .first->getSecond();
15849 DemandedElts.setBit(Idx);
15850 }
15851 }
15852 for (const auto &[Vec, DemandedElts] : VectorOpsToExtracts)
15854 DemandedElts, /*Insert=*/false,
15855 /*Extract=*/true, CostKind);
15856 // Check that gather of extractelements can be represented as just a
15857 // shuffle of a single/two vectors the scalars are extracted from.
15858 // Found the bunch of extractelement instructions that must be gathered
15859 // into a vector and can be represented as a permutation elements in a
15860 // single input vector or of 2 input vectors.
15861 // Done for reused if same extractelements were vectorized already.
15862 if (!PrevNodeFound)
15863 Cost += computeExtractCost(VL, Mask, ShuffleKinds, NumParts);
15864 InVectors.assign(1, E);
15865 CommonMask.assign(Mask.begin(), Mask.end());
15866 transformMaskAfterShuffle(CommonMask, CommonMask);
15867 SameNodesEstimated = false;
15868 if (NumParts != 1 && UniqueBases.size() != 1) {
15869 UseVecBaseAsInput = true;
15870 VecBase =
15871 Constant::getNullValue(getWidenedType(ScalarTy, CommonMask.size()));
15872 }
15873 return VecBase;
15874 }
15875 /// Checks if the specified entry \p E needs to be delayed because of its
15876 /// dependency nodes.
15877 std::optional<InstructionCost>
15878 needToDelay(const TreeEntry *,
15880 // No need to delay the cost estimation during analysis.
15881 return std::nullopt;
15882 }
15883 /// Reset the builder to handle perfect diamond match.
15885 IsFinalized = false;
15886 CommonMask.clear();
15887 InVectors.clear();
15888 Cost = 0;
15889 VectorizedVals.clear();
15890 SameNodesEstimated = true;
15891 }
15892 void add(const TreeEntry &E1, const TreeEntry &E2, ArrayRef<int> Mask) {
15893 BVValues.reset();
15894 if (&E1 == &E2) {
15895 assert(all_of(Mask,
15896 [&](int Idx) {
15897 return Idx < static_cast<int>(E1.getVectorFactor());
15898 }) &&
15899 "Expected single vector shuffle mask.");
15900 add(E1, Mask);
15901 return;
15902 }
15903 if (InVectors.empty()) {
15904 CommonMask.assign(Mask.begin(), Mask.end());
15905 InVectors.assign({&E1, &E2});
15906 return;
15907 }
15908 assert(!CommonMask.empty() && "Expected non-empty common mask.");
15909 auto *MaskVecTy = getWidenedType(ScalarTy, Mask.size());
15910 unsigned NumParts = R.getNumberOfParts(MaskVecTy, ScalarTy, Mask.size());
15911 unsigned SliceSize = getPartNumElems(Mask.size(), NumParts);
15912 const auto *It = find_if(Mask, not_equal_to(PoisonMaskElem));
15913 unsigned Part = std::distance(Mask.begin(), It) / SliceSize;
15914 estimateNodesPermuteCost(E1, &E2, Mask, Part, SliceSize);
15915 }
15916 void add(const TreeEntry &E1, ArrayRef<int> Mask) {
15917 BVValues.reset();
15918 if (InVectors.empty()) {
15919 CommonMask.assign(Mask.begin(), Mask.end());
15920 InVectors.assign(1, &E1);
15921 return;
15922 }
15923 assert(!CommonMask.empty() && "Expected non-empty common mask.");
15924 auto *MaskVecTy = getWidenedType(ScalarTy, Mask.size());
15925 unsigned NumParts = R.getNumberOfParts(MaskVecTy, ScalarTy, Mask.size());
15926 unsigned SliceSize = getPartNumElems(Mask.size(), NumParts);
15927 const auto *It = find_if(Mask, not_equal_to(PoisonMaskElem));
15928 unsigned Part = std::distance(Mask.begin(), It) / SliceSize;
15929 estimateNodesPermuteCost(E1, nullptr, Mask, Part, SliceSize);
15930 if (!SameNodesEstimated && InVectors.size() == 1)
15931 InVectors.emplace_back(&E1);
15932 }
15933 /// Adds 2 input vectors and the mask for their shuffling.
15934 void add(Value *V1, Value *V2, ArrayRef<int> Mask) {
15935 // May come only for shuffling of 2 vectors with extractelements, already
15936 // handled in adjustExtracts.
15937 assert(InVectors.size() == 1 &&
15938 all_of(enumerate(CommonMask),
15939 [&](auto P) {
15940 if (P.value() == PoisonMaskElem)
15941 return Mask[P.index()] == PoisonMaskElem;
15942 auto *EI = cast<ExtractElementInst>(
15943 cast<const TreeEntry *>(InVectors.front().Vec)
15944 ->getOrdered(P.index()));
15945 return EI->getVectorOperand() == V1 ||
15946 EI->getVectorOperand() == V2;
15947 }) &&
15948 "Expected extractelement vectors.");
15949 }
15950 /// Adds another one input vector and the mask for the shuffling.
15951 void
15952 add(Value *V1, ArrayRef<int> Mask, bool ForExtracts = false,
15954 if (BVValues && !isa<Constant>(V1))
15955 BVValues.reset();
15956 if (InVectors.empty()) {
15957 assert(CommonMask.empty() && !ForExtracts &&
15958 "Expected empty input mask/vectors.");
15959 CommonMask.assign(Mask.begin(), Mask.end());
15960 InVectors.assign(1, InVector(V1, ContextHint));
15961 return;
15962 }
15963 if (ForExtracts) {
15964 // No need to add vectors here, already handled them in adjustExtracts.
15965 assert(InVectors.size() == 1 &&
15966 isa<const TreeEntry *>(InVectors[0].Vec) && !CommonMask.empty() &&
15967 all_of(enumerate(CommonMask),
15968 [&](auto P) {
15969 Value *Scalar = cast<const TreeEntry *>(InVectors[0].Vec)
15970 ->getOrdered(P.index());
15971 if (P.value() == PoisonMaskElem)
15972 return P.value() == Mask[P.index()] ||
15973 isa<UndefValue>(Scalar);
15974 if (isa<Constant>(V1))
15975 return true;
15976 auto *EI = cast<ExtractElementInst>(Scalar);
15977 return EI->getVectorOperand() == V1;
15978 }) &&
15979 "Expected only tree entry for extractelement vectors.");
15980 return;
15981 }
15982 assert(!InVectors.empty() && !CommonMask.empty() &&
15983 "Expected only tree entries from extracts/reused buildvectors.");
15984 unsigned VF = getVF(V1);
15985 if (InVectors.size() == 2) {
15986 Cost +=
15987 createShuffle(InVectors.front().Vec, InVectors.back().Vec, CommonMask,
15988 {}, InVectors.front().Ctx, InVectors.back().Ctx);
15989 transformMaskAfterShuffle(CommonMask, CommonMask);
15990 VF = std::max<unsigned>(VF, CommonMask.size());
15991 } else if (const auto *InTE =
15992 dyn_cast<const TreeEntry *>(InVectors.front().Vec)) {
15993 VF = std::max(VF, InTE->getVectorFactor());
15994 } else {
15995 VF = std::max(VF, cast<FixedVectorType>(
15996 cast<Value *>(InVectors.front().Vec)->getType())
15997 ->getNumElements());
15998 }
15999 InVectors.emplace_back(V1, ContextHint);
16000 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
16001 if (Mask[Idx] != PoisonMaskElem && CommonMask[Idx] == PoisonMaskElem)
16002 CommonMask[Idx] = Mask[Idx] + VF;
16003 }
16004 Value *
16005 gather(ArrayRef<Value *> VL, unsigned MaskVF = 0, Value *Root = nullptr,
16007 Cost += getBuildVectorCost(VL, Root, ContextHint);
16008 if (BVValues) {
16009 if (BVValues->empty() && InVectors.empty())
16010 BVValues->assign(VL.begin(), VL.end());
16011 else
16012 BVValues.reset();
16013 }
16014 if (!Root) {
16015 // FIXME: Need to find a way to avoid use of getNullValue here.
16017 unsigned VF = VL.size();
16018 if (MaskVF != 0)
16019 VF = std::min(VF, MaskVF);
16020 Type *VLScalarTy = VL.front()->getType();
16021 for (Value *V : VL.take_front(VF)) {
16022 Type *ScalarTy = VLScalarTy->getScalarType();
16023 if (isa<PoisonValue>(V)) {
16025 continue;
16026 }
16027 if (isa<UndefValue>(V)) {
16029 continue;
16030 }
16032 }
16033 if (auto *VecTy = dyn_cast<FixedVectorType>(VLScalarTy)) {
16034 assert(R.Opts.slp_revec && "FixedVectorType is not expected.");
16035 // When REVEC is enabled, we need to expand vector types into scalar
16036 // types.
16037 Vals = replicateMask(Vals, VecTy->getNumElements());
16038 }
16039 return ConstantVector::get(Vals);
16040 }
16043 cast<FixedVectorType>(Root->getType())->getNumElements()),
16044 getAllOnesValue(*R.DL, ScalarTy->getScalarType()));
16045 }
16046 /// Estimates the cost of the gather of zero-extended sub-fields of width
16047 /// \p FieldWidth of the same wider integer scalar \p Src, byte swapped if
16048 /// \p IsBSwap, permuted by \p Mask, as a bitcast to the field vector plus a
16049 /// permutation and an extension to the lane type.
16051 ArrayRef<int> Mask, bool IsBSwap,
16052 const TreeEntry &E) {
16053 auto *FieldTy = IntegerType::get(Src->getContext(), FieldWidth);
16054 unsigned SrcWidth = Src->getType()->getIntegerBitWidth();
16055 assert(SrcWidth % FieldWidth == 0 &&
16056 "Expected the field width to divide the source width.");
16057 unsigned NumFields = SrcWidth / FieldWidth;
16058 auto *FieldVecTy = cast<VectorType>(getWidenedType(FieldTy, NumFields));
16059 TTI::CastContextHint CCH = R.getCastContextHint(E);
16060 InstructionCost Cost = TTI.getCastInstrCost(
16061 Instruction::BitCast, FieldVecTy, Src->getType(), CCH, CostKind);
16062 if (IsBSwap) {
16063 IntrinsicCostAttributes CostAttrs(Intrinsic::bswap, Src->getType(),
16064 {Src->getType()});
16065 Cost += TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
16066 }
16067 // The permutation is elided only for the full-length identity mask.
16068 if (Mask.size() != NumFields ||
16069 !ShuffleVectorInst::isIdentityMask(Mask, NumFields))
16070 Cost += getShuffleCost(TTI, TTI::SK_PermuteSingleSrc, FieldVecTy,
16071 CostKind, Mask);
16072 if (!ScalarTy->isIntegerTy(FieldWidth))
16073 Cost += TTI.getCastInstrCost(
16074 Instruction::ZExt, getWidenedType(ScalarTy, Mask.size()),
16075 getWidenedType(FieldTy, Mask.size()), CCH, CostKind);
16076 // The extraction instructions and their chains of single-use operands die
16077 // once the fields are emitted from the source scalar; their scalar cost is
16078 // credited back for the gathers directly feeding the reduction.
16079 // Instructions vectorized elsewhere are skipped: their scalar cost is
16080 // already a part of the scalar baseline.
16081 if (R.UserIgnoreList &&
16082 (!E.UserTreeIndex || E.UserTreeIndex.UserTE->Idx == 0)) {
16083 auto GetScalarCost = [&](Instruction *I) {
16084 return isa<CastInst>(I)
16085 ? TTI.getCastInstrCost(I->getOpcode(), I->getType(),
16086 I->getOperand(0)->getType(),
16087 TTI::getCastContextHint(I), CostKind,
16088 I)
16089 : TTI.getArithmeticInstrCost(
16090 I->getOpcode(), I->getType(), CostKind,
16091 TTI::getOperandInfo(I->getOperand(0)),
16092 TTI::getOperandInfo(I->getOperand(1)),
16093 {I->getOperand(0), I->getOperand(1)}, I);
16094 };
16095 for (Instruction *I : make_isa_range<Instruction>(E.Scalars)) {
16096 if (!CheckedExtracts.insert(I).second || R.isVectorized(I) ||
16097 !R.areAllUsersVectorized(I, &VectorizedVals))
16098 continue;
16099 Cost -= GetScalarCost(I);
16100 for (auto *Op = dyn_cast<Instruction>(I->getOperand(0));
16101 Op && Op != Src && isa<BinaryOperator, CastInst>(Op) &&
16102 Op->hasOneUse() && !R.isVectorized(Op) &&
16103 CheckedExtracts.insert(Op).second;
16104 Op = dyn_cast<Instruction>(Op->getOperand(0)))
16105 Cost -= GetScalarCost(Op);
16106 }
16107 }
16108 return Cost;
16109 }
16111 /// Finalize emission of the shuffles.
16113 ArrayRef<int> ExtMask,
16114 ArrayRef<std::pair<const TreeEntry *, unsigned>> SubVectors,
16115 ArrayRef<int> SubVectorsMask, unsigned VF = 0,
16118 Action = {}) {
16119 IsFinalized = true;
16120 if (Action) {
16122 InVectors.front().Vec;
16123 if (InVectors.size() == 2)
16124 Cost += createShuffle(Vec, InVectors.back().Vec, CommonMask, {},
16125 InVectors.front().Ctx, InVectors.back().Ctx);
16126 else
16127 Cost +=
16128 createShuffle(Vec, nullptr, CommonMask, {}, InVectors.front().Ctx);
16129 transformMaskAfterShuffle(CommonMask, CommonMask);
16130 assert(VF > 0 &&
16131 "Expected vector length for the final value before action.");
16132 Value *V = cast<Value *>(Vec);
16133 Action(V, CommonMask, [this](Value *V1, Value *V2, ArrayRef<int> Mask) {
16134 Cost += createShuffle(V1, V2, Mask);
16135 return V1;
16136 });
16137 InVectors.front() = V;
16138 }
16139 if (!SubVectors.empty()) {
16140 const PointerUnion<Value *, const TreeEntry *> &Vec =
16141 InVectors.front().Vec;
16142 if (InVectors.size() == 2)
16143 Cost += createShuffle(Vec, InVectors.back().Vec, CommonMask, {},
16144 InVectors.front().Ctx, InVectors.back().Ctx);
16145 else
16146 Cost +=
16147 createShuffle(Vec, nullptr, CommonMask, {}, InVectors.front().Ctx);
16148 transformMaskAfterShuffle(CommonMask, CommonMask);
16149 // Add subvectors permutation cost.
16150 if (!SubVectorsMask.empty()) {
16151 assert(SubVectorsMask.size() <= CommonMask.size() &&
16152 "Expected same size of masks for subvectors and common mask.");
16153 SmallVector<int> SVMask(CommonMask.size(), PoisonMaskElem);
16154 copy(SubVectorsMask, SVMask.begin());
16155 for (auto [I1, I2] : zip(SVMask, CommonMask)) {
16156 if (I2 != PoisonMaskElem) {
16157 assert(I1 == PoisonMaskElem && "Expected unused subvectors mask");
16158 I1 = I2 + CommonMask.size();
16159 }
16160 }
16163 cast<VectorType>(getWidenedType(ScalarTy, CommonMask.size())),
16164 CostKind, SVMask);
16165 }
16166 for (auto [E, Idx] : SubVectors) {
16167 Type *EScalarTy = E->Scalars.front()->getType();
16168 bool IsSigned = true;
16169 if (auto It = R.MinBWs.find(E); It != R.MinBWs.end()) {
16170 EScalarTy =
16171 IntegerType::get(EScalarTy->getContext(), It->second.first);
16172 IsSigned = It->second.second;
16173 }
16174 if (ScalarTy != EScalarTy) {
16175 unsigned CastOpcode = Instruction::Trunc;
16176 unsigned DstSz = R.DL->getTypeSizeInBits(ScalarTy);
16177 unsigned SrcSz = R.DL->getTypeSizeInBits(EScalarTy);
16178 if (DstSz > SrcSz)
16179 CastOpcode = IsSigned ? Instruction::SExt : Instruction::ZExt;
16180 Cost += TTI.getCastInstrCost(
16181 CastOpcode, getWidenedType(ScalarTy, E->getVectorFactor()),
16182 getWidenedType(EScalarTy, E->getVectorFactor()),
16184 }
16187 cast<VectorType>(getWidenedType(ScalarTy, CommonMask.size())),
16188 CostKind, {}, Idx,
16189 cast<VectorType>(getWidenedType(ScalarTy, E->getVectorFactor())));
16190 if (!CommonMask.empty()) {
16191 std::iota(std::next(CommonMask.begin(), Idx),
16192 std::next(CommonMask.begin(), Idx + E->getVectorFactor()),
16193 Idx);
16194 }
16195 }
16196 }
16197
16198 if (!ExtMask.empty()) {
16199 if (CommonMask.empty()) {
16200 CommonMask.assign(ExtMask.begin(), ExtMask.end());
16201 } else {
16202 SmallVector<int> NewMask(ExtMask.size(), PoisonMaskElem);
16203 for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
16204 if (ExtMask[I] == PoisonMaskElem)
16205 continue;
16206 NewMask[I] = CommonMask[ExtMask[I]];
16207 }
16208 CommonMask.swap(NewMask);
16209 }
16210 }
16211 if (CommonMask.empty()) {
16212 assert(InVectors.size() == 1 && "Expected only one vector with no mask");
16213 return Cost;
16214 }
16216 if (BVValues)
16217 VL = *BVValues;
16218 if (InVectors.size() == 2)
16219 return Cost + createShuffle(InVectors.front().Vec, InVectors.back().Vec,
16220 CommonMask, VL, InVectors.front().Ctx,
16221 InVectors.back().Ctx);
16222 return Cost + createShuffle(InVectors.front().Vec, nullptr, CommonMask, VL,
16223 InVectors.front().Ctx);
16224 }
16225
16227 assert((IsFinalized || CommonMask.empty()) &&
16228 "Shuffle construction must be finalized.");
16229 }
16230};
16231
16232const BoUpSLP::TreeEntry *BoUpSLP::getOperandEntry(const TreeEntry *E,
16233 unsigned Idx) const {
16234 TreeEntry *Op = OperandsToTreeEntry.at({E, Idx});
16235 assert(Op->isSame(E->getOperand(Idx)) && "Operands mismatch!");
16236 return Op;
16237}
16238
16240 if (TE.State == TreeEntry::ScatterVectorize ||
16241 TE.State == TreeEntry::StridedVectorize)
16243 if (TE.State == TreeEntry::CompressVectorize ||
16244 TE.State == TreeEntry::BlendedLoadVectorize)
16246 if (TE.State == TreeEntry::Vectorize && TE.getOpcode() == Instruction::Load &&
16247 !TE.isAltShuffle()) {
16248 if (TE.ReorderIndices.empty())
16250 SmallVector<int> Mask;
16251 inversePermutation(TE.ReorderIndices, Mask);
16252 if (ShuffleVectorInst::isReverseMask(Mask, Mask.size()))
16254 }
16255 // A gather of extracted sub-fields inherits the context of the entry
16256 // vectorizing the common source scalar, or of the source scalar load. The
16257 // scalars erased by the vectorization have no operands to match.
16258 if (TE.isGather() && none_of(make_isa_range<Instruction>(TE.Scalars),
16259 [&](Instruction *I) { return isDeleted(I); }))
16260 if (std::optional<std::tuple<Value *, unsigned, SmallVector<int>>> Fields =
16261 matchGatheredExtractedFields(TE.Scalars, *DL)) {
16262 Value *Src = std::get<0>(*Fields);
16263 if (ArrayRef<TreeEntry *> TEs = getTreeEntries(Src); !TEs.empty())
16264 return getCastContextHint(*TEs.front());
16265 if (isa<LoadInst>(Src))
16267 }
16269}
16270
16271uint64_t BoUpSLP::getScaleToLoopIterations(const TreeEntry &TE, Value *Scalar,
16272 Instruction *U) {
16273 BasicBlock *Parent = nullptr;
16274 if (U) {
16275 // The extractelement for a PHI-node user is created in the incoming
16276 // block that feeds the matching operand, not in the PHI block itself
16277 // When the PHI is inside a loop that incoming block can belong to a deeper
16278 // loop than the PHI block. Scaling by the PHI block would use
16279 // the outer trip count instead of inner*outer, and because
16280 // ExtractCostCalculated deduplicates by scalar (only the first external
16281 // user fixes the scale) it would also make the cost depend on external-user
16282 // ordering. A PHI outside all loops is a plain loop-exit phi: its live-out
16283 // lanes are normally rebuilt as a vector LCSSA phi in the exit block, which
16284 // hoists the extract out of the loop, so scale = 1 (via U->getParent()
16285 // below) is kept and the adjustment is restricted to in-loop PHIs.
16286 if (auto *PHI = dyn_cast<PHINode>(U); PHI && Scalar) {
16287 if (LI->getLoopFor(PHI->getParent())) {
16288 // Use the deepest incoming block among all slots where Scalar
16289 // appears, to be conservative when the same value appears in
16290 // multiple predecessors.
16291 for (unsigned I : seq<unsigned>(PHI->getNumIncomingValues())) {
16292 if (PHI->getIncomingValue(I) != Scalar)
16293 continue;
16294 BasicBlock *InBB = PHI->getIncomingBlock(I);
16295 if (!Parent || LI->getLoopDepth(InBB) > LI->getLoopDepth(Parent))
16296 Parent = InBB;
16297 }
16298 }
16299 }
16300 if (!Parent)
16301 Parent = U->getParent();
16302 } else if (TE.isGather() || TE.State == TreeEntry::SplitVectorize) {
16303 EdgeInfo EI = TE.UserTreeIndex;
16304 while (EI.UserTE) {
16305 if (EI.UserTE->isGather() ||
16306 EI.UserTE->State == TreeEntry::SplitVectorize) {
16307 EI = EI.UserTE->UserTreeIndex;
16308 continue;
16309 }
16310 if (EI.UserTE->State == TreeEntry::Vectorize &&
16311 EI.UserTE->getOpcode() == Instruction::PHI) {
16312 auto *PH = cast<PHINode>(EI.UserTE->getMainOp());
16313 Parent = PH->getIncomingBlock(EI.EdgeIdx);
16314 const Loop *PhiL = LI->getLoopFor(PH->getParent());
16315 const Loop *InL = LI->getLoopFor(Parent);
16316 if (PhiL && InL && !PhiL->contains(InL) && !InL->contains(PhiL)) {
16317 const SCEV *PhiBTC = SE->getBackedgeTakenCount(PhiL);
16318 const SCEV *InBTC = SE->getBackedgeTakenCount(InL);
16319 if (isa<SCEVCouldNotCompute>(PhiBTC) || PhiBTC != InBTC) {
16320 // If all gathered elements are invariant in the phi's nest below
16321 // the common ancestor of the two nests, the gather is a pure
16322 // nest-crossing transfer, paid once per crossing: scale it by
16323 // the common parent nest.
16324 const Loop *FirstVariantL =
16325 findInnermostNonInvariantLoop(PhiL, TE.Scalars);
16326 if (FirstVariantL && FirstVariantL->contains(InL))
16327 Parent = FirstVariantL->getHeader();
16328 }
16329 }
16330 } else {
16331 Parent = EI.UserTE->getMainOp()->getParent();
16332 }
16333 break;
16334 }
16335 if (!Parent)
16336 return 1;
16337 } else {
16338 Parent = TE.getMainOp()->getParent();
16339 }
16340 const Loop *L = LI->getLoopFor(Parent);
16341 if (!L)
16342 return 1;
16343 // The entry's cost is paid once per execution of the innermost loop in
16344 // which some of its operands are variant. Operands that are invariant in
16345 // all enclosing loops are executed once (LICM will hoist them out).
16346 return getLoopNestScale(findInnermostNonInvariantLoop(
16347 L, Scalar ? ArrayRef(Scalar) : ArrayRef(TE.Scalars)));
16348}
16349
16350uint64_t BoUpSLP::getLoopNestScale(const Loop *L) {
16351 if (!L || Opts.slp_cost_loop_trip_count == 0)
16352 return 1;
16353 if (auto It = LoopNestScaleCache.find(L); It != LoopNestScaleCache.end())
16354 return It->second;
16355 // Collect loops from L outward up to (but not including) the first cached
16356 // ancestor or the function top, then walk back inward multiplying trip
16357 // counts. Use uint64_t to avoid silent overflow on deep/large nests.
16358 SmallVector<const Loop *> Chain;
16359 for (const Loop *Cur = L; Cur; Cur = Cur->getParentLoop()) {
16360 if (LoopNestScaleCache.contains(Cur))
16361 break;
16362 Chain.push_back(Cur);
16363 }
16364 assert(!Chain.empty() && "Early-return above should have handled cache hit.");
16365 uint64_t Scale = 1;
16366 if (const Loop *Parent = Chain.back()->getParentLoop())
16367 Scale = LoopNestScaleCache.lookup(Parent);
16368 // Walk from the outermost uncached loop inward, accumulating trip counts.
16369 // Use SaturatingMultiply to clamp at uint64_t max on deep/large nests
16370 // rather than wrapping around.
16371 for (const Loop *Cur : reverse(Chain)) {
16372 uint64_t TC = std::max<uint64_t>(
16373 1, getLoopTripCount(Cur, *SE, Opts.slp_cost_loop_trip_count));
16374 Scale = SaturatingMultiply(Scale, TC);
16375 LoopNestScaleCache.try_emplace(Cur, std::max<uint64_t>(1, Scale));
16376 }
16377 return std::max<uint64_t>(1, Scale);
16378}
16379
16380uint64_t BoUpSLP::getGatherNodeEffectiveScale(const TreeEntry &TE,
16381 Instruction *U) {
16382 // Only meaningful for gather/buildvector-like entries; the per-lane
16383 // insertelements that make up such an entry are LICM-hoistable by
16384 // optimizeGatherSequence() when their operand is loop-invariant.
16385 assert((TE.isGather() || TE.State == TreeEntry::SplitVectorize) &&
16386 "Expected gather/split tree entry.");
16387
16388 uint64_t BaseScale = getScaleToLoopIterations(TE, nullptr, U);
16389 if (!Opts.slp_per_lane_gather_scale || Opts.slp_cost_loop_trip_count == 0 ||
16390 BaseScale <= 1)
16391 return BaseScale;
16392
16393 // Average the per-lane execution scales: for each lane, reuse the same
16394 // scale helper the rest of the cost model uses, but ask it about that
16395 // one lane's value. Lanes that are loop-invariant in the current nest
16396 // collapse to their outer-loop scale (or 1 for fully invariant/constant
16397 // lanes), which matches the LICM hoisting performed by
16398 // optimizeGatherSequence(). Cap per-lane contributions by BaseScale so a
16399 // refinement can never raise the cost above the whole-entry scale.
16400 // Each lane contributes at most BaseScale, so Sum is bounded above by
16401 // N * BaseScale. If BaseScale is near uint64_t max (saturated by
16402 // getLoopNestScale on a deep nest) Sum can still overflow uint64_t,
16403 // which would silently wrap and produce a wrong average. Use
16404 // SaturatingAdd and bail out to BaseScale on overflow: the true average
16405 // is bounded above by BaseScale anyway, so this preserves the
16406 // refinement's invariant that it can never raise cost.
16407 uint64_t Sum = 0;
16408 unsigned N = 0;
16409 bool Overflow = false;
16410 for (Value *V :
16411 make_filter_range(TE.Scalars, [](Value *V) { return !isConstant(V); })) {
16412 ++N;
16413 uint64_t LaneScale =
16414 std::min(getScaleToLoopIterations(TE, V, U), BaseScale);
16415 Sum = SaturatingAdd(Sum, LaneScale, &Overflow);
16416 if (Overflow)
16417 return BaseScale;
16418 }
16419 if (N == 0)
16420 return BaseScale;
16421 // Ceil-divide so we never round the effective scale down below 1.
16422 uint64_t Numerator = SaturatingAdd(Sum, uint64_t(N - 1), &Overflow);
16423 if (Overflow)
16424 return BaseScale;
16425 uint64_t Avg = Numerator / N;
16426 return std::clamp<uint64_t>(Avg, 1, BaseScale);
16427}
16428
16429uint64_t BoUpSLP::getEntryEffectiveScale(const TreeEntry &TE, Instruction *U) {
16430 if (TE.isGather() || TE.State == TreeEntry::SplitVectorize)
16431 return getGatherNodeEffectiveScale(TE, U);
16432 return getScaleToLoopIterations(TE);
16433}
16434
16436BoUpSLP::getVectorSpillReloadCost(const TreeEntry *E, Type *ScalarTy,
16437 Type *VecTy, Type *FinalVecTy,
16438 const TTI::TargetCostKind CostKind) const {
16439 InstructionCost SpillsReloads = 0;
16440
16441 // Estimate vector register pressure per target register class: operand
16442 // vectors plus the result. The same vector operand is counted once via
16443 // CountedOpEntries deduplication. PHIs take the max operand pressure across
16444 // incoming slots (only one predecessor is live at a time) plus the result.
16445 // All-constant operand bundles are skipped.
16446 if (!E->hasState() || E->getOpcode() == Instruction::Store ||
16447 E->getOpcode() == Instruction::ExtractElement ||
16448 E->getOpcode() == Instruction::ExtractValue ||
16449 E->getOpcode() == Instruction::Freeze ||
16450 (E->getOpcode() == Instruction::Load &&
16451 E->State != TreeEntry::ScatterVectorize))
16452 return SpillsReloads;
16453
16454 const bool IsPHI =
16455 E->State == TreeEntry::Vectorize && E->getOpcode() == Instruction::PHI;
16456 SmallPtrSet<const TreeEntry *, 8> CountedOpEntries;
16457 SmallDenseMap<unsigned, unsigned> PressureByClass;
16458 auto AddPartsToClass = [&](unsigned RegClass, unsigned Parts) {
16459 assert(Parts != 0 && "Expected non-zero number of parts (registers).");
16460 PressureByClass[RegClass] += Parts;
16461 };
16462
16463 auto GetEntryVecTy = [&](const TreeEntry *TE) -> std::pair<Type *, Type *> {
16464 Type *ScalarTy = getValueType(TE->Scalars.front(), Opts.slp_revec);
16465 auto BWIt = MinBWs.find(TE);
16466 if (BWIt != MinBWs.end()) {
16467 auto *VTy = dyn_cast<FixedVectorType>(ScalarTy);
16468 ScalarTy = IntegerType::get(F->getContext(), BWIt->second.first);
16469 if (VTy)
16470 ScalarTy = getWidenedType(ScalarTy, VTy->getNumElements());
16471 }
16472 return std::make_pair(ScalarTy,
16473 getWidenedType(ScalarTy, TE->getVectorFactor()));
16474 };
16475
16476 if (E->State == TreeEntry::SplitVectorize) {
16477 for (const auto &[Idx, _] : E->CombinedEntriesWithIndices) {
16478 const TreeEntry *OpTE = VectorizableTree[Idx].get();
16479
16480 if (!CountedOpEntries.insert(OpTE).second)
16481 continue;
16482 auto [ScalarTy, OpVecTy] = GetEntryVecTy(OpTE);
16483 const unsigned Parts = getNumberOfParts(OpVecTy, ScalarTy);
16484 if (Parts == 0)
16485 continue;
16486 const unsigned RC =
16487 TTI->getRegisterClassForType(/*Vector=*/true, OpVecTy);
16488 AddPartsToClass(RC, Parts);
16489 }
16490 } else if (IsPHI) {
16491 // Only one predecessor is live at a time - take the max operand pressure
16492 // across incoming slots.
16493 SmallDenseMap<unsigned, unsigned> MaxOpPressureByClass;
16494 for (unsigned Idx : seq<unsigned>(E->getNumOperands())) {
16495 const TreeEntry *OpTE = getOperandEntry(E, Idx);
16496 auto [ScalarTy, OpVecTy] = GetEntryVecTy(OpTE);
16497 const unsigned Parts = getNumberOfParts(OpVecTy, ScalarTy);
16498 if (Parts == 0)
16499 continue;
16500 const unsigned RC =
16501 TTI->getRegisterClassForType(/*Vector=*/true, OpVecTy);
16502 MaxOpPressureByClass[RC] = std::max(MaxOpPressureByClass[RC], Parts);
16503 }
16504 for (auto [RC, Parts] : MaxOpPressureByClass)
16505 AddPartsToClass(RC, Parts);
16506 } else {
16507 for (unsigned Idx : seq<unsigned>(E->getNumOperands())) {
16508 // InsertElement operand 0 is the vector being inserted into, which is
16509 // built incrementally and does not occupy an extra register.
16510 if ((E->getOpcode() == Instruction::InsertElement ||
16511 E->getOpcode() == Instruction::InsertValue) &&
16512 Idx == 0)
16513 continue;
16514 ArrayRef<Value *> Ops = E->getOperand(Idx);
16515 if (Ops.empty() || allConstant(Ops) || isSplat(Ops))
16516 continue;
16517 Value *Op = Ops.front();
16518 if (!Op)
16519 continue;
16520 const TreeEntry *OpTE = getOperandEntry(E, Idx);
16521
16522 if (!CountedOpEntries.insert(OpTE).second)
16523 continue;
16524 auto *OpVecTy = getWidenedType(Op->getType(), Ops.size());
16525 const unsigned Parts = getNumberOfParts(OpVecTy, Op->getType());
16526 if (Parts == 0)
16527 continue;
16528 const unsigned RC =
16529 TTI->getRegisterClassForType(/*Vector=*/true, OpVecTy);
16530 AddPartsToClass(RC, Parts);
16531 }
16532 }
16533
16534 if (E->getOpcode() != Instruction::Load) {
16535 const unsigned ResParts = getNumberOfParts(VecTy, ScalarTy);
16536 if (ResParts != 0) {
16537 const unsigned RC = TTI->getRegisterClassForType(/*Vector=*/true, VecTy);
16538 AddPartsToClass(RC, ResParts);
16539 }
16540 if (VecTy != FinalVecTy) {
16541 const unsigned FinalResParts = getNumberOfParts(FinalVecTy, ScalarTy);
16542 if (FinalResParts != 0) {
16543 const unsigned RC =
16544 TTI->getRegisterClassForType(/*Vector=*/true, FinalVecTy);
16545 AddPartsToClass(RC, FinalResParts);
16546 }
16547 }
16548 }
16549
16550 for (auto [RegClass, UsedRegs] : PressureByClass) {
16551 const unsigned NumAvailRegs = TTI->getNumberOfRegisters(RegClass);
16552 if (NumAvailRegs == 0 || UsedRegs <= NumAvailRegs)
16553 continue;
16554 const unsigned SpillCount = UsedRegs - NumAvailRegs;
16555 InstructionCost SingleRegSpillReload =
16556 TTI->getRegisterClassReloadCost(RegClass, CostKind);
16557 // No need to spill cost only for the root entry (Idx == 0), for reduction
16558 // and non-returning instructions, like void calls.
16559 if (E->Idx > 0 || !UserIgnoreList || !E->Scalars[0]->getType()->isVoidTy())
16560 SingleRegSpillReload +=
16561 TTI->getRegisterClassSpillCost(RegClass, CostKind);
16562 SpillsReloads += SingleRegSpillReload * SpillCount;
16563 }
16564 return SpillsReloads;
16565}
16566
16567/// \returns the cast opcode, which gives the same result for the operand,
16568/// demoted with the signedness \p IsSigned, as \p Opcode gives for the original
16569/// operand, or std::nullopt if the operand must be extended back first.
16570static std::optional<unsigned> getCastOpcodeForDemotedOperand(unsigned Opcode,
16571 bool IsSigned) {
16572 switch (Opcode) {
16573 case Instruction::SExt:
16574 case Instruction::SIToFP:
16575 // The zero extended operand is non-negative.
16576 if (IsSigned)
16577 return Opcode;
16578 return Opcode == Instruction::SExt ? Instruction::ZExt
16579 : Instruction::UIToFP;
16580 case Instruction::ZExt:
16581 case Instruction::UIToFP:
16582 // Cannot absorb the sign extension of the operand.
16583 if (IsSigned)
16584 return std::nullopt;
16585 return Opcode;
16586 default:
16587 return std::nullopt;
16588 }
16589}
16590
16592BoUpSLP::getEntryCost(const TreeEntry *E, ArrayRef<Value *> VectorizedVals,
16593 SmallPtrSetImpl<Value *> &CheckedExtracts) {
16594 ArrayRef<Value *> VL = E->Scalars;
16595
16596 Type *ScalarTy = getValueType(VL[0], Opts.slp_revec);
16597 if (Opts.slp_revec && E->State == TreeEntry::Vectorize &&
16598 E->getOpcode() == Instruction::InsertElement &&
16599 !E->getOperand(1).back()->getType()->isVectorTy())
16600 ScalarTy = ScalarTy->getScalarType();
16601 if (!isValidElementType(ScalarTy, Opts.slp_revec))
16603
16604 // If we have computed a smaller type for the expression, update VecTy so
16605 // that the costs will be accurate.
16606 auto It = MinBWs.find(E);
16607 Type *OrigScalarTy = ScalarTy;
16608 if (It != MinBWs.end()) {
16609 auto *VecTy = dyn_cast<FixedVectorType>(ScalarTy);
16610 ScalarTy = IntegerType::get(F->getContext(), It->second.first);
16611 if (VecTy)
16612 ScalarTy = getWidenedType(ScalarTy, VecTy->getNumElements());
16613 } else if (E->Idx == 0 && isReducedBitcastRoot() &&
16614 getRootNode().CombinedOp != TreeEntry::ReducedBitPack) {
16615 const TreeEntry *ZExt = getOperandEntry(E, /*Idx=*/0);
16616 ScalarTy = cast<CastInst>(ZExt->getMainOp())->getSrcTy();
16617 }
16618 auto *VecTy = getWidenedType(ScalarTy, VL.size());
16619 unsigned EntryVF = E->getVectorFactor();
16620 auto *FinalVecTy = getWidenedType(ScalarTy, EntryVF);
16621
16622 const InstructionCost SpillsReloads =
16623 getVectorSpillReloadCost(E, ScalarTy, VecTy, FinalVecTy, CostKind);
16624 if (E->isGather() || TransformedToGatherNodes.contains(E)) {
16625 if (allConstant(VL))
16626 return 0;
16629 // The fmuls of the node turned into a gather stay scalar and lose the
16630 // fusion with their vectorized fadd/fsub users.
16631 return SpillsReloads +
16632 processBuildVector<ShuffleCostEstimator, InstructionCost>(
16633 E, ScalarTy, *TTI, VectorizedVals, *this, CheckedExtracts) +
16634 getUnfusedFMulsPenalty(*E);
16635 }
16636 if (E->State == TreeEntry::SplitVectorize) {
16637 assert(E->CombinedEntriesWithIndices.size() == 2 &&
16638 "Expected exactly 2 combined entries.");
16639 assert(E->ReuseShuffleIndices.empty() && "Expected empty reuses mask.");
16640 InstructionCost VectorCost = 0;
16641 if (E->ReorderIndices.empty()) {
16642 VectorCost = getShuffleCost(
16643 *TTI, TTI::SK_InsertSubvector, cast<VectorType>(FinalVecTy), CostKind,
16644 {}, E->CombinedEntriesWithIndices.back().second,
16646 ScalarTy,
16647 VectorizableTree[E->CombinedEntriesWithIndices.back().first]
16648 ->getVectorFactor())));
16649 } else {
16650 unsigned CommonVF =
16651 std::max(VectorizableTree[E->CombinedEntriesWithIndices.front().first]
16652 ->getVectorFactor(),
16653 VectorizableTree[E->CombinedEntriesWithIndices.back().first]
16654 ->getVectorFactor());
16655 VectorCost =
16657 cast<VectorType>(getWidenedType(ScalarTy, CommonVF)),
16658 CostKind, E->getSplitMask());
16659 }
16660 VectorCost += SpillsReloads;
16661 LLVM_DEBUG(dumpTreeCosts(E, 0, VectorCost, 0, "Calculated costs for Tree"));
16662 return VectorCost;
16663 }
16664 InstructionCost CommonCost = 0;
16665 SmallVector<int> Mask;
16666 if (!E->ReorderIndices.empty() && E->State != TreeEntry::CompressVectorize &&
16667 (E->State != TreeEntry::StridedVectorize || !E->isReverse() ||
16669 SmallVector<int> NewMask;
16670 if (E->getOpcode() == Instruction::Store) {
16671 // For stores the order is actually a mask.
16672 NewMask.resize(E->ReorderIndices.size());
16673 copy(E->ReorderIndices, NewMask.begin());
16674 } else {
16675 inversePermutation(E->ReorderIndices, NewMask);
16676 }
16677 addMask(Mask, NewMask);
16678 }
16679 if (!E->ReuseShuffleIndices.empty())
16680 addMask(Mask, E->ReuseShuffleIndices);
16681 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask, Mask.size())) {
16682 assert(!isa<StructType>(FinalVecTy) &&
16683 "Expected non-struct vector type for shuffle cost calculation.");
16684 CommonCost = getShuffleCost(*TTI, TTI::SK_PermuteSingleSrc,
16685 cast<VectorType>(FinalVecTy), CostKind, Mask,
16686 /*Index=*/0, cast<VectorType>(VecTy));
16687 }
16688 assert((E->State == TreeEntry::Vectorize ||
16689 E->State == TreeEntry::ScatterVectorize ||
16690 E->State == TreeEntry::StridedVectorize ||
16691 E->State == TreeEntry::ExpandVectorize ||
16692 E->State == TreeEntry::CompressVectorize ||
16693 E->State == TreeEntry::BlendedLoadVectorize) &&
16694 "Unhandled state");
16695 assert(E->getOpcode() &&
16696 ((allSameType(VL) && allSameBlock(VL)) ||
16697 (E->getOpcode() == Instruction::GetElementPtr &&
16698 E->getMainOp()->getType()->isPointerTy()) ||
16699 E->hasCopyableElements()) &&
16700 "Invalid VL");
16701 Instruction *VL0 = E->getMainOp();
16702 unsigned ShuffleOrOp =
16703 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
16704 if (E->CombinedOp != TreeEntry::NotCombinedOp)
16705 ShuffleOrOp = E->CombinedOp;
16706 SmallSetVector<Value *, 16> UniqueValues;
16707 SmallVector<unsigned, 16> UniqueIndexes;
16708 for (auto [Idx, V] : enumerate(VL))
16709 if (UniqueValues.insert(V))
16710 UniqueIndexes.push_back(Idx);
16711 const unsigned Sz = UniqueValues.size();
16712 SmallBitVector UsedScalars(Sz, false);
16713 for (unsigned I = 0; I < Sz; ++I) {
16714 if (isa<Instruction>(UniqueValues[I]) &&
16715 !E->isCopyableElement(UniqueValues[I]) &&
16716 getTreeEntries(UniqueValues[I]).front() == E)
16717 continue;
16718 UsedScalars.set(I);
16719 }
16720 auto GetCastContextHint = [&](Value *V) {
16721 if (ArrayRef<TreeEntry *> OpTEs = getTreeEntries(V); OpTEs.size() == 1)
16722 return getCastContextHint(*OpTEs.front());
16723 InstructionsState SrcState = getSameOpcode(E->getOperand(0), *TLI);
16724 if (SrcState && SrcState.getOpcode() == Instruction::Load &&
16725 !SrcState.isAltShuffle())
16728 };
16729 auto GetCostDiff =
16730 [=](function_ref<InstructionCost(unsigned)> ScalarEltCost,
16731 function_ref<InstructionCost(InstructionCost)> VectorCost) {
16732 // Calculate the cost of this instruction.
16733 InstructionCost ScalarCost = 0;
16734 if (isa<CastInst, CallInst>(VL0)) {
16735 // For some of the instructions no need to calculate cost for each
16736 // particular instruction, we can use the cost of the single
16737 // instruction x total number of scalar instructions.
16738 ScalarCost = (Sz - UsedScalars.count()) * ScalarEltCost(0);
16739 } else {
16740 for (unsigned I = 0; I < Sz; ++I) {
16741 if (UsedScalars.test(I))
16742 continue;
16743 ScalarCost += ScalarEltCost(I);
16744 }
16745 }
16746
16747 InstructionCost VecCost = VectorCost(CommonCost);
16748 // Check if the current node must be resized, if the parent node is not
16749 // resized. Nodes without a parent (roots of the splat gather
16750 // subtrees) are resized back to their original type when the reusing
16751 // gather nodes are emitted.
16752 if (It != MinBWs.end() && !UnaryInstruction::isCast(E->getOpcode()) &&
16753 E->Idx != 0 &&
16754 (E->getOpcode() != Instruction::Load || E->UserTreeIndex)) {
16755 const EdgeInfo &EI = E->UserTreeIndex;
16756 if (!EI.UserTE || !EI.UserTE->hasState() ||
16757 EI.UserTE->getOpcode() != Instruction::Select ||
16758 EI.EdgeIdx != 0) {
16759 auto UserBWIt = MinBWs.find(EI.UserTE);
16760 Type *UserScalarTy =
16761 !EI.UserTE ? OrigScalarTy
16762 : (EI.UserTE->isGather() ||
16763 EI.UserTE->State == TreeEntry::SplitVectorize)
16764 ? EI.UserTE->Scalars.front()->getType()
16765 : EI.UserTE->getOperand(EI.EdgeIdx).front()->getType();
16766 if (UserBWIt != MinBWs.end())
16767 UserScalarTy = IntegerType::get(ScalarTy->getContext(),
16768 UserBWIt->second.first);
16769 if (ScalarTy != UserScalarTy) {
16770 unsigned BWSz = DL->getTypeSizeInBits(ScalarTy);
16771 unsigned SrcBWSz = DL->getTypeSizeInBits(UserScalarTy);
16772 unsigned VecOpcode;
16773 auto *UserVecTy = getWidenedType(UserScalarTy, E->Scalars.size());
16774 if (BWSz > SrcBWSz)
16775 VecOpcode = Instruction::Trunc;
16776 else
16777 VecOpcode =
16778 It->second.second ? Instruction::SExt : Instruction::ZExt;
16779 TTI::CastContextHint CCH = GetCastContextHint(VL0);
16780 VecCost += TTI->getCastInstrCost(VecOpcode, UserVecTy, VecTy, CCH,
16781 CostKind);
16782 }
16783 }
16784 }
16785 VecCost += SpillsReloads;
16786 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost - CommonCost,
16787 ScalarCost, "Calculated costs for Tree"));
16788 return VecCost - ScalarCost;
16789 };
16790 // Price peeled intermediate instructions on the scalar side: they are
16791 // erased when the node vectorizes. The peeled cost is folded into the
16792 // first scalar-cost query so the cost dump reports the full scalar cost.
16793 // Peeled chain links are always 2-operand associative binops, priced per
16794 // instruction so the operand properties (constants, uniformity) apply.
16795 auto GetCostDiffWithPeeled =
16796 [&](function_ref<InstructionCost(unsigned)> ScalarEltCost,
16797 function_ref<InstructionCost(InstructionCost)> VectorCost) {
16798 InstructionCost PeeledScalarCost = 0;
16799 for (Value *V : E->getReassocScalars()) {
16800 auto *I = cast<Instruction>(V);
16801 TTI::OperandValueInfo Op1Info = TTI::getOperandInfo(I->getOperand(0));
16802 TTI::OperandValueInfo Op2Info = TTI::getOperandInfo(I->getOperand(1));
16803 PeeledScalarCost += TTI->getArithmeticInstrCost(
16804 I->getOpcode(), OrigScalarTy, CostKind, Op1Info, Op2Info, {}, I);
16805 }
16806 bool PeeledCostAdded = false;
16807 InstructionCost CostDiff = GetCostDiff(
16808 [&](unsigned Idx) {
16809 InstructionCost Cost = ScalarEltCost(Idx);
16810 if (!PeeledCostAdded) {
16811 PeeledCostAdded = true;
16812 Cost += PeeledScalarCost;
16813 }
16814 return Cost;
16815 },
16816 VectorCost);
16817 // Every scalar may be marked as used elsewhere, leaving the
16818 // scalar-cost query uncalled and the peeled cost unapplied.
16819 if (!PeeledCostAdded)
16820 CostDiff -= PeeledScalarCost;
16821 return CostDiff;
16822 };
16823 // Calculate cost difference from vectorizing set of GEPs.
16824 // Negative value means vectorizing is profitable.
16825 auto GetGEPCostDiff = [=](ArrayRef<Value *> Ptrs, Value *BasePtr) {
16826 assert((E->State == TreeEntry::Vectorize ||
16827 E->State == TreeEntry::StridedVectorize ||
16828 E->State == TreeEntry::ExpandVectorize ||
16829 E->State == TreeEntry::CompressVectorize) &&
16830 "Entry state expected to be Vectorize, StridedVectorize, "
16831 "ExpandVectorize or CompressVectorize here.");
16832 InstructionCost ScalarCost = 0;
16833 InstructionCost VecCost = 0;
16834 std::tie(ScalarCost, VecCost) =
16835 getGEPCosts(*TTI, Ptrs, BasePtr, E->getOpcode(), CostKind, OrigScalarTy,
16836 cast<VectorType>(VecTy));
16837 LLVM_DEBUG(dumpTreeCosts(E, 0, VecCost, ScalarCost,
16838 "Calculated GEPs cost for Tree"));
16839
16840 return VecCost - ScalarCost + SpillsReloads;
16841 };
16842
16843 auto GetMinMaxCost = [&](Type *Ty, Instruction *VI = nullptr) {
16844 auto [MinMaxID, SelectOnly] = canConvertToMinOrMaxIntrinsic(VI ? VI : VL);
16845 if (MinMaxID == Intrinsic::not_intrinsic)
16847 Type *CanonicalType = Ty;
16848 if (CanonicalType->isPtrOrPtrVectorTy())
16849 CanonicalType = CanonicalType->getWithNewType(IntegerType::get(
16850 CanonicalType->getContext(),
16851 DL->getTypeSizeInBits(CanonicalType->getScalarType())));
16852
16853 IntrinsicCostAttributes CostAttrs(MinMaxID, CanonicalType,
16854 {CanonicalType, CanonicalType});
16856 TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
16857 // If the selects are the only uses of the compares, they will be
16858 // dead and we can adjust the cost by removing their cost.
16859 if (VI && SelectOnly) {
16860 assert((!Ty->isVectorTy() || Opts.slp_revec) &&
16861 "Expected only for scalar type.");
16862 auto *CI = cast<CmpInst>(VI->getOperand(0));
16863 IntrinsicCost -= TTI->getCmpSelInstrCost(
16864 CI->getOpcode(), Ty, Builder.getInt1Ty(), CI->getPredicate(),
16865 CostKind, TTI::getOperandInfo(CI->getOperand(0)),
16866 TTI::getOperandInfo(CI->getOperand(1)), CI);
16867 }
16868 return IntrinsicCost;
16869 };
16870 // The fadd/fsub, fused with its fmul operand into an fmuladd in the scalar
16871 // code. If the fmul is not vectorized, the vector code still emits it, so
16872 // only the fusion delta is attributed to the fadd/fsub.
16873 auto GetFMulAddCost = [&, &TTI = *TTI](const InstructionsState &S,
16874 Instruction *VI) {
16875 InstructionCost Cost = canConvertToFMA(VI, S, *DT, *DL, TTI, *TLI, *this);
16877 if (!Cost.isValid() || !FMul || isVectorized(FMul))
16878 return Cost;
16879 InstructionCost FMulCost = getUnfusedBinOpCost(FMul, TTI, *TLI, CostKind);
16880 return Cost > FMulCost ? Cost - FMulCost : InstructionCost(TTI::TCC_Free);
16881 };
16882 // The fmul, fused into its fadd/fsub user, is free if the user lane is
16883 // priced as fmuladd, otherwise the user stays scalar and only the fusion
16884 // delta is attributed to the fmul.
16885 auto GetFusedFMulCost = [&, &TTI = *TTI](Instruction *VI) {
16886 auto [U, FMACost] = getFMulFusingUser(VI);
16887 if (!U)
16889 if (isFusedVectorizedFAddSub(U))
16891 InstructionCost FAddCost = getUnfusedBinOpCost(U, TTI, *TLI, CostKind);
16892 return FMACost > FAddCost ? FMACost - FAddCost
16894 };
16895 switch (ShuffleOrOp) {
16896 case Instruction::PHI: {
16897 // Count reused scalars.
16898 InstructionCost ScalarCost = 0;
16899 SmallPtrSet<const TreeEntry *, 4> CountedOps;
16900 for (PHINode *PHI : make_isa_range<PHINode>(UniqueValues)) {
16901 ValueList Operands(PHI->getNumIncomingValues(), nullptr);
16902 for (unsigned I = 0, N = PHI->getNumIncomingValues(); I < N; ++I) {
16903 Value *Op = PHI->getIncomingValue(I);
16904 Operands[I] = Op;
16905 }
16906 if (const TreeEntry *OpTE =
16907 getSameValuesTreeEntry(Operands.front(), Operands))
16908 if (CountedOps.insert(OpTE).second &&
16909 !OpTE->ReuseShuffleIndices.empty())
16910 ScalarCost += TTI::TCC_Basic * (OpTE->ReuseShuffleIndices.size() -
16911 OpTE->Scalars.size());
16912 }
16913
16914 return CommonCost - ScalarCost + SpillsReloads;
16915 }
16916 case Instruction::ExtractValue:
16917 case Instruction::ExtractElement: {
16918 // For ExtractValue entries vectorized via the struct-call path the scalar
16919 // extractvalue instructions are free (they become extractvalue from a
16920 // struct-of-vectors, which is also free). The cost is fully captured by
16921 // the underlying Call entry and the external-use extraction costs.
16922 if (ShuffleOrOp == Instruction::ExtractValue && !E->StructEVIndices.empty())
16923 return CommonCost;
16924 APInt DemandedElts;
16925 APInt CopyableInsertElts;
16926 VectorType *SrcVecTy = nullptr;
16927 auto GetScalarCost = [&](unsigned Idx) {
16928 if (isa<PoisonValue>(UniqueValues[Idx]))
16930
16931 // Copyable lanes are not extracts; they are inserted into the reused
16932 // source vector, so charge the insert to the vector side only.
16933 if (E->isCopyableElement(UniqueValues[Idx])) {
16934 if (CopyableInsertElts.isZero())
16935 CopyableInsertElts = APInt::getZero(E->getVectorFactor());
16936 CopyableInsertElts.setBit(Idx);
16938 }
16939
16940 auto *I = cast<Instruction>(UniqueValues[Idx]);
16941 // Undef/poison extract indices form holes in the reused source vector,
16942 // such lanes are free.
16943 std::optional<unsigned> ExtIdx = getExtractIndex(I);
16944 if (!ExtIdx)
16946 if (!SrcVecTy) {
16947 if (ShuffleOrOp == Instruction::ExtractElement) {
16948 auto *EE = cast<ExtractElementInst>(I);
16949 SrcVecTy = EE->getVectorOperandType();
16950 } else {
16951 auto *EV = cast<ExtractValueInst>(I);
16952 Type *AggregateTy = EV->getAggregateOperand()->getType();
16953 unsigned NumElts;
16954 if (auto *ATy = dyn_cast<ArrayType>(AggregateTy))
16955 NumElts = ATy->getNumElements();
16956 else
16957 NumElts = AggregateTy->getStructNumElements();
16958 SrcVecTy = cast<VectorType>(getWidenedType(OrigScalarTy, NumElts));
16959 }
16960 }
16961 if (I->hasOneUse()) {
16962 Instruction *Ext = I->user_back();
16963 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
16965 // Use getExtractWithExtendCost() to calculate the cost of
16966 // extractelement/ext pair.
16967 InstructionCost Cost = TTI->getExtractWithExtendCost(
16968 Ext->getOpcode(), Ext->getType(), SrcVecTy, *ExtIdx, CostKind);
16969 // Subtract the cost of s|zext which is subtracted separately.
16970 Cost -= TTI->getCastInstrCost(
16971 Ext->getOpcode(), Ext->getType(), I->getType(),
16972 TTI::getCastContextHint(Ext), CostKind, Ext);
16973 return Cost;
16974 }
16975 }
16976 // The extract, which the target folds into its users (e.g. the lane
16977 // operand of a by-element fmul on AArch64), costs nothing in the scalar
16978 // code; its removal saves nothing.
16979 if (ShuffleOrOp == Instruction::ExtractElement &&
16980 TTI->getVectorInstrCost(*I, SrcVecTy, CostKind, *ExtIdx,
16983 if (DemandedElts.isZero())
16984 DemandedElts = APInt::getZero(getNumElements(SrcVecTy));
16985 DemandedElts.setBit(*ExtIdx);
16987 };
16988 auto GetVectorCost = [&, &TTI = *TTI](InstructionCost CommonCost) {
16989 return CommonCost +
16990 (CopyableInsertElts.isZero()
16992 : TTI.getScalarizationOverhead(
16994 getWidenedType(OrigScalarTy, E->getVectorFactor())),
16995 CopyableInsertElts, /*Insert=*/true,
16996 /*Extract=*/false, CostKind)) -
16997 (DemandedElts.isZero()
16999 : TTI.getScalarizationOverhead(SrcVecTy, DemandedElts,
17000 /*Insert=*/false,
17001 /*Extract=*/true, CostKind));
17002 };
17003 return GetCostDiff(GetScalarCost, GetVectorCost);
17004 }
17005 case Instruction::InsertValue:
17006 case Instruction::InsertElement: {
17007 assert(E->ReuseShuffleIndices.empty() &&
17008 "Unique insertelements only are expected.");
17009 FixedVectorType *SrcVecTy = getInsertBuildVectorSrcTy(E);
17010 unsigned const NumElts = getNumElements(SrcVecTy);
17011 unsigned const NumScalars = VL.size();
17012
17013 unsigned NumOfParts =
17014 getNumberOfParts(SrcVecTy, VL0->getOperand(1)->getType());
17015
17016 SmallVector<int> InsertMask(NumElts, PoisonMaskElem);
17017 unsigned OffsetBeg = *getElementIndex(VL.front());
17018 unsigned OffsetEnd = OffsetBeg;
17019 InsertMask[OffsetBeg] = 0;
17020 for (auto [I, V] : enumerate(VL.drop_front())) {
17021 unsigned Idx = *getElementIndex(V);
17022 if (OffsetBeg > Idx)
17023 OffsetBeg = Idx;
17024 else if (OffsetEnd < Idx)
17025 OffsetEnd = Idx;
17026 InsertMask[Idx] = I + 1;
17027 }
17028 unsigned VecScalarsSz = PowerOf2Ceil(NumElts);
17029 if (NumOfParts > 0 && NumOfParts < NumElts)
17030 VecScalarsSz = PowerOf2Ceil((NumElts + NumOfParts - 1) / NumOfParts);
17031 unsigned VecSz = (1 + OffsetEnd / VecScalarsSz - OffsetBeg / VecScalarsSz) *
17032 VecScalarsSz;
17033 unsigned Offset = VecScalarsSz * (OffsetBeg / VecScalarsSz);
17034 unsigned InsertVecSz = std::min<unsigned>(
17035 PowerOf2Ceil(OffsetEnd - OffsetBeg + 1),
17036 ((OffsetEnd - OffsetBeg + VecScalarsSz) / VecScalarsSz) * VecScalarsSz);
17037 bool IsWholeSubvector =
17038 OffsetBeg == Offset && ((OffsetEnd + 1) % VecScalarsSz == 0);
17039 // Check if we can safely insert a subvector. If it is not possible, just
17040 // generate a whole-sized vector and shuffle the source vector and the new
17041 // subvector.
17042 if (OffsetBeg + InsertVecSz > VecSz) {
17043 // Align OffsetBeg to generate correct mask.
17044 OffsetBeg = alignDown(OffsetBeg, VecSz, Offset);
17045 InsertVecSz = VecSz;
17046 }
17047
17048 APInt DemandedElts = APInt::getZero(NumElts);
17049 // TODO: Add support for Instruction::InsertValue.
17050 SmallVector<int> Mask;
17051 if (!E->ReorderIndices.empty()) {
17052 inversePermutation(E->ReorderIndices, Mask);
17053 Mask.append(InsertVecSz - Mask.size(), PoisonMaskElem);
17054 } else {
17055 Mask.assign(VecSz, PoisonMaskElem);
17056 std::iota(Mask.begin(), std::next(Mask.begin(), InsertVecSz), 0);
17057 }
17058 bool IsIdentity = true;
17059 SmallVector<int> PrevMask(InsertVecSz, PoisonMaskElem);
17060 SmallVector<Value *> AdjustedVL(NumElts, PoisonValue::get(ScalarTy));
17061 Mask.swap(PrevMask);
17062 for (unsigned I = 0; I < NumScalars; ++I) {
17063 unsigned InsertIdx = *getElementIndex(VL[PrevMask[I]]);
17064 DemandedElts.setBit(InsertIdx);
17065 AdjustedVL[InsertIdx] = VL[PrevMask[I]];
17066 IsIdentity &= InsertIdx - OffsetBeg == I;
17067 Mask[InsertIdx - OffsetBeg] = I;
17068 }
17069 assert(Offset < NumElts && "Failed to find vector index offset");
17070
17072 // First cost - resize to actual vector size if not identity shuffle or
17073 // need to shift the vector.
17074 // Do not calculate the cost if the actual size is the register size and
17075 // we can merge this shuffle with the following SK_Select.
17076 auto *InsertVecTy = cast<VectorType>(getWidenedType(ScalarTy, InsertVecSz));
17077 if (!IsIdentity)
17079 InsertVecTy, CostKind, Mask);
17080 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
17081 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
17082 }));
17083 // Second cost - permutation with subvector, if some elements are from the
17084 // initial vector or inserting a subvector.
17085 // TODO: Implement the analysis of the FirstInsert->getOperand(0)
17086 // subvector of ActualVecTy.
17087 SmallBitVector InMask =
17088 isUndefVector(FirstInsert->getOperand(0),
17089 buildUseMask(NumElts, InsertMask, UseMask::UndefsAsMask));
17091 *TTI, Opts.slp_revec, ScalarTy, SrcVecTy, DemandedElts,
17092 /*Insert=*/true, /*Extract=*/false, CostKind, InMask.all(), AdjustedVL,
17093 TTI::getVectorInstrContextHint(AdjustedVL, DemandedElts));
17094 if (!InMask.all() && NumScalars != NumElts && !IsWholeSubvector) {
17095 if (InsertVecSz != VecSz) {
17096 auto *ActualVecTy = cast<VectorType>(getWidenedType(ScalarTy, VecSz));
17097 Cost += getShuffleCost(*TTI, TTI::SK_InsertSubvector, ActualVecTy,
17098 CostKind, {}, OffsetBeg - Offset, InsertVecTy);
17099 } else {
17100 for (unsigned I = 0, End = OffsetBeg - Offset; I < End; ++I)
17101 Mask[I] = InMask.test(I) ? PoisonMaskElem : I;
17102 for (unsigned I = OffsetBeg - Offset, End = OffsetEnd - Offset;
17103 I <= End; ++I)
17104 if (Mask[I] != PoisonMaskElem)
17105 Mask[I] = I + VecSz;
17106 for (unsigned I = OffsetEnd + 1 - Offset; I < VecSz; ++I)
17107 Mask[I] =
17108 ((I >= InMask.size()) || InMask.test(I)) ? PoisonMaskElem : I;
17109 Cost += getShuffleCost(*TTI, TTI::SK_PermuteTwoSrc, InsertVecTy,
17110 CostKind, Mask);
17111 }
17112 }
17113 if (ShuffleOrOp == Instruction::InsertValue &&
17115 // Match the stack slot alignment used during codegen (see the store +
17116 // load roundtrip in vectorizeTree()): the slot holds both the source
17117 // vector and the original aggregate.
17118 Align VecAlign = std::max(DL->getPrefTypeAlign(SrcVecTy),
17119 DL->getPrefTypeAlign(VL0->getType()));
17120 // The stack slot roundtrip is synthesized by codegen; there is no IR
17121 // value or pointer to take operand info from.
17122 Cost += TTI->getMemoryOpCost(Instruction::Store, SrcVecTy, VecAlign,
17123 /*AddressSpace=*/0, CostKind) +
17124 TTI->getMemoryOpCost(Instruction::Load, VL0->getType(), VecAlign,
17125 /*AddressSpace=*/0, CostKind);
17126 }
17127 return Cost + SpillsReloads;
17128 }
17129 case Instruction::ZExt:
17130 case Instruction::SExt:
17131 case Instruction::FPToUI:
17132 case Instruction::FPToSI:
17133 case Instruction::FPExt:
17134 case Instruction::PtrToInt:
17135 case Instruction::PtrToAddr:
17136 case Instruction::IntToPtr:
17137 case Instruction::SIToFP:
17138 case Instruction::UIToFP:
17139 case Instruction::Trunc:
17140 case Instruction::FPTrunc:
17141 case Instruction::BitCast: {
17142 auto SrcIt = MinBWs.find(getOperandEntry(E, 0));
17143 Type *SrcScalarTy = VL0->getOperand(0)->getType();
17144 auto *SrcVecTy = getWidenedType(SrcScalarTy, VL.size());
17145 unsigned Opcode = ShuffleOrOp;
17146 unsigned VecOpcode = Opcode;
17147 // zext and uitofp cannot absorb the sign extension of a signed demoted
17148 // operand and inttoptr needs the original type, so extend it back first.
17149 std::optional<std::pair<uint64_t, bool>> ExtBackBW;
17150 if (SrcIt != MinBWs.end() &&
17151 (Opcode == Instruction::IntToPtr ||
17152 (SrcIt->second.second &&
17153 (Opcode == Instruction::UIToFP || Opcode == Instruction::ZExt)))) {
17154 ExtBackBW = SrcIt->second;
17155 SrcIt = MinBWs.end();
17156 }
17157 if (!ScalarTy->isFPOrFPVectorTy() && !SrcScalarTy->isFPOrFPVectorTy() &&
17158 (SrcIt != MinBWs.end() || It != MinBWs.end())) {
17159 // Check if the values are candidates to demote.
17160 unsigned SrcBWSz = DL->getTypeSizeInBits(SrcScalarTy->getScalarType());
17161 if (SrcIt != MinBWs.end()) {
17162 SrcBWSz = SrcIt->second.first;
17163 unsigned SrcScalarTyNumElements = getNumElements(SrcScalarTy);
17164 SrcScalarTy = IntegerType::get(F->getContext(), SrcBWSz);
17165 SrcVecTy =
17166 getWidenedType(SrcScalarTy, VL.size() * SrcScalarTyNumElements);
17167 }
17168 unsigned BWSz = DL->getTypeSizeInBits(ScalarTy->getScalarType());
17169 if (BWSz == SrcBWSz) {
17170 VecOpcode = Instruction::BitCast;
17171 } else if (BWSz < SrcBWSz) {
17172 VecOpcode = Instruction::Trunc;
17173 } else if (It != MinBWs.end()) {
17174 assert(BWSz > SrcBWSz && "Invalid cast!");
17175 VecOpcode = It->second.second ? Instruction::SExt : Instruction::ZExt;
17176 } else if (SrcIt != MinBWs.end()) {
17177 assert(BWSz > SrcBWSz && "Invalid cast!");
17178 VecOpcode =
17179 SrcIt->second.second ? Instruction::SExt : Instruction::ZExt;
17180 }
17181 } else if (VecOpcode == Instruction::SIToFP && SrcIt != MinBWs.end() &&
17182 !SrcIt->second.second) {
17183 VecOpcode = Instruction::UIToFP;
17184 }
17185 auto GetScalarCost = [&](unsigned Idx) -> InstructionCost {
17186 assert(Idx == 0 && "Expected 0 index only");
17187 return TTI->getCastInstrCost(Opcode, VL0->getType(),
17188 VL0->getOperand(0)->getType(),
17189 TTI::getCastContextHint(VL0), CostKind, VL0);
17190 };
17191 auto GetVectorCost = [=](InstructionCost CommonCost) {
17192 TTI::CastContextHint CCH = GetCastContextHint(VL0->getOperand(0));
17193 if (ExtBackBW)
17194 CommonCost += TTI->getCastInstrCost(
17195 ExtBackBW->second ? Instruction::SExt : Instruction::ZExt, SrcVecTy,
17196 SrcVecTy->getWithNewBitWidth(ExtBackBW->first), CCH, CostKind);
17197 // Do not count cost here if minimum bitwidth is in effect and it is just
17198 // a bitcast (here it is just a noop).
17199 if (VecOpcode != Opcode && VecOpcode == Instruction::BitCast)
17200 return CommonCost;
17201 auto *VI =
17202 VL0->getOpcode() == Opcode && VecOpcode == Opcode ? VL0 : nullptr;
17203
17204 bool IsArithmeticExtendedReduction =
17205 E->Idx == 0 && UserIgnoreList &&
17206 all_of(*UserIgnoreList, [](Value *V) {
17207 auto *I = cast<Instruction>(V);
17208 return is_contained({Instruction::Add, Instruction::FAdd,
17209 Instruction::Mul, Instruction::FMul,
17210 Instruction::And, Instruction::Or,
17211 Instruction::Xor},
17212 I->getOpcode());
17213 });
17214 if (IsArithmeticExtendedReduction &&
17215 (VecOpcode == Instruction::ZExt || VecOpcode == Instruction::SExt))
17216 return CommonCost;
17217 // The scalar cast describes the users of the vector cast. If the scalar
17218 // cast of the vector element types is free by itself (e.g. i32 to i64
17219 // zext), it makes the vector cast free as well, which is true only for
17220 // the widening arithmetic users.
17221 if (VI &&
17222 any_of(VI->users(),
17223 [](const User *U) {
17224 return !is_contained(
17225 {Instruction::Add, Instruction::Sub, Instruction::Mul},
17226 cast<Instruction>(U)->getOpcode());
17227 }) &&
17228 TTI->getCastInstrCost(VecOpcode, VecTy->getScalarType(),
17229 SrcVecTy->getScalarType(),
17230 TTI::getCastContextHint(VL0), CostKind) == 0)
17231 VI = nullptr;
17232 return CommonCost + TTI->getCastInstrCost(VecOpcode, VecTy, SrcVecTy, CCH,
17233 CostKind, VI);
17234 };
17235 return GetCostDiff(GetScalarCost, GetVectorCost);
17236 }
17237 case Instruction::FCmp:
17238 case Instruction::ICmp:
17239 // Override ScalarTy/VecTy with the compared operand type (not i1). The
17240 // cost of a compare instruction is determined by the operand width, and
17241 // getCmpSelInstrCost expects the compared type as its first type arg.
17242 OrigScalarTy = ScalarTy =
17243 getValueType(VL0, Opts.slp_revec, /*LookThroughCmp=*/true);
17244 VecTy = getWidenedType(ScalarTy, VL.size());
17245 [[fallthrough]];
17246 case Instruction::Select: {
17247 const CmpInst *CondCmp = [&]() -> const CmpInst * {
17248 if (ShuffleOrOp != Instruction::Select)
17249 return nullptr;
17250 ArrayRef<Value *> Cond = E->getOperand(0);
17252 auto *Cmp = Ext ? dyn_cast<CmpInst>(Ext->getVectorOperand()) : nullptr;
17253 if (!Cmp || getNumElements(Cmp->getType()) != Cond.size() ||
17254 any_of(enumerate(Cond), [&](const auto &P) {
17255 return !match(P.value(), m_ExtractElt(m_Specific(Cmp),
17256 m_SpecificInt(P.index())));
17257 }))
17258 return nullptr;
17259 return Cmp;
17260 }();
17261 CmpPredicate VecPred, SwappedVecPred;
17262 auto MatchCmp = m_Cmp(VecPred, m_Value(), m_Value());
17263 if (CondCmp)
17264 VecPred = CondCmp->getPredicate();
17265 if (CondCmp || match(VL0, m_Select(MatchCmp, m_Value(), m_Value())) ||
17266 match(VL0, MatchCmp))
17267 SwappedVecPred = CmpInst::getSwappedPredicate(VecPred);
17268 else
17269 SwappedVecPred = VecPred = ScalarTy->isFloatingPointTy()
17272 // The bit tests of trunc X to i1 lanes compare and A, B with a constant.
17273 const bool IsBitTest = any_of(E->Scalars, IsaPred<TruncInst>);
17274 auto GetScalarCost = [&](unsigned Idx) {
17275 if (isa<PoisonValue>(UniqueValues[Idx]))
17277
17278 if (!isa<SelectInst>(UniqueValues[Idx])) {
17279 auto *I = cast<Instruction>(UniqueValues[Idx]);
17280 InstructionCost Cost = TTI->getInstructionCost(I, CostKind);
17281 // The and of the bit test is erased with the compare.
17282 if (IsBitTest && isa<ICmpInst>(I))
17283 Cost += TTI->getInstructionCost(cast<Instruction>(I->getOperand(0)),
17284 CostKind);
17285 return Cost;
17286 }
17287
17288 auto *VI = cast<Instruction>(UniqueValues[Idx]);
17289 CmpPredicate CurrentPred = CondCmp ? CondCmp->getPredicate()
17290 : ScalarTy->isFloatingPointTy()
17293 Value *LHS = nullptr, *RHS = nullptr;
17294 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
17295 bool IsSelect =
17296 ShuffleOrOp == Instruction::Select &&
17297 (match(VI, m_Select(MatchCmp, m_Value(LHS), m_Value(RHS))) ||
17299 if ((!IsSelect && !match(VI, MatchCmp)) ||
17300 (CurrentPred != static_cast<CmpInst::Predicate>(VecPred) &&
17301 CurrentPred != static_cast<CmpInst::Predicate>(SwappedVecPred)))
17302 VecPred = SwappedVecPred = ScalarTy->isFloatingPointTy()
17305
17306 // Check if operands are of i1 types, like a condition expression.
17307 // TODO: consider implementing this in TTI.
17309 if (IsSelect && LHS->getType() == VI->getOperand(0)->getType()) {
17310 assert(LHS->getType() == RHS->getType() &&
17311 "Expected same type for LHS/RHS");
17312 // select i1 v, i1 true, i1 b -> or i1 v, i1 b
17313 if (match(LHS, m_AllOnes())) {
17314 ScalarCost = TTI->getArithmeticInstrCost(
17315 Instruction::Or, LHS->getType(), CostKind,
17316 TTI::getOperandInfo(VI->getOperand(0)), TTI::getOperandInfo(RHS));
17317 } else if (match(RHS, m_Zero())) {
17318 // select i1 v, i1 b, i1 false -> and i1 v, i1 b
17319 ScalarCost = TTI->getArithmeticInstrCost(
17320 Instruction::And, LHS->getType(), CostKind,
17321 TTI::getOperandInfo(VI->getOperand(0)), TTI::getOperandInfo(LHS));
17322 }
17323 }
17324 if (!ScalarCost.isValid()) {
17325 // For selects, the "condition type" arg is the condition operand's
17326 // type; for standalone compares, it is the result type (i1).
17327 ScalarCost = TTI->getCmpSelInstrCost(
17328 E->getOpcode(), OrigScalarTy,
17329 ShuffleOrOp == Instruction::Select ? VL0->getOperand(0)->getType()
17330 : VL0->getType(),
17331 CurrentPred, CostKind,
17333 VI->getOperand(ShuffleOrOp == Instruction::Select ? 1 : 0)),
17335 VI->getOperand(ShuffleOrOp == Instruction::Select ? 2 : 1)),
17336 VI);
17337 }
17338 InstructionCost IntrinsicCost = GetMinMaxCost(OrigScalarTy, VI);
17339 if (IntrinsicCost.isValid())
17340 ScalarCost = IntrinsicCost;
17341
17342 return ScalarCost;
17343 };
17344 auto GetVectorCost = [&](InstructionCost CommonCost) {
17345 // An absorbed boolean zero-test leaf emits no conversion; only the
17346 // reorder shuffle (in CommonCost) may remain.
17347 if (isBooleanizedNode(E))
17348 return CommonCost;
17349 // For selects, the condition type may differ from the result type
17350 // (e.g. condition is <N x i1> while result is <N x i32>). For
17351 // compares, the result type IS the mask (i1/vNi1). Construct the
17352 // right type so getCmpSelInstrCost sees the actual mask/result width.
17353 auto *MaskTy = cast<VectorType>(getWidenedType(
17354 ShuffleOrOp == Instruction::Select ? VL0->getOperand(0)->getType()
17355 : VL0->getType(),
17356 VL.size()));
17357
17359 if (ShuffleOrOp == Instruction::Select) {
17360 ArrayRef<Value *> Cond = E->getOperand(0);
17361 ArrayRef<Value *> LHS = E->getOperand(1);
17362 ArrayRef<Value *> RHS = E->getOperand(2);
17363 // select <VF x i1>, <VF x i1>, <VF x i1>?
17364 // TODO: consider implementing this in TTI.
17365 if (Cond.front()->getType() == LHS.front()->getType()) {
17366 // select <VF x i1> v, <VF x i1> true, <VF x i1> b -> or <VF x i1> v,
17367 // <VF x i1> b
17368 if (all_of(LHS, [&](Value *V) { return match(V, m_AllOnes()); })) {
17369 VecCost = TTI->getArithmeticInstrCost(
17370 Instruction::Or, VecTy, CostKind, TTI::getOperandInfo(Cond),
17372 } else if (all_of(RHS,
17373 [&](Value *V) { return match(V, m_Zero()); })) {
17374 // select <VF x i1> v, <VF x i1> b, <VF x i1> false -> and <VF x i1>
17375 // v, <VF x i1> b
17376 VecCost = TTI->getArithmeticInstrCost(
17377 Instruction::And, VecTy, CostKind, TTI::getOperandInfo(Cond),
17379 }
17380 }
17381 }
17382 if (!VecCost.isValid()) {
17383 VecCost = TTI->getCmpSelInstrCost(
17384 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind,
17386 E->getOperand(ShuffleOrOp == Instruction::Select ? 1 : 0)),
17388 E->getOperand(ShuffleOrOp == Instruction::Select ? 2 : 1)),
17389 VL0);
17390 if (IsBitTest)
17391 VecCost +=
17392 TTI->getArithmeticInstrCost(Instruction::And, VecTy, CostKind);
17393 if (isa<SelectInst>(VL0)) {
17394 unsigned CondNumElements = getNumElements(MaskTy);
17395 unsigned VecTyNumElements = getNumElements(VecTy);
17396 assert(VecTyNumElements >= CondNumElements &&
17397 VecTyNumElements % CondNumElements == 0 &&
17398 "Cannot vectorize Instruction::Select");
17399 if (CondNumElements != VecTyNumElements) {
17400 // When the return type is i1 but the source is fixed vector type,
17401 // we need to duplicate the condition value.
17402 VecCost += getShuffleCost(
17403 *TTI, TTI::SK_PermuteSingleSrc, MaskTy, CostKind,
17404 createReplicatedMask(VecTyNumElements / CondNumElements,
17405 CondNumElements));
17406 }
17407 }
17408 }
17409 return VecCost + CommonCost;
17410 };
17411 return GetCostDiff(GetScalarCost, GetVectorCost);
17412 }
17413 case TreeEntry::MinMax: {
17414 auto GetScalarCost = [&](unsigned Idx) {
17415 return GetMinMaxCost(OrigScalarTy);
17416 };
17417 auto GetVectorCost = [&](InstructionCost CommonCost) {
17418 InstructionCost VecCost = GetMinMaxCost(VecTy);
17419 return VecCost + CommonCost;
17420 };
17421 return GetCostDiff(GetScalarCost, GetVectorCost);
17422 }
17423 case TreeEntry::FMulAdd: {
17424 auto GetScalarCost = [&](unsigned Idx) {
17425 if (isa<PoisonValue>(UniqueValues[Idx]))
17427 auto *I = cast<Instruction>(UniqueValues[Idx]);
17428 InstructionCost Cost = GetFMulAddCost(E->getOperations(), I);
17429 if (Cost.isValid())
17430 return Cost;
17431 // The lanes without the fmul, e.g. the constant lanes of the fmul node,
17432 // stay plain fadd/fsub.
17433 unsigned Lane = UniqueIndexes[Idx];
17434 Value *Op1 = E->getOperand(0)[Lane];
17435 Value *Op2 = E->getOperand(1)[Lane];
17436 return TTI->getArithmeticInstrCost(
17437 E->getOpcode(), OrigScalarTy, CostKind, TTI::getOperandInfo(Op1),
17438 TTI::getOperandInfo(Op2), {Op1, Op2}, I, TLI);
17439 };
17440 auto GetVectorCost = [&, &TTI = *TTI](InstructionCost CommonCost) {
17441 FastMathFlags FMF;
17442 FMF.set();
17443 for (FPMathOperator *FPCI : make_isa_range<FPMathOperator>(E->Scalars)) {
17444 FMF &= FPCI->getFastMathFlags();
17445 // The fused fmul may sit in either operand (c - a*b included).
17446 if (Instruction *FMul =
17448 FMF &= FMul->getFastMathFlags();
17449 }
17450 IntrinsicCostAttributes ICA(Intrinsic::fmuladd, VecTy,
17451 {VecTy, VecTy, VecTy}, FMF);
17452 InstructionCost VecCost = TTI.getIntrinsicInstrCost(ICA, CostKind);
17453 return VecCost + CommonCost;
17454 };
17455 return GetCostDiff(GetScalarCost, GetVectorCost);
17456 }
17457 case TreeEntry::ReducedBitcast:
17458 case TreeEntry::ReducedBitcastBSwap: {
17459 auto GetScalarCost = [&, &TTI = *TTI](unsigned Idx) {
17460 if (isa<PoisonValue>(UniqueValues[Idx]))
17462 auto *Shl = dyn_cast<Instruction>(UniqueValues[Idx]);
17463 if (!Shl)
17465 InstructionCost ScalarCost = TTI.getInstructionCost(Shl, CostKind);
17466 auto *ZExt = dyn_cast<Instruction>(Shl->getOperand(0));
17467 if (!ZExt)
17468 return ScalarCost;
17469 ScalarCost += TTI.getInstructionCost(ZExt, CostKind);
17470 return ScalarCost;
17471 };
17472 auto GetVectorCost = [&, &TTI = *TTI](InstructionCost CommonCost) {
17473 const TreeEntry *LhsTE = getOperandEntry(E, /*Idx=*/0);
17474 TTI::CastContextHint CastCtx =
17475 getCastContextHint(*getOperandEntry(LhsTE, /*Idx=*/0));
17476 Type *SrcScalarTy = cast<ZExtInst>(LhsTE->getMainOp())->getSrcTy();
17477 auto *SrcVecTy = getWidenedType(SrcScalarTy, LhsTE->getVectorFactor());
17478 InstructionCost BitcastCost = TTI.getCastInstrCost(
17479 Instruction::BitCast, ScalarTy, SrcVecTy, CastCtx, CostKind);
17480 if (ShuffleOrOp == TreeEntry::ReducedBitcastBSwap) {
17481 auto *SrcType = IntegerType::getIntNTy(
17482 ScalarTy->getContext(),
17483 DL->getTypeSizeInBits(SrcScalarTy) * EntryVF);
17484 IntrinsicCostAttributes CostAttrs(Intrinsic::bswap, SrcType, {SrcType});
17486 TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
17487 BitcastCost += IntrinsicCost;
17488 if (SrcType != ScalarTy) {
17489 BitcastCost += TTI.getCastInstrCost(Instruction::ZExt, ScalarTy,
17490 SrcType, CastCtx, CostKind);
17491 }
17492 }
17493 return BitcastCost + CommonCost;
17494 };
17495 return GetCostDiff(GetScalarCost, GetVectorCost);
17496 }
17497 case TreeEntry::ReducedBitcastLoads:
17498 case TreeEntry::ReducedBitcastBSwapLoads: {
17499 auto GetScalarCost = [&, &TTI = *TTI](unsigned Idx) {
17500 if (isa<PoisonValue>(UniqueValues[Idx]))
17502 auto *Shl = dyn_cast<Instruction>(UniqueValues[Idx]);
17503 if (!Shl)
17505 InstructionCost ScalarCost = TTI.getInstructionCost(Shl, CostKind);
17506 auto *ZExt = dyn_cast<Instruction>(Shl->getOperand(0));
17507 if (!ZExt)
17508 return ScalarCost;
17509 ScalarCost += TTI.getInstructionCost(ZExt, CostKind);
17510 auto *Load = dyn_cast<Instruction>(ZExt->getOperand(0));
17511 if (!Load)
17512 return ScalarCost;
17513 ScalarCost += TTI.getInstructionCost(Load, CostKind);
17514 return ScalarCost;
17515 };
17516 auto GetVectorCost = [&, &TTI = *TTI](InstructionCost CommonCost) {
17517 const TreeEntry *LhsTE = getOperandEntry(E, /*Idx=*/0);
17518 const TreeEntry *LoadTE = getOperandEntry(LhsTE, /*Idx=*/0);
17519 LoadInst *LI0 = LoadTE->getFirstLoad();
17520 auto *SrcType = IntegerType::getIntNTy(
17521 ScalarTy->getContext(),
17522 DL->getTypeSizeInBits(LI0->getType()) * EntryVF);
17523 InstructionCost LoadCost =
17524 TTI.getMemoryOpCost(Instruction::Load, SrcType, LI0->getAlign(),
17525 LI0->getPointerAddressSpace(), CostKind);
17526 if (ShuffleOrOp == TreeEntry::ReducedBitcastBSwapLoads) {
17527 IntrinsicCostAttributes CostAttrs(Intrinsic::bswap, SrcType, {SrcType});
17529 TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
17530 LoadCost += IntrinsicCost;
17531 if (SrcType != ScalarTy) {
17532 LoadCost +=
17533 TTI.getCastInstrCost(Instruction::ZExt, ScalarTy, SrcType,
17534 getCastContextHint(*LoadTE), CostKind);
17535 }
17536 }
17537 return LoadCost + CommonCost;
17538 };
17539 return GetCostDiff(GetScalarCost, GetVectorCost);
17540 }
17541 case TreeEntry::ReducedBitPack: {
17542 const TreeEntry *ShlTE =
17543 E->getOpcode() == Instruction::And ? getOperandEntry(E, /*Idx=*/0) : E;
17544 const TreeEntry *LhsTE = getOperandEntry(ShlTE, /*Idx=*/0);
17545 std::optional<BitPackInfo> Info = computeBitPackLayout(*E);
17546 const TreeEntry *SrcTE = Info ? getBitPackSource(*LhsTE, *Info) : LhsTE;
17547 // The scalars of the root, the shl and the combined chain are removed.
17548 SmallVector<const TreeEntry *> CombinedTEs = {E};
17549 if (ShlTE != E)
17550 CombinedTEs.push_back(ShlTE);
17551 for (const TreeEntry *TE = LhsTE; TE != SrcTE;
17552 TE = getOperandEntry(TE, /*Idx=*/0))
17553 CombinedTEs.push_back(TE);
17554 auto GetLaneCost = [&, &TTI = *TTI](unsigned Lane) {
17555 InstructionCost ScalarCost = 0;
17556 for (const TreeEntry *TE : CombinedTEs) {
17557 auto *I = dyn_cast<Instruction>(TE->Scalars[Lane]);
17558 // A copyable lane is the operand of the node, costed with its node.
17559 if (!I || TE->isCopyableElement(I))
17560 continue;
17561 if (I->isCast()) {
17562 ScalarCost += TTI.getCastInstrCost(
17563 I->getOpcode(), I->getType(), I->getOperand(0)->getType(),
17564 TTI::getCastContextHint(I), CostKind, I);
17565 continue;
17566 }
17568 {Instruction::And, Instruction::LShr, Instruction::Shl},
17569 I->getOpcode()) &&
17570 "Expected and/shift in the bit pack.");
17571 ScalarCost += TTI.getArithmeticInstrCost(
17572 I->getOpcode(), I->getType(), CostKind,
17573 TTI::getOperandInfo(I->getOperand(0)),
17574 TTI::getOperandInfo(I->getOperand(1)),
17575 {I->getOperand(0), I->getOperand(1)}, I, TLI);
17576 }
17577 return ScalarCost;
17578 };
17579 auto GetScalarCost = [&](unsigned Idx) {
17580 return GetLaneCost(UniqueIndexes[Idx]);
17581 };
17582 auto GetVectorCost = [&, &TTI = *TTI](InstructionCost CommonCost) {
17583 if (!Info)
17585 unsigned ShiftWidth;
17586 // The pack works on the vectorized operand in its own (possibly
17587 // demoted) type.
17588 Type *SrcScalarTy = SrcTE->Scalars.front()->getType();
17589 if (auto It = MinBWs.find(SrcTE); It != MinBWs.end())
17590 SrcScalarTy = IntegerType::get(F->getContext(), It->second.first);
17591 // The source lanes are packed into the node type.
17592 Type *DstScalarTy = SrcTE == LhsTE ? SrcScalarTy : ScalarTy;
17593 InstructionCost PackCost =
17594 getBitPackCost(TTI,
17596 SrcScalarTy, SrcTE->getVectorFactor())),
17597 DstScalarTy, *Info, getZExtSrcWidth(*SrcTE),
17598 getCastContextHint(*SrcTE), CostKind, TLI,
17599 E->getMainOp(), ShiftWidth);
17600 // A demoted result is re-extended to the reduction type.
17601 if (DstScalarTy != OrigScalarTy) {
17602 auto It = MinBWs.find(E);
17603 PackCost += TTI.getCastInstrCost(
17604 It != MinBWs.end() && It->second.second ? Instruction::SExt
17605 : Instruction::ZExt,
17606 OrigScalarTy, DstScalarTy, getCastContextHint(*LhsTE), CostKind);
17607 }
17608 // The copyable lanes are not the scalars of the node, but their scalars
17609 // in the shl and the combined chain are removed too.
17610 for (auto [Lane, V] : enumerate(E->Scalars))
17611 if (E->isCopyableElement(V))
17612 PackCost -= GetLaneCost(Lane);
17613 return PackCost + CommonCost;
17614 };
17615 return GetCostDiff(GetScalarCost, GetVectorCost);
17616 }
17617 case TreeEntry::ReducedCmpBitcast: {
17618 auto GetScalarCost = [&, &TTI = *TTI](unsigned Idx) {
17619 if (isa<PoisonValue>(UniqueValues[Idx]))
17621 auto *Sel = dyn_cast<Instruction>(UniqueValues[Idx]);
17622 if (!Sel)
17624 InstructionCost ScalarCost = TTI.getInstructionCost(Sel, CostKind);
17625 return ScalarCost;
17626 };
17627 auto GetVectorCost = [&, &TTI = *TTI](InstructionCost CommonCost) {
17628 Type *CmpTy = CmpInst::makeCmpResultType(VecTy);
17629 auto *DstTy =
17630 IntegerType::getIntNTy(ScalarTy->getContext(), E->getVectorFactor());
17631 InstructionCost BitcastCost =
17632 TTI.getCastInstrCost(Instruction::BitCast, DstTy, CmpTy,
17633 TTI::CastContextHint::None, CostKind);
17634 if (DstTy != ScalarTy) {
17635 BitcastCost +=
17636 TTI.getCastInstrCost(Instruction::ZExt, ScalarTy, DstTy,
17637 TTI::CastContextHint::None, CostKind);
17638 }
17639 return BitcastCost + CommonCost;
17640 };
17641 return GetCostDiff(GetScalarCost, GetVectorCost);
17642 }
17643 case Instruction::FNeg:
17644 case Instruction::Add:
17645 case Instruction::FAdd:
17646 case Instruction::Sub:
17647 case Instruction::FSub:
17648 case Instruction::Mul:
17649 case Instruction::FMul:
17650 case Instruction::UDiv:
17651 case Instruction::SDiv:
17652 case Instruction::FDiv:
17653 case Instruction::URem:
17654 case Instruction::SRem:
17655 case Instruction::FRem:
17656 case Instruction::Shl:
17657 case Instruction::LShr:
17658 case Instruction::AShr:
17659 case Instruction::And:
17660 case Instruction::Or:
17661 case Instruction::Xor: {
17662 auto GetScalarCost = [&](unsigned Idx) {
17663 if (isa<PoisonValue>(UniqueValues[Idx]))
17665
17666 // We cannot retrieve the operand from UniqueValues[Idx] because an
17667 // interchangeable instruction may be used. The order and the actual
17668 // operand might differ from what is retrieved from UniqueValues[Idx].
17669 unsigned Lane = UniqueIndexes[Idx];
17670 Value *Op1 = E->getOperand(0)[Lane];
17671 Value *Op2;
17672 SmallVector<const Value *, 2> Operands(1, Op1);
17673 if (isa<UnaryOperator>(UniqueValues[Idx])) {
17674 Op2 = Op1;
17675 } else {
17676 Op2 = E->getOperand(1)[Lane];
17677 Operands.push_back(Op2);
17678 }
17681 auto *I = dyn_cast<Instruction>(UniqueValues[Idx]);
17682 InstructionCost ScalarCost = TTI->getArithmeticInstrCost(
17683 ShuffleOrOp, OrigScalarTy, CostKind, Op1Info, Op2Info, Operands,
17684 I && I->getOpcode() == ShuffleOrOp ? I : nullptr);
17685 if (I && (ShuffleOrOp == Instruction::FAdd ||
17686 ShuffleOrOp == Instruction::FSub)) {
17687 InstructionCost IntrinsicCost = GetFMulAddCost(E->getOperations(), I);
17688 if (IntrinsicCost.isValid())
17689 ScalarCost = IntrinsicCost;
17690 } else if (I && ShuffleOrOp == Instruction::FMul) {
17691 InstructionCost FusedCost = GetFusedFMulCost(I);
17692 if (FusedCost.isValid())
17693 ScalarCost = FusedCost;
17694 }
17695 return ScalarCost;
17696 };
17697 auto GetVectorCost = [=](InstructionCost CommonCost) {
17698 // And peephole only applies to plain 2-operand nodes.
17699 if (ShuffleOrOp == Instruction::And && It != MinBWs.end() &&
17700 !E->hasReassocScalars()) {
17701 for (unsigned I : seq<unsigned>(0, E->getNumOperands())) {
17702 ArrayRef<Value *> Ops = E->getOperand(I);
17703 if (all_of(Ops, [&](Value *Op) {
17704 auto *CI = dyn_cast<ConstantInt>(Op);
17705 return CI && CI->getValue().countr_one() >= It->second.first;
17706 }))
17707 return CommonCost;
17708 }
17709 }
17710 // Masked path ignores Op1Info/Op2Info like its codegen does; keep it
17711 // out of the operand-aware cost comparison below.
17712 if (InstructionCost MaskedCost = getMaskedDivRemCost(
17713 *TTI, Opts.slp_revec, ShuffleOrOp, ScalarTy, VL.size(), CostKind);
17714 MaskedCost.isValid())
17715 return MaskedCost + CommonCost;
17716 unsigned OpIdx = isa<UnaryOperator>(VL0) ? 0 : 1;
17717 TTI::OperandValueInfo Op1Info = TTI::getOperandInfo(E->getOperand(0));
17718 TTI::OperandValueInfo Op2Info = TTI::getOperandInfo(E->getOperand(OpIdx));
17719 InstructionCost Cost = TTI->getArithmeticInstrCost(
17720 ShuffleOrOp, VecTy, CostKind, Op1Info, Op2Info, {},
17721 VL0->getOpcode() == ShuffleOrOp ? VL0 : nullptr, TLI);
17722 // N columns need N-1 vector combines; price extra columns
17723 // conservatively, skipping identity-only columns (not combined by
17724 // codegen).
17725 if (E->hasReassocScalars()) {
17726 const unsigned CombineOpcode = getReassocCombineOpcode(E->getOpcode());
17727 for (unsigned Idx : seq<unsigned>(2, E->getNumOperands())) {
17728 if (all_of(E->getOperand(Idx), [&](Value *V) {
17729 return isBinOpIdentityConstant(V, CombineOpcode,
17730 E->isReassocNegatedOp(Idx));
17731 }))
17732 continue;
17733 // The first operand is the running fold, a computed value with no
17734 // static properties to model.
17735 Cost += TTI->getArithmeticInstrCost(
17736 ShuffleOrOp, VecTy, CostKind, {},
17737 TTI::getOperandInfo(E->getOperand(Idx)), {},
17738 VL0->getOpcode() == ShuffleOrOp ? VL0 : nullptr, TLI);
17739 }
17740 }
17741 return Cost + CommonCost;
17742 };
17743 return GetCostDiffWithPeeled(GetScalarCost, GetVectorCost);
17744 }
17745 case Instruction::GetElementPtr: {
17746 return CommonCost + GetGEPCostDiff(VL, VL0);
17747 }
17748 case Instruction::Load: {
17749 auto GetScalarCost = [&](unsigned Idx) {
17750 auto *VI = cast<LoadInst>(UniqueValues[Idx]);
17751 return TTI->getMemoryOpCost(
17752 Instruction::Load, OrigScalarTy, VI->getAlign(),
17753 VI->getPointerAddressSpace(), CostKind,
17754 TTI::getOperandInfo(VI->getPointerOperand()), VI);
17755 };
17756 auto *LI0 = cast<LoadInst>(VL0);
17757 auto GetVectorCost = [&](InstructionCost CommonCost) {
17758 InstructionCost VecLdCost;
17759 switch (E->State) {
17760 case TreeEntry::Vectorize:
17761 if (unsigned Factor = E->getInterleaveFactor()) {
17762 VecLdCost = TTI->getInterleavedMemoryOpCost(
17763 Instruction::Load, VecTy, Factor, {}, LI0->getAlign(),
17764 LI0->getPointerAddressSpace(), CostKind);
17765
17766 } else {
17767 LoadInst *FirstLI = E->getFirstLoad();
17768 VecLdCost = TTI->getMemoryOpCost(
17769 Instruction::Load, VecTy,
17770 commonAlignment(FirstLI->getAlign(),
17771 getVectorLoadShift(E->Scalars)),
17772 FirstLI->getPointerAddressSpace(), CostKind,
17774 }
17775 break;
17776 case TreeEntry::StridedVectorize: {
17777 const StridedPtrInfo &SPtrInfo = TreeEntryToStridedPtrInfoMap.at(E);
17778 FixedVectorType *StridedLoadTy = SPtrInfo.Ty;
17779 assert(StridedLoadTy && "Missing StridedPointerInfo for tree entry.");
17780 Align CommonAlignment =
17781 computeCommonAlignment<LoadInst>(UniqueValues.getArrayRef());
17782 bool IsReverse = E->isReverse() && !isWidenedStridedLoad(E);
17783 Value *Stride = getStrideBytesIfConstant(SPtrInfo.StrideVal, ScalarTy,
17784 *DL, IsReverse);
17785 VecLdCost = TTI->getMemIntrinsicInstrCost(
17786 MemIntrinsicCostAttributes(Intrinsic::experimental_vp_strided_load,
17787 StridedLoadTy, LI0->getPointerOperand(),
17788 /*VariableMask=*/false, CommonAlignment,
17789 /*I=*/nullptr, Stride),
17790 CostKind);
17791 if (StridedLoadTy != VecTy)
17792 VecLdCost +=
17793 getWidenedStridedCastCost(*TTI, StridedLoadTy, VecTy, *DL,
17794 getCastContextHint(*E), CostKind);
17795
17796 break;
17797 }
17798 case TreeEntry::CompressVectorize: {
17799 bool IsMasked;
17800 unsigned InterleaveFactor;
17801 SmallVector<int> CompressMask;
17802 VectorType *LoadVecTy;
17803 SmallVector<Value *> Scalars(VL);
17804 if (!E->ReorderIndices.empty()) {
17805 SmallVector<int> Mask(E->ReorderIndices.begin(),
17806 E->ReorderIndices.end());
17807 reorderScalars(Scalars, Mask);
17808 }
17809 SmallVector<Value *> PointerOps(Scalars.size());
17810 for (auto [I, V] : enumerate(Scalars))
17811 PointerOps[I] = cast<LoadInst>(V)->getPointerOperand();
17812 [[maybe_unused]] bool IsVectorized = isMaskedLoadCompress(
17813 Scalars, PointerOps, E->ReorderIndices, *TTI, *DL, *SE, *AC, *DT,
17814 *TLI, CostKind, [](Value *) { return true; }, Opts.slp_revec,
17815 IsMasked, InterleaveFactor, CompressMask, LoadVecTy, Cache);
17816 CompressEntryToData.try_emplace(E, CompressMask, LoadVecTy,
17817 InterleaveFactor, IsMasked);
17818 Align CommonAlignment = LI0->getAlign();
17819 // For REVEC the emitted shuffle uses the compress mask expanded to the
17820 // individual elements of the vector scalars.
17821 SmallVector<int> CompressCostMask(CompressMask);
17823 CompressCostMask);
17824 if (InterleaveFactor) {
17825 VecLdCost = TTI->getInterleavedMemoryOpCost(
17826 Instruction::Load, LoadVecTy, InterleaveFactor, {},
17827 CommonAlignment, LI0->getPointerAddressSpace(), CostKind);
17828 } else if (IsMasked) {
17829 VecLdCost = TTI->getMemIntrinsicInstrCost(
17830 MemIntrinsicCostAttributes(Intrinsic::masked_load, LoadVecTy,
17831 CommonAlignment,
17832 LI0->getPointerAddressSpace()),
17833 CostKind);
17834 // TODO: include this cost into CommonCost.
17835 VecLdCost += getShuffleCost(*TTI, TTI::SK_PermuteSingleSrc, LoadVecTy,
17836 CostKind, CompressCostMask);
17837 } else {
17838 VecLdCost = TTI->getMemoryOpCost(
17839 Instruction::Load, LoadVecTy, CommonAlignment,
17840 LI0->getPointerAddressSpace(), CostKind,
17842 // TODO: include this cost into CommonCost.
17843 VecLdCost += getShuffleCost(*TTI, TTI::SK_PermuteSingleSrc, LoadVecTy,
17844 CostKind, CompressCostMask);
17845 }
17846 break;
17847 }
17848 case TreeEntry::ScatterVectorize: {
17849 Align CommonAlignment =
17850 computeCommonAlignment<LoadInst>(UniqueValues.getArrayRef());
17851 VecLdCost = TTI->getMemIntrinsicInstrCost(
17852 MemIntrinsicCostAttributes(Intrinsic::masked_gather, VecTy,
17853 LI0->getPointerOperand(),
17854 /*VariableMask=*/false, CommonAlignment),
17855 CostKind);
17856 break;
17857 }
17858 case TreeEntry::BlendedLoadVectorize: {
17859 // Two masked loads (one per candidate base) blended by a select.
17860 Align CommonAlignment =
17861 computeBlendedLoadBaseAlignment(UniqueValues.getArrayRef(), *DL);
17862 VecLdCost = getBlendedLoadCost(*TTI, VecTy, CommonAlignment,
17863 LI0->getPointerAddressSpace(), CostKind);
17864 break;
17865 }
17866 case TreeEntry::ExpandVectorize:
17867 case TreeEntry::CombinedVectorize:
17868 case TreeEntry::SplitVectorize:
17869 case TreeEntry::NeedToGather:
17870 llvm_unreachable("Unexpected vectorization state.");
17871 }
17872 return VecLdCost + CommonCost;
17873 };
17874
17875 InstructionCost Cost = GetCostDiff(GetScalarCost, GetVectorCost);
17876 // Masked gather and blended loads are not terminal nodes: their address
17877 // cost is estimated separately (blended loads have no per-lane address).
17878 if (E->State == TreeEntry::ScatterVectorize ||
17879 E->State == TreeEntry::BlendedLoadVectorize)
17880 return Cost;
17881
17882 // Estimate cost of GEPs since this tree node is a terminator.
17883 SmallVector<Value *> PointerOps;
17884 for (LoadInst *LI : make_isa_range<LoadInst>(VL))
17885 PointerOps.push_back(LI->getPointerOperand());
17886 return Cost + GetGEPCostDiff(PointerOps, LI0->getPointerOperand());
17887 }
17888 case Instruction::Store: {
17889 bool IsReorder = !E->ReorderIndices.empty();
17890 auto GetScalarCost = [=](unsigned Idx) {
17891 auto *VI = cast<StoreInst>(VL[Idx]);
17892 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(VI->getValueOperand());
17893 return TTI->getMemoryOpCost(Instruction::Store, OrigScalarTy,
17894 VI->getAlign(), VI->getPointerAddressSpace(),
17895 CostKind, OpInfo, VI);
17896 };
17897 auto *BaseSI =
17898 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
17899 auto GetVectorCost = [=](InstructionCost CommonCost) {
17900 // We know that we can merge the stores. Calculate the cost.
17901 InstructionCost VecStCost;
17902 if (E->State == TreeEntry::StridedVectorize) {
17903 const StridedPtrInfo &SPtrInfo = TreeEntryToStridedPtrInfoMap.at(E);
17904 FixedVectorType *StridedStoreTy = SPtrInfo.Ty;
17905 assert(StridedStoreTy && "Missing StridedPointerInfo for tree entry.");
17906 Align CommonAlignment =
17907 computeCommonAlignment<StoreInst>(UniqueValues.getArrayRef());
17908 Value *Stride =
17909 getStrideBytesIfConstant(SPtrInfo.StrideVal, ScalarTy, *DL);
17910 VecStCost = TTI->getMemIntrinsicInstrCost(
17911 MemIntrinsicCostAttributes(Intrinsic::experimental_vp_strided_store,
17912 StridedStoreTy,
17913 BaseSI->getPointerOperand(),
17914 /*VariableMask=*/false, CommonAlignment,
17915 /*I=*/nullptr, Stride),
17916 CostKind);
17917 if (StridedStoreTy != VecTy)
17918 VecStCost +=
17919 getWidenedStridedCastCost(*TTI, VecTy, StridedStoreTy, *DL,
17920 getCastContextHint(*E), CostKind);
17921 } else if (E->State == TreeEntry::ExpandVectorize) {
17922 const StridedPtrInfo &SPtrInfo = TreeEntryToStridedPtrInfoMap.at(E);
17923 FixedVectorType *MaskedStoreTy = SPtrInfo.Ty;
17924 assert(MaskedStoreTy && "Missing StridedPointerInfo for tree entry.");
17925 Align CommonAlignment =
17926 computeCommonAlignment<StoreInst>(UniqueValues.getArrayRef());
17927 // Masked store: the values are expanded into the widened vector and
17928 // stored with a constant mask.
17929 VecStCost = TTI->getMemIntrinsicInstrCost(
17930 MemIntrinsicCostAttributes(Intrinsic::masked_store, MaskedStoreTy,
17931 CommonAlignment,
17932 BaseSI->getPointerAddressSpace()),
17933 CostKind);
17934 } else {
17935 assert(E->State == TreeEntry::Vectorize &&
17936 "Expected either strided, consecutive, or expanded stores.");
17937 if (unsigned Factor = E->getInterleaveFactor()) {
17938 assert(E->ReuseShuffleIndices.empty() && !E->ReorderIndices.empty() &&
17939 "No reused shuffles expected");
17940 CommonCost = 0;
17941 VecStCost = TTI->getInterleavedMemoryOpCost(
17942 Instruction::Store, VecTy, Factor, {}, BaseSI->getAlign(),
17943 BaseSI->getPointerAddressSpace(), CostKind);
17944 } else {
17945 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(E->getOperand(0));
17946 VecStCost = TTI->getMemoryOpCost(
17947 Instruction::Store, VecTy, BaseSI->getAlign(),
17948 BaseSI->getPointerAddressSpace(), CostKind, OpInfo);
17949 }
17950 }
17951 return VecStCost + CommonCost;
17952 };
17953 SmallVector<Value *> PointerOps(VL.size());
17954 for (auto [I, V] : enumerate(VL)) {
17955 unsigned Idx = IsReorder ? E->ReorderIndices[I] : I;
17956 PointerOps[Idx] = cast<StoreInst>(V)->getPointerOperand();
17957 }
17958
17959 return GetCostDiff(GetScalarCost, GetVectorCost) +
17960 GetGEPCostDiff(PointerOps, BaseSI->getPointerOperand());
17961 }
17962 case Instruction::Call: {
17963 auto GetScalarCost = [&](unsigned Idx) {
17964 // A copyable lane has no scalar call of its own; its real cost is
17965 // accounted for wherever it is otherwise computed.
17966 if (isa<PoisonValue>(UniqueValues[Idx]) ||
17967 E->isCopyableElement(UniqueValues[Idx]))
17969 auto *CI = cast<CallInst>(UniqueValues[Idx]);
17971 if (ID != Intrinsic::not_intrinsic) {
17972 IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
17973 return TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
17974 }
17975 return TTI->getCallInstrCost(CI->getCalledFunction(),
17977 CI->getFunctionType()->params(), CostKind);
17978 };
17979 auto GetVectorCost = [=](InstructionCost CommonCost) {
17980 auto *CI = cast<CallInst>(VL0);
17983 CI, ID, getNumElements(VecTy),
17984 It != MinBWs.end() ? It->second.first : 0, *TTI);
17985 auto VecCallCosts =
17986 getVectorCallCosts(CI, VecTy, *TTI, *TLI, ArgTys, CostKind);
17987 return std::min(VecCallCosts.first, VecCallCosts.second) + CommonCost;
17988 };
17989 return GetCostDiff(GetScalarCost, GetVectorCost);
17990 }
17991 case Instruction::ShuffleVector: {
17992 if (!Opts.slp_revec || E->isAltShuffle())
17993 assert(E->isAltShuffle() &&
17994 ((Instruction::isBinaryOp(E->getOpcode()) &&
17995 Instruction::isBinaryOp(E->getAltOpcode())) ||
17996 (Instruction::isCast(E->getOpcode()) &&
17997 Instruction::isCast(E->getAltOpcode())) ||
17998 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
17999 "Invalid Shuffle Vector Operand");
18000 // Try to find the previous shuffle node with the same operands and same
18001 // main/alternate ops.
18002 auto TryFindNodeWithEqualOperands = [=]() {
18003 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
18004 if (TE.get() == E)
18005 break;
18006 if (TE->hasState() && TE->isAltShuffle() &&
18007 ((TE->getOpcode() == E->getOpcode() &&
18008 TE->getAltOpcode() == E->getAltOpcode()) ||
18009 (TE->getOpcode() == E->getAltOpcode() &&
18010 TE->getAltOpcode() == E->getOpcode())) &&
18011 TE->hasEqualOperands(*E))
18012 return true;
18013 }
18014 return false;
18015 };
18016 auto GetScalarCost = [&](unsigned Idx) {
18017 if (isa<PoisonValue>(UniqueValues[Idx]))
18019
18020 auto *VI = cast<Instruction>(UniqueValues[Idx]);
18021 assert(E->getMatchingMainOpOrAltOp(VI) &&
18022 "Unexpected main/alternate opcode");
18023 (void)E;
18024 if (auto *CI = dyn_cast<CmpInst>(VI))
18025 return TTI->getCmpSelInstrCost(
18026 CI->getOpcode(), CI->getOperand(0)->getType(), CI->getType(),
18027 CI->getPredicate(), CostKind,
18029 TTI::getOperandInfo(CI->getOperand(1)), CI);
18030 if (auto *CI = dyn_cast<CastInst>(VI))
18031 return TTI->getCastInstrCost(CI->getOpcode(), CI->getDestTy(),
18032 CI->getSrcTy(),
18033 TTI::getCastContextHint(CI), CostKind, CI);
18034 if (auto *SV = dyn_cast<ShuffleVectorInst>(VI)) {
18035 int Index;
18036 [[maybe_unused]] bool IsExtractSubvectorMask =
18037 SV->isExtractSubvectorMask(Index);
18038 assert(IsExtractSubvectorMask && "Not supported shufflevector usage.");
18039 auto *SubTy = cast<VectorType>(SV->getType());
18040 return TTI->getShuffleCost(
18042 cast<VectorType>(SV->getOperand(0)->getType()), CostKind,
18043 SV->getShuffleMask(), Index, SubTy,
18044 {SV->getOperand(0), SV->getOperand(1)}, SV,
18046 }
18047 // The backend fuses fmul+fadd/fsub pairs in the scalar code.
18049 if (match(VI, m_CombineOr(m_FAdd(m_Value(), m_Value()),
18050 m_FSub(m_Value(), m_Value()))))
18051 FusedCost = GetFMulAddCost(InstructionsState(VI, VI), VI);
18052 else if (match(VI, m_FMul(m_Value(), m_Value())))
18053 FusedCost = GetFusedFMulCost(VI);
18054 if (FusedCost.isValid())
18055 return FusedCost;
18056 return TTI->getArithmeticInstrCost(
18057 VI->getOpcode(), VI->getType(), CostKind,
18058 TTI::getOperandInfo(VI->getOperand(0)),
18059 TTI::getOperandInfo(VI->getOperand(1)),
18060 {VI->getOperand(0), VI->getOperand(1)}, VI, TLI);
18061 };
18062 // Need to clear CommonCost since the final shuffle cost is included into
18063 // vector cost.
18064 auto GetVectorCost = [&, &TTIRef = *TTI](InstructionCost) {
18065 // VecCost is equal to sum of the cost of creating 2 vectors
18066 // and the cost of creating shuffle.
18067 InstructionCost VecCost = 0;
18068 if (TryFindNodeWithEqualOperands()) {
18069 LLVM_DEBUG({
18070 dbgs() << "SLP: diamond match for alternate node found.\n";
18071 E->dump();
18072 });
18073 // No need to add new vector costs here since we're going to reuse
18074 // same main/alternate vector ops, just do different shuffling.
18075 } else if (Instruction::isBinaryOp(E->getOpcode())) {
18076 // Peeled alternate chains fold the operand columns into one pure
18077 // main-opcode chain and one pure alt-opcode chain, followed by a
18078 // single lane-select shuffle; a plain alternate node is a single
18079 // combine. Each combine is priced with the properties of the column
18080 // it folds in; the other operand is the running fold, which stays
18081 // constant while every folded column is constant (such combines
18082 // constant-fold away in codegen) and stays uniform while every
18083 // folded column is uniform.
18084 auto ChainCost = [&](unsigned Opcode) {
18086 TTI::OperandValueInfo RunningInfo =
18087 TTI::getOperandInfo(E->getOperand(0));
18088 for (unsigned Idx : seq<unsigned>(1, E->getNumOperands())) {
18089 TTI::OperandValueInfo ColInfo =
18090 TTI::getOperandInfo(E->getOperand(Idx));
18091 if (!RunningInfo.isConstant() || !ColInfo.isConstant())
18092 Cost += TTIRef.getArithmeticInstrCost(
18093 Opcode, VecTy, CostKind, RunningInfo, ColInfo, {},
18094 Opcode == E->getOpcode() ? E->getMainOp() : E->getAltOp(),
18095 TLI);
18097 if (RunningInfo.isConstant() && ColInfo.isConstant())
18098 Kind = RunningInfo.Kind == TTI::OK_UniformConstantValue &&
18102 else if (RunningInfo.isUniform() && ColInfo.isUniform())
18104 RunningInfo = {Kind, TTI::OP_None};
18105 }
18106 return Cost;
18107 };
18108 VecCost = ChainCost(E->getOpcode()) + ChainCost(E->getAltOpcode());
18109 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
18110 auto *MaskTy = getWidenedType(Builder.getInt1Ty(), VL.size());
18111 TTI::OperandValueInfo Op0Info = TTI::getOperandInfo(E->getOperand(0));
18112 TTI::OperandValueInfo Op1Info = TTI::getOperandInfo(E->getOperand(1));
18113 VecCost = TTIRef.getCmpSelInstrCost(E->getOpcode(), VecTy, MaskTy,
18114 CI0->getPredicate(), CostKind,
18115 Op0Info, Op1Info, VL0);
18116 VecCost += TTIRef.getCmpSelInstrCost(
18117 E->getOpcode(), VecTy, MaskTy,
18118 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, Op0Info,
18119 Op1Info, E->getAltOp());
18120 } else {
18121 Type *SrcTy =
18122 getWidenedType(E->getMainOp()->getOperand(0)->getType(), VL.size());
18124 GetCastContextHint(E->getMainOp()->getOperand(0));
18125 unsigned Opcode0 = E->getOpcode();
18126 unsigned Opcode1 = E->getAltOpcode();
18127 // The casts of the demoted operand must take its signedness into
18128 // account. If any of them cannot do it, the operand is extended back
18129 // first.
18130 if (auto SrcIt = MinBWs.find(getOperandEntry(E, 0));
18131 SrcIt != MinBWs.end()) {
18132 Type *DemotedSrcTy = SrcTy->getWithNewBitWidth(SrcIt->second.first);
18133 std::optional<unsigned> DemotedOpcode0 =
18134 getCastOpcodeForDemotedOperand(Opcode0, SrcIt->second.second);
18135 std::optional<unsigned> DemotedOpcode1 =
18136 getCastOpcodeForDemotedOperand(Opcode1, SrcIt->second.second);
18137 if (DemotedOpcode0 && DemotedOpcode1) {
18138 Opcode0 = *DemotedOpcode0;
18139 Opcode1 = *DemotedOpcode1;
18140 SrcTy = DemotedSrcTy;
18141 } else {
18142 VecCost += TTIRef.getCastInstrCost(
18143 SrcIt->second.second ? Instruction::SExt : Instruction::ZExt,
18144 SrcTy, DemotedSrcTy, CCH, CostKind);
18145 }
18146 }
18147 if (SrcTy->isIntOrIntVectorTy() && ScalarTy->isIntegerTy()) {
18148 unsigned BWSz = DL->getTypeSizeInBits(ScalarTy);
18149 unsigned SrcBWSz = DL->getTypeSizeInBits(SrcTy->getScalarType());
18150 if (BWSz <= SrcBWSz) {
18151 if (BWSz < SrcBWSz)
18152 VecCost += TTIRef.getCastInstrCost(Instruction::Trunc, VecTy,
18153 SrcTy, CCH, CostKind);
18154 LLVM_DEBUG({
18155 dbgs()
18156 << "SLP: alternate extension, which should be truncated.\n";
18157 E->dump();
18158 });
18159 return VecCost;
18160 }
18161 }
18162 // Same casts of the demoted operand, no need to shuffle.
18163 if (Opcode0 == Opcode1)
18164 return VecCost +
18165 TTIRef.getCastInstrCost(Opcode0, VecTy, SrcTy, CCH, CostKind);
18166 VecCost += TTIRef.getCastInstrCost(Opcode0, VecTy, SrcTy, CCH, CostKind,
18167 E->getMainOp());
18168 VecCost += TTIRef.getCastInstrCost(Opcode1, VecTy, SrcTy, CCH, CostKind,
18169 E->getAltOp());
18170 }
18171 SmallVector<int> Mask;
18172 E->buildAltOpShuffleMask(
18173 [&](Instruction *I) {
18174 assert(E->getMatchingMainOpOrAltOp(I) &&
18175 "Unexpected main/alternate opcode");
18176 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp(),
18177 *TLI);
18178 },
18179 Mask);
18181 cast<VectorType>(FinalVecTy), CostKind, Mask);
18182 // Patterns like [fadd,fsub] can be combined into a single instruction
18183 // in x86. Reordering them into [fsub,fadd] blocks this pattern. So we
18184 // need to take into account their order when looking for the most used
18185 // order. Linearized chains emit no alternate-ops pattern.
18186 if (E->hasReassocScalars())
18187 return VecCost;
18188 unsigned Opcode0 = E->getOpcode();
18189 unsigned Opcode1 = E->getAltOpcode();
18190 SmallBitVector OpcodeMask(
18191 getAltInstrMask(E->Scalars, ScalarTy, Opcode0, Opcode1));
18192 // If this pattern is supported by the target then we consider the
18193 // order.
18194 if (TTIRef.isLegalAltInstr(cast<VectorType>(VecTy), Opcode0, Opcode1,
18195 OpcodeMask, E->Scalars)) {
18196 InstructionCost AltVecCost =
18197 TTIRef.getAltInstrCost(cast<VectorType>(VecTy), Opcode0, Opcode1,
18198 OpcodeMask, CostKind, E->Scalars);
18199 return AltVecCost < VecCost ? AltVecCost : VecCost;
18200 }
18201 // TODO: Check the reverse order too.
18202 return VecCost;
18203 };
18204 if (Opts.slp_revec && !E->isAltShuffle())
18205 return GetCostDiff(
18206 GetScalarCost, [&](InstructionCost) -> InstructionCost {
18207 // If a group uses mask in order, the shufflevector can be
18208 // eliminated by instcombine. Then the cost is 0.
18210 "Not supported shufflevector usage.");
18211 auto *SV = cast<ShuffleVectorInst>(VL.front());
18212 unsigned SVNumElements =
18213 cast<FixedVectorType>(SV->getOperand(0)->getType())
18214 ->getNumElements();
18215 unsigned GroupSize = SVNumElements / SV->getShuffleMask().size();
18216 for (size_t I = 0, End = VL.size(); I != End; I += GroupSize) {
18217 ArrayRef<Value *> Group = VL.slice(I, GroupSize);
18218 int NextIndex = 0;
18219 if (!all_of(Group, [&](Value *V) {
18221 "Not supported shufflevector usage.");
18222 auto *SV = cast<ShuffleVectorInst>(V);
18223 int Index;
18224 [[maybe_unused]] bool IsExtractSubvectorMask =
18225 SV->isExtractSubvectorMask(Index);
18226 assert(IsExtractSubvectorMask &&
18227 "Not supported shufflevector usage.");
18228 if (NextIndex != Index)
18229 return false;
18230 NextIndex += SV->getShuffleMask().size();
18231 return true;
18232 }))
18233 return getShuffleCost(*TTI,
18235 cast<VectorType>(VecTy), CostKind,
18236 calculateShufflevectorMask(E->Scalars));
18237 }
18238 return TTI::TCC_Free;
18239 });
18240 return GetCostDiffWithPeeled(GetScalarCost, GetVectorCost);
18241 }
18242 case Instruction::Freeze:
18243 return CommonCost;
18244 default:
18245 llvm_unreachable("Unknown instruction");
18246 }
18247}
18248
18249bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
18250 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
18251 << VectorizableTree.size() << " is fully vectorizable .\n");
18252
18253 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
18254 SmallVector<int> Mask;
18255 return TE->isGather() &&
18256 !any_of(TE->Scalars,
18257 [this](Value *V) { return EphValues.contains(V); }) &&
18258 (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
18259 TE->Scalars.size() < Limit ||
18260 matchGatheredExtractedFields(TE->Scalars, *DL) ||
18261 // Nodes with copyable lanes may mix in non-extract lanes, which
18262 // are not representable as a shuffle of the source vector.
18263 (((TE->hasState() &&
18264 TE->getOpcode() == Instruction::ExtractElement &&
18265 !TE->hasCopyableElements()) ||
18267 isFixedVectorShuffle(TE->Scalars, Mask, AC, Cache)) ||
18268 (TE->hasState() && TE->getOpcode() == Instruction::Load &&
18269 !TE->isAltShuffle()) ||
18270 any_of(TE->Scalars, IsaPred<LoadInst>));
18271 };
18272
18273 // We only handle trees of heights 1 and 2.
18274 if (VectorizableTree.size() == 1 &&
18275 (VectorizableTree[0]->State == TreeEntry::Vectorize ||
18276 VectorizableTree[0]->State == TreeEntry::StridedVectorize ||
18277 VectorizableTree[0]->State == TreeEntry::ExpandVectorize ||
18278 VectorizableTree[0]->State == TreeEntry::CompressVectorize ||
18279 VectorizableTree[0]->State == TreeEntry::BlendedLoadVectorize ||
18280 (ForReduction &&
18281 AreVectorizableGathers(VectorizableTree[0].get(),
18282 VectorizableTree[0]->Scalars.size()) &&
18283 VectorizableTree[0]->getVectorFactor() > 2)))
18284 return true;
18285
18286 if (VectorizableTree.size() != 2)
18287 return false;
18288
18289 // Handle splat and all-constants stores. Also try to vectorize tiny trees
18290 // with the second gather nodes if they have less scalar operands rather than
18291 // the initial tree element (may be profitable to shuffle the second gather)
18292 // or they are extractelements, which form shuffle.
18293 if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
18294 AreVectorizableGathers(VectorizableTree[1].get(),
18295 VectorizableTree[0]->Scalars.size()))
18296 return true;
18297
18298 // Gathering cost would be too much for tiny trees.
18299 if (VectorizableTree[0]->isGather() ||
18300 (VectorizableTree[1]->isGather() &&
18301 VectorizableTree[0]->State != TreeEntry::ScatterVectorize &&
18302 VectorizableTree[0]->State != TreeEntry::StridedVectorize &&
18303 VectorizableTree[0]->State != TreeEntry::ExpandVectorize &&
18304 VectorizableTree[0]->State != TreeEntry::CompressVectorize &&
18305 VectorizableTree[0]->State != TreeEntry::BlendedLoadVectorize))
18306 return false;
18307
18308 return true;
18309}
18310
18311bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
18312 if (!DebugCounter::shouldExecute(VectorizedGraphs))
18313 return true;
18314
18315 // If we are revectorizing reduction, it may result in same reduction pattern
18316 // with shuffles as leaves of the reduction. Prevent SLP from revectorizing
18317 // that shuffle pattern.
18318 if (Opts.slp_revec && ForReduction && VectorizableTree.size() == 3 &&
18319 VectorizableTree[0]->State == TreeEntry::Vectorize &&
18320 VectorizableTree[0]->getOpcode() == Instruction::ShuffleVector &&
18321 VectorizableTree[1]->isGather() &&
18322 isSplat(VectorizableTree[1]->Scalars) &&
18323 VectorizableTree[2]->isGather() &&
18324 allConstant(VectorizableTree[2]->Scalars)) {
18325 LLVM_DEBUG(dbgs() << "SLP: Rejecting reduction tree with 3 nodes(shuffle "
18326 "as root and remaining are gather nodes).\n");
18327 return true;
18328 }
18329
18330 // Graph is empty - do nothing.
18331 if (VectorizableTree.empty()) {
18332 assert(ExternalUses.empty() && "We shouldn't have any external users");
18333
18334 return true;
18335 }
18336
18337 // FIXME: support buildvector of the gather nodes with struct types.
18338 if (any_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
18339 return TE->isGather() &&
18340 isa<StructType>(TE->Scalars.front()->getType());
18341 })) {
18342 LLVM_DEBUG(
18343 dbgs() << "SLP: rejecting tree with buildvector struct values of size "
18344 << VectorizableTree.size() << ".\n");
18345 return true;
18346 }
18347
18348 // Cache values from the root node and the cost-threshold options to avoid
18349 // re-querying them inside hot predicates below.
18350 const unsigned TreeSize = VectorizableTree.size();
18351 const TreeEntry &Front = getRootNode();
18352 const bool FrontIsGather = Front.isGather();
18353 const bool FrontHasState = Front.hasState();
18354 const unsigned FrontOpcode = FrontHasState ? Front.getOpcode() : 0u;
18355 const bool ThresholdSet = Opts.slp_threshold.has_value();
18356 const bool ThresholdNonNegative = getCostThreshold() >= 0;
18357
18358 constexpr unsigned Limit = 4;
18359 constexpr unsigned LargeTree = 20;
18360 constexpr unsigned LimitTreeSize = 36;
18361
18362 // The remaining size-1/size-<=MinTreeSize early bail-outs only apply to
18363 // non-reduction trees; group them under a single guard to avoid 3 separate
18364 // !ForReduction short-circuits when reducing.
18365 if (!ForReduction) {
18366 // Single gather node: bail out for ExtractElement or any node containing a
18367 // real Instruction scalar.
18368 if (TreeSize == 1 && FrontIsGather) {
18369 if (FrontHasState && FrontOpcode == Instruction::ExtractElement)
18370 return true;
18371 if (any_of(Front.Scalars, IsaPred<Instruction>))
18372 return true;
18373 }
18374 if (TreeSize <= Opts.slp_min_tree_size &&
18375 all_of(VectorizableTree, [](const std::unique_ptr<TreeEntry> &TE) {
18376 return TE->isGather() || TE->State == TreeEntry::SplitVectorize;
18377 }))
18378 return true;
18379 if (TreeSize == 1 && getCostThreshold() < 0 && FrontHasState &&
18380 FrontOpcode == Instruction::ExtractElement &&
18381 (Front.getVectorFactor() == 2 ||
18382 all_of(make_isa_range<Instruction>(Front.Scalars),
18383 [&](Instruction *I) {
18384 return !areAllUsersVectorized(I, UserIgnoreList);
18385 })))
18386 return true;
18387 }
18388 // No need to vectorize inserts of gathered values.
18389 if (TreeSize == 2 && isa<InsertElementInst>(Front.Scalars[0]) &&
18390 VectorizableTree[1]->isGather() &&
18391 (VectorizableTree[1]->getVectorFactor() <= 2 ||
18392 !(isSplat(VectorizableTree[1]->Scalars) ||
18393 allConstant(VectorizableTree[1]->Scalars))))
18394 return true;
18395
18396 // The tree with only 3 nodes, where 2 last are gathers/buildvectors, not
18397 // profitable for vectorization.
18398 if (TreeSize == 3 && getCostThreshold() == 0 &&
18399 (!ForReduction || Front.getVectorFactor() <= 2) &&
18400 all_of(ArrayRef(VectorizableTree).drop_front(),
18401 [&](const std::unique_ptr<TreeEntry> &TE) {
18402 return TE->isGather() && TE->getVectorFactor() <= Limit &&
18403 !all_of(
18404 TE->Scalars,
18406 }))
18407 return true;
18408
18409 // All remaining bail-out heuristics require !ForReduction. Group them under
18410 // a single guard so reduction trees skip them with one branch instead of one
18411 // per check.
18412 if (!ForReduction) {
18413 // The single vectorized node, fed by the buildvectors, only repacks the
18414 // scalars, the gathers and the extracts are paid for the one vector
18415 // instruction. The vector call replaces the several expensive scalar ones,
18416 // while the store merges the lanes instead of extracting them back.
18417 if (TreeSize > 1 && ThresholdNonNegative &&
18418 (!FrontHasState || (FrontOpcode != Instruction::Call &&
18419 FrontOpcode != Instruction::Store)) &&
18420 count_if(VectorizableTree,
18421 [](const std::unique_ptr<TreeEntry> &TE) {
18422 return TE->State == TreeEntry::Vectorize;
18423 }) == 1 &&
18424 all_of(VectorizableTree, [](const std::unique_ptr<TreeEntry> &TE) {
18425 return TE->State == TreeEntry::Vectorize ||
18426 (TE->isGather() && !isSplat(TE->Scalars) &&
18427 !all_of(TE->Scalars,
18429 }))
18430 return true;
18431
18432 // If the graph includes only PHI nodes and gathers, it is defnitely not
18433 // profitable for the vectorization, we can skip it, if the cost threshold
18434 // is default. The cost of vectorized PHI nodes is almost always 0 + the
18435 // cost of gathers/buildvectors.
18436 if (!ThresholdSet &&
18437 all_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
18438 const bool IsGather = TE->isGather();
18439 const bool HasState = TE->hasState();
18440 const unsigned Op = HasState ? TE->getOpcode() : 0u;
18441 if (IsGather && (!HasState || Op != Instruction::ExtractElement) &&
18442 static_cast<unsigned>(
18443 count_if(TE->Scalars, IsaPred<ExtractElementInst>)) <= Limit)
18444 return true;
18445 return HasState && Op == Instruction::PHI;
18446 }))
18447 return true;
18448
18449 // Do not vectorize small tree of phis only, if all vector phis are also
18450 // gathered.
18451 if (ThresholdSet && TreeSize <= Limit) {
18452 bool HasVectorPhi = false;
18453 auto Compatible = [&](const std::unique_ptr<TreeEntry> &TE) {
18454 const bool IsGather = TE->isGather();
18455 const bool HasState = TE->hasState();
18456 const unsigned Op = HasState ? TE->getOpcode() : 0u;
18457 if (IsGather && (!HasState || Op != Instruction::ExtractElement) &&
18458 static_cast<unsigned>(
18459 count_if(TE->Scalars, IsaPred<ExtractElementInst>)) <= Limit)
18460 return true;
18461 if (!HasState)
18462 return false;
18463 if (Op == Instruction::InsertElement)
18464 return true;
18465 if (Op != Instruction::PHI)
18466 return false;
18467 if (TE->State == TreeEntry::Vectorize)
18468 HasVectorPhi = true;
18469 return all_of(TE->Scalars, [&](Value *V) {
18470 return isa<PoisonValue>(V) || MustGather.contains(V);
18471 });
18472 };
18473 if (all_of(VectorizableTree, Compatible) && HasVectorPhi)
18474 return true;
18475 }
18476
18477 // PHI nodes only and gathers cannot be vectorized, skip.
18478 if (ThresholdNonNegative) {
18479 const bool IsLargeTree = TreeSize >= LargeTree;
18480 bool HasSingleLoad = false;
18481 if (all_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
18482 const bool IsGather = TE->isGather();
18483 const bool HasState = TE->hasState();
18484 const unsigned Op = HasState ? TE->getOpcode() : 0u;
18485 // HasSingleLoad/PrevLoad are only consulted in the
18486 // IsLargeTree branch; skip the bookkeeping otherwise.
18487 if (IsLargeTree) {
18488 const bool PrevLoad = HasSingleLoad;
18489 HasSingleLoad |=
18490 HasState && !IsGather &&
18491 (Op == Instruction::Load || TE->hasCopyableElements()) &&
18492 (TE->getVectorFactor() > 2 || TE->ReorderIndices.empty());
18493 if (HasState) {
18494 if (Op == Instruction::PHI)
18495 return true;
18496 if (TE->getVectorFactor() <= Limit &&
18497 (Op == Instruction::Store ||
18498 (Op == Instruction::Load && !PrevLoad)))
18499 return true;
18500 }
18501 } else if (HasState && Op == Instruction::PHI) {
18502 return true;
18503 }
18504 return IsGather && (!HasState || Op != Instruction::ExtractElement);
18505 }))
18506 return true;
18507
18508 // Single non-phi vector node - skip the tree.
18509 if (TreeSize >= 5 && Front.getVectorFactor() <= 2 &&
18510 Front.Scalars.front()->getType()->isIntegerTy()) {
18511 bool VectorNodeFound = false;
18512 bool AnyNonConst = false;
18513 if (all_of(VectorizableTree,
18514 [&](const std::unique_ptr<TreeEntry> &TE) {
18515 if (TE->State == TreeEntry::Vectorize && TE->hasState()) {
18516 const unsigned Op = TE->getOpcode();
18517 if (Op == Instruction::PHI ||
18518 !TE->ReorderIndices.empty())
18519 return true;
18520 if (VectorNodeFound)
18521 return false;
18522 VectorNodeFound = true;
18523 return true;
18524 }
18525 // Once AnyNonConst is true, skip the O(n) allConstant
18526 // walk for subsequent entries.
18527 if (!AnyNonConst)
18528 AnyNonConst = !allConstant(TE->Scalars);
18529 return TE->isGather() ||
18530 TE->State == TreeEntry::SplitVectorize;
18531 }) &&
18532 AnyNonConst)
18533 return true;
18534 }
18535 }
18536
18537 // Common predicate for "phis, buildvectors, split nodes and small nodes
18538 // with reuses" used by the two checks below. Cheap checks are evaluated
18539 // before expensive Scalars walks.
18540 auto IsBenignNode = [&](const TreeEntry &TE) {
18541 if (TE.State == TreeEntry::SplitVectorize)
18542 return true;
18543 const bool IsGather = TE.isGather();
18544 const bool HasState = TE.hasState();
18545 if (HasState) {
18546 const unsigned Op = TE.getOpcode();
18547 if (Op == Instruction::PHI)
18548 return true;
18549 const unsigned ScalarsSize = TE.Scalars.size();
18550 if (TE.Idx == 0 && ScalarsSize == 2 && Op == Instruction::ICmp &&
18551 TreeSize > LimitTreeSize)
18552 return true;
18553 if (ScalarsSize == 2 &&
18554 (!TE.ReuseShuffleIndices.empty() || !TE.ReorderIndices.empty() ||
18555 TE.isAltShuffle()))
18556 return true;
18557 if (TE.hasCopyableElements() &&
18558 static_cast<unsigned>(count_if(
18559 TE.Scalars, IsaPred<PHINode, Constant>)) >= ScalarsSize / 2)
18560 return true;
18561 }
18562 return IsGather && none_of(TE.Scalars, IsaPred<ExtractElementInst>);
18563 };
18564
18565 // If the tree contains only phis, buildvectors, split nodes and
18566 // small nodes with reuses, we can skip it.
18567 if (!ThresholdSet) {
18568 SmallVector<const TreeEntry *> StoreLoadNodes;
18569 unsigned NumGathers = 0;
18570 if (all_of(VectorizableTree,
18571 [&](const std::unique_ptr<TreeEntry> &TE) {
18572 const bool IsGather = TE->isGather();
18573 if (!IsGather && TE->hasState()) {
18574 const unsigned Op = TE->getOpcode();
18575 if (Op == Instruction::Load || Op == Instruction::Store) {
18576 StoreLoadNodes.push_back(TE.get());
18577 return true;
18578 }
18579 }
18580 if (IsGather)
18581 ++NumGathers;
18582 return IsBenignNode(*TE);
18583 }) &&
18584 (StoreLoadNodes.empty() ||
18585 (TreeSize > LimitTreeSize * StoreLoadNodes.size() &&
18586 (NumGathers > 0 ||
18587 none_of(StoreLoadNodes, [&](const TreeEntry *TE) {
18588 return TE->getOpcode() == Instruction::Store ||
18589 all_of(make_isa_range<LoadInst>(TE->Scalars),
18590 [&](LoadInst *LI) {
18591 return areAllUsersVectorized(LI);
18592 });
18593 })))))
18594 return true;
18595 }
18596
18597 // If the tree contains only phis, buildvectors, split nodes and
18598 // small nodes with reuses, we can skip it.
18599 if (ThresholdNonNegative && TreeSize > LimitTreeSize) {
18600 const TreeEntry *VectorNode = nullptr;
18601 if (all_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
18602 if (!TE->isGather() && TE->hasState() &&
18603 TE->State != TreeEntry::SplitVectorize &&
18604 TE->getOpcode() != Instruction::PHI) {
18605 if (VectorNode)
18606 return false;
18607 VectorNode = TE.get();
18608 return true;
18609 }
18610 return IsBenignNode(*TE);
18611 }))
18612 return true;
18613 }
18614
18615 // If the tree contains only buildvector, 2 non-buildvectors (with root
18616 // user tree node) and other buildvectors, we can skip it.
18617 if (ThresholdSet && TreeSize >= Limit &&
18618 Front.State == TreeEntry::SplitVectorize &&
18619 count_if(ArrayRef(VectorizableTree).drop_front(),
18620 [](const std::unique_ptr<TreeEntry> &TE) {
18621 return !TE->isGather() && TE->UserTreeIndex.UserTE &&
18622 TE->UserTreeIndex.UserTE->Idx == 0;
18623 }) == 2)
18624 return true;
18625
18626 // If the tree contains only vectorization of the phi node from the
18627 // buildvector - skip it.
18628 if (ThresholdSet && TreeSize > 2 && Front.State == TreeEntry::Vectorize &&
18629 FrontOpcode == Instruction::InsertElement &&
18630 VectorizableTree[1]->State == TreeEntry::Vectorize &&
18631 VectorizableTree[1]->getOpcode() == Instruction::PHI &&
18632 all_of(ArrayRef(VectorizableTree).drop_front(2),
18633 [](const std::unique_ptr<TreeEntry> &TE) {
18634 return TE->isGather();
18635 }))
18636 return true;
18637 }
18638
18639 // We can vectorize the tree if its size is greater than or equal to the
18640 // minimum size specified by the MinTreeSize command line option.
18641 if (TreeSize >= Opts.slp_min_tree_size)
18642 return false;
18643
18644 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
18645 // can vectorize it if we can prove it fully vectorizable.
18646 if (isFullyVectorizableTinyTree(ForReduction))
18647 return false;
18648
18649 // Check if any of the gather node forms an insertelement buildvector
18650 // somewhere. TreeSize >= 1 is guaranteed, so the multi-node case reduces to
18651 // a simple TreeSize > 1 short-circuit.
18652 // A gather with copyable lanes is not a real instruction node; do not let
18653 // its state qualify it as a buildvector-forming node.
18654 const bool IsAllowedSingleBVNode =
18655 TreeSize > 1 ||
18656 (FrontHasState && !Front.isAltShuffle() && !Front.hasCopyableElements() &&
18657 FrontOpcode != Instruction::PHI &&
18658 FrontOpcode != Instruction::GetElementPtr &&
18659 allSameBlock(Front.Scalars));
18660 if (any_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
18661 return TE->isGather() && all_of(TE->Scalars, [&](Value *V) {
18662 return isa<ExtractElementInst, Constant>(V) ||
18663 (IsAllowedSingleBVNode &&
18664 !V->hasNUsesOrMore(UsesLimit) &&
18665 any_of(V->users(), IsaPred<InsertElementInst>));
18666 });
18667 }))
18668 return false;
18669
18670 const TreeEntry &Back = *VectorizableTree.back();
18671 if (Back.isGather() && Back.hasState() && Back.isAltShuffle()) {
18672 const unsigned BackVF = Back.getVectorFactor();
18673 if (BackVF > 2 && allSameBlock(Back.Scalars) &&
18674 !Back.Scalars.front()->getType()->isVectorTy() &&
18675 TTI->getScalarizationOverhead(
18677 getWidenedType(Back.Scalars.front()->getType(), BackVF)),
18678 APInt::getAllOnes(BackVF),
18679 /*Insert=*/true, /*Extract=*/false, CostKind) > -getCostThreshold())
18680 return false;
18681 }
18682
18683 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
18684 // vectorizable.
18685 return true;
18686}
18687
18690 constexpr unsigned SmallTree = 3;
18691 if (getRootNode().isNonPowOf2Vec() &&
18692 getCanonicalGraphSize() <= SmallTree &&
18693 count_if(ArrayRef(VectorizableTree).drop_front(getCanonicalGraphSize()),
18694 [](const std::unique_ptr<TreeEntry> &TE) {
18695 return TE->isGather() && TE->hasState() &&
18696 TE->getOpcode() == Instruction::Load &&
18697 !allSameBlock(TE->Scalars);
18698 }) == 1)
18699 return true;
18700 return false;
18701 }
18702 bool Res = false;
18703 for (unsigned Idx : seq<unsigned>(getTreeSize())) {
18704 TreeEntry &E = *VectorizableTree[Idx];
18705 if (E.State == TreeEntry::SplitVectorize)
18706 return false;
18707 if (!E.isGather())
18708 continue;
18709 if ((E.hasState() && E.getOpcode() != Instruction::Load) ||
18710 (!E.hasState() &&
18712 (isa<ExtractElementInst>(E.Scalars.front()) &&
18713 getSameOpcode(ArrayRef(E.Scalars).drop_front(), *TLI).valid()))
18714 return false;
18715 if (isSplat(E.Scalars) || allConstant(E.Scalars))
18716 continue;
18717 Res = true;
18718 }
18719 return Res;
18720}
18721
18723 // Walk the vectorizable tree from the root towards its leaves, tracking
18724 // which vectorized operand values would be live across each tree edge
18725 // (i.e. between the last instruction of an operand entry and the last
18726 // instruction of its user entry). When the live range crosses a call
18727 // instruction that is not part of the vectorized tree, query TTI for the
18728 // cost of keeping the value live across it (for example, if spills and
18729 // fills are required).
18730
18731 const TreeEntry *Root = &getRootNode();
18732 if (Root->isGather())
18733 return 0;
18734
18735 InstructionCost Cost = 0;
18737 EntriesToOperands;
18738 SmallDenseMap<const TreeEntry *, Instruction *> EntriesToLastInstruction;
18739 SmallPtrSet<const Instruction *, 8> LastInstructions;
18740 SmallPtrSet<const TreeEntry *, 8> ScalarOrPseudoEntries;
18741 for (const auto &TEPtr : VectorizableTree) {
18742 if (TEPtr->CombinedOp == TreeEntry::ReducedBitcast ||
18743 TEPtr->CombinedOp == TreeEntry::ReducedBitcastBSwap ||
18744 TEPtr->CombinedOp == TreeEntry::ReducedBitcastLoads ||
18745 TEPtr->CombinedOp == TreeEntry::ReducedBitcastBSwapLoads ||
18746 TEPtr->CombinedOp == TreeEntry::ReducedBitPack ||
18747 TEPtr->CombinedOp == TreeEntry::ReducedCmpBitcast) {
18748 ScalarOrPseudoEntries.insert(TEPtr.get());
18749 continue;
18750 }
18751 if (!TEPtr->isGather()) {
18752 Instruction *LastInst = &getLastInstructionInBundle(TEPtr.get());
18753 EntriesToLastInstruction.try_emplace(TEPtr.get(), LastInst);
18754 LastInstructions.insert(LastInst);
18755 }
18756 if (TEPtr->UserTreeIndex)
18757 EntriesToOperands[TEPtr->UserTreeIndex.UserTE].push_back(TEPtr.get());
18758 }
18759
18760 // Cache NoCallIntrinsicOrDoesNotReturn results - the same intrinsic call may
18761 // be queried many times during the spill cost scan, and each computation
18762 // involves two potentially expensive TTI virtual calls.
18763 SmallDenseMap<const IntrinsicInst *, bool> NoCallIntrinsicCache;
18764 auto NoCallIntrinsicOrDoesNotReturn =
18765 [this, &NoCallIntrinsicCache](const Instruction *I) {
18766 const auto *CB = dyn_cast<CallBase>(I);
18767 if (!CB)
18768 return false;
18769 if (CB->doesNotReturn())
18770 return true;
18771 const auto *II = dyn_cast<IntrinsicInst>(CB);
18772 if (!II)
18773 return false;
18774 if (II->isAssumeLikeIntrinsic())
18775 return true;
18776 auto [It, Inserted] = NoCallIntrinsicCache.try_emplace(II);
18777 if (!Inserted)
18778 return It->second;
18779 IntrinsicCostAttributes ICA(II->getIntrinsicID(), *II);
18780 InstructionCost IntrCost = TTI->getIntrinsicInstrCost(ICA, CostKind);
18781 InstructionCost CallCost = TTI->getCallInstrCost(
18782 nullptr, II->getType(), ICA.getArgTypes(), CostKind);
18783 bool Res = IntrCost < CallCost;
18784 It->second = Res;
18785 return Res;
18786 };
18787
18788 // Maps last instruction in the entry to the last instruction for the one of
18789 // operand entries and the flag. If the flag is true, there are no calls in
18790 // between these instructions.
18792 CheckedInstructions;
18793 unsigned Budget = 0;
18794 const unsigned BudgetLimit =
18795 Opts.slp_schedule_budget / VectorizableTree.size();
18796 auto CheckForNonVecCallsInSameBlock = [&](Instruction *First,
18797 const Instruction *Last) {
18798 assert(First->getParent() == Last->getParent() &&
18799 "Expected instructions in same block.");
18800 if (auto It = CheckedInstructions.find(Last);
18801 It != CheckedInstructions.end()) {
18802 const Instruction *Checked = It->second.getPointer();
18803 const bool NoCallsInCachedRange = It->second.getInt() != 0;
18804 if (Checked == First)
18805 return NoCallsInCachedRange;
18806 if (Checked->comesBefore(First))
18807 // In every cached state (full clean scan, call-found, or
18808 // budget-exhausted) the region strictly above `Checked` up to `Last`
18809 // was inspected and proved call-free. Since `First` is above
18810 // `Checked`, the queried range [First, Last] is contained in that
18811 // call-free region, regardless of whether bit is 0 or 1.
18812 return true;
18813 Last = Checked;
18814 } else if (Last == First || Last->comesBefore(First)) {
18815 // Empty range.
18816 return true;
18817 }
18819 ++First->getIterator().getReverse(),
18820 PrevInstIt =
18821 Last->getIterator().getReverse();
18822 SmallVector<const Instruction *> LastInstsInRange;
18823 while (InstIt != PrevInstIt && Budget <= BudgetLimit) {
18824 // Debug information does not impact spill cost.
18825 // Vectorized calls, represented as vector intrinsics, do not impact spill
18826 // cost.
18827 if (const auto *CB = dyn_cast<CallBase>(&*PrevInstIt);
18828 CB && !NoCallIntrinsicOrDoesNotReturn(CB) && !isVectorized(CB)) {
18829 for (const Instruction *LastInst : LastInstsInRange)
18830 CheckedInstructions.try_emplace(LastInst, &*PrevInstIt, 0);
18831 return false;
18832 }
18833 if (LastInstructions.contains(&*PrevInstIt))
18834 LastInstsInRange.push_back(&*PrevInstIt);
18835
18836 ++PrevInstIt;
18837 ++Budget;
18838 }
18839 // If we reached the scan's lower bound (`PrevInstIt == InstIt`) then the
18840 // whole [First, Last] range was inspected and found call-free, even if
18841 // Budget just overflowed at the very last step; do not mislabel such a
18842 // completed scan as "has call".
18843 const bool Completed = PrevInstIt == InstIt;
18844 const bool NoCallsInRange = Completed || Budget <= BudgetLimit;
18845 for (const Instruction *LastInst : LastInstsInRange)
18846 CheckedInstructions.try_emplace(
18847 LastInst, Completed ? First : &*PrevInstIt, NoCallsInRange ? 1 : 0);
18848 return NoCallsInRange;
18849 };
18850 // The spill/reload is executed once per execution of the call, so the
18851 // cost is scaled by the trip count of the loop containing the call, even
18852 // for hoisted loop-invariant values defined outside of it.
18853 auto GetSpillScale = [&](const BasicBlock *BB) {
18854 return getLoopNestScale(LI->getLoopFor(BB));
18855 };
18856 auto AddCosts = [&](const TreeEntry *Op, uint64_t Scale) {
18857 if (ScalarOrPseudoEntries.contains(Op))
18858 return;
18859 Type *ScalarTy = Op->Scalars.front()->getType();
18860 auto It = MinBWs.find(Op);
18861 if (It != MinBWs.end())
18862 ScalarTy = IntegerType::get(ScalarTy->getContext(), It->second.first);
18863 auto *VecTy = getWidenedType(ScalarTy, Op->getVectorFactor());
18864 InstructionCost KeepLiveCost = TTI->getCostOfKeepingLiveOverCall(VecTy);
18865 KeepLiveCost *= Scale;
18866 Cost += KeepLiveCost;
18867 if (ScalarTy->isVectorTy()) {
18868 // Handle revec dead vector instructions.
18869 Cost -= Op->Scalars.size() * TTI->getCostOfKeepingLiveOverCall(ScalarTy) *
18870 Scale;
18871 }
18872 };
18873 // Memoize the relationship between blocks, i.e. the spill scale if every
18874 // path between the blocks crosses a non-vectorized call, 0 if there is (at
18875 // least one) call-free path. This allows to skip the analysis of the same
18876 // block paths multiple times.
18878 ParentOpParentToPreds;
18879 // Memoize whether a basic block contains a non-terminator no-return call.
18880 // Such blocks are dead-end paths in normal control flow (execution does not
18881 // exit them past the no-return call), so the block is excluded from the
18882 // spill cost analysis. Terminator no-return calls (invoke/callbr) are not
18883 // block-killing because they still have live CFG successors (e.g. the
18884 // unwind destination of an invoke).
18885 SmallDenseMap<const BasicBlock *, bool> BlockHasNoReturnCallCache;
18886 auto BlockHasNoReturnCall = [&](const BasicBlock *BB) {
18887 auto [It, Inserted] = BlockHasNoReturnCallCache.try_emplace(BB, false);
18888 if (!Inserted)
18889 return It->second;
18890 for (const CallBase &CB : make_isa_range<CallBase>(*BB)) {
18891 if (CB.doesNotReturn() && !CB.isTerminator()) {
18892 It->second = true;
18893 return true;
18894 }
18895 }
18896 return false;
18897 };
18898 // Memoize whether a loop's body (all blocks of the loop, including
18899 // sub-loops) contains any non-vec call.
18900 SmallDenseMap<const Loop *, bool> LoopBodyHasNonVecCall;
18901 auto LoopBodyHasCall = [&](const Loop *L) {
18902 if (auto It = LoopBodyHasNonVecCall.find(L);
18903 It != LoopBodyHasNonVecCall.end())
18904 return It->second;
18905 auto IsNotCatchSwitch = [](BasicBlock *BB) {
18906 return !isa<CatchSwitchInst>(BB->getTerminator());
18907 };
18908 for (BasicBlock *BB : make_filter_range(L->blocks(), IsNotCatchSwitch)) {
18909 // Blocks containing a no-return call are dead-end paths and never
18910 // actually flow back through the loop's back-edge, so their calls do
18911 // not keep loop-invariant vector values live across calls.
18912 if (BlockHasNoReturnCall(BB))
18913 continue;
18914 for (const Instruction &I : *BB) {
18915 const auto *CB = dyn_cast<CallBase>(&I);
18916 if (!CB || NoCallIntrinsicOrDoesNotReturn(CB) || isVectorized(CB))
18917 continue;
18918 LoopBodyHasNonVecCall.try_emplace(L, true);
18919 return true;
18920 }
18921 }
18922 LoopBodyHasNonVecCall.try_emplace(L, false);
18923 return false;
18924 };
18925 auto GetLoopInvariantSpillRegion = [&](BasicBlock *UseBB,
18926 BasicBlock *DefBB) -> const Loop * {
18927 // If DefBB is outside a loop containing UseBB, the value is live across
18928 // iterations of that loop. A non-vectorized call in the loop may therefore
18929 // require a spill even when the entry path from DefBB to UseBB is
18930 // call-free. Return the outermost such loop containing a relevant call so
18931 // its execution scale can be used to cost the spill.
18932 const Loop *L = LI->getLoopFor(UseBB);
18933 const Loop *Outermost = nullptr;
18934 while (L && !L->contains(DefBB)) {
18935 Outermost = L;
18936 L = L->getParentLoop();
18937 }
18938 return (Outermost && LoopBodyHasCall(Outermost)) ? Outermost : nullptr;
18939 };
18940 auto CheckPredecessors = [&](BasicBlock *Root, BasicBlock *Pred,
18941 BasicBlock *OpParent) {
18942 auto Key = std::make_pair(Root, OpParent);
18943 if (auto It = ParentOpParentToPreds.find(Key);
18944 It != ParentOpParentToPreds.end())
18945 return It->second;
18946 uint64_t Res = 0;
18947 scope_exit Cleanup([&]() { ParentOpParentToPreds.try_emplace(Key, Res); });
18948 if (const auto *L = GetLoopInvariantSpillRegion(Root, OpParent)) {
18949 Res = getLoopNestScale(L);
18950 return Res;
18951 }
18953 if (Pred)
18954 Worklist.push_back(Pred);
18955 else
18956 Worklist.append(pred_begin(Root), pred_end(Root));
18958 // With "at least one call-free path" semantics we can only reliably
18959 // memoize the exact (Root, OpParent) query. Pairs for intermediate
18960 // blocks that were visited during the BFS are not necessarily
18961 // call-free-reachable to OpParent themselves - we may have reached
18962 // OpParent through a *sibling* path that bypassed them.
18963 // We return 0 (no spill cost) if at least one backward path from
18964 // some predecessor of Root back to OpParent is call-free. Only when
18965 // *every* such path goes through a non-vec call do we charge the spill
18966 // cost: only then is it actually necessary to keep the vectorized value
18967 // live across a call and therefore spill/reload it.
18968 //
18969 // A BB is only explored further (its predecessors added to the worklist)
18970 // when it is itself call-free and not strictly dominated by Root (blocks
18971 // dominated by Root are only reachable via loop back-edges - they sit
18972 // *after* Root in forward execution and must not be counted).
18973 //
18974 // If we ever pop OpParent from the worklist, we have reached it through
18975 // a chain of call-free, non-dominated blocks: a call-free path exists
18976 // and we return 0. If the worklist is exhausted or the scan budget
18977 // overflows without reaching OpParent, no call-free path was found and
18978 // we return the scale of the loop containing Root, so the caller charges
18979 // the spill cost.
18980 while (!Worklist.empty()) {
18981 BasicBlock *BB = Worklist.pop_back_val();
18982 if (BB == OpParent)
18983 return Res;
18984 if (!Visited.insert(BB).second)
18985 continue;
18986 // Blocks strictly dominated by Root are reached only *after* Root in
18987 // forward execution (via loop back-edges); skip them and their
18988 // dominated predecessors.
18989 if (DT->properlyDominates(Root, BB))
18990 continue;
18991 // A block containing a no-return call cannot reach Root via the
18992 // forward edge being analyzed: execution does not continue past the
18993 // no-return call, so the BB -> ... -> Root path is dead. Drop the
18994 // block from the analysis without following its predecessors.
18995 if (BlockHasNoReturnCall(BB))
18996 continue;
18997 auto Pair = std::make_pair(BB, OpParent);
18998 if (auto It = ParentOpParentToPreds.find(Pair);
18999 It != ParentOpParentToPreds.end()) {
19000 // BB is known to reach OpParent via a call-free path.
19001 if (It->second == 0)
19002 return Res;
19003 // BB is known to be blocked from OpParent by calls; keep checking
19004 // other paths.
19005 continue;
19006 }
19007 unsigned BlockSize = BB->size();
19008 if (BlockSize > static_cast<unsigned>(Opts.slp_schedule_budget))
19009 continue;
19010 Budget += BlockSize;
19011 if (Budget > BudgetLimit)
19012 break;
19013 if (!isa<CatchSwitchInst>(BB->getTerminator()) &&
19014 !CheckForNonVecCallsInSameBlock(&*BB->getFirstNonPHIOrAlloca(),
19015 BB->getTerminator()))
19016 continue;
19017 Worklist.append(pred_begin(BB), pred_end(BB));
19018 }
19019 Res = GetSpillScale(Root);
19020 return Res;
19021 };
19022 SmallVector<const TreeEntry *> LiveEntries(1, Root);
19023 auto FindNonScalarParentEntry = [&](const TreeEntry *E) -> const TreeEntry * {
19024 assert(ScalarOrPseudoEntries.contains(E) &&
19025 "Expected scalar or pseudo entry.");
19026 const TreeEntry *Entry = E;
19027 while (Entry->UserTreeIndex) {
19028 Entry = Entry->UserTreeIndex.UserTE;
19029 if (!ScalarOrPseudoEntries.contains(Entry))
19030 return Entry;
19031 }
19032 return nullptr;
19033 };
19034 auto IsCoveredByMatchingVectorEntry = [&](const TreeEntry *Gather,
19035 const Loop *SpillLoop) -> bool {
19036 assert(Gather->isGather() && "Expected a gather/buildvector entry.");
19037
19038 Value *LookupValue = nullptr;
19039 if (Gather->hasState()) {
19040 LookupValue = Gather->getMainOp();
19041 } else {
19042 auto *It = find_if_not(Gather->Scalars, IsaPred<UndefValue>);
19043 if (It == Gather->Scalars.end())
19044 return false;
19045 LookupValue = *It;
19046 }
19047
19048 // Find the real vector entry reused by this perfect-diamond gather.
19049 const TreeEntry *SameTE =
19050 getSameValuesTreeEntry(LookupValue, Gather->Scalars, /*SameVF=*/true);
19051 if (!SameTE || SameTE == Gather || SameTE->State != TreeEntry::Vectorize ||
19052 ScalarOrPseudoEntries.contains(SameTE) || !SameTE->UserTreeIndex)
19053 return false;
19054
19055 // A reordered or reuse-shuffled match materializes a separate shuffled
19056 // vector that is itself live across the call; only an exact match reuses
19057 // the same vector value.
19058 if (!SameTE->ReorderIndices.empty() || !SameTE->ReuseShuffleIndices.empty())
19059 return false;
19060
19061 // Only permit an ordinary vectorized user.
19062 const TreeEntry *UserTE = SameTE->UserTreeIndex.UserTE;
19063 assert(UserTE && "Expected a user tree entry.");
19064 if (UserTE->State != TreeEntry::Vectorize ||
19065 ScalarOrPseudoEntries.contains(UserTE) ||
19066 UserTE->getOpcode() == Instruction::PHI)
19067 return false;
19068
19069 // Different demoted bitwidth would make the two edge costs unequal.
19070 if (MinBWs.lookup(SameTE).first != MinBWs.lookup(Gather).first)
19071 return false;
19072
19073 // The spill walk does not descend through gather entries; if any ancestor
19074 // of the matching entry's user is a gather or a combined scalar/pseudo
19075 // entry, the matching edge is never charged and de-duplicating would lose
19076 // the spill cost entirely.
19077 for (const TreeEntry *E = UserTE; E != Root;) {
19078 if (!E->UserTreeIndex)
19079 return false;
19080 E = E->UserTreeIndex.UserTE;
19081 if (E->isGather() || ScalarOrPseudoEntries.contains(E))
19082 return false;
19083 }
19084
19085 Instruction *Def = EntriesToLastInstruction.at(SameTE);
19086 Instruction *Use = EntriesToLastInstruction.at(UserTE);
19087
19088 // Require the matching entry to be defined outside the loop and its use to
19089 // execute directly in the same loop as the gather user.
19090 if (SpillLoop->contains(Def->getParent()) ||
19091 LI->getLoopFor(Use->getParent()) != SpillLoop)
19092 return false;
19093
19094 // Ensure that the matching entry is also loop invariant.
19095 if (!all_of(make_isa_range<Instruction>(SameTE->Scalars),
19096 [&](Instruction *I) { return SpillLoop->isLoopInvariant(I); }))
19097 return false;
19098
19099 // A non-vec call between Def and the end of its block preempts the
19100 // loop-invariant charge for the matching entry's edge with a smaller
19101 // scale, so de-duplicating would drop the in-loop spill cost.
19102 if (!CheckForNonVecCallsInSameBlock(Def, Def->getParent()->getTerminator()))
19103 return false;
19104
19105 return GetLoopInvariantSpillRegion(Use->getParent(), Def->getParent()) ==
19106 SpillLoop;
19107 };
19108 while (!LiveEntries.empty()) {
19109 const TreeEntry *Entry = LiveEntries.pop_back_val();
19110 const auto OpIt = EntriesToOperands.find(Entry);
19111 if (OpIt == EntriesToOperands.end())
19112 continue;
19114 if (Operands.empty())
19115 continue;
19116 if (ScalarOrPseudoEntries.contains(Entry)) {
19117 Entry = FindNonScalarParentEntry(Entry);
19118 if (!Entry) {
19119 for (const TreeEntry *Op : Operands) {
19120 if (!Op->isGather())
19121 LiveEntries.push_back(Op);
19122 }
19123 continue;
19124 }
19125 }
19126 Instruction *LastInst = EntriesToLastInstruction.at(Entry);
19127 BasicBlock *Parent = LastInst->getParent();
19128 for (const TreeEntry *Op : Operands) {
19129 if (!Op->isGather())
19130 LiveEntries.push_back(Op);
19131 if (ScalarOrPseudoEntries.contains(Op))
19132 continue;
19133 if (Entry->State == TreeEntry::SplitVectorize ||
19134 (Op->isGather() && allConstant(Op->Scalars)))
19135 continue;
19136
19137 // Reset the scan budget for analysis of each edge.
19138 Budget = 0;
19139
19140 // A gather with all loop-invariant lanes is hoisted to the loop
19141 // preheader by optimizeGatherSequence, so its vector value becomes live
19142 // across any non-vectorized call in the loop body. Charge it like any
19143 // other vectorized value live over a call instead of skipping it.
19144 if (Entry->hasState() && Entry->getOpcode() != Instruction::PHI &&
19145 Op->isGather()) {
19146 if (const Loop *L = LI->getLoopFor(Parent);
19147 L && L->getLoopPreheader() && LoopBodyHasCall(L) &&
19149 [&](Instruction *I) { return L->isLoopInvariant(I); }))
19150 if (!IsCoveredByMatchingVectorEntry(Op, L))
19151 AddCosts(Op, GetSpillScale(Parent));
19152 // Vectorized parts of the gather node are combined at the user
19153 // position and are live across the calls in between.
19154 for (const auto &[Idx, _] : Op->CombinedEntriesWithIndices) {
19155 const TreeEntry *SubTE = VectorizableTree[Idx].get();
19156 if (SubTE->isGather() || TransformedToGatherNodes.contains(SubTE) ||
19157 ScalarOrPseudoEntries.contains(SubTE))
19158 continue;
19159 LiveEntries.push_back(SubTE);
19160 Instruction *SubLastInst = EntriesToLastInstruction.at(SubTE);
19161 Budget = 0;
19162 if (SubLastInst->getParent() == Parent &&
19163 !CheckForNonVecCallsInSameBlock(SubLastInst, LastInst))
19164 AddCosts(SubTE, GetSpillScale(Parent));
19165 }
19166 continue;
19167 }
19168 BasicBlock *Pred = nullptr;
19169 if (auto *Phi = dyn_cast<PHINode>(Entry->getMainOp()))
19170 Pred = Phi->getIncomingBlock(Op->UserTreeIndex.EdgeIdx);
19171 BasicBlock *OpParent;
19172 Instruction *OpLastInst;
19173 if (Op->isGather()) {
19174 assert(Entry->getOpcode() == Instruction::PHI &&
19175 "Expected phi node only.");
19176 OpParent = cast<PHINode>(Entry->getMainOp())
19177 ->getIncomingBlock(Op->UserTreeIndex.EdgeIdx);
19178 OpLastInst = OpParent->getTerminator();
19179 for (Instruction *Inst : make_isa_range<Instruction>(Op->Scalars)) {
19180 if (isVectorized(Inst)) {
19181 OpParent = Inst->getParent();
19182 OpLastInst = Inst;
19183 break;
19184 }
19185 }
19186 } else {
19187 OpLastInst = EntriesToLastInstruction.at(Op);
19188 OpParent = OpLastInst->getParent();
19189 }
19190 // Check the call instructions within the same basic blocks.
19191 if (OpParent == Parent) {
19192 if (Entry->getOpcode() == Instruction::PHI) {
19193 if (!CheckForNonVecCallsInSameBlock(LastInst, OpLastInst))
19194 AddCosts(Op, GetSpillScale(Parent));
19195 continue;
19196 }
19197 if (!CheckForNonVecCallsInSameBlock(OpLastInst, LastInst))
19198 AddCosts(Op, GetSpillScale(Parent));
19199 continue;
19200 }
19201 // Check for call instruction in between blocks.
19202 // 1. Check entry's block to the head.
19203 if (Entry->getOpcode() != Instruction::PHI &&
19204 !CheckForNonVecCallsInSameBlock(&*Parent->getFirstNonPHIOrAlloca(),
19205 LastInst)) {
19206 AddCosts(Op, GetSpillScale(Parent));
19207 continue;
19208 }
19209 // 2. Check op's block from the end.
19210 if (!CheckForNonVecCallsInSameBlock(OpLastInst,
19211 OpParent->getTerminator())) {
19212 AddCosts(Op, GetSpillScale(OpParent));
19213 continue;
19214 }
19215 // 3. Check the predecessors of entry's block till op's block.
19216 if (uint64_t Scale = CheckPredecessors(Parent, Pred, OpParent))
19217 AddCosts(Op, Scale);
19218 }
19219 }
19220
19221 return Cost;
19222}
19223
19225 // An absorbable boolean leaf is a one-use trunc of a wide value or a
19226 // one-use zero-test of a value from [0, 1]; bit 0 of the wide value is the
19227 // i1 lane value in both cases.
19228 auto GetBoolLeafWideTy = [&](const TreeEntry *OpE) -> Type * {
19229 if (OpE->State != TreeEntry::Vectorize || OpE->isAltShuffle() ||
19230 OpE->hasCopyableElements() || !OpE->ReuseShuffleIndices.empty() ||
19231 OpE->CombinedOp != TreeEntry::NotCombinedOp)
19232 return nullptr;
19233 unsigned WideOpIdx;
19234 bool IsZeroTest = OpE->getOpcode() == Instruction::ICmp;
19235 if (OpE->getOpcode() == Instruction::Trunc) {
19236 if (!all_of(OpE->Scalars, [](Value *V) {
19237 return match(V, m_OneUse(m_Trunc(m_Value())));
19238 }))
19239 return nullptr;
19240 WideOpIdx = 0;
19241 } else if (IsZeroTest) {
19242 if (!all_of(OpE->Scalars, [](Value *V) {
19243 auto *CI = dyn_cast<ICmpInst>(V);
19244 return CI && CI->hasOneUse() &&
19245 CI->getPredicate() == ICmpInst::ICMP_NE;
19246 }))
19247 return nullptr;
19248 if (all_of(OpE->getOperand(0),
19249 [](Value *V) { return match(V, m_Zero()); }))
19250 WideOpIdx = 1;
19251 else if (all_of(OpE->getOperand(1),
19252 [](Value *V) { return match(V, m_Zero()); }))
19253 WideOpIdx = 0;
19254 else
19255 return nullptr;
19256 } else {
19257 return nullptr;
19258 }
19259 Type *WideTy = OpE->getOperand(WideOpIdx).front()->getType();
19260 if (!WideTy->isIntegerTy())
19261 return nullptr;
19262 for (Value *W : OpE->getOperand(WideOpIdx)) {
19263 if (W->getType() != WideTy || !isGuaranteedNotToBePoison(W) ||
19264 (IsZeroTest && computeKnownBits(W, *DL).getMaxValue() != 1))
19265 return nullptr;
19266 }
19267 return WideTy;
19268 };
19269 // The wide value of a booleanized node is valid only in bit 0, so every
19270 // tree user must consume it as an i1 vector: either a booleanized and/or
19271 // node (which uses the wide value directly) or a node whose emission
19272 // truncates the operand back to the i1 vector type.
19273 auto IsSafeBoolUser = [&](const TreeEntry *UserTE, unsigned EdgeIdx) {
19274 if (!UserTE->hasState() || UserTE->isAltShuffle())
19275 return false;
19276 if (Instruction::isBinaryOp(UserTE->getOpcode()))
19277 return true;
19278 switch (UserTE->getOpcode()) {
19279 case Instruction::Store:
19280 return EdgeIdx == 0;
19281 case Instruction::InsertElement:
19282 return EdgeIdx == 1;
19283 case Instruction::Select:
19284 return EdgeIdx != 0;
19285 case Instruction::Freeze:
19286 case Instruction::PHI:
19287 return true;
19288 default:
19289 return false;
19290 }
19291 };
19292 // Visit operand nodes before their users so that booleanized and/or nodes
19293 // chain: an and/or node whose operand is itself a booleanized and/or node
19294 // consumes the wide value directly.
19295 for (const std::unique_ptr<TreeEntry> &TE : reverse(VectorizableTree)) {
19296 // Logical and/or on i1 with booleanized wide leaves is emitted in the
19297 // wide type: bit 0 of a bitwise and/or is the and/or of the operands'
19298 // bit 0. The leaf conversions are absorbed and a single trunc of the
19299 // wide vector result restores the i1 lanes. Wide leaves must be
19300 // non-poison: and/or may mask poison in the i1 type, which the wide ops
19301 // would propagate instead.
19302 if (TE->State != TreeEntry::Vectorize || TE->isAltShuffle() ||
19303 (TE->getOpcode() != Instruction::And &&
19304 TE->getOpcode() != Instruction::Or) ||
19305 !TE->getMainOp()->getType()->isIntegerTy(1) ||
19306 !TE->ReuseShuffleIndices.empty() || TE->hasCopyableElements() ||
19307 TE->CombinedOp != TreeEntry::NotCombinedOp ||
19308 // The i1 flags (e.g. disjoint) do not apply to the wide op.
19309 any_of(TE->Scalars,
19310 [](Value *V) {
19311 auto *I = dyn_cast<Instruction>(V);
19312 return !I || I->hasPoisonGeneratingFlags();
19313 }) ||
19314 any_of(TE->getReassocScalars(),
19315 [](Value *V) {
19316 return cast<Instruction>(V)->hasPoisonGeneratingFlags();
19317 }) ||
19318 // Reduction trees are handled by the reduction's own booleanization.
19319 UserIgnoreList ||
19320 (TE->UserTreeIndex.UserTE &&
19321 !IsSafeBoolUser(TE->UserTreeIndex.UserTE,
19322 TE->UserTreeIndex.EdgeIdx)) ||
19323 !all_of(TE->Scalars,
19324 [&](Value *V) { return getTreeEntries(V).size() == 1; }))
19325 continue;
19326 Type *WideTy = nullptr;
19327 bool Bail = false;
19328 for (unsigned I : seq<unsigned>(TE->getNumOperands())) {
19329 const TreeEntry *OpE = getOperandEntry(TE.get(), I);
19330 Type *ColTy = GetBoolLeafWideTy(OpE);
19331 if (!ColTy && isBooleanizedNode(OpE) &&
19332 (OpE->getOpcode() == Instruction::And ||
19333 OpE->getOpcode() == Instruction::Or))
19334 ColTy = IntegerType::get(F->getContext(), MinBWs.lookup(OpE).first);
19335 if (!ColTy || (WideTy && ColTy != WideTy)) {
19336 Bail = true;
19337 break;
19338 }
19339 WideTy = ColTy;
19340 }
19341 if (Bail || !WideTy)
19342 continue;
19343 unsigned WideBW = WideTy->getIntegerBitWidth();
19344 MinBWs.try_emplace(TE.get(), WideBW, /*IsSigned=*/false);
19345 for (unsigned I : seq<unsigned>(TE->getNumOperands()))
19346 MinBWs.try_emplace(getOperandEntry(TE.get(), I), WideBW,
19347 /*IsSigned=*/false);
19348 }
19349}
19350
19353 Instruction *RdxRoot) {
19354 // FIXME: support buildvector of the gather nodes with struct types.
19355 if (any_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
19356 return TE->isGather() &&
19357 isa<StructType>(TE->Scalars.front()->getType());
19358 })) {
19359 LLVM_DEBUG(
19360 dbgs() << "SLP: rejecting tree with buildvector struct values of size "
19361 << VectorizableTree.size() << ".\n");
19363 }
19364
19365 // The tree is priced, so its minimal vector nodes are analyzed, including the
19366 // ones, trimmed below as non-profitable. The verdict of the tree itself does
19367 // not matter: the retry with the single-user seeds rebuilds the same narrow
19368 // nodes, and their cost without the tree is not better. The wider nodes are
19369 // not registered: their rejection does not prevent the members from forming
19370 // the profitable narrower node. Same for the trees, rejected before the cost
19371 // estimation, and for the buildvector trees, rejected by the insert/extract
19372 // overhead rather than by the members themselves.
19373 const TreeEntry &Root = getRootNode();
19374 if (!Root.hasState() ||
19375 !isa<InsertElementInst, InsertValueInst>(Root.getMainOp())) {
19376 for (const std::unique_ptr<TreeEntry> &TE : make_filter_range(
19377 VectorizableTree, [](const std::unique_ptr<TreeEntry> &TE) {
19378 return !TE->isGather() && TE->Scalars.size() <= 2;
19379 })) {
19380 for (Value *V : TE->Scalars)
19381 if (isa_and_present<Instruction>(V) && !TE->isCopyableElement(V))
19382 AnalyzedScalars.insert(V);
19383 }
19384 }
19385
19387 SmallPtrSet<Value *, 4> CheckedExtracts;
19388 SmallSetVector<TreeEntry *, 4> GatheredLoadsNodes;
19390 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
19391 << VectorizableTree.size() << ".\n");
19392 // The V-only-dependent part of the predicate. Same V is commonly seen in
19393 // multiple TEs (shared scalars), so cache the result across calls.
19394 // DeletedNodes is read-only during this cost loop, so caching is safe.
19395 const size_t NumVectScalars = ScalarToTreeEntries.size() + 1;
19396 SmallDenseMap<Value *, bool> ExternalUseVCache;
19397 auto IsExternallyUsedV = [&](Value *V) {
19398 auto [It, Inserted] = ExternalUseVCache.try_emplace(V);
19399 if (!Inserted)
19400 return It->second;
19401 bool Res = false;
19402 if (V->hasOneUse() || V->getType()->isVoidTy()) {
19403 // Res stays false.
19404 } else if (V->hasNUsesOrMore(NumVectScalars)) {
19405 Res = true;
19406 } else if (auto *I = dyn_cast<Instruction>(V)) {
19407 Res = any_of(I->users(), [&](const User *U) {
19408 // store/insertelt v, [cast]U will likely be vectorized.
19409 if (match(U,
19410 m_InsertElt(m_Value(), m_OneUse(m_CastOrSelf(m_Specific(I))),
19411 m_ConstantInt())))
19412 return false;
19413 if (match(U, m_InsertElt(m_Value(), m_Specific(I), m_ConstantInt())))
19414 return false;
19415 if (match(U, m_Store(m_OneUse(m_CastOrSelf(m_Specific(I))), m_Value())))
19416 return false;
19417 if (match(U, m_Store(m_Specific(I), m_Value())))
19418 return false;
19419 ArrayRef<TreeEntry *> Entries = getTreeEntries(U);
19420 if (Entries.empty() && !MustGather.contains(U))
19421 return true;
19422 if (any_of(Entries,
19423 [&](TreeEntry *TE) { return DeletedNodes.contains(TE); }))
19424 return true;
19425 return any_of(ValueToGatherNodes.lookup(U), [&](const TreeEntry *TE) {
19426 return DeletedNodes.contains(TE);
19427 });
19428 });
19429 }
19430 It->second = Res;
19431 return Res;
19432 };
19433 auto IsExternallyUsed = [&](const TreeEntry &TE, Value *V) {
19434 assert(TE.hasState() && !TE.isGather() &&
19435 TE.State != TreeEntry::SplitVectorize && "Expected vector node.");
19436 if (TE.hasCopyableElements() && TE.isCopyableElement(V))
19437 return false;
19438 return IsExternallyUsedV(V);
19439 };
19440 InstructionCost Cost = 0;
19442 uint64_t PrevScale = 0;
19443 BasicBlock *PrevVecParent = nullptr;
19444 for (const std::unique_ptr<TreeEntry> &Ptr : VectorizableTree) {
19445 TreeEntry &TE = *Ptr;
19446 // No need to count the cost for combined entries, they are combined and
19447 // just skip their cost.
19448 if (TE.State == TreeEntry::CombinedVectorize) {
19449 LLVM_DEBUG(
19450 dbgs() << "SLP: Skipping cost for combined node that starts with "
19451 << *TE.Scalars[0] << ".\n";
19452 TE.dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
19453 NodesCosts.try_emplace(&TE);
19454 continue;
19455 }
19456 if (TE.hasState() &&
19457 (TE.isGather() || TE.State == TreeEntry::SplitVectorize)) {
19458 if (const TreeEntry *E =
19459 getSameValuesTreeEntry(TE.getMainOp(), TE.Scalars);
19460 E && E->getVectorFactor() == TE.getVectorFactor()) {
19461 // Some gather nodes might be absolutely the same as some vectorizable
19462 // nodes after reordering, need to handle it.
19463 LLVM_DEBUG(dbgs() << "SLP: Adding cost 0 for bundle "
19464 << shortBundleName(TE.Scalars, TE.Idx) << ".\n"
19465 << "SLP: Current total cost = " << Cost << "\n");
19466 NodesCosts.try_emplace(&TE);
19467 continue;
19468 }
19469 }
19470
19471 // Exclude cost of gather loads nodes which are not used. These nodes were
19472 // built as part of the final attempt to vectorize gathered loads.
19473 assert((!TE.isGather() || TE.Idx == 0 || TE.UserTreeIndex) &&
19474 "Expected gather nodes with users only.");
19475
19476 InstructionCost C = getEntryCost(&TE, VectorizedVals, CheckedExtracts);
19477 uint64_t Scale = 0;
19478 bool CostIsFree = C == 0;
19479 // For gather/buildvector (and split-vectorize) entries, prefer the
19480 // per-lane refined scale that accounts for LICM-hoistable insertelements
19481 // when an operand is invariant in the current loop nest but defined in
19482 // an outer loop. This prevents over-costing cross-loop-nest buildvectors.
19483 if (!CostIsFree && !TE.isGather() && TE.hasState()) {
19484 if (PrevVecParent == TE.getMainOp()->getParent()) {
19485 Scale = PrevScale;
19486 C *= Scale;
19487 EntryToScale.try_emplace(&TE, Scale);
19488 }
19489 }
19490 if (!CostIsFree && !Scale) {
19491 Scale = getEntryEffectiveScale(TE, TE.Idx == 0 ? RdxRoot : nullptr);
19492 C *= Scale;
19493 EntryToScale.try_emplace(&TE, Scale);
19494 if (!TE.isGather() && TE.hasState()) {
19495 PrevVecParent = TE.getMainOp()->getParent();
19496 PrevScale = Scale;
19497 }
19498 }
19499 Cost += C;
19500 NodesCosts.try_emplace(&TE, C);
19501 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle "
19502 << shortBundleName(TE.Scalars, TE.Idx) << ".\n"
19503 << "SLP: Current total cost = " << Cost << "\n");
19504 // Add gathered loads nodes to the set for later processing.
19505 if (TE.Idx > 0 && !TE.UserTreeIndex && TE.hasState() &&
19506 TE.getOpcode() == Instruction::Load)
19507 GatheredLoadsNodes.insert(&TE);
19508 if (!TE.isGather() && TE.State != TreeEntry::SplitVectorize &&
19509 !(TE.Idx == 0 && (TE.getOpcode() == Instruction::InsertElement ||
19510 TE.getOpcode() == Instruction::InsertValue ||
19511 TE.getOpcode() == Instruction::Store)) &&
19512 !isa<StructType>(getValueType(TE.Scalars.front(), Opts.slp_revec))) {
19513 // Calculate costs of external uses.
19514 APInt DemandedElts = APInt::getZero(TE.getVectorFactor());
19515 for (Value *V : TE.Scalars) {
19516 if (IsExternallyUsed(TE, V))
19517 DemandedElts.setBit(TE.findLaneForValue(V));
19518 }
19519 if (!DemandedElts.isZero()) {
19520 Type *ScalarTy = TE.Scalars.front()->getType();
19521 auto It = MinBWs.find(&TE);
19522 if (It != MinBWs.end())
19523 ScalarTy = IntegerType::get(ScalarTy->getContext(), It->second.first);
19524 auto *VecTy = getWidenedType(ScalarTy, TE.getVectorFactor());
19525 InstructionCost ExtCost =
19526 getScalarizationOverhead(*TTI, Opts.slp_revec, ScalarTy,
19527 cast<VectorType>(VecTy), DemandedElts,
19528 /*Insert=*/false,
19529 /*Extract=*/true, CostKind);
19530 if (ExtCost.isValid() && ExtCost != 0) {
19531 if (!Scale)
19532 Scale = getScaleToLoopIterations(TE);
19533 ExtCost *= Scale;
19534 EntryToScale.try_emplace(&TE, Scale);
19535 }
19536 ExtractCosts.try_emplace(&TE, ExtCost);
19537 }
19538 }
19539 }
19540 // Bail out if the cost threshold is negative and cost already below it.
19541 // The splat subtrees may still force extracts of their scalars on top of
19542 // the node cost and have to be trimmed, so do not bail out if there are
19543 // any.
19544 if (getCostThreshold() < 0 && Cost < -getCostThreshold() &&
19545 SplatGatheredScalarsRoots.empty())
19546 return Cost;
19547 // The narrow non-profitable tree in loop? Skip, may cause regressions.
19548 constexpr unsigned PartLimit = 2;
19549 // Measure the narrowness by the width the tree is vectorized at.
19550 const TreeEntry *RootTE = &getRootNode();
19551 unsigned Sz;
19552 if (auto It = MinBWs.find(RootTE); It != MinBWs.end()) {
19553 Sz = It->second.first;
19554 } else {
19555 Sz = std::max<unsigned>(
19556 getVectorElementSize(RootTE->Scalars.front()),
19557 DL->getTypeSizeInBits(
19558 getValueType(RootTE->Scalars.front(), Opts.slp_revec)
19559 ->getScalarType()));
19560 }
19561 const unsigned MinVF = getMinVF(Sz);
19562 if (Cost >= -getCostThreshold() &&
19563 getRootNodeScalars().size() * PartLimit <= MinVF &&
19564 (!getRootNode().hasState() ||
19565 (getRootNode().getOpcode() != Instruction::Store &&
19566 LI->getLoopFor(getRootNode().getMainOp()->getParent()))))
19567 return Cost;
19568 // Store the cost + external uses estimation as the first element of the
19569 // tuple, just the cost as the second element of the tuple. Required to return
19570 // correct cost estimation for the tree, extracts are calculated separately.
19571 // Extracts, calculated here, are just quick estimations.
19573 std::tuple<InstructionCost, InstructionCost, SmallVector<unsigned>>>
19574 SubtreeCosts(VectorizableTree.size());
19575 auto IsNotDeleted = [&](const TreeEntry *TE) {
19576 return !DeletedNodes.contains(TE);
19577 };
19578 // (Re)computes the subtree costs for the nodes that are not deleted.
19579 auto ComputeSubtreeCosts = [&]() {
19580 SubtreeCosts.assign(
19581 VectorizableTree.size(),
19582 std::tuple<InstructionCost, InstructionCost, SmallVector<unsigned>>());
19583 auto UpdateParentNodes =
19584 [&](const TreeEntry *UserTE, const TreeEntry *TE,
19586 SmallDenseSet<std::pair<const TreeEntry *, const TreeEntry *>, 4>
19587 &VisitedUser,
19588 bool AddToList = true) {
19589 while (UserTE &&
19590 VisitedUser.insert(std::make_pair(TE, UserTE)).second) {
19591 std::get<0>(SubtreeCosts[UserTE->Idx]) += TotalCost;
19592 std::get<1>(SubtreeCosts[UserTE->Idx]) += Cost;
19593 if (AddToList)
19594 std::get<2>(SubtreeCosts[UserTE->Idx]).push_back(TE->Idx);
19595 UserTE = UserTE->UserTreeIndex.UserTE;
19596 }
19597 };
19598 for (const std::unique_ptr<TreeEntry> &Ptr : VectorizableTree) {
19599 TreeEntry &TE = *Ptr;
19600 if (DeletedNodes.contains(&TE))
19601 continue;
19602 // Combined subnodes are not costed on their own (their cost is 0), but
19603 // must be included into the ancestors' subtree node lists, so that they
19604 // get deleted together with the trimmed combined root.
19605 InstructionCost C = NodesCosts.at(&TE);
19606 InstructionCost ExtractCost = ExtractCosts.lookup(&TE);
19607 std::get<0>(SubtreeCosts[TE.Idx]) += C + ExtractCost;
19608 std::get<1>(SubtreeCosts[TE.Idx]) += C;
19609 if (const TreeEntry *UserTE = TE.UserTreeIndex.UserTE) {
19610 SmallDenseSet<std::pair<const TreeEntry *, const TreeEntry *>, 4>
19611 VisitedUser;
19612 UpdateParentNodes(UserTE, &TE, C + ExtractCost, C, VisitedUser);
19613 }
19614 }
19615 SmallDenseSet<std::pair<const TreeEntry *, const TreeEntry *>, 4> Visited;
19616 for (TreeEntry *TE : make_filter_range(GatheredLoadsNodes, IsNotDeleted)) {
19617 InstructionCost TotalCost = std::get<0>(SubtreeCosts[TE->Idx]);
19618 InstructionCost Cost = std::get<1>(SubtreeCosts[TE->Idx]);
19619 for (Value *V : TE->Scalars) {
19620 const auto Nodes = ValueToGatherNodes.lookup(V);
19621 for (const TreeEntry *BVTE : make_filter_range(Nodes, IsNotDeleted))
19622 UpdateParentNodes(BVTE, TE, TotalCost, Cost, Visited,
19623 /*AddToList=*/false);
19624 }
19625 }
19626 };
19627 ComputeSubtreeCosts();
19628 using ValuesToInsertTy =
19629 SmallDenseMap<const TreeEntry *, SmallVector<Value *>>;
19630 auto GetScalarTy = [&](const TreeEntry *TE) {
19631 Type *ScalarTy = TE->Scalars.front()->getType();
19632 auto It = MinBWs.find(TE);
19633 if (It != MinBWs.end())
19634 ScalarTy = IntegerType::get(ScalarTy->getContext(), It->second.first);
19635 return ScalarTy;
19636 };
19637 // Lanes of the subtree scalars used by the surviving gather nodes, and the
19638 // values to materialize in those gathers if the subtree is deleted.
19639 auto FindDemandedElts = [&](TreeEntry *TE, ValuesToInsertTy &ValuesToInsert) {
19640 APInt DemandedElts = APInt::getZero(TE->getVectorFactor());
19641 for (Value *V : TE->Scalars) {
19642 unsigned Pos = TE->findLaneForValue(V);
19643 const auto Nodes = ValueToGatherNodes.lookup(V);
19644 for (const TreeEntry *BVE : make_filter_range(Nodes, IsNotDeleted)) {
19645 DemandedElts.setBit(Pos);
19646 ValuesToInsert.try_emplace(BVE).first->second.push_back(V);
19647 }
19648 }
19649 return DemandedElts;
19650 };
19651 // Cost of materializing the values directly in the surviving gather nodes
19652 // that use them.
19653 auto GetGatherInsertCost = [&](Type *ScalarTy,
19654 const ValuesToInsertTy &ValuesToInsert) {
19655 InstructionCost BVCost = 0;
19656 for (const auto &[BVE, Values] : ValuesToInsert) {
19657 APInt BVDemandedElts = APInt::getZero(BVE->getVectorFactor());
19658 SmallVector<Value *> BVValues(BVE->getVectorFactor(),
19659 PoisonValue::get(ScalarTy));
19660 for (Value *V : Values) {
19661 unsigned Pos = BVE->findLaneForValue(V);
19662 BVValues[Pos] = V;
19663 BVDemandedElts.setBit(Pos);
19664 }
19665 BVCost += getScalarizationOverhead(
19666 *TTI, Opts.slp_revec, ScalarTy,
19667 cast<VectorType>(getWidenedType(ScalarTy, BVE->getVectorFactor())),
19668 BVDemandedElts, /*Insert=*/true, /*Extract=*/false, CostKind,
19669 BVDemandedElts.isAllOnes(), BVValues);
19670 }
19671 return BVCost;
19672 };
19673 auto RecostEntry = [&](const TreeEntry *TE) {
19674 InstructionCost C = getEntryCost(TE, VectorizedVals, CheckedExtracts);
19675 if (!C.isValid() || C == 0)
19676 return C;
19677 uint64_t Scale = EntryToScale.lookup(TE);
19678 if (!Scale)
19679 Scale = getEntryEffectiveScale(*TE, TE->Idx == 0 ? RdxRoot : nullptr);
19680 return C * Scale;
19681 };
19682 // A splat subtree pays off only if some surviving gather node reuses it and
19683 // its price plus the extracts of its scalars used by the remaining scalar
19684 // code plus the current cost of the gather nodes that reuse it is not worse
19685 // than re-emitting those gathers without the subtree.
19686 auto IsSplatSubtreeProfitable = [&](TreeEntry *TE,
19687 ValuesToInsertTy &ValuesToInsert,
19688 InstructionCost &CurrentGathersCost,
19689 InstructionCost &DroppedGathersCost) {
19690 if (FindDemandedElts(TE, ValuesToInsert).isZero())
19691 return false;
19692 APInt ExtractElts = APInt::getZero(TE->getVectorFactor());
19693 for (Instruction *I : make_isa_range<Instruction>(TE->Scalars)) {
19694 if (TE->isCopyableElement(I))
19695 continue;
19696 // Too many users - the scalar is extracted anyway.
19697 if (I->hasNUsesOrMore(UsesLimit) || any_of(I->users(), [&](User *U) {
19698 return none_of(getTreeEntries(U), [&](const TreeEntry *UseTE) {
19699 return !DeletedNodes.contains(UseTE) &&
19700 !TransformedToGatherNodes.contains(UseTE);
19701 });
19702 }))
19703 ExtractElts.setBit(TE->findLaneForValue(I));
19704 }
19705 Type *ScalarTy = GetScalarTy(TE);
19707 *TTI, Opts.slp_revec, ScalarTy,
19708 cast<VectorType>(getWidenedType(ScalarTy, TE->getVectorFactor())),
19709 ExtractElts, /*Insert=*/false, /*Extract=*/true, CostKind);
19710 // Scale the extract cost to the subtree's execution frequency: the
19711 // subtree and gather costs it is compared against are already loop-scaled.
19712 if (KeepCost.isValid() && KeepCost != 0)
19713 KeepCost *= getEntryEffectiveScale(*TE);
19714 // Add the cost of the subtree itself, computed before any trimming:
19715 // trimming of the subtree's own nodes would otherwise make it look
19716 // artificially cheap. The inner nodes of the subtree keep their external
19717 // scalar users too, so their extracts are part of the price as well.
19718 KeepCost += std::get<1>(SubtreeCosts[TE->Idx]);
19719 for (unsigned Idx : std::get<2>(SubtreeCosts[TE->Idx]))
19720 KeepCost += ExtractCosts.lookup(VectorizableTree[Idx].get());
19721 // The reusing gather nodes currently pay the broadcast cost; without
19722 // the subtree they fall back to plain insertion sequences. Gather
19723 // nodes already erased from NodesCosts are being deleted and do not
19724 // count on either side.
19725 CurrentGathersCost = 0;
19726 for (const auto &[BVE, _] : ValuesToInsert)
19727 CurrentGathersCost += NodesCosts.lookup(BVE);
19728 KeepCost += CurrentGathersCost;
19729 // Re-cost the gather nodes with the subtree tentatively deleted.
19730 DeletedNodes.insert(TE);
19731 SmallVector<TreeEntry *> TempDeleted;
19732 for (unsigned Idx : std::get<2>(SubtreeCosts[TE->Idx])) {
19733 TreeEntry *Child = VectorizableTree[Idx].get();
19734 if (DeletedNodes.insert(Child).second)
19735 TempDeleted.push_back(Child);
19736 }
19737 DroppedGathersCost = 0;
19738 auto HasCost = [&](const auto &P) { return NodesCosts.contains(P.first); };
19739 for (const auto &[BVE, _] : make_filter_range(ValuesToInsert, HasCost))
19740 DroppedGathersCost += RecostEntry(BVE);
19741 DeletedNodes.erase(TE);
19742 for (TreeEntry *Child : TempDeleted)
19743 DeletedNodes.erase(Child);
19744 // On a cost tie prefer dropping the subtree: the reusing gathers
19745 // materialize the scalars at the same price with fewer instructions.
19746 return KeepCost < DroppedGathersCost;
19747 };
19748 // Re-price the gathers that reused a dropped splat subtree, so the
19749 // remaining subtrees are checked against the costs with it deleted.
19750 auto SyncGatherCosts = [&](const ValuesToInsertTy &ValuesToInsert) {
19751 for (const auto &[BVE, _] : ValuesToInsert)
19752 if (!DeletedNodes.contains(BVE))
19753 NodesCosts[BVE] = RecostEntry(BVE);
19754 };
19755 // Deletes the subtree. The per-node costs are erased eagerly only where the
19756 // total is recomputed from them right after the deletion.
19757 auto DeleteSubtree = [&](TreeEntry *TE, bool EraseCosts) {
19758 DeletedNodes.insert(TE);
19759 if (EraseCosts)
19760 NodesCosts.erase(TE);
19761 for (unsigned Idx : std::get<2>(SubtreeCosts[TE->Idx])) {
19762 TreeEntry *Child = VectorizableTree[Idx].get();
19763 DeletedNodes.insert(Child);
19764 if (EraseCosts)
19765 NodesCosts.erase(Child);
19766 }
19767 };
19768 // Gathered loads subtrees left without surviving gather users are dead.
19769 auto DropDeadGatheredLoads = [&](bool EraseCosts) {
19770 for (TreeEntry *TE : make_filter_range(GatheredLoadsNodes, IsNotDeleted)) {
19771 ValuesToInsertTy ValuesToInsert;
19772 if (!FindDemandedElts(TE, ValuesToInsert).isZero())
19773 continue;
19774 DeleteSubtree(TE, EraseCosts);
19775 }
19776 };
19777 // Drops the splat subtrees that are unused by the surviving gathers or do
19778 // not pay off; returns true if anything was dropped.
19779 auto DropUnprofitableSplatSubtrees = [&](bool EraseCosts) {
19780 bool Dropped = false;
19781 for (TreeEntry *TE :
19782 make_filter_range(SplatGatheredScalarsRoots, IsNotDeleted)) {
19783 ValuesToInsertTy ValuesToInsert;
19784 InstructionCost CurrentGathersCost = 0, DroppedGathersCost = 0;
19785 if (IsSplatSubtreeProfitable(TE, ValuesToInsert, CurrentGathersCost,
19786 DroppedGathersCost))
19787 continue;
19788 DeleteSubtree(TE, EraseCosts);
19789 SyncGatherCosts(ValuesToInsert);
19790 Dropped = true;
19791 }
19792 return Dropped;
19793 };
19794 auto SumNodesCosts = [&]() {
19795 InstructionCost C = 0;
19796 for (const auto &P : NodesCosts)
19797 C += P.second;
19798 return C;
19799 };
19800 // The splat subtrees are speculative. The ones that do not pay off even in
19801 // the full tree are dropped before the trimming: the reusing gathers are
19802 // priced for the broadcast from the subtree vector while the subtree is
19803 // around, which distorts the trimming decisions of the main tree, and fewer
19804 // surviving gathers after the trimming can only make keeping a subtree less
19805 // profitable.
19806 if (DropUnprofitableSplatSubtrees(/*EraseCosts=*/true)) {
19807 DropDeadGatheredLoads(/*EraseCosts=*/true);
19808 ComputeSubtreeCosts();
19809 Cost = SumNodesCosts();
19810 }
19811 using CostIndicesTy =
19812 std::pair<TreeEntry *, std::tuple<InstructionCost, InstructionCost,
19813 SmallVector<unsigned>>>;
19814 struct FirstGreater {
19815 bool operator()(const CostIndicesTy &LHS, const CostIndicesTy &RHS) const {
19816 return std::get<0>(LHS.second) < std::get<0>(RHS.second) ||
19817 (std::get<0>(LHS.second) == std::get<0>(RHS.second) &&
19818 LHS.first->Idx < RHS.first->Idx);
19819 }
19820 };
19821 PriorityQueue<CostIndicesTy, SmallVector<CostIndicesTy>, FirstGreater>
19822 Worklist;
19823 // Combined subnodes are not trimmed on their own, only as a whole combined
19824 // node, so only the root nodes are checked and included into the worklist.
19825 for (const auto [Idx, P] :
19826 make_filter_range(enumerate(SubtreeCosts), [&](const auto &Elem) {
19827 return VectorizableTree[Elem.index()]->State !=
19828 TreeEntry::CombinedVectorize;
19829 }))
19830 Worklist.emplace(VectorizableTree[Idx].get(), P);
19831
19832 // Narrow store trees with non-profitable immediate values - exit.
19833 if (!UserIgnoreList && getRootNode().getVectorFactor() < MinVF &&
19834 getRootNode().hasState() &&
19835 getRootNode().getOpcode() == Instruction::Store &&
19836 (Worklist.top().first->Idx == 0 || Worklist.top().first->Idx == 1))
19837 return Cost;
19838
19839 // Node costs and deleted nodes before any trimming; the restored tree is
19840 // priced from them if the trimming is reverted.
19841 const SmallDenseMap<const TreeEntry *, InstructionCost> OrigNodesCosts =
19842 NodesCosts;
19843 const SmallPtrSet<const TreeEntry *, 8> OrigDeletedNodes = DeletedNodes;
19844 bool Changed = false;
19845 bool PreferTrimmedTree = false;
19846 while (!Worklist.empty() && std::get<0>(Worklist.top().second) > 0) {
19847 TreeEntry *TE = Worklist.top().first;
19848 if (TE->isGather() || TE->Idx == 0 || DeletedNodes.contains(TE) ||
19849 isa<StructType>(getValueType(TE->Scalars.front(), Opts.slp_revec)) ||
19850 // Splat subtree roots are decided by the keep/drop check below: their
19851 // scalars are materialized in the reusing splat gathers, not in a
19852 // gather of the root's own scalars.
19853 is_contained(SplatGatheredScalarsRoots, TE) ||
19854 // Exit early if the parent node is split node and any of scalars is
19855 // used in other split nodes.
19856 (TE->UserTreeIndex &&
19857 TE->UserTreeIndex.UserTE->State == TreeEntry::SplitVectorize &&
19858 any_of(TE->Scalars, [&](Value *V) {
19859 ArrayRef<TreeEntry *> Entries = getSplitTreeEntries(V);
19860 return Entries.size() > 1;
19861 }))) {
19862 Worklist.pop();
19863 continue;
19864 }
19865 // Skip inversed compare nodes, they cannot be transformed to buildvectors.
19866 if (TE->State == TreeEntry::Vectorize && !TE->isAltShuffle() &&
19867 (TE->getOpcode() == Instruction::ICmp ||
19868 TE->getOpcode() == Instruction::FCmp) &&
19869 any_of(make_isa_range<CmpInst>(TE->Scalars), [&](CmpInst *I) {
19870 return I->getPredicate() !=
19871 cast<CmpInst>(TE->getMainOp())->getPredicate();
19872 })) {
19873 Worklist.pop();
19874 continue;
19875 }
19876 // A zext feeding a bit pack is priced as part of the pack: its vectorized
19877 // form makes the compaction back to the source width free, so keep it.
19878 if (TE->UserTreeIndex && TE->UserTreeIndex.EdgeIdx == 0 &&
19879 TE->UserTreeIndex.UserTE->CombinedOp == TreeEntry::ReducedBitPack &&
19880 getZExtSrcWidth(*TE) != 0) {
19881 Worklist.pop();
19882 continue;
19883 }
19884
19885 // Calculate the gather cost of the root node.
19886 InstructionCost TotalSubtreeCost = std::get<0>(Worklist.top().second);
19887 InstructionCost SubtreeCost = std::get<1>(Worklist.top().second);
19888 if (TotalSubtreeCost < TE->Scalars.size()) {
19889 Worklist.pop();
19890 continue;
19891 }
19892 if (!TransformedToGatherNodes.empty()) {
19893 for (unsigned Idx : std::get<2>(Worklist.top().second)) {
19894 auto It = TransformedToGatherNodes.find(VectorizableTree[Idx].get());
19895 if (It != TransformedToGatherNodes.end()) {
19896 TotalSubtreeCost -= std::get<0>(SubtreeCosts[Idx]);
19897 SubtreeCost -= std::get<1>(SubtreeCosts[Idx]);
19898 TotalSubtreeCost += It->second;
19899 SubtreeCost += It->second;
19900 }
19901 }
19902 }
19903 if (TotalSubtreeCost < 0 || TotalSubtreeCost < TE->Scalars.size()) {
19904 Worklist.pop();
19905 continue;
19906 }
19907 const unsigned EntryVF = TE->getVectorFactor();
19908 APInt DemandedElts = APInt::getZero(EntryVF);
19909 for (auto [Idx, V] : enumerate(TE->Scalars)) {
19910 if (!isConstant(V))
19911 DemandedElts.setBit(Idx);
19912 }
19913
19914 Type *ScalarTy = getValueType(TE->Scalars.front(), Opts.slp_revec);
19915 auto It = MinBWs.find(TE);
19916 if (It != MinBWs.end())
19917 ScalarTy = IntegerType::get(ScalarTy->getContext(), It->second.first);
19918 auto *VecTy = getWidenedType(ScalarTy, EntryVF);
19920 *TTI, Opts.slp_revec, ScalarTy, cast<VectorType>(VecTy), DemandedElts,
19921 /*Insert=*/true, /*Extract=*/false, CostKind);
19922 SmallVector<int> Mask;
19923 if (!TE->ReorderIndices.empty() &&
19924 TE->State != TreeEntry::CompressVectorize &&
19925 (TE->State != TreeEntry::StridedVectorize || !TE->isReverse() ||
19926 isWidenedStridedLoad(TE))) {
19927 SmallVector<int> NewMask;
19928 if (TE->getOpcode() == Instruction::Store) {
19929 // For stores the order is actually a mask.
19930 NewMask.resize(TE->ReorderIndices.size());
19931 copy(TE->ReorderIndices, NewMask.begin());
19932 } else {
19933 inversePermutation(TE->ReorderIndices, NewMask);
19934 }
19935 addMask(Mask, NewMask);
19936 }
19937 if (!TE->ReuseShuffleIndices.empty())
19938 addMask(Mask, TE->ReuseShuffleIndices);
19939 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask, EntryVF))
19940 GatherCost += getShuffleCost(*TTI, TTI::SK_PermuteSingleSrc,
19941 cast<VectorType>(VecTy), CostKind, Mask);
19942 // If all scalars are reused in gather node(s) or other vector nodes, there
19943 // might be extra cost for inserting them.
19944 if ((!TE->hasState() || !TE->isAltShuffle()) &&
19945 all_of(TE->Scalars, [&](Value *V) {
19946 return (TE->hasCopyableElements() && TE->isCopyableElement(V)) ||
19947 isConstant(V) || isGathered(V) || getTreeEntries(V).size() > 1;
19948 }))
19949 GatherCost *= 2;
19950 // The fmuls, priced as fused into their vectorized fadd/fsub users, stay
19951 // scalar and unfused in the gathered form.
19952 GatherCost += getUnfusedFMulsPenalty(*TE);
19953 // Erase subtree if it is non-profitable.
19954 ArrayRef<unsigned> Nodes = std::get<2>(Worklist.top().second);
19955 // Prefer trimming equal-cost alternate-shuffle subtrees rooted at binary
19956 // ops: alt-shuffles introduce runtime shuffle overhead that the cost model
19957 // may underestimate. Skip if the subtree contains ExtractElement nodes,
19958 // since those operate on already-materialized vectors where the cost model
19959 // is more accurate.
19960 auto IsEqualCostAltShuffleToTrim = [&]() {
19961 return TotalSubtreeCost == GatherCost && TE->hasState() &&
19962 TE->isAltShuffle() && Instruction::isBinaryOp(TE->getOpcode()) &&
19963 none_of(Nodes, [&](unsigned Idx) {
19964 return VectorizableTree[Idx]->hasState() &&
19965 VectorizableTree[Idx]->getOpcode() ==
19966 Instruction::ExtractElement;
19967 });
19968 };
19969 // Non-power-of-2 entries may have inflated costs - add a margin of 1
19970 // before trimming to avoid over-pruning.
19971 bool HasNonPowerOf2 = any_of(Nodes, [&](unsigned Idx) {
19972 return !has_single_bit(VectorizableTree[Idx]->Scalars.size());
19973 });
19974 InstructionCost TrimMargin = HasNonPowerOf2 ? 1 : 0;
19975 if (TotalSubtreeCost > GatherCost + TrimMargin ||
19976 IsEqualCostAltShuffleToTrim()) {
19977 PreferTrimmedTree |= TotalSubtreeCost == GatherCost;
19978 // If the remaining tree is just a buildvector - exit, it will cause
19979 // endless attempts to vectorize. When the tree is already profitable,
19980 // skip trimming this node and let the post-loop logic (including
19981 // gathered loads processing) decide.
19982 if (getRootNode().hasState() &&
19983 getRootNode().getOpcode() == Instruction::InsertElement &&
19984 TE->Idx == 1) {
19985 if (Cost < -getCostThreshold()) {
19986 LLVM_DEBUG(dbgs() << "SLP: Skipping trim of node " << TE->Idx
19987 << " - tree already profitable with cost " << Cost
19988 << ".\n");
19989 Worklist.pop();
19990 continue;
19991 }
19993 }
19994
19995 LLVM_DEBUG(dbgs() << "SLP: Trimming unprofitable subtree at node "
19996 << TE->Idx << " with cost "
19997 << std::get<0>(Worklist.top().second)
19998 << " and gather cost " << GatherCost << ".\n");
19999 if (TE->UserTreeIndex) {
20000 TransformedToGatherNodes.try_emplace(TE, GatherCost);
20001 NodesCosts.erase(TE);
20002 } else {
20003 DeletedNodes.insert(TE);
20004 TransformedToGatherNodes.erase(TE);
20005 NodesCosts.erase(TE);
20006 }
20007 for (unsigned Idx : Nodes) {
20008 TreeEntry &ChildTE = *VectorizableTree[Idx];
20009 DeletedNodes.insert(&ChildTE);
20010 TransformedToGatherNodes.erase(&ChildTE);
20011 NodesCosts.erase(&ChildTE);
20012 }
20013 Changed = true;
20014 }
20015 Worklist.pop();
20016 }
20017 // The VF=2 instruction-count veto rejects the whole tree when the vector code
20018 // has more instructions than the scalar code. The auxiliary subtrees - splat
20019 // gather roots and gathered loads - are optional: the surviving gathers can
20020 // re-materialize their scalars. Drop the reused ones while the tree exceeds
20021 // the budget so a kept subtree cannot reject the main tree. The gate mirrors
20022 // the veto conditions.
20023 const bool ApplyInstCountVeto =
20024 (!SplatGatheredScalarsRoots.empty() || !GatheredLoadsNodes.empty()) &&
20025 CostKind != TTI::TCK_CodeSize && Opts.slp_inst_count_check &&
20026 TTI->preferSLPInstCountCheck() && getRootNode().getVectorFactor() == 2 &&
20027 getCostThreshold() == 0 &&
20028 (!Opts.slp_revec ||
20030 const Loop *InstCountLoop = nullptr;
20031 if (ApplyInstCountVeto && Opts.slp_cost_loop_trip_count != 0 &&
20032 getRootNode().hasState())
20033 InstCountLoop = LI->getLoopFor(getRootNode().getMainOp()->getParent());
20034 auto TrimAuxSubtreesForInstCount = [&](InstructionCost &Cost,
20035 bool UseCurrentNodeCosts) {
20036 if (!ApplyInstCountVeto || bypassesInstCountCheck(Cost))
20037 return;
20038 // Current cost of the subtree rooted at TE from the per-node costs.
20039 auto GetCurrentSubtreeCost = [&](const TreeEntry *TE) {
20040 InstructionCost C = NodesCosts.lookup(TE);
20041 for (unsigned Idx : std::get<2>(SubtreeCosts[TE->Idx]))
20042 C += NodesCosts.lookup(VectorizableTree[Idx].get());
20043 return C;
20044 };
20045 auto DropReusedSubtree = [&](TreeEntry *TE, bool DeadOnly) {
20046 if (DeletedNodes.contains(TE) || TransformedToGatherNodes.contains(TE))
20047 return false;
20048 ValuesToInsertTy ValuesToInsert;
20049 const bool IsDead = FindDemandedElts(TE, ValuesToInsert).isZero();
20050 if (!IsDead && DeadOnly)
20051 return false;
20052 InstructionCost CurrentGathersCost = 0;
20053 for (const auto &[BVE, _] : ValuesToInsert)
20054 CurrentGathersCost += NodesCosts.lookup(BVE);
20055 DeleteSubtree(TE, /*EraseCosts=*/false);
20056 // All reusers were dropped: the subtree is dead. Without current node
20057 // costs the total conservatively keeps the subtree cost.
20058 if (IsDead) {
20059 if (UseCurrentNodeCosts)
20060 Cost -= GetCurrentSubtreeCost(TE);
20061 return true;
20062 }
20063 InstructionCost DroppedGathersCost = 0;
20064 for (const auto &[BVE, _] : ValuesToInsert)
20065 if (NodesCosts.contains(BVE))
20066 DroppedGathersCost += RecostEntry(BVE);
20067 // The pre-trimming subtree cost matches the total only while the tree
20068 // is intact or restored; an accepted trimming leaves the total holding
20069 // just the current costs of the surviving subtree nodes.
20070 InstructionCost SubtreeCost = UseCurrentNodeCosts
20071 ? GetCurrentSubtreeCost(TE)
20072 : std::get<1>(SubtreeCosts[TE->Idx]);
20073 Cost += DroppedGathersCost - CurrentGathersCost - SubtreeCost;
20074 SyncGatherCosts(ValuesToInsert);
20075 return true;
20076 };
20077 // Recompute the counts only after an actual drop. Dropping a root can
20078 // kill the reusers of a root from the other list, so repeat until no more
20079 // drops; dead subtrees are removed even under the budget.
20080 uint64_t NumScalar = getNumScalarInsts(InstCountLoop);
20081 uint64_t NumVector = getNumVectorInsts(InstCountLoop);
20082 bool Retry;
20083 do {
20084 Retry = false;
20085 for (ArrayRef<TreeEntry *> Roots :
20086 {ArrayRef<TreeEntry *>(SplatGatheredScalarsRoots),
20087 GatheredLoadsNodes.getArrayRef()})
20088 for (TreeEntry *TE : Roots)
20089 if (DropReusedSubtree(TE, /*DeadOnly=*/NumVector <= NumScalar)) {
20090 NumScalar = getNumScalarInsts(InstCountLoop);
20091 NumVector = getNumVectorInsts(InstCountLoop);
20092 Retry = true;
20093 }
20094 } while (Retry);
20095 };
20096 if (!Changed) {
20097 // The splat subtrees are not linked to the tree root, so their cost is
20098 // not included in the root's subtree cost; add it explicitly. Drop the
20099 // unprofitable ones instead of letting them reject the whole tree.
20100 InstructionCost TotalCost = std::get<1>(SubtreeCosts.front());
20101 for (TreeEntry *TE :
20102 make_filter_range(SplatGatheredScalarsRoots, [&](TreeEntry *TE) {
20103 return !DeletedNodes.contains(TE);
20104 })) {
20105 ValuesToInsertTy ValuesToInsert;
20106 InstructionCost CurrentGathersCost = 0, DroppedGathersCost = 0;
20107 if (IsSplatSubtreeProfitable(TE, ValuesToInsert, CurrentGathersCost,
20108 DroppedGathersCost)) {
20109 TotalCost += std::get<1>(SubtreeCosts[TE->Idx]);
20110 continue;
20111 }
20112 DeleteSubtree(TE, /*EraseCosts=*/false);
20113 // The gather nodes that reused the subtree are re-emitted without it.
20114 TotalCost += DroppedGathersCost - CurrentGathersCost;
20115 SyncGatherCosts(ValuesToInsert);
20116 }
20117 DropDeadGatheredLoads(/*EraseCosts=*/false);
20118 TrimAuxSubtreesForInstCount(TotalCost, /*UseCurrentNodeCosts=*/false);
20119 return TotalCost;
20120 }
20121
20122 SmallPtrSet<TreeEntry *, 4> SubtreesToDelete;
20123 InstructionCost LoadsExtractsCost = 0;
20124 // Check if all gather nodes that reuse the splat subtrees are marked for
20125 // deletion. In this case the whole splat subtree must be deleted. If only
20126 // some of the gathers are trimmed, keeping the subtree still costs its full
20127 // price plus the extracts of the scalars used by the remaining scalar code,
20128 // while the surviving gathers can materialize the splatted scalars
20129 // directly. Drop the subtree if it does not pay off.
20130 for (TreeEntry *TE :
20131 make_filter_range(SplatGatheredScalarsRoots, [&](TreeEntry *TE) {
20132 return !DeletedNodes.contains(TE);
20133 })) {
20134 ValuesToInsertTy ValuesToInsert;
20135 InstructionCost CurrentGathersCost, DroppedGathersCost;
20136 if (IsSplatSubtreeProfitable(TE, ValuesToInsert, CurrentGathersCost,
20137 DroppedGathersCost))
20138 continue;
20139 SubtreesToDelete.insert(TE);
20140 NodesCosts.erase(TE);
20141 }
20142
20143 // Check if all loads of gathered loads nodes are marked for deletion. In this
20144 // case the whole gathered loads subtree must be deleted.
20145 // Also, try to account for extracts, which might be required, if only part of
20146 // gathered load must be vectorized. Keep partially vectorized nodes, if
20147 // extracts are cheaper than gathers.
20148 for (TreeEntry *TE :
20149 make_filter_range(GatheredLoadsNodes, [&](TreeEntry *TE) {
20150 return !DeletedNodes.contains(TE) &&
20151 !TransformedToGatherNodes.contains(TE);
20152 })) {
20153 SubtreesToDelete.insert(TE);
20154 // All loads are removed from gathered? Need to delete the subtree.
20155 ValuesToInsertTy ValuesToInsert;
20156 APInt DemandedElts = FindDemandedElts(TE, ValuesToInsert);
20157 if (!DemandedElts.isZero()) {
20158 Type *ScalarTy = GetScalarTy(TE);
20159 auto *VecTy = getWidenedType(ScalarTy, TE->getVectorFactor());
20161 *TTI, Opts.slp_revec, ScalarTy, cast<VectorType>(VecTy), DemandedElts,
20162 /*Insert=*/false, /*Extract=*/true, CostKind);
20163 InstructionCost BVCost = GetGatherInsertCost(ScalarTy, ValuesToInsert);
20164 if (ExtractsCost < BVCost) {
20165 LoadsExtractsCost += ExtractsCost;
20166 SubtreesToDelete.erase(TE);
20167 continue;
20168 }
20169 LoadsExtractsCost += BVCost;
20170 }
20171 NodesCosts.erase(TE);
20172 }
20173
20174 // Deleted all subtrees rooted at gathered loads nodes or splat subtrees.
20175 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
20176 if (TE->UserTreeIndex &&
20177 SubtreesToDelete.contains(TE->UserTreeIndex.UserTE)) {
20178 DeletedNodes.insert(TE.get());
20179 NodesCosts.erase(TE.get());
20180 SubtreesToDelete.insert(TE.get());
20181 }
20182 if (SubtreesToDelete.contains(TE.get()))
20183 DeletedNodes.insert(TE.get());
20184 }
20185
20186 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
20187 if (!TE->UserTreeIndex && TransformedToGatherNodes.contains(TE.get())) {
20188 assert(TE->getOpcode() == Instruction::Load && "Expected load only.");
20189 continue;
20190 }
20191 if (DeletedNodes.contains(TE.get()))
20192 continue;
20193 // Gather costs depend on the set of vectorized nodes available for
20194 // reuse, which changes during trimming, so recalculate them for all
20195 // gather nodes, not just for the transformed ones.
20196 if (TE->isGather() || !NodesCosts.contains(TE.get()))
20197 NodesCosts[TE.get()] = RecostEntry(TE.get());
20198 }
20199
20200 LLVM_DEBUG(dbgs() << "SLP: Recalculate costs after tree trimming.\n");
20201 InstructionCost NewCost = 0;
20202 for (const auto &P : NodesCosts) {
20203 NewCost += P.second;
20204 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << P.second << " for bundle "
20205 << shortBundleName(P.first->Scalars, P.first->Idx)
20206 << ".\n"
20207 << "SLP: Current total cost = " << NewCost << "\n");
20208 }
20209 // The trimming is reverted if the restored tree is not more expensive. The
20210 // restored tree is priced the same way as the trimmed one, from the per-node
20211 // costs: adjusting the pre-trimming total incrementally is not exact with
20212 // the auxiliary subtrees around, since the subtree costs recorded before the
20213 // trimming fold in the gathered loads they reuse, and the gathers inside a
20214 // subtree change their price once their reuse sources are dropped.
20215 auto ComputeRestoredCost = [&]() {
20216 DeletedNodes = OrigDeletedNodes;
20217 TransformedToGatherNodes.clear();
20218 NodesCosts = OrigNodesCosts;
20219 if (!SplatGatheredScalarsRoots.empty()) {
20220 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree)
20221 if (TE->isGather() && !DeletedNodes.contains(TE.get()))
20222 NodesCosts[TE.get()] = RecostEntry(TE.get());
20223 DropUnprofitableSplatSubtrees(/*EraseCosts=*/false);
20224 // Dropping the splat subtrees may leave the gathered loads subtrees
20225 // built for them without surviving gather users.
20226 DropDeadGatheredLoads(/*EraseCosts=*/false);
20227 for (const TreeEntry *TE : DeletedNodes)
20228 NodesCosts.erase(TE);
20229 }
20230 return SumNodesCosts();
20231 };
20232 const InstructionCost TrimmedCost = NewCost + LoadsExtractsCost;
20233 auto TrimmedDeletedNodes = DeletedNodes;
20234 auto TrimmedTransformedNodes = TransformedToGatherNodes;
20235 auto TrimmedNodesCosts = NodesCosts;
20236 const InstructionCost RestoredCost = ComputeRestoredCost();
20237 LLVM_DEBUG(dbgs() << "SLP: Trimmed tree cost = " << TrimmedCost
20238 << ", restored tree cost = " << RestoredCost << ".\n");
20239 const bool Reverted = TrimmedCost > RestoredCost ||
20240 (!PreferTrimmedTree && TrimmedCost == RestoredCost);
20241 if (Reverted) {
20242 NewCost = RestoredCost;
20243 } else {
20244 DeletedNodes = std::move(TrimmedDeletedNodes);
20245 TransformedToGatherNodes = std::move(TrimmedTransformedNodes);
20246 NodesCosts = std::move(TrimmedNodesCosts);
20247 // If the remaining tree is just a buildvector - exit, it will cause
20248 // endless attempts to vectorize.
20249 if (VectorizableTree.size() >= 2 && getRootNode().hasState() &&
20250 getRootNode().getOpcode() == Instruction::InsertElement &&
20251 TransformedToGatherNodes.contains(VectorizableTree[1].get()))
20253 if (VectorizableTree.size() >= 3 && getRootNode().hasState() &&
20254 getRootNode().getOpcode() == Instruction::InsertElement &&
20255 VectorizableTree[1]->hasState() &&
20256 VectorizableTree[1]->State == TreeEntry::Vectorize &&
20257 (VectorizableTree[1]->getOpcode() == Instruction::ZExt ||
20258 VectorizableTree[1]->getOpcode() == Instruction::SExt ||
20259 VectorizableTree[1]->getOpcode() == Instruction::Trunc) &&
20260 TransformedToGatherNodes.contains(VectorizableTree[2].get()))
20262 }
20263 TrimAuxSubtreesForInstCount(NewCost, /*UseCurrentNodeCosts=*/true);
20264 return NewCost;
20265}
20266
20267namespace {
20268/// Data type for handling buildvector sequences with the reused scalars from
20269/// other tree entries.
20270template <typename T> struct ShuffledInsertData {
20271 /// List of insertelements to be replaced by shuffles.
20272 SmallVector<InsertElementInst *> InsertElements;
20273 /// The parent vectors and shuffle mask for the given list of inserts.
20274 MapVector<T, SmallVector<int>> ValueMasks;
20275};
20276} // namespace
20277
20279 ArrayRef<Value *> VectorizedVals,
20280 InstructionCost ReductionCost,
20281 Instruction *RdxRoot) {
20282 // Reject vectorization if the vector code would produce more instructions
20283 // than the scalar code. The cost model may underestimate overhead from
20284 // shuffles, inserts, and extracts.
20285 // FIXME: remove this as soon as correct fractional model is landed for all
20286 // targets.
20287 if (CostKind != TTI::TCK_CodeSize && Opts.slp_inst_count_check &&
20288 TTI->preferSLPInstCountCheck() && getRootNode().getVectorFactor() == 2 &&
20289 getCostThreshold() == 0 &&
20290 (!Opts.slp_revec ||
20291 !isa<VectorType>(getRootNodeScalars().front()->getType()))) {
20292 // Loop containing the tree root; null for flat code or disabled
20293 // loop-aware modeling. Shared by both calls below.
20294 const Loop *TreeLoop = nullptr;
20295 if (Opts.slp_cost_loop_trip_count != 0 && getRootNode().hasState())
20296 TreeLoop = LI->getLoopFor(getRootNode().getMainOp()->getParent());
20297 uint64_t NumScalar = getNumScalarInsts(TreeLoop);
20298 uint64_t NumVector = getNumVectorInsts(TreeLoop);
20299 // In loops, the extracts are not scaled by the trip count and just break
20300 // the ties of the scaled counts. Ignore them under the high register
20301 // pressure: the vector code holds several lanes per register.
20302 if (NumVector > NumScalar && TreeLoop && !ExternalUses.empty()) {
20303 const uint64_t NumNoExtracts =
20304 getNumVectorInsts(TreeLoop, /*CountExtracts=*/false);
20305 Instruction *Root = getRootNode().getMainOp();
20306 if (NumNoExtracts <= NumScalar &&
20307 hasHighRegisterPressure(Opts.slp_schedule_budget, *Root->getParent(),
20308 getValueType(Root, Opts.slp_revec), *TTI))
20309 NumVector = NumNoExtracts;
20310 }
20311 LLVM_DEBUG(dbgs() << "SLP: Inst count check: vector=" << NumVector
20312 << " scalar=" << NumScalar << "\n");
20313 if (NumVector > NumScalar && !bypassesInstCountCheck(TreeCost)) {
20314 LLVM_DEBUG(dbgs() << "SLP: Rejecting tree: vector inst count "
20315 << NumVector << " > scalar inst count " << NumScalar
20316 << ".\n");
20318 }
20319 }
20320 InstructionCost Cost = TreeCost;
20321
20323 EntryToScale;
20324 auto ScaleCost = [&](InstructionCost C, const TreeEntry &TE,
20325 Value *Scalar = nullptr, Instruction *U = nullptr) {
20326 if (!C.isValid() || C == 0)
20327 return C;
20328 uint64_t &Scale =
20329 EntryToScale.try_emplace(std::make_tuple(&TE, Scalar, U), 0)
20330 .first->getSecond();
20331 if (!Scale)
20332 Scale = getScaleToLoopIterations(TE, Scalar, U);
20333 LLVM_DEBUG(dbgs() << "Scale " << Scale << " For entry " << TE.Idx << "\n");
20334 return C * Scale;
20335 };
20336 Instruction *ReductionRoot = RdxRoot;
20337 if (UserIgnoreList) {
20338 // Scale reduction cost to the factor of the loop nest trip count.
20339 ReductionCost = ScaleCost(ReductionCost, getRootNode(), /*Scalar=*/nullptr,
20340 ReductionRoot);
20341 }
20342
20343 // Add the cost for reduction.
20344 Cost += ReductionCost;
20345
20346 if (any_of(ExternalUses, [](const ExternalUser &EU) {
20347 return isa<StructType>(EU.Scalar->getType()) &&
20348 (EU.E.Idx != 0 || EU.E.State != TreeEntry::Vectorize ||
20349 EU.E.getOpcode() != Instruction::InsertValue) &&
20351 }))
20353
20354 // Skip trees, which are non-profitable even if there are insertelements with
20355 // external uses.
20356 constexpr unsigned CostLimit = 100;
20357 if (Cost >= -getCostThreshold() + CostLimit &&
20358 (VectorizableTree.size() - DeletedNodes.size()) *
20359 getRootNode().getVectorFactor() <
20360 CostLimit)
20361 return Cost;
20362
20363 if (Cost >= -getCostThreshold() &&
20364 none_of(ExternalUses, [](const ExternalUser &EU) {
20365 return isa_and_nonnull<InsertElementInst>(EU.User);
20366 }))
20367 return Cost;
20368
20370 ExtractCostCalculated;
20371 InstructionCost ExtractCost = 0;
20373 SmallVector<APInt> DemandedElts;
20374 SmallDenseSet<Value *, 4> UsedInserts;
20376 std::optional<DenseMap<Value *, unsigned>> ValueToExtUses;
20378 SmallPtrSet<Value *, 4> ScalarOpsFromCasts;
20379 // Keep track {Scalar, Index, User} tuple.
20380 // On AArch64, this helps in fusing a mov instruction, associated with
20381 // extractelement, with fmul in the backend so that extractelement is free.
20383 // Record every external use: a missing entry is indistinguishable from
20384 // lane 0 and is priced as a free extract by the extract-fusion cost model.
20385 for (ExternalUser &EU : ExternalUses)
20386 ScalarUserAndIdx.emplace_back(EU.Scalar, EU.User, EU.Lane);
20387 // Detect external uses that drive address computations: the scalar (through
20388 // an optional single-use index-promotion cast) is used as a GEP index.
20389 bool AllUsersGEPSWithStoresLoads = true;
20391 Type *UserScalarTy = nullptr;
20392 for (ExternalUser &EU : ExternalUses) {
20393 Value *Usr = EU.User;
20394 if (Usr && match(Usr, m_OneUse(m_ZExtOrSExt(m_Value()))))
20395 Usr = cast<Instruction>(Usr)->user_back();
20397 // Only a GEP that feeds a single load/store of a fixed access type drives
20398 // a real memory address computation.
20399 Type *AccessTy = nullptr;
20400 if (User && User->hasOneUse() &&
20402 AccessTy = getValueType(User->user_back(), Opts.slp_revec);
20403 if (AccessTy && !isa<ScalableVectorType>(AccessTy) &&
20404 (!UserScalarTy || UserScalarTy == AccessTy)) {
20405 UserScalarTy = AccessTy;
20406 Pointers.push_back(User);
20407 } else {
20408 AllUsersGEPSWithStoresLoads = false;
20409 break;
20410 }
20411 }
20412
20413 // Pre-pass: for each externally-used scalar, find the basic block at which
20414 // the extractelement will be placed by codegen. This mirrors what
20415 // vectorizeTree does: the extract is placed at the nearest common dominator
20416 // of all effective use sites. For a non-PHI user the effective site is the
20417 // user's own block; for a PHI user it is the incoming block for the scalar
20418 // operand (the predecessor of the PHI on the edge that carries the scalar).
20419 // Using the NCD of all effective sites rather than the first-encountered
20420 // user's block makes the extract-cost scale order-independent and correct
20421 // even when users live in different loop nests.
20422 SmallDenseMap<Value *, BasicBlock *> ScalarToExtractBlock;
20423 for (const ExternalUser &EU :
20424 make_filter_range(ExternalUses, [](const ExternalUser &EU) {
20425 return EU.User && !isa<InsertElementInst>(EU.User);
20426 })) {
20427 if (EphValues.count(EU.User))
20428 continue;
20429 BasicBlock *UserParent = cast<Instruction>(EU.User)->getParent();
20430 if (!DT->isReachableFromEntry(UserParent) || UserParent->isEHPad() ||
20431 isa<UnreachableInst>(UserParent->getTerminator()))
20432 continue;
20433 BasicBlock *UseBlock = nullptr;
20434 if (auto *PHI = dyn_cast<PHINode>(EU.User)) {
20435 // When the PHI itself is inside a loop, the extractelement is placed
20436 // in the incoming block for the scalar operand (the predecessor edge),
20437 // not in the PHI's own block. This applies to LCSSA phis at an inner-
20438 // loop exit that are still inside an outer loop: the incoming block is
20439 // in the inner loop while the PHI block is in the outer loop.
20440 // When the PHI is outside all loops (a true loop-exit phi), codegen
20441 // uses a vector phi at the exit block and the extract stays there
20442 // (scale = 1), so we keep the PHI's own block as the effective site.
20443 if (LI->getLoopFor(PHI->getParent())) {
20444 for (unsigned Idx : seq<unsigned>(PHI->getNumIncomingValues())) {
20445 if (PHI->getIncomingValue(Idx) != EU.Scalar)
20446 continue;
20447 BasicBlock *InBB = PHI->getIncomingBlock(Idx);
20448 UseBlock =
20449 UseBlock ? DT->findNearestCommonDominator(UseBlock, InBB) : InBB;
20450 }
20451 }
20452 if (!UseBlock)
20453 UseBlock = cast<Instruction>(EU.User)->getParent();
20454 } else {
20455 UseBlock = cast<Instruction>(EU.User)->getParent();
20456 }
20457 auto [It, Inserted] = ScalarToExtractBlock.try_emplace(EU.Scalar, UseBlock);
20458 if (!Inserted && It->second && UseBlock)
20459 It->second = DT->findNearestCommonDominator(It->second, UseBlock);
20460 }
20461
20462 SmallDenseSet<std::pair<Value *, Value *>, 8> CheckedScalarUser;
20463 for (ExternalUser &EU : ExternalUses) {
20464 LLVM_DEBUG(dbgs() << "SLP: Computing cost for external use of TreeEntry "
20465 << EU.E.Idx << " in lane " << EU.Lane << "\n");
20466 LLVM_DEBUG(if (EU.User) dbgs() << " User:" << *EU.User << "\n";
20467 else dbgs() << " User: nullptr\n");
20468 LLVM_DEBUG(dbgs() << " Use: " << EU.Scalar->getNameOrAsOperand() << "\n");
20469
20470 // Uses by ephemeral values are free (because the ephemeral value will be
20471 // removed prior to code generation, and so the extraction will be
20472 // removed as well).
20473 if (EphValues.count(EU.User))
20474 continue;
20475
20476 // Check if the scalar for the given user or all users is accounted already.
20477 if (!CheckedScalarUser.insert(std::make_pair(EU.Scalar, EU.User)).second ||
20478 (EU.User &&
20479 CheckedScalarUser.contains(std::make_pair(EU.Scalar, nullptr))))
20480 continue;
20481
20482 // Used in unreachable blocks or in EH pads (rarely executed) or is
20483 // terminated with unreachable instruction.
20484 if (BasicBlock *UserParent =
20485 EU.User ? cast<Instruction>(EU.User)->getParent() : nullptr;
20486 UserParent &&
20487 (!DT->isReachableFromEntry(UserParent) || UserParent->isEHPad() ||
20488 isa<UnreachableInst>(UserParent->getTerminator())))
20489 continue;
20490
20491 // No extract cost for vector "scalar" if REVEC is disabled.
20492 if (isVectorizedTy(EU.Scalar->getType()) &&
20493 (!Opts.slp_revec ||
20494 (EU.E.hasState() && EU.E.getOpcode() == Instruction::InsertElement)))
20495 continue;
20496
20497 if (isa<InsertValueInst>(EU.Scalar))
20498 continue;
20499
20500 // If found user is an insertelement, do not calculate extract cost but try
20501 // to detect it as a final shuffled/identity match.
20502 // TODO: what if a user is insertvalue when REVEC is enabled?
20503 if (auto *VU = dyn_cast_if_present<InsertElementInst>(EU.User);
20504 VU && VU->getOperand(1) == EU.Scalar) {
20505 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
20506 if (!UsedInserts.insert(VU).second)
20507 continue;
20508 std::optional<unsigned> InsertIdx = getElementIndex(VU);
20509 if (InsertIdx) {
20510 const TreeEntry *ScalarTE = &EU.E;
20511 auto *It = find_if(
20512 ShuffledInserts,
20513 [this, VU](const ShuffledInsertData<const TreeEntry *> &Data) {
20514 // Checks if 2 insertelements are from the same buildvector.
20515 InsertElementInst *VecInsert = Data.InsertElements.front();
20517 VU, VecInsert, [this](InsertElementInst *II) -> Value * {
20518 Value *Op0 = II->getOperand(0);
20519 if (isVectorized(II) && !isVectorized(Op0))
20520 return nullptr;
20521 return Op0;
20522 });
20523 });
20524 int VecId = -1;
20525 if (It == ShuffledInserts.end()) {
20526 auto &Data = ShuffledInserts.emplace_back();
20527 Data.InsertElements.emplace_back(VU);
20528 DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
20529 VecId = ShuffledInserts.size() - 1;
20530 auto It = MinBWs.find(ScalarTE);
20531 if (It != MinBWs.end() &&
20532 VectorCasts
20533 .insert(std::make_pair(ScalarTE, FTy->getElementType()))
20534 .second) {
20535 unsigned BWSz = It->second.first;
20536 unsigned DstBWSz = DL->getTypeSizeInBits(FTy->getElementType());
20537 unsigned VecOpcode;
20538 if (DstBWSz < BWSz)
20539 VecOpcode = Instruction::Trunc;
20540 else
20541 VecOpcode =
20542 It->second.second ? Instruction::SExt : Instruction::ZExt;
20543 InstructionCost C = TTI->getCastInstrCost(
20544 VecOpcode, FTy,
20545 getWidenedType(IntegerType::get(FTy->getContext(), BWSz),
20546 FTy->getNumElements()),
20547 getCastContextHint(*ScalarTE), CostKind);
20548 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
20549 << " for extending externally used vector with "
20550 "non-equal minimum bitwidth.\n");
20551 Cost += C;
20552 }
20553 } else {
20554 if (isFirstInsertElement(VU, It->InsertElements.front()))
20555 It->InsertElements.front() = VU;
20556 VecId = std::distance(ShuffledInserts.begin(), It);
20557 }
20558 int InIdx = *InsertIdx;
20559 SmallVectorImpl<int> &Mask =
20560 ShuffledInserts[VecId].ValueMasks[ScalarTE];
20561 if (Mask.empty())
20562 Mask.assign(FTy->getNumElements(), PoisonMaskElem);
20563 Mask[InIdx] = EU.Lane;
20564 DemandedElts[VecId].setBit(InIdx);
20565 continue;
20566 }
20567 }
20568 }
20569
20570 // If we plan to rewrite the tree in a smaller type, we will need to sign
20571 // extend the extracted value back to the original type. Here, we account
20572 // for the extract and the added cost of the sign extend if needed.
20573 InstructionCost ExtraCost = TTI::TCC_Free;
20574 auto *ScalarTy = EU.Scalar->getType();
20575 const unsigned BundleWidth = EU.E.getVectorFactor();
20576 assert(EU.Lane < BundleWidth && "Extracted lane out of bounds.");
20577 auto *VecTy = getWidenedType(ScalarTy, BundleWidth);
20578 const TreeEntry *Entry = &EU.E;
20579 auto It = MinBWs.find(Entry);
20581 if (isa<StructType>(VecTy)) {
20582 assert(EU.User && "Expected user for struct extract");
20583 const auto *EV = cast<ExtractValueInst>(EU.User);
20584 Indices.assign(EV->getIndices());
20585 }
20586 // We only add extract cost once for the same scalar and struct field.
20587 auto ExtractKey = std::make_pair(EU.Scalar, Indices);
20588 if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
20589 !ExtractCostCalculated.insert(ExtractKey).second)
20590 continue;
20591 if (It != MinBWs.end()) {
20592 Type *MinTy = IntegerType::get(F->getContext(), It->second.first);
20593 if (auto *VecTy = dyn_cast<FixedVectorType>(ScalarTy))
20594 MinTy = getWidenedType(MinTy, VecTy->getNumElements());
20595 unsigned Extend = isKnownNonNegative(EU.Scalar, SimplifyQuery(*DL))
20596 ? Instruction::ZExt
20597 : Instruction::SExt;
20598 VecTy = getWidenedType(MinTy, BundleWidth);
20599 ExtraCost =
20600 getExtractWithExtendCost(*TTI, Opts.slp_revec, Extend, ScalarTy,
20601 cast<VectorType>(VecTy), EU.Lane, CostKind);
20602 LLVM_DEBUG(dbgs() << " ExtractExtend or ExtractSubvec cost: "
20603 << ExtraCost << "\n");
20604 } else {
20605 Type *ExtractTy = VecTy;
20606 if (auto *ST = dyn_cast<StructType>(VecTy)) {
20607 ExtractTy = ExtractValueInst::getIndexedType(ST, Indices);
20608 }
20609 ExtraCost = getVectorInstrCost(
20610 *TTI, Opts.slp_revec, ScalarTy, Instruction::ExtractElement,
20611 ExtractTy, CostKind, EU.Lane, EU.Scalar, ScalarUserAndIdx);
20612 LLVM_DEBUG(dbgs() << " ExtractElement cost for " << *ScalarTy << " from "
20613 << *VecTy << ": " << ExtraCost << "\n");
20614 }
20615 // Leave the scalar instructions as is if they are cheaper than extracts.
20616 if (Entry->Idx != 0 || Entry->getOpcode() == Instruction::GetElementPtr ||
20617 Entry->getOpcode() == Instruction::Load) {
20618 // Checks if the user of the external scalar is phi in loop body.
20619 auto IsPhiInLoop = [&](const ExternalUser &U) {
20620 if (auto *Phi = dyn_cast_if_present<PHINode>(U.User)) {
20621 auto *I = cast<Instruction>(U.Scalar);
20622 const Loop *L = LI->getLoopFor(Phi->getParent());
20623 return L && (Phi->getParent() == I->getParent() ||
20624 L == LI->getLoopFor(I->getParent()));
20625 }
20626 return false;
20627 };
20628 if (!ValueToExtUses) {
20629 ValueToExtUses.emplace();
20630 // Ignore phis in loops.
20631 for (const auto &P :
20632 make_filter_range(enumerate(ExternalUses), [&](const auto &P) {
20633 return !IsPhiInLoop(P.value());
20634 }))
20635 ValueToExtUses->try_emplace(P.value().Scalar, P.index());
20636 }
20637 // Can use original instruction, if no operands vectorized or they are
20638 // marked as externally used already.
20639 auto *Inst = cast<Instruction>(EU.Scalar);
20640 InstructionCost ScalarCost = TTI->getInstructionCost(Inst, CostKind);
20641 auto OperandIsScalar = [&](Value *V) {
20642 if (!isVectorized(V)) {
20643 // Some extractelements might be not vectorized, but
20644 // transformed into shuffle and removed from the function,
20645 // consider it here.
20646 if (auto *EE = dyn_cast<ExtractElementInst>(V))
20647 return !EE->hasOneUse() || !MustGather.contains(EE);
20648 return true;
20649 }
20650 if (isa<StructType>(V->getType()))
20651 return false;
20652 return ValueToExtUses->contains(V);
20653 };
20654 // The original freeze may produce a value different from the vector lane
20655 // if its operand is undef or poison.
20656 bool CanBeUsedAsScalar =
20657 !isa<FreezeInst>(Inst) && all_of(Inst->operands(), OperandIsScalar);
20658 bool CanBeUsedAsScalarCast = false;
20659 if (auto *CI = dyn_cast<CastInst>(Inst); CI && !CanBeUsedAsScalar) {
20660 if (auto *Op = dyn_cast<Instruction>(CI->getOperand(0));
20661 Op && !isa<FreezeInst>(Op) &&
20662 all_of(Op->operands(), OperandIsScalar)) {
20663 InstructionCost OpCost =
20664 (isVectorized(Op) && !ValueToExtUses->contains(Op))
20665 ? TTI->getInstructionCost(Op, CostKind)
20666 : 0;
20667 if (ScalarCost + OpCost <= ExtraCost) {
20668 CanBeUsedAsScalar = CanBeUsedAsScalarCast = true;
20669 ScalarCost += OpCost;
20670 }
20671 }
20672 }
20673 if (CanBeUsedAsScalar) {
20674 bool KeepScalar = ScalarCost <= ExtraCost;
20675 // Try to keep original scalar if the user is the phi node from the same
20676 // block as the root phis, currently vectorized. It allows to keep
20677 // better ordering info of PHIs, being vectorized currently.
20678 bool IsProfitablePHIUser =
20679 (KeepScalar || (ScalarCost - ExtraCost <= TTI::TCC_Basic &&
20680 getRootNodeScalars().size() > 2)) &&
20681 getRootNode().hasState() &&
20682 getRootNode().getOpcode() == Instruction::PHI &&
20683 !Inst->hasNUsesOrMore(UsesLimit) &&
20684 none_of(Inst->users(),
20685 [&](User *U) {
20686 auto *PHIUser = dyn_cast<PHINode>(U);
20687 return (!PHIUser ||
20688 PHIUser->getParent() !=
20689 getRootNode().getMainOp()->getParent()) &&
20690 !isVectorized(U);
20691 }) &&
20692 count_if(Entry->Scalars, [&](Value *V) {
20693 return ValueToExtUses->contains(V);
20694 }) <= 2;
20695 // The extracted address index hides the consecutive accesses of the
20696 // users from the later trees.
20697 auto *GEPUser = dyn_cast_if_present<GetElementPtrInst>(EU.User);
20698 const bool IsAddressIndex =
20699 GEPUser && GEPUser->getPointerOperand() != EU.Scalar;
20700 if (IsProfitablePHIUser) {
20701 KeepScalar = true;
20702 } else if (KeepScalar && ScalarCost != TTI::TCC_Free &&
20703 ExtraCost - ScalarCost <= TTI::TCC_Basic &&
20704 !IsAddressIndex &&
20705 (!GatheredLoadsEntriesFirst.has_value() ||
20706 Entry->Idx < *GatheredLoadsEntriesFirst)) {
20707 unsigned ScalarUsesCount = count_if(Entry->Scalars, [&](Value *V) {
20708 return ValueToExtUses->contains(V);
20709 });
20710 auto It = ExtractsCount.find(Entry);
20711 if (It != ExtractsCount.end()) {
20712 assert(ScalarUsesCount >= It->getSecond().size() &&
20713 "Expected total number of external uses not less than "
20714 "number of scalar uses.");
20715 ScalarUsesCount -= It->getSecond().size();
20716 }
20717 // Keep original scalar if number of externally used instructions in
20718 // the same entry is not power of 2. It may help to do some extra
20719 // vectorization for now.
20720 KeepScalar = ScalarUsesCount <= 1 || !has_single_bit(ScalarUsesCount);
20721 }
20722 if (KeepScalar) {
20723 ExternalUsesAsOriginalScalar.insert(EU.Scalar);
20724 // Struct operands cannot be rebuilt by the !User extraction
20725 // path (it has no insertvalue chain), so leave their existing
20726 // ExtractValueInst user in place.
20727 for (Value *V : make_filter_range(Inst->operands(), [](Value *V) {
20728 return !isa<StructType>(V->getType());
20729 })) {
20730 auto It = ValueToExtUses->find(V);
20731 if (It != ValueToExtUses->end()) {
20732 // Replace all uses to avoid compiler crash.
20733 ExternalUses[It->second].User = nullptr;
20734 }
20735 }
20736 ExtraCost = ScalarCost;
20737 if (!IsPhiInLoop(EU))
20738 ExtractsCount[Entry].insert(Inst);
20739 if (CanBeUsedAsScalarCast) {
20740 ScalarOpsFromCasts.insert(Inst->getOperand(0));
20741 // Update the users of the operands of the cast operand to avoid
20742 // compiler crash.
20743 if (auto *IOp = dyn_cast<Instruction>(Inst->getOperand(0))) {
20744 for (Value *V : make_filter_range(IOp->operands(), [](Value *V) {
20745 return !isa<StructType>(V->getType());
20746 })) {
20747 auto It = ValueToExtUses->find(V);
20748 if (It != ValueToExtUses->end()) {
20749 // Replace all uses to avoid compiler crash.
20750 ExternalUses[It->second].User = nullptr;
20751 }
20752 }
20753 }
20754 }
20755 }
20756 }
20757 }
20758
20759 // Scale the extract cost by the execution frequency of the block where
20760 // codegen will place the extractelement. That block is the nearest common
20761 // dominator of all effective use sites (precomputed in ScalarToExtractBlock
20762 // above), which is order-independent. For scalars kept as originals the
20763 // existing ScaleCost path (user-block based) remains correct, since the
20764 // scalar instruction executes at its definition site's frequency.
20765 if (!ExternalUsesAsOriginalScalar.contains(EU.Scalar)) {
20766 if (ExtraCost.isValid() && ExtraCost != 0) {
20767 if (!EU.User) {
20768 // No external user instruction is recorded (User == nullptr): the
20769 // scalar stays live in vectorized instructions or is used as an
20770 // extra arg, and is not present in ScalarToExtractBlock (the
20771 // pre-pass only records sites of real users). vectorizeTree() then
20772 // places the extractelement right after the vectorized instruction
20773 // (in the entry's block) and replaces the scalar uses with it, so
20774 // scale by the entry block's execution frequency to match that
20775 // placement.
20776 ExtraCost = ScaleCost(ExtraCost, *Entry, EU.Scalar, /*U=*/nullptr);
20777 } else {
20778 BasicBlock *ExtractBB = ScalarToExtractBlock.lookup(EU.Scalar);
20779 if (const Loop *L = ExtractBB ? LI->getLoopFor(ExtractBB) : nullptr) {
20780 uint64_t Scale = getLoopNestScale(
20783 << "SLP: Extract scale " << Scale << " (NCD block) for "
20784 << EU.Scalar->getNameOrAsOperand() << "\n");
20785 ExtraCost *= Scale;
20786 }
20787 }
20788 }
20789 } else {
20790 ExtraCost = ScaleCost(ExtraCost, *Entry, EU.Scalar,
20792 }
20793
20794 ExtractCost += ExtraCost;
20795 }
20796 // Charge the pointer-chain cost difference once when every escaped scalar
20797 // is used only to drive an address computation (see the detection loop
20798 // above). Vectorizing the tree in this pattern forces lane extracts (or a
20799 // vector GEP with unknown stride) to drive the address computation, which is
20800 // typically more expensive than keeping the indices scalar in a unit-stride
20801 // address chain. Add the delta once rather than per external use.
20802 if (AllUsersGEPSWithStoresLoads && !Pointers.empty()) {
20803 const TreeEntry &RootEntry = getRootNode();
20804 const Value *CommonBase = getUnderlyingObject(Pointers.front());
20805 if (all_of(Pointers, [CommonBase](const Value *P) {
20806 return getUnderlyingObject(P) == CommonBase;
20807 })) {
20808 auto *VecTy = getWidenedType(UserScalarTy, RootEntry.Scalars.size());
20809 InstructionCost ScalarGEPCost = TTI->getPointersChainCost(
20810 Pointers, CommonBase, TTI::PointersChainInfo::getUnitStride(),
20811 UserScalarTy, CostKind);
20812 InstructionCost VectorGEPCost = TTI->getPointersChainCost(
20813 Pointers, CommonBase, TTI::PointersChainInfo::getUnknownStride(),
20814 VecTy, CostKind);
20815 ExtractCost += ScaleCost(VectorGEPCost - ScalarGEPCost, RootEntry);
20816 }
20817 }
20818 // Insert externals for extract of operands of casts to be emitted as scalars
20819 // instead of extractelement.
20820 for (Value *V : ScalarOpsFromCasts) {
20821 ExternalUsesAsOriginalScalar.insert(V);
20822 if (ArrayRef<TreeEntry *> TEs = getTreeEntries(V); !TEs.empty()) {
20823 const auto *It = find_if_not(TEs, [&](TreeEntry *TE) {
20824 return TransformedToGatherNodes.contains(TE) ||
20825 DeletedNodes.contains(TE);
20826 });
20827 if (It != TEs.end()) {
20828 const TreeEntry *UserTE = *It;
20829 ExternalUses.emplace_back(V, nullptr, *UserTE,
20830 UserTE->findLaneForValue(V));
20831 }
20832 }
20833 }
20834 // Add reduced value cost, if resized.
20835 if (!VectorizedVals.empty()) {
20836 const TreeEntry &Root = getRootNode();
20837 auto BWIt = MinBWs.find(&Root);
20838 if (BWIt != MinBWs.end()) {
20839 Type *DstTy = Root.Scalars.front()->getType();
20840 unsigned OriginalSz = DL->getTypeSizeInBits(DstTy->getScalarType());
20841 unsigned SrcSz =
20842 ReductionBitWidth == 0 ? BWIt->second.first : ReductionBitWidth;
20843 if (OriginalSz != SrcSz) {
20844 unsigned Opcode = Instruction::Trunc;
20845 if (OriginalSz > SrcSz)
20846 Opcode = BWIt->second.second ? Instruction::SExt : Instruction::ZExt;
20847 Type *SrcTy = IntegerType::get(DstTy->getContext(), SrcSz);
20848 if (auto *VecTy = dyn_cast<FixedVectorType>(DstTy)) {
20849 assert(Opts.slp_revec && "Only supported by REVEC.");
20850 SrcTy = getWidenedType(SrcTy, VecTy->getNumElements());
20851 }
20852 InstructionCost CastCost = TTI->getCastInstrCost(
20853 Opcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind);
20854 CastCost = ScaleCost(CastCost, Root, /*Scalar=*/nullptr, ReductionRoot);
20855 Cost += CastCost;
20856 }
20857 }
20858 }
20859
20860 // Buildvector with externally used scalars, which should remain as scalars,
20861 // should not be vectorized, the compiler may hang.
20862 if (getCostThreshold() < 0 && VectorizableTree.size() > 1 &&
20863 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
20864 VectorizableTree[1]->hasState() &&
20865 VectorizableTree[1]->State == TreeEntry::Vectorize &&
20866 all_of(VectorizableTree[1]->Scalars, [&](Value *V) {
20867 return ExternalUsesAsOriginalScalar.contains(V);
20868 }))
20870
20871 Cost += ExtractCost;
20872 auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask,
20873 bool ForSingleMask) {
20874 InstructionCost C = 0;
20875 unsigned VF = Mask.size();
20876 unsigned VecVF = TE->getVectorFactor();
20877 bool HasLargeIndex =
20878 any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); });
20879 if ((VF != VecVF && HasLargeIndex) ||
20881
20882 if (HasLargeIndex) {
20883 SmallVector<int> OrigMask(VecVF, PoisonMaskElem);
20884 std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
20885 OrigMask.begin());
20886 C = getShuffleCost(
20888 cast<VectorType>(getWidenedType(TE->getMainOp()->getType(), VecVF)),
20889 CostKind, OrigMask);
20890 LLVM_DEBUG(
20891 dbgs() << "SLP: Adding cost " << C
20892 << " for final shuffle of insertelement external users.\n";
20893 TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
20894 Cost += C;
20895 return std::make_pair(TE, true);
20896 }
20897
20898 if (!ForSingleMask) {
20899 SmallVector<int> ResizeMask(VF, PoisonMaskElem);
20900 for (unsigned I = 0; I < VF; ++I) {
20901 if (Mask[I] != PoisonMaskElem)
20902 ResizeMask[Mask[I]] = Mask[I];
20903 }
20904 if (!ShuffleVectorInst::isIdentityMask(ResizeMask, VF))
20907 TE->getMainOp()->getType(), VecVF)),
20908 CostKind, ResizeMask);
20909 LLVM_DEBUG(
20910 dbgs() << "SLP: Adding cost " << C
20911 << " for final shuffle of insertelement external users.\n";
20912 TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
20913
20914 Cost += C;
20915 }
20916 }
20917 return std::make_pair(TE, false);
20918 };
20919 // Calculate the cost of the reshuffled vectors, if any.
20920 for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) {
20921 Value *Base = ShuffledInserts[I].InsertElements.front()->getOperand(0);
20922 auto Vector = ShuffledInserts[I].ValueMasks.takeVector();
20923 unsigned VF = 0;
20924 auto EstimateShufflesCost = [&](ArrayRef<int> Mask,
20926 assert((TEs.size() == 1 || TEs.size() == 2) &&
20927 "Expected exactly 1 or 2 tree entries.");
20928 if (TEs.size() == 1) {
20929 if (VF == 0)
20930 VF = TEs.front()->getVectorFactor();
20931 auto *FTy = getWidenedType(TEs.back()->Scalars.front()->getType(), VF);
20932 if (!ShuffleVectorInst::isIdentityMask(Mask, VF) &&
20933 !all_of(enumerate(Mask), [=](const auto &Data) {
20934 return Data.value() == PoisonMaskElem ||
20935 (Data.index() < VF &&
20936 static_cast<int>(Data.index()) == Data.value());
20937 })) {
20940 cast<VectorType>(FTy), CostKind, Mask);
20941 C = ScaleCost(C, *TEs.front());
20942 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
20943 << " for final shuffle of insertelement "
20944 "external users.\n";
20945 TEs.front()->dump();
20946 dbgs() << "SLP: Current total cost = " << Cost << "\n");
20947 Cost += C;
20948 }
20949 } else {
20950 if (VF == 0) {
20951 if (TEs.front() &&
20952 TEs.front()->getVectorFactor() == TEs.back()->getVectorFactor())
20953 VF = TEs.front()->getVectorFactor();
20954 else
20955 VF = Mask.size();
20956 }
20957 auto *FTy = getWidenedType(TEs.back()->Scalars.front()->getType(), VF);
20959 *TTI, TTI::SK_PermuteTwoSrc, cast<VectorType>(FTy), CostKind, Mask);
20960 C = ScaleCost(C, *TEs.back());
20961 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
20962 << " for final shuffle of vector node and external "
20963 "insertelement users.\n";
20964 if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
20965 dbgs() << "SLP: Current total cost = " << Cost << "\n");
20966 Cost += C;
20967 }
20968 VF = Mask.size();
20969 return TEs.back();
20970 };
20972 MutableArrayRef(Vector.data(), Vector.size()), Base,
20973 [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
20974 EstimateShufflesCost);
20975 InstructionCost InsertCost = TTI->getScalarizationOverhead(
20977 ShuffledInserts[I].InsertElements.front()->getType()),
20978 DemandedElts[I],
20979 /*Insert*/ true, /*Extract*/ false, CostKind);
20980 Cost -= InsertCost;
20981 }
20982
20983 // Add the cost for reduced value resize (if required).
20984 if (ReductionBitWidth != 0) {
20985 assert(UserIgnoreList && "Expected reduction tree.");
20986 const TreeEntry &E = getRootNode();
20987 auto It = MinBWs.find(&E);
20988 if (It != MinBWs.end() && It->second.first != ReductionBitWidth) {
20989 unsigned SrcSize = It->second.first;
20990 unsigned DstSize = ReductionBitWidth;
20991 unsigned Opcode = Instruction::Trunc;
20992 if (SrcSize < DstSize) {
20993 bool IsArithmeticExtendedReduction =
20994 all_of(*UserIgnoreList, [](Value *V) {
20995 auto *I = cast<Instruction>(V);
20996 return is_contained({Instruction::Add, Instruction::FAdd,
20997 Instruction::Mul, Instruction::FMul,
20998 Instruction::And, Instruction::Or,
20999 Instruction::Xor},
21000 I->getOpcode());
21001 });
21002 if (IsArithmeticExtendedReduction)
21003 Opcode =
21004 Instruction::BitCast; // Handle it by getExtendedReductionCost
21005 else
21006 Opcode = It->second.second ? Instruction::SExt : Instruction::ZExt;
21007 }
21008 if (Opcode != Instruction::BitCast) {
21009 auto *SrcVecTy =
21010 getWidenedType(Builder.getIntNTy(SrcSize), E.getVectorFactor());
21011 auto *DstVecTy =
21012 getWidenedType(Builder.getIntNTy(DstSize), E.getVectorFactor());
21014 switch (E.getOpcode()) {
21015 case Instruction::SExt:
21016 case Instruction::ZExt:
21017 case Instruction::Trunc: {
21018 // Split and gather roots have no operand entry to take the context
21019 // hint from.
21020 if (E.isGather() || E.State == TreeEntry::SplitVectorize)
21021 break;
21022 const TreeEntry *OpTE = getOperandEntry(&E, 0);
21023 CCH = getCastContextHint(*OpTE);
21024 break;
21025 }
21026 default:
21027 break;
21028 }
21029 InstructionCost CastCost =
21030 TTI->getCastInstrCost(Opcode, DstVecTy, SrcVecTy, CCH, CostKind);
21031 CastCost = ScaleCost(CastCost, getRootNode(), /*Scalar=*/nullptr,
21032 ReductionRoot);
21033 Cost += CastCost;
21034 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << CastCost
21035 << " for final resize for reduction from " << SrcVecTy
21036 << " to " << DstVecTy << "\n";
21037 dbgs() << "SLP: Current total cost = " << Cost << "\n");
21038 }
21039 }
21040 }
21041
21042 std::optional<InstructionCost> SpillCost;
21043 if (Cost < -getCostThreshold()) {
21044 SpillCost = getSpillCost();
21045 Cost += *SpillCost;
21046 }
21047#ifndef NDEBUG
21048 SmallString<256> Str;
21049 {
21050 raw_svector_ostream OS(Str);
21051 OS << "SLP: Spill Cost = ";
21052 if (SpillCost)
21053 OS << *SpillCost;
21054 else
21055 OS << "<skipped>";
21056 OS << ".\nSLP: Extract Cost = " << ExtractCost << ".\n";
21057 if (ReductionRoot)
21058 OS << "SLP: Reduction Cost = " << ReductionCost << ".\n";
21059 OS << "SLP: Total Cost = " << Cost << ".\n";
21060 }
21061 LLVM_DEBUG(dbgs() << Str);
21062 if (Opts.view_slp_tree)
21063 ViewGraph(this, "SLP" + F->getName(), false, Str);
21064#endif
21065
21066 return Cost;
21067}
21068
21069/// Tries to find extractelement instructions with constant indices from fixed
21070/// vector type and gather such instructions into a bunch, which highly likely
21071/// might be detected as a shuffle of 1 or 2 input vectors. If this attempt was
21072/// successful, the matched scalars are replaced by poison values in \p VL for
21073/// future analysis.
21074std::optional<TTI::ShuffleKind>
21075BoUpSLP::tryToGatherSingleRegisterExtractElements(
21077 // Scan list of gathered scalars for extractelements that can be represented
21078 // as shuffles.
21080 SmallVector<int> UndefVectorExtracts;
21081 for (int I = 0, E = VL.size(); I < E; ++I) {
21082 auto *EI = dyn_cast<ExtractElementInst>(VL[I]);
21083 if (!EI) {
21084 if (isa<UndefValue>(VL[I]))
21085 UndefVectorExtracts.push_back(I);
21086 continue;
21087 }
21088 auto *VecTy = dyn_cast<FixedVectorType>(EI->getVectorOperandType());
21089 if (!VecTy || !isa<ConstantInt, UndefValue>(EI->getIndexOperand()))
21090 continue;
21091 std::optional<unsigned> Idx = getExtractIndex(EI);
21092 // Undefined index.
21093 if (!Idx) {
21094 UndefVectorExtracts.push_back(I);
21095 continue;
21096 }
21097 if (Idx >= VecTy->getNumElements()) {
21098 UndefVectorExtracts.push_back(I);
21099 continue;
21100 }
21101 SmallBitVector ExtractMask(VecTy->getNumElements(), true);
21102 ExtractMask.reset(*Idx);
21103 if (isUndefVector</*IsPoisonOnly=*/true>(EI->getVectorOperand(),
21104 ExtractMask)
21105 .all()) {
21106 UndefVectorExtracts.push_back(I);
21107 continue;
21108 }
21109 VectorOpToIdx[EI->getVectorOperand()].push_back(I);
21110 }
21111 // Sort the vector operands by the maximum number of uses in extractelements.
21113 VectorOpToIdx.takeVector();
21114 stable_sort(Vectors, [](const auto &P1, const auto &P2) {
21115 return P1.second.size() > P2.second.size();
21116 });
21117 // Find the best pair of the vectors or a single vector.
21118 const int UndefSz = UndefVectorExtracts.size();
21119 unsigned SingleMax = 0;
21120 unsigned PairMax = 0;
21121 if (!Vectors.empty()) {
21122 SingleMax = Vectors.front().second.size() + UndefSz;
21123 if (Vectors.size() > 1) {
21124 auto *ItNext = std::next(Vectors.begin());
21125 PairMax = SingleMax + ItNext->second.size();
21126 }
21127 }
21128 if (SingleMax == 0 && PairMax == 0 && UndefSz == 0)
21129 return std::nullopt;
21130 // Check if better to perform a shuffle of 2 vectors or just of a single
21131 // vector.
21132 SmallVector<Value *> SavedVL(VL.begin(), VL.end());
21133 SmallVector<Value *> GatheredExtracts(
21134 VL.size(), PoisonValue::get(VL.front()->getType()));
21135 if (SingleMax >= PairMax && SingleMax) {
21136 for (int Idx : Vectors.front().second)
21137 std::swap(GatheredExtracts[Idx], VL[Idx]);
21138 } else if (!Vectors.empty()) {
21139 for (unsigned Idx : {0, 1})
21140 for (int Idx : Vectors[Idx].second)
21141 std::swap(GatheredExtracts[Idx], VL[Idx]);
21142 }
21143 // Add extracts from undefs too.
21144 for (int Idx : UndefVectorExtracts)
21145 std::swap(GatheredExtracts[Idx], VL[Idx]);
21146 // Check that gather of extractelements can be represented as just a
21147 // shuffle of a single/two vectors the scalars are extracted from.
21148 std::optional<TTI::ShuffleKind> Res =
21149 isFixedVectorShuffle(GatheredExtracts, Mask, AC, Cache);
21150 if (!Res || all_of(Mask, equal_to(PoisonMaskElem))) {
21151 // TODO: try to check other subsets if possible.
21152 // Restore the original VL and mask if attempt was not successful.
21153 copy(SavedVL, VL.begin());
21154 Mask.assign(VL.size(), PoisonMaskElem);
21155 return std::nullopt;
21156 }
21157 // Restore unused scalars from mask, if some of the extractelements were not
21158 // selected for shuffle.
21159 for (int I = 0, E = GatheredExtracts.size(); I < E; ++I) {
21160 if (Mask[I] == PoisonMaskElem && !isa<PoisonValue>(GatheredExtracts[I]) &&
21161 isa<UndefValue>(GatheredExtracts[I])) {
21162 std::swap(VL[I], GatheredExtracts[I]);
21163 continue;
21164 }
21165 auto *EI = dyn_cast<ExtractElementInst>(VL[I]);
21166 if (!EI || !isa<FixedVectorType>(EI->getVectorOperandType()) ||
21167 !isa<ConstantInt, UndefValue>(EI->getIndexOperand()) ||
21168 is_contained(UndefVectorExtracts, I))
21169 continue;
21170 }
21171 return Res;
21172}
21173
21174/// Tries to find extractelement instructions with constant indices from fixed
21175/// vector type and gather such instructions into a bunch, which highly likely
21176/// might be detected as a shuffle of 1 or 2 input vectors. If this attempt was
21177/// successful, the matched scalars are replaced by poison values in \p VL for
21178/// future analysis.
21180BoUpSLP::tryToGatherExtractElements(SmallVectorImpl<Value *> &VL,
21181 SmallVectorImpl<int> &Mask,
21182 unsigned NumParts) const {
21183 assert(NumParts > 0 && "NumParts expected be greater than or equal to 1.");
21185 Mask.assign(VL.size(), PoisonMaskElem);
21186 unsigned SliceSize = getPartNumElems(VL.size(), NumParts);
21187 for (unsigned Part : seq<unsigned>(NumParts)) {
21188 // Scan list of gathered scalars for extractelements that can be represented
21189 // as shuffles.
21190 const unsigned PartOffset = Part * SliceSize;
21191 const unsigned PartSize = getNumElems(VL.size(), SliceSize, Part);
21192 // It may happen in case of revec, need to check no access out of bounds.
21193 if (PartOffset + PartSize > VL.size())
21194 break;
21196 MutableArrayRef(VL).slice(PartOffset, PartSize);
21197 SmallVector<int> SubMask;
21198 std::optional<TTI::ShuffleKind> Res =
21199 tryToGatherSingleRegisterExtractElements(SubVL, SubMask);
21200 ShufflesRes[Part] = Res;
21201 copy(SubMask, std::next(Mask.begin(), Part * SliceSize));
21202 if (SubVL.size() != SliceSize)
21203 break;
21204 }
21205 if (none_of(ShufflesRes, [](const std::optional<TTI::ShuffleKind> &Res) {
21206 return Res.has_value();
21207 }))
21208 ShufflesRes.clear();
21209 return ShufflesRes;
21210}
21211
21212std::optional<TargetTransformInfo::ShuffleKind>
21213BoUpSLP::isGatherShuffledSingleRegisterEntry(
21214 const TreeEntry *TE, ArrayRef<Value *> VL, MutableArrayRef<int> Mask,
21215 SmallVectorImpl<const TreeEntry *> &Entries, unsigned Part, bool ForOrder,
21216 unsigned SliceSize) {
21217 Entries.clear();
21218 if (TE->Idx == 0)
21219 return std::nullopt;
21220 const unsigned MaskBase = Part * SliceSize;
21221 // TODO: currently checking only for Scalars in the tree entry, need to count
21222 // reused elements too for better cost estimation.
21223 auto GetUserEntry = [&](const TreeEntry *TE) {
21224 while (TE->UserTreeIndex && TE->UserTreeIndex.EdgeIdx == UINT_MAX)
21225 TE = TE->UserTreeIndex.UserTE;
21226 if (TE == &getRootNode())
21227 return EdgeInfo(const_cast<TreeEntry *>(TE), 0);
21228 return TE->UserTreeIndex;
21229 };
21230 auto HasGatherUser = [&](const TreeEntry *TE) {
21231 while (TE->Idx != 0 && TE->UserTreeIndex) {
21232 if (TE->UserTreeIndex.EdgeIdx == UINT_MAX)
21233 return true;
21234 TE = TE->UserTreeIndex.UserTE;
21235 }
21236 return false;
21237 };
21238 const EdgeInfo TEUseEI = GetUserEntry(TE);
21239 if (!TEUseEI || (TEUseEI.UserTE->Idx == 0 && TEUseEI.UserTE->isGather() &&
21240 !TEUseEI.UserTE->hasState()))
21241 return std::nullopt;
21242 const Instruction *TEInsertPt = &getLastInstructionInBundle(TEUseEI.UserTE);
21243 const BasicBlock *TEInsertBlock = nullptr;
21244 // Main node of PHI entries keeps the correct order of operands/incoming
21245 // blocks.
21246 if (auto *PHI = TEUseEI.UserTE->hasState()
21247 ? dyn_cast<PHINode>(TEUseEI.UserTE->getMainOp())
21248 : nullptr;
21249 PHI && TEUseEI.UserTE->State != TreeEntry::SplitVectorize) {
21250 TEInsertBlock = PHI->getIncomingBlock(TEUseEI.EdgeIdx);
21251 TEInsertPt = TEInsertBlock->getTerminator();
21252 } else {
21253 TEInsertBlock = TEInsertPt->getParent();
21254 }
21255 if (!DT->isReachableFromEntry(TEInsertBlock))
21256 return std::nullopt;
21257 auto *NodeUI = DT->getNode(TEInsertBlock);
21258 assert(NodeUI && "Should only process reachable instructions");
21259 SmallPtrSet<Value *, 4> GatheredScalars(llvm::from_range, VL);
21260 auto CheckOrdering = [&](const Instruction *InsertPt) {
21261 // Argument InsertPt is an instruction where vector code for some other
21262 // tree entry (one that shares one or more scalars with TE) is going to be
21263 // generated. This lambda returns true if insertion point of vector code
21264 // for the TE dominates that point (otherwise dependency is the other way
21265 // around). The other node is not limited to be of a gather kind. Gather
21266 // nodes are not scheduled and their vector code is inserted before their
21267 // first user. If user is PHI, that is supposed to be at the end of a
21268 // predecessor block. Otherwise it is the last instruction among scalars of
21269 // the user node. So, instead of checking dependency between instructions
21270 // themselves, we check dependency between their insertion points for vector
21271 // code (since each scalar instruction ends up as a lane of a vector
21272 // instruction).
21273 const BasicBlock *InsertBlock = InsertPt->getParent();
21274 auto *NodeEUI = DT->getNode(InsertBlock);
21275 if (!NodeEUI)
21276 return false;
21277 assert((NodeUI == NodeEUI) ==
21278 (NodeUI->getDFSNumIn() == NodeEUI->getDFSNumIn()) &&
21279 "Different nodes should have different DFS numbers");
21280 // Check the order of the gather nodes users.
21281 if (TEInsertPt->getParent() != InsertBlock &&
21282 (DT->dominates(NodeUI, NodeEUI) || !DT->dominates(NodeEUI, NodeUI)))
21283 return false;
21284 if (TEInsertPt->getParent() == InsertBlock &&
21285 TEInsertPt->comesBefore(InsertPt))
21286 return false;
21287 return true;
21288 };
21289 // Find all tree entries used by the gathered values. If no common entries
21290 // found - not a shuffle.
21291 // Here we build a set of tree nodes for each gathered value and trying to
21292 // find the intersection between these sets. If we have at least one common
21293 // tree node for each gathered value - we have just a permutation of the
21294 // single vector. If we have 2 different sets, we're in situation where we
21295 // have a permutation of 2 input vectors.
21297 SmallDenseMap<Value *, int> UsedValuesEntry;
21298 SmallPtrSet<const Value *, 16> VisitedValue;
21299 bool IsReusedNodeFound = false;
21300 auto CheckAndUseSameNode = [&](const TreeEntry *TEPtr) {
21301 // The node is reused - exit.
21302 if (IsReusedNodeFound)
21303 return false;
21304 if ((TEPtr->getVectorFactor() != VL.size() &&
21305 TEPtr->Scalars.size() != VL.size()) ||
21306 (!TEPtr->isSame(VL) && !TEPtr->isSame(TE->Scalars)))
21307 return false;
21308 IsReusedNodeFound =
21309 equal(TE->Scalars, TEPtr->Scalars) &&
21310 equal(TE->ReorderIndices, TEPtr->ReorderIndices) &&
21311 equal(TE->ReuseShuffleIndices, TEPtr->ReuseShuffleIndices);
21312 UsedTEs.clear();
21313 UsedTEs.emplace_back().insert(TEPtr);
21314 auto IsNotConstant = [](Value *V) { return !isConstant(V); };
21315 for (Value *V : make_filter_range(VL, IsNotConstant))
21316 UsedValuesEntry.try_emplace(V, 0);
21317 return true;
21318 };
21319 auto CheckParentNodes = [&](const TreeEntry *User1, const TreeEntry *User2,
21320 unsigned EdgeIdx) {
21321 const TreeEntry *Ptr1 = User1;
21322 const TreeEntry *Ptr2 = User2;
21323 SmallDenseMap<const TreeEntry *, unsigned> PtrToIdx;
21324 while (Ptr2) {
21325 PtrToIdx.try_emplace(Ptr2, EdgeIdx);
21326 EdgeIdx = Ptr2->UserTreeIndex.EdgeIdx;
21327 Ptr2 = Ptr2->UserTreeIndex.UserTE;
21328 }
21329 while (Ptr1) {
21330 unsigned Idx = Ptr1->UserTreeIndex.EdgeIdx;
21331 Ptr1 = Ptr1->UserTreeIndex.UserTE;
21332 if (auto It = PtrToIdx.find(Ptr1); It != PtrToIdx.end())
21333 return Idx < It->second;
21334 }
21335 return false;
21336 };
21337 // Cache `isUsedOutsideBlock(TEInsertPt)` - TEInsertPt is loop-invariant and
21338 // the function walks the instruction's user list.
21339 std::optional<bool> TEInsertPtUsedOutsideBlock;
21340 auto IsTEInsertPtUsedOutsideBlock = [&] {
21341 if (!TEInsertPtUsedOutsideBlock)
21342 TEInsertPtUsedOutsideBlock =
21343 isUsedOutsideBlock(const_cast<Instruction *>(TEInsertPt));
21344 return *TEInsertPtUsedOutsideBlock;
21345 };
21346 // Cache the TEUseEI/TEInsertPt-only prefix of the per-call lambda predicate
21347 // below - all of these depend only on outer-scope state, not the lambda's
21348 // arguments.
21349 const bool TEUseEIInsertPtUsedOutside =
21350 TEUseEI && TEUseEI.UserTE && TEUseEI.UserTE->hasCopyableElements() &&
21351 !TEUseEI.UserTE->isCopyableElement(
21352 const_cast<Instruction *>(TEInsertPt)) &&
21353 IsTEInsertPtUsedOutsideBlock();
21354 auto CheckNonSchedulableOrdering = [&](const TreeEntry *E,
21355 Instruction *InsertPt) {
21356 return TEUseEIInsertPtUsedOutside &&
21357 InsertPt->getNextNode() == TEInsertPt &&
21358 (!E->hasCopyableElements() || !E->isCopyableElement(InsertPt) ||
21359 !isUsedOutsideBlock(InsertPt));
21360 };
21361 // Cache the TEUseEI.UserTE-dependent predicate - it is invariant across the
21362 // double loop below. all_of with isUsedOutsideBlock walks each scalar's
21363 // users and is the expensive component.
21364 const bool TEUserNeedsEmitFirst =
21365 TEUseEI.UserTE->State == TreeEntry::Vectorize &&
21366 TEUseEI.UserTE->hasState() &&
21367 (TEUseEI.UserTE->getOpcode() != Instruction::PHI ||
21368 TEUseEI.UserTE->isAltShuffle()) &&
21369 all_of(TEUseEI.UserTE->Scalars, isUsedOutsideBlock);
21370 // Cache `all_of(UserTE->Scalars, isUsedOutsideBlock)` per UserTE - the
21371 // same UserTE may be encountered for many TEPtr values inside the loop.
21372 SmallDenseMap<const TreeEntry *, bool> ScalarsUsedOutsideBlockCache;
21373 auto AllScalarsUsedOutsideBlock = [&](const TreeEntry *UserTE) {
21374 auto [It, Inserted] = ScalarsUsedOutsideBlockCache.try_emplace(UserTE);
21375 if (!Inserted)
21376 return It->second;
21377 bool Res = all_of(UserTE->Scalars, isUsedOutsideBlock);
21378 It->second = Res;
21379 return Res;
21380 };
21381 for (Value *V : VL) {
21382 if (isConstant(V) || !VisitedValue.insert(V).second)
21383 continue;
21384 // Build a list of tree entries where V is used.
21385 SmallPtrSet<const TreeEntry *, 4> VToTEs;
21387 ValueToGatherNodes.lookup(V).takeVector());
21388 if (TransformedToGatherNodes.contains(TE)) {
21389 auto IsLiveUserGather = [&](TreeEntry *E) {
21390 return TE != E && TransformedToGatherNodes.contains(E) &&
21391 E->UserTreeIndex && !E->UserTreeIndex.UserTE->isGather();
21392 };
21393 for (TreeEntry *E :
21394 make_filter_range(getSplitTreeEntries(V), IsLiveUserGather))
21395 GatherNodes.push_back(E);
21396 for (TreeEntry *E :
21397 make_filter_range(getTreeEntries(V), IsLiveUserGather))
21398 GatherNodes.push_back(E);
21399 } else if (const TreeEntry *E = getSameValuesTreeEntry(V, TE->Scalars);
21400 E && !TEUserNeedsEmitFirst &&
21401 TransformedToGatherNodes.contains(E) && E->UserTreeIndex &&
21402 E->UserTreeIndex.UserTE == TE->UserTreeIndex.UserTE &&
21403 !E->UserTreeIndex.UserTE->isGather()) {
21404 // Regular gathers reuse only perfectly matched transformed nodes of the
21405 // same user. Gathers, emitted before their user, cannot reuse transformed
21406 // nodes, which are emitted with the user.
21407 GatherNodes.push_back(E);
21408 }
21409 for (const TreeEntry *TEPtr :
21410 make_filter_range(GatherNodes, [&](const TreeEntry *TEPtr) {
21411 return TEPtr != TE && TEPtr->Idx != 0 &&
21412 !DeletedNodes.contains(TEPtr);
21413 })) {
21414 assert(any_of(TEPtr->Scalars,
21415 [&](Value *V) { return GatheredScalars.contains(V); }) &&
21416 "Must contain at least single gathered value.");
21417 assert(TEPtr->UserTreeIndex &&
21418 "Expected only single user of a gather node.");
21419 if (any_of(TEPtr->CombinedEntriesWithIndices,
21420 [&](const auto &P) { return P.first == TE->Idx; }))
21421 continue;
21422 const EdgeInfo &UseEI = TEPtr->UserTreeIndex;
21423
21424 PHINode *UserPHI = (UseEI.UserTE->State != TreeEntry::SplitVectorize &&
21425 UseEI.UserTE->hasState())
21426 ? dyn_cast<PHINode>(UseEI.UserTE->getMainOp())
21427 : nullptr;
21428 Instruction *InsertPt =
21429 UserPHI ? UserPHI->getIncomingBlock(UseEI.EdgeIdx)->getTerminator()
21430 : &getLastInstructionInBundle(UseEI.UserTE);
21431 if (TEInsertPt == InsertPt) {
21432 // Check nodes, which might be emitted first.
21433 if (TEUserNeedsEmitFirst) {
21434 if (UseEI.UserTE->State != TreeEntry::Vectorize ||
21435 (UseEI.UserTE->hasState() &&
21436 UseEI.UserTE->getOpcode() == Instruction::PHI &&
21437 !UseEI.UserTE->isAltShuffle()) ||
21438 !AllScalarsUsedOutsideBlock(UseEI.UserTE))
21439 continue;
21440 }
21441
21442 // If the schedulable insertion point is used in multiple entries - just
21443 // exit, no known ordering at this point, available only after real
21444 // scheduling.
21445 if (!doesNotNeedToBeScheduled(InsertPt) &&
21446 (TEUseEI.UserTE != UseEI.UserTE || TEUseEI.EdgeIdx < UseEI.EdgeIdx))
21447 continue;
21448 // If the users are the PHI nodes with the same incoming blocks - skip.
21449 if (TEUseEI.UserTE->State == TreeEntry::Vectorize &&
21450 TEUseEI.UserTE->getOpcode() == Instruction::PHI &&
21451 UseEI.UserTE->State == TreeEntry::Vectorize &&
21452 UseEI.UserTE->getOpcode() == Instruction::PHI &&
21453 TEUseEI.UserTE != UseEI.UserTE)
21454 continue;
21455 // If 2 gathers are operands of the same entry (regardless of whether
21456 // user is PHI or else), compare operands indices, use the earlier one
21457 // as the base.
21458 if (TEUseEI.UserTE == UseEI.UserTE && TEUseEI.EdgeIdx < UseEI.EdgeIdx)
21459 continue;
21460 // If the user instruction is used for some reason in different
21461 // vectorized nodes - make it depend on index.
21462 if (TEUseEI.UserTE != UseEI.UserTE &&
21463 (TEUseEI.UserTE->Idx < UseEI.UserTE->Idx ||
21464 HasGatherUser(TEUseEI.UserTE)))
21465 continue;
21466 // If the user node is the operand of the other user node - skip.
21467 if (CheckParentNodes(TEUseEI.UserTE, UseEI.UserTE, UseEI.EdgeIdx))
21468 continue;
21469 }
21470
21471 if (!TEUseEI.UserTE->isGather() && !UserPHI &&
21472 TEUseEI.UserTE->doesNotNeedToSchedule() !=
21473 UseEI.UserTE->doesNotNeedToSchedule() &&
21474 is_contained(UseEI.UserTE->Scalars, TEInsertPt))
21475 continue;
21476 // Check if the user node of the TE comes after user node of TEPtr,
21477 // otherwise TEPtr depends on TE.
21478 if ((TEInsertBlock != InsertPt->getParent() ||
21479 TEUseEI.EdgeIdx < UseEI.EdgeIdx || TEUseEI.UserTE != UseEI.UserTE) &&
21480 (!CheckOrdering(InsertPt) ||
21481 (UseEI.UserTE->hasCopyableElements() &&
21482 IsTEInsertPtUsedOutsideBlock() &&
21483 is_contained(UseEI.UserTE->Scalars, TEInsertPt))))
21484 continue;
21485 // The node is reused - exit.
21486 if (CheckAndUseSameNode(TEPtr))
21487 break;
21488 // The parent node is copyable with last inst used outside? And the last
21489 // inst is the next inst for the lastinst of TEPtr? Exit, if yes, to
21490 // preserve def-use chain.
21491 if (CheckNonSchedulableOrdering(UseEI.UserTE, InsertPt))
21492 continue;
21493 VToTEs.insert(TEPtr);
21494 }
21495 if (ArrayRef<TreeEntry *> VTEs = getSplitTreeEntries(V); !VTEs.empty()) {
21496 const auto *It = find_if(VTEs, [&](const TreeEntry *MTE) {
21497 return MTE != TE && MTE != TEUseEI.UserTE &&
21498 !DeletedNodes.contains(MTE) &&
21499 !TransformedToGatherNodes.contains(MTE);
21500 });
21501 if (It != VTEs.end()) {
21502 const TreeEntry *VTE = *It;
21503 if (none_of(TE->CombinedEntriesWithIndices,
21504 [&](const auto &P) { return P.first == VTE->Idx; })) {
21505 Instruction &LastBundleInst = getLastInstructionInBundle(VTE);
21506 if (&LastBundleInst == TEInsertPt || !CheckOrdering(&LastBundleInst))
21507 continue;
21508 }
21509 // The node is reused - exit.
21510 if (CheckAndUseSameNode(VTE))
21511 break;
21512 VToTEs.insert(VTE);
21513 }
21514 }
21515 ArrayRef<TreeEntry *> VTEs = getTreeEntries(V);
21516 // The wide loads also hold the copyable loads.
21517 if (auto It = CopyableLoadsToTreeEntries.find(V);
21518 VTEs.empty() && It != CopyableLoadsToTreeEntries.end())
21519 VTEs = It->second;
21520 if (!VTEs.empty()) {
21521 const auto *It = find_if(VTEs, [&, MainTE = TE](const TreeEntry *TE) {
21522 return TE != MainTE && !DeletedNodes.contains(TE) &&
21523 !TransformedToGatherNodes.contains(TE);
21524 });
21525 if (It != VTEs.end()) {
21526 const TreeEntry *VTE = *It;
21527 if (ForOrder && VTE->Idx < GatheredLoadsEntriesFirst.value_or(0) &&
21528 VTEs.size() > 1 && VTE->State != TreeEntry::Vectorize) {
21529 VTEs = VTEs.drop_front();
21530 // Iterate through all vectorized nodes.
21531 const auto *MIt = find_if(VTEs, [](const TreeEntry *MTE) {
21532 return MTE->State == TreeEntry::Vectorize;
21533 });
21534 if (MIt == VTEs.end())
21535 continue;
21536 VTE = *MIt;
21537 }
21538 if (none_of(TE->CombinedEntriesWithIndices,
21539 [&](const auto &P) { return P.first == VTE->Idx; })) {
21540 Instruction &LastBundleInst = getLastInstructionInBundle(VTE);
21541 if (&LastBundleInst == TEInsertPt ||
21542 !CheckOrdering(&LastBundleInst) ||
21543 CheckNonSchedulableOrdering(VTE, &LastBundleInst))
21544 continue;
21545 }
21546 // The node is reused - exit.
21547 if (CheckAndUseSameNode(VTE))
21548 break;
21549 VToTEs.insert(VTE);
21550 }
21551 }
21552 if (IsReusedNodeFound)
21553 break;
21554 if (VToTEs.empty())
21555 continue;
21556 if (UsedTEs.empty()) {
21557 // The first iteration, just insert the list of nodes to vector.
21558 UsedTEs.push_back(VToTEs);
21559 UsedValuesEntry.try_emplace(V, 0);
21560 } else {
21561 // Need to check if there are any previously used tree nodes which use V.
21562 // If there are no such nodes, consider that we have another one input
21563 // vector.
21564 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
21565 unsigned Idx = 0;
21566 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
21567 // Do we have a non-empty intersection of previously listed tree entries
21568 // and tree entries using current V?
21569 set_intersect(VToTEs, Set);
21570 if (!VToTEs.empty()) {
21571 // Yes, write the new subset and continue analysis for the next
21572 // scalar.
21573 Set.swap(VToTEs);
21574 break;
21575 }
21576 VToTEs = SavedVToTEs;
21577 ++Idx;
21578 }
21579 // No non-empty intersection found - need to add a second set of possible
21580 // source vectors.
21581 if (Idx == UsedTEs.size()) {
21582 // If the number of input vectors is greater than 2 - not a permutation,
21583 // fallback to the regular gather.
21584 // TODO: support multiple reshuffled nodes.
21585 if (UsedTEs.size() == 2)
21586 continue;
21587 UsedTEs.push_back(SavedVToTEs);
21588 Idx = UsedTEs.size() - 1;
21589 }
21590 UsedValuesEntry.try_emplace(V, Idx);
21591 }
21592 }
21593
21594 if (UsedTEs.empty()) {
21595 Entries.clear();
21596 return std::nullopt;
21597 }
21598
21599 unsigned VF = 0;
21600 if (UsedTEs.size() == 1) {
21601 // Keep the order to avoid non-determinism.
21602 SmallVector<const TreeEntry *> FirstEntries(UsedTEs.front().begin(),
21603 UsedTEs.front().end());
21604 sort(FirstEntries, [](const TreeEntry *TE1, const TreeEntry *TE2) {
21605 return TE1->Idx < TE2->Idx;
21606 });
21607 // Try to find the perfect match in another gather node at first.
21608 auto *It = find_if(FirstEntries, [=](const TreeEntry *EntryPtr) {
21609 return (EntryPtr->getVectorFactor() == TE->Scalars.size() &&
21610 EntryPtr->isSame(TE->Scalars)) ||
21611 EntryPtr->isSame(VL);
21612 });
21613 if (It != FirstEntries.end() &&
21614 (IsReusedNodeFound || (*It)->getVectorFactor() == VL.size() ||
21615 ((*It)->getVectorFactor() == TE->Scalars.size() &&
21616 TE->ReuseShuffleIndices.size() == VL.size() &&
21617 (*It)->isSame(TE->Scalars)))) {
21618 Entries.push_back(*It);
21619 if (IsReusedNodeFound || (*It)->getVectorFactor() == VL.size()) {
21620 std::iota(std::next(Mask.begin(), MaskBase),
21621 std::next(Mask.begin(), MaskBase + VL.size()), 0);
21622 } else {
21623 SmallVector<int> CommonMask = TE->getCommonMask();
21624 copy(CommonMask, Mask.begin());
21625 }
21626 // Clear undef scalars.
21627 for (unsigned I : seq<unsigned>(VL.size()))
21628 if (isa<PoisonValue>(VL[I]))
21629 Mask[MaskBase + I] = PoisonMaskElem;
21631 }
21632 // No perfect match, just shuffle, so choose the first tree node from the
21633 // tree.
21634 Entries.push_back(FirstEntries.front());
21635 // Update mapping between values and corresponding tree entries.
21636 for (auto &P : UsedValuesEntry)
21637 P.second = 0;
21638 VF = FirstEntries.front()->getVectorFactor();
21639 } else {
21640 // Try to find nodes with the same vector factor.
21641 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
21642 // Keep the order of tree nodes to avoid non-determinism.
21643 DenseMap<int, const TreeEntry *> VFToTE;
21644 for (const TreeEntry *TE : UsedTEs.front()) {
21645 unsigned VF = TE->getVectorFactor();
21646 auto It = VFToTE.find(VF);
21647 if (It != VFToTE.end()) {
21648 if (It->second->Idx > TE->Idx)
21649 It->getSecond() = TE;
21650 continue;
21651 }
21652 VFToTE.try_emplace(VF, TE);
21653 }
21654 // Same, keep the order to avoid non-determinism.
21655 SmallVector<const TreeEntry *> SecondEntries(UsedTEs.back().begin(),
21656 UsedTEs.back().end());
21657 sort(SecondEntries, [](const TreeEntry *TE1, const TreeEntry *TE2) {
21658 return TE1->Idx < TE2->Idx;
21659 });
21660 for (const TreeEntry *TE : SecondEntries) {
21661 auto It = VFToTE.find(TE->getVectorFactor());
21662 if (It != VFToTE.end()) {
21663 VF = It->first;
21664 Entries.push_back(It->second);
21665 Entries.push_back(TE);
21666 break;
21667 }
21668 }
21669 // No 2 source vectors with the same vector factor - just choose 2 with max
21670 // index.
21671 if (Entries.empty()) {
21673 UsedTEs.front(), [](const TreeEntry *TE1, const TreeEntry *TE2) {
21674 return TE1->Idx < TE2->Idx;
21675 }));
21676 Entries.push_back(SecondEntries.front());
21677 VF = std::max(Entries.front()->getVectorFactor(),
21678 Entries.back()->getVectorFactor());
21679 } else {
21680 VF = Entries.front()->getVectorFactor();
21681 }
21682 SmallVector<SmallPtrSet<Value *, 8>> ValuesToEntries;
21683 for (const TreeEntry *E : Entries)
21684 ValuesToEntries.emplace_back().insert(E->Scalars.begin(),
21685 E->Scalars.end());
21686 // Update mapping between values and corresponding tree entries.
21687 for (auto &P : UsedValuesEntry) {
21688 for (unsigned Idx : seq<unsigned>(ValuesToEntries.size()))
21689 if (ValuesToEntries[Idx].contains(P.first)) {
21690 P.second = Idx;
21691 break;
21692 }
21693 }
21694 }
21695
21696 bool IsSplatOrUndefs = isSplat(VL) || all_of(VL, IsaPred<UndefValue>);
21697 // Checks if the 2 PHIs are compatible in terms of high possibility to be
21698 // vectorized.
21699 auto AreCompatiblePHIs = [&](Value *V, Value *V1) {
21700 auto *PHI = cast<PHINode>(V);
21701 auto *PHI1 = cast<PHINode>(V1);
21702 // Check that all incoming values are compatible/from same parent (if they
21703 // are instructions).
21704 // The incoming values are compatible if they all are constants, or
21705 // instruction with the same/alternate opcodes from the same basic block.
21706 for (int I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
21707 Value *In = PHI->getIncomingValue(I);
21708 Value *In1 = PHI1->getIncomingValue(I);
21709 if (isConstant(In) && isConstant(In1))
21710 continue;
21711 if (!getSameOpcode({In, In1}, *TLI))
21712 return false;
21713 if (cast<Instruction>(In)->getParent() !=
21715 return false;
21716 }
21717 return true;
21718 };
21719 // Check if the value can be ignored during analysis for shuffled gathers.
21720 // We suppose it is better to ignore instruction, which do not form splats,
21721 // are not vectorized/not extractelements (these instructions will be handled
21722 // by extractelements processing) or may form vector node in future.
21723 // Cache results - each V in VL is queried up to 3 times (direct +
21724 // NeighborMightBeIgnored from both neighbors), and areAllUsersVectorized
21725 // walks each instruction's user list.
21726 SmallDenseMap<Value *, bool> MightBeIgnoredCache;
21727 auto MightBeIgnored = [=, &MightBeIgnoredCache](Value *V) {
21728 auto [It, Inserted] = MightBeIgnoredCache.try_emplace(V);
21729 if (!Inserted)
21730 return It->second;
21731 auto *I = dyn_cast<Instruction>(V);
21732 bool Res = I && !IsSplatOrUndefs && !isVectorized(I) &&
21734 !areAllUsersVectorized(I, UserIgnoreList) && isSimple(I);
21735 It->second = Res;
21736 return Res;
21737 };
21738 // Check that the neighbor instruction may form a full vector node with the
21739 // current instruction V. It is possible, if they have same/alternate opcode
21740 // and same parent basic block.
21741 auto NeighborMightBeIgnored = [&](Value *V, int Idx) {
21742 Value *V1 = VL[Idx];
21743 bool UsedInSameVTE = false;
21744 auto It = UsedValuesEntry.find(V1);
21745 if (It != UsedValuesEntry.end())
21746 UsedInSameVTE = It->second == UsedValuesEntry.find(V)->second;
21747 return V != V1 && MightBeIgnored(V1) && !UsedInSameVTE &&
21748 getSameOpcode({V, V1}, *TLI) &&
21749 cast<Instruction>(V)->getParent() ==
21750 cast<Instruction>(V1)->getParent() &&
21751 (!isa<PHINode>(V1) || AreCompatiblePHIs(V, V1));
21752 };
21753 // Build a shuffle mask for better cost estimation and vector emission.
21754 SmallBitVector UsedIdxs(Entries.size());
21756 for (int I = 0, E = VL.size(); I < E; ++I) {
21757 Value *V = VL[I];
21758 auto It = UsedValuesEntry.find(V);
21759 if (It == UsedValuesEntry.end())
21760 continue;
21761 // Do not try to shuffle scalars, if they are constants, or instructions
21762 // that can be vectorized as a result of the following vector build
21763 // vectorization.
21764 if (isConstant(V) || (MightBeIgnored(V) &&
21765 ((I > 0 && NeighborMightBeIgnored(V, I - 1)) ||
21766 (I != E - 1 && NeighborMightBeIgnored(V, I + 1)))))
21767 continue;
21768 unsigned Idx = It->second;
21769 EntryLanes.emplace_back(Idx, I);
21770 UsedIdxs.set(Idx);
21771 }
21772 // Iterate through all shuffled scalars and select entries, which can be used
21773 // for final shuffle.
21775 for (unsigned I = 0, Sz = Entries.size(); I < Sz; ++I) {
21776 if (!UsedIdxs.test(I))
21777 continue;
21778 // Fix the entry number for the given scalar. If it is the first entry, set
21779 // Pair.first to 0, otherwise to 1 (currently select at max 2 nodes).
21780 // These indices are used when calculating final shuffle mask as the vector
21781 // offset.
21782 for (std::pair<unsigned, int> &Pair : EntryLanes)
21783 if (Pair.first == I)
21784 Pair.first = TempEntries.size();
21785 TempEntries.push_back(Entries[I]);
21786 }
21787 Entries.swap(TempEntries);
21788 if (EntryLanes.size() == Entries.size() &&
21789 !VL.equals(ArrayRef(TE->Scalars)
21790 .slice(MaskBase, getNumElems(TE->Scalars.size(), SliceSize,
21791 Part)))) {
21792 // We may have here 1 or 2 entries only. If the number of scalars is equal
21793 // to the number of entries, no need to do the analysis, it is not very
21794 // profitable. Since VL is not the same as TE->Scalars, it means we already
21795 // have some shuffles before. Cut off not profitable case.
21796 Entries.clear();
21797 return std::nullopt;
21798 }
21799 // Build the final mask, check for the identity shuffle, if possible.
21800 bool IsIdentity = Entries.size() == 1;
21801 // Pair.first is the offset to the vector, while Pair.second is the index of
21802 // scalar in the list.
21803 for (const std::pair<unsigned, int> &Pair : EntryLanes) {
21804 unsigned Idx = MaskBase + Pair.second;
21805 Mask[Idx] =
21806 Pair.first * VF +
21807 (ForOrder ? std::distance(
21808 Entries[Pair.first]->Scalars.begin(),
21809 find(Entries[Pair.first]->Scalars, VL[Pair.second]))
21810 : Entries[Pair.first]->findLaneForValue(VL[Pair.second]));
21811 IsIdentity &= Mask[Idx] == Pair.second;
21812 }
21813 if (ForOrder || IsIdentity || Entries.empty()) {
21814 switch (Entries.size()) {
21815 case 1:
21816 if (IsIdentity || EntryLanes.size() > 1 || VL.size() <= 2)
21818 break;
21819 case 2:
21820 if (EntryLanes.size() > 2 || VL.size() <= 2)
21822 break;
21823 default:
21824 break;
21825 }
21826 } else if (!isa<VectorType>(VL.front()->getType()) &&
21827 (EntryLanes.size() > Entries.size() || VL.size() <= 2)) {
21828 // Do the cost estimation if shuffle beneficial than buildvector.
21829 SmallVector<int> SubMask(std::next(Mask.begin(), MaskBase),
21830 std::next(Mask.begin(), MaskBase + VL.size()));
21831 int MinElement = SubMask.front(), MaxElement = SubMask.front();
21832 for (int Idx : make_filter_range(
21833 SubMask, [](int Idx) { return Idx != PoisonMaskElem; })) {
21834 if (MinElement == PoisonMaskElem || MinElement % VF > Idx % VF)
21835 MinElement = Idx;
21836 if (MaxElement == PoisonMaskElem || MaxElement % VF < Idx % VF)
21837 MaxElement = Idx;
21838 }
21839 assert(MaxElement >= 0 && MinElement >= 0 &&
21840 MaxElement % VF >= MinElement % VF &&
21841 "Expected at least single element.");
21842 // If the leading [0, MinIdx) range sits in its own register part(s),
21843 // skip those whole parts when sizing the destination - everything below
21844 // the register-aligned floor is unused and never indexed.
21845 unsigned Offset = 0;
21846 unsigned MinIdx = MinElement % VF;
21847 if (MinIdx > 1) {
21848 unsigned RegFloor = getFloorFullVectorNumberOfElements(
21849 *TTI, VL.front()->getType(), MinIdx, Opts.slp_revec);
21850 auto *RegFloorTy = getWidenedType(VL.front()->getType(), RegFloor);
21851 unsigned RegFloorParts =
21852 getNumberOfParts(RegFloorTy, VL.front()->getType(), RegFloor);
21853 if (RegFloorParts > 1)
21854 Offset = RegFloor;
21855 }
21856 unsigned NewVF =
21857 std::max<unsigned>(VL.size(), (MaxElement % VF) - Offset + 1);
21858 if (NewVF < VF) {
21859 for (int &Idx : make_filter_range(
21860 SubMask, [](int Idx) { return Idx != PoisonMaskElem; }))
21861 Idx = (Idx % VF) - Offset + (Idx >= static_cast<int>(VF) ? NewVF : 0);
21862 } else {
21863 NewVF = VF;
21864 }
21865
21866 auto *VecTy =
21867 cast<VectorType>(getWidenedType(VL.front()->getType(), NewVF));
21868 auto *MaskVecTy =
21869 cast<VectorType>(getWidenedType(VL.front()->getType(), SubMask.size()));
21870 auto GetShuffleCost = [&,
21871 &TTI = *TTI](ArrayRef<int> Mask,
21873 VectorType *VecTy) -> InstructionCost {
21874 if (Entries.size() == 1 && Entries.front()->getInterleaveFactor() > 0 &&
21876 Mask, Entries.front()->getInterleaveFactor()))
21877 return TTI::TCC_Free;
21878 return getShuffleCost(TTI,
21879 Entries.size() > 1 ? TTI::SK_PermuteTwoSrc
21881 VecTy, CostKind, Mask);
21882 };
21883 InstructionCost ShuffleCost = GetShuffleCost(SubMask, Entries, VecTy);
21884 InstructionCost FirstShuffleCost = 0;
21885 SmallVector<int> FirstMask(SubMask.begin(), SubMask.end());
21886 if (Entries.size() == 1 || !Entries[0]->isGather()) {
21887 FirstShuffleCost = ShuffleCost;
21888 } else {
21889 // Transform mask to include only first entry.
21890 APInt DemandedElts = APInt::getAllOnes(SubMask.size());
21891 bool IsIdentity = true;
21892 for (auto [I, Idx] : enumerate(FirstMask)) {
21893 if (Idx >= static_cast<int>(NewVF)) {
21895 } else {
21896 DemandedElts.clearBit(I);
21897 if (Idx != PoisonMaskElem)
21898 IsIdentity &= static_cast<int>(I) == Idx;
21899 }
21900 }
21901 if (!IsIdentity)
21902 FirstShuffleCost = GetShuffleCost(FirstMask, Entries.front(), VecTy);
21903 FirstShuffleCost +=
21904 getScalarizationOverhead(*TTI, Opts.slp_revec, VL.front()->getType(),
21905 MaskVecTy, DemandedElts, /*Insert=*/true,
21906 /*Extract=*/false, CostKind);
21907 }
21908 InstructionCost SecondShuffleCost = 0;
21909 SmallVector<int> SecondMask(SubMask.begin(), SubMask.end());
21910 if (Entries.size() == 1 || !Entries[1]->isGather()) {
21911 SecondShuffleCost = ShuffleCost;
21912 } else {
21913 // Transform mask to include only first entry.
21914 APInt DemandedElts = APInt::getAllOnes(SubMask.size());
21915 bool IsIdentity = true;
21916 for (auto [I, Idx] : enumerate(SecondMask)) {
21917 if (Idx < static_cast<int>(NewVF) && Idx >= 0) {
21919 } else {
21920 DemandedElts.clearBit(I);
21921 if (Idx != PoisonMaskElem) {
21922 Idx -= NewVF;
21923 IsIdentity &= static_cast<int>(I) == Idx;
21924 }
21925 }
21926 }
21927 if (!IsIdentity)
21928 SecondShuffleCost = GetShuffleCost(SecondMask, Entries[1], VecTy);
21929 SecondShuffleCost +=
21930 getScalarizationOverhead(*TTI, Opts.slp_revec, VL.front()->getType(),
21931 MaskVecTy, DemandedElts, /*Insert=*/true,
21932 /*Extract=*/false, CostKind);
21933 }
21934 APInt DemandedElts = APInt::getAllOnes(SubMask.size());
21935 for (auto [I, Idx] : enumerate(SubMask))
21936 if (Idx == PoisonMaskElem)
21937 DemandedElts.clearBit(I);
21938 InstructionCost BuildVectorCost =
21939 getScalarizationOverhead(*TTI, Opts.slp_revec, VL.front()->getType(),
21940 MaskVecTy, DemandedElts, /*Insert=*/true,
21941 /*Extract=*/false, CostKind);
21942 const TreeEntry *BestEntry = nullptr;
21943 auto MaskSlice = MutableArrayRef(Mask).slice(MaskBase, VL.size());
21944 if (FirstShuffleCost < ShuffleCost) {
21945 for (int &Idx : MaskSlice)
21946 if (Idx >= static_cast<int>(VF))
21948 BestEntry = Entries.front();
21949 ShuffleCost = FirstShuffleCost;
21950 }
21951 if (SecondShuffleCost < ShuffleCost) {
21952 for (int &Idx : MaskSlice) {
21953 if (Idx < static_cast<int>(VF))
21955 else
21956 Idx -= VF;
21957 }
21958 BestEntry = Entries[1];
21959 ShuffleCost = SecondShuffleCost;
21960 }
21961 if (BuildVectorCost >= ShuffleCost) {
21962 if (BestEntry) {
21963 Entries.clear();
21964 Entries.push_back(BestEntry);
21965 }
21966 return Entries.size() > 1 ? TargetTransformInfo::SK_PermuteTwoSrc
21968 }
21969 }
21970 Entries.clear();
21971 // Clear the corresponding mask elements.
21972 std::fill(std::next(Mask.begin(), MaskBase),
21973 std::next(Mask.begin(), MaskBase + VL.size()), PoisonMaskElem);
21974 return std::nullopt;
21975}
21976
21978BoUpSLP::isGatherShuffledEntry(
21979 const TreeEntry *TE, ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask,
21980 SmallVectorImpl<SmallVector<const TreeEntry *>> &Entries, unsigned NumParts,
21981 Type *ScalarTy, bool ForOrder) {
21982 assert(NumParts > 0 && NumParts < VL.size() &&
21983 "Expected positive number of registers.");
21984 Entries.clear();
21985 // No need to check for the topmost gather node.
21986 if (TE == &getRootNode() &&
21987 (!GatheredLoadsEntriesFirst.has_value() ||
21988 none_of(ArrayRef(VectorizableTree).drop_front(),
21989 [](const std::unique_ptr<TreeEntry> &TE) {
21990 return !TE->isGather();
21991 })))
21992 return {};
21993 Mask.assign(VL.size(), PoisonMaskElem);
21994 assert((TE->UserTreeIndex || TE == &getRootNode()) &&
21995 "Expected only single user of the gather node.");
21996 unsigned PWSz =
21997 getFullVectorNumberOfElements(*TTI, ScalarTy, VL.size(), Opts.slp_revec);
21998 if (TE->UserTreeIndex && TE->UserTreeIndex.UserTE->isGather() &&
21999 TE->UserTreeIndex.EdgeIdx == UINT_MAX &&
22000 (TE->Idx == 0 ||
22001 (TE->hasState() && TE->getOpcode() == Instruction::ExtractElement) ||
22002 isSplat(TE->Scalars) ||
22003 (TE->hasState() &&
22004 getSameValuesTreeEntry(TE->getMainOp(), TE->Scalars))))
22005 return {};
22006 unsigned SliceSize = getPartNumElems(PWSz, NumParts);
22008 for (unsigned Part : seq<unsigned>(NumParts)) {
22009 if (Part * SliceSize >= VL.size())
22010 break;
22011 ArrayRef<Value *> SubVL =
22012 VL.slice(Part * SliceSize, getNumElems(VL.size(), SliceSize, Part));
22013 SmallVectorImpl<const TreeEntry *> &SubEntries = Entries.emplace_back();
22014 std::optional<TTI::ShuffleKind> SubRes =
22015 isGatherShuffledSingleRegisterEntry(TE, SubVL, Mask, SubEntries, Part,
22016 ForOrder, SliceSize);
22017 if (!SubRes)
22018 SubEntries.clear();
22019 Res.push_back(SubRes);
22020 if (SubEntries.size() == 1 && *SubRes == TTI::SK_PermuteSingleSrc &&
22021 SubEntries.front()->getVectorFactor() == VL.size() &&
22022 (SubEntries.front()->isSame(TE->Scalars) ||
22023 SubEntries.front()->isSame(VL))) {
22024 SmallVector<const TreeEntry *> LocalSubEntries;
22025 LocalSubEntries.swap(SubEntries);
22026 Entries.clear();
22027 Res.clear();
22028 std::iota(Mask.begin(), Mask.end(), 0);
22029 // Clear undef scalars.
22030 for (int I = 0, Sz = VL.size(); I < Sz; ++I)
22031 if (isa<PoisonValue>(VL[I]))
22033 Entries.emplace_back(1, LocalSubEntries.front());
22035 return Res;
22036 }
22037 }
22038 if (all_of(Res,
22039 [](const std::optional<TTI::ShuffleKind> &SK) { return !SK; })) {
22040 Entries.clear();
22041 return {};
22042 }
22043 return Res;
22044}
22045
22046InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL, bool ForPoisonSrc,
22047 Type *ScalarTy) const {
22048 const unsigned VF = VL.size();
22049 auto *VecTy = getWidenedType(ScalarTy, VF);
22050 // Find the cost of inserting/extracting values from the vector.
22051 // Check if the same elements are inserted several times and count them as
22052 // shuffle candidates.
22053 APInt DemandedElements = APInt::getZero(VF);
22055 auto EstimateInsertCost = [&](unsigned I, Value *V) {
22056 DemandedElements.setBit(I);
22057 if (V->getType() != ScalarTy)
22058 Cost += TTI->getCastInstrCost(Instruction::Trunc, ScalarTy, V->getType(),
22059 TTI::CastContextHint::None, CostKind);
22060 };
22061 SmallVector<int> ConstantShuffleMask(VF, PoisonMaskElem);
22062 std::iota(ConstantShuffleMask.begin(), ConstantShuffleMask.end(), 0);
22063 // No need to shuffle duplicates for constants.
22064 for (auto [I, V] : make_filter_range(enumerate(VL), [&](const auto &P) {
22065 return !(ForPoisonSrc && isConstant(P.value())) &&
22066 !isa<UndefValue>(P.value());
22067 })) {
22068 if (isConstant(V)) {
22069 ConstantShuffleMask[I] = I + VF;
22070 continue;
22071 }
22072 EstimateInsertCost(I, V);
22073 }
22074 // FIXME: add a cost for constant vector materialization.
22075 bool IsAnyNonUndefConst =
22076 any_of(VL, [](Value *V) { return !isa<UndefValue>(V) && isConstant(V); });
22077 // 1. Shuffle input source vector and constant vector.
22078 if (!ForPoisonSrc && IsAnyNonUndefConst) {
22079 Cost +=
22081 cast<VectorType>(VecTy), CostKind, ConstantShuffleMask);
22082 }
22083
22084 // 2. Insert unique non-constants.
22085 if (!DemandedElements.isZero())
22086 Cost += getScalarizationOverhead(*TTI, Opts.slp_revec, ScalarTy,
22087 cast<VectorType>(VecTy), DemandedElements,
22088 /*Insert=*/true,
22089 /*Extract=*/false, CostKind,
22090 ForPoisonSrc && !IsAnyNonUndefConst, VL);
22091 return Cost;
22092}
22093
22094Instruction &BoUpSLP::getLastInstructionInBundle(const TreeEntry *E) {
22095 auto It = EntryToLastInstruction.find(E);
22096 if (It != EntryToLastInstruction.end())
22097 return *cast<Instruction>(It->second);
22098 Instruction *Res = nullptr;
22099 // Get the basic block this bundle is in. All instructions in the bundle
22100 // should be in this block (except for extractelement-like instructions with
22101 // constant indices or gathered loads or copyables).
22102 Instruction *Front;
22103 unsigned Opcode;
22104 if (E->hasState()) {
22105 Front = E->getMainOp();
22106 Opcode = E->getOpcode();
22107 } else {
22108 Front = cast<Instruction>(*find_if(E->Scalars, IsaPred<Instruction>));
22109 Opcode = Front->getOpcode();
22110 }
22111 auto *BB = Front->getParent();
22112 assert(
22113 ((GatheredLoadsEntriesFirst.has_value() && Opcode == Instruction::Load &&
22114 E->isGather() && E->Idx < *GatheredLoadsEntriesFirst) ||
22115 E->State == TreeEntry::SplitVectorize || E->hasCopyableElements() ||
22116 all_of(E->Scalars,
22117 [=](Value *V) -> bool {
22118 if (Opcode == Instruction::GetElementPtr &&
22119 !isa<GetElementPtrInst>(V))
22120 return true;
22121 auto *I = dyn_cast<Instruction>(V);
22122 return !I || !E->getMatchingMainOpOrAltOp(I) ||
22123 I->getParent() == BB || isVectorLikeInstWithConstOps(I);
22124 })) &&
22125 "Expected gathered loads or GEPs or instructions from same basic "
22126 "block.");
22127
22128 auto FindLastInst = [&]() {
22129 Instruction *LastInst = Front;
22130 for (Instruction *I : make_isa_range<Instruction>(E->Scalars)) {
22131 if (E->isCopyableElement(I))
22132 continue;
22133 if (LastInst->getParent() == I->getParent()) {
22134 if (LastInst->comesBefore(I))
22135 LastInst = I;
22136 continue;
22137 }
22138 assert(((Opcode == Instruction::GetElementPtr &&
22140 E->State == TreeEntry::SplitVectorize ||
22141 (isVectorLikeInstWithConstOps(LastInst) &&
22143 (GatheredLoadsEntriesFirst.has_value() &&
22144 Opcode == Instruction::Load && E->isGather() &&
22145 E->Idx < *GatheredLoadsEntriesFirst)) &&
22146 "Expected vector-like or non-GEP in GEP node insts only.");
22147 if (!DT->isReachableFromEntry(LastInst->getParent())) {
22148 LastInst = I;
22149 continue;
22150 }
22151 if (!DT->isReachableFromEntry(I->getParent()))
22152 continue;
22153 auto *NodeA = DT->getNode(LastInst->getParent());
22154 auto *NodeB = DT->getNode(I->getParent());
22155 assert(NodeA && "Should only process reachable instructions");
22156 assert(NodeB && "Should only process reachable instructions");
22157 assert((NodeA == NodeB) ==
22158 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
22159 "Different nodes should have different DFS numbers");
22160 if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn())
22161 LastInst = I;
22162 }
22163 BB = LastInst->getParent();
22164 return LastInst;
22165 };
22166
22167 auto FindFirstInst = [&]() {
22168 Instruction *FirstInst = Front;
22169 for (Instruction *I : make_isa_range<Instruction>(E->Scalars)) {
22170 if (E->isCopyableElement(I))
22171 continue;
22172 if (FirstInst->getParent() == I->getParent()) {
22173 if (I->comesBefore(FirstInst))
22174 FirstInst = I;
22175 continue;
22176 }
22177 assert(((Opcode == Instruction::GetElementPtr &&
22179 (isVectorLikeInstWithConstOps(FirstInst) &&
22181 "Expected vector-like or non-GEP in GEP node insts only.");
22182 if (!DT->isReachableFromEntry(FirstInst->getParent())) {
22183 FirstInst = I;
22184 continue;
22185 }
22186 if (!DT->isReachableFromEntry(I->getParent()))
22187 continue;
22188 auto *NodeA = DT->getNode(FirstInst->getParent());
22189 auto *NodeB = DT->getNode(I->getParent());
22190 assert(NodeA && "Should only process reachable instructions");
22191 assert(NodeB && "Should only process reachable instructions");
22192 assert((NodeA == NodeB) ==
22193 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
22194 "Different nodes should have different DFS numbers");
22195 if (NodeA->getDFSNumIn() > NodeB->getDFSNumIn())
22196 FirstInst = I;
22197 }
22198 return FirstInst;
22199 };
22200
22201 if (E->State == TreeEntry::SplitVectorize) {
22202 Res = FindLastInst();
22203 if (ArrayRef<TreeEntry *> Entries = getTreeEntries(Res); !Entries.empty()) {
22204 for (auto *E : Entries) {
22205 auto *I = dyn_cast_if_present<Instruction>(E->VectorizedValue);
22206 if (!I)
22207 I = &getLastInstructionInBundle(E);
22208 if (Res->getParent() == I->getParent() && Res->comesBefore(I))
22209 Res = I;
22210 }
22211 }
22212 EntryToLastInstruction.try_emplace(E, Res);
22213 return *Res;
22214 }
22215
22216 // Set insertpoint for gathered loads to the very first load.
22217 if (GatheredLoadsEntriesFirst.has_value() &&
22218 E->Idx >= *GatheredLoadsEntriesFirst && !E->isGather() &&
22219 Opcode == Instruction::Load) {
22220 Res = FindFirstInst();
22221 EntryToLastInstruction.try_emplace(E, Res);
22222 return *Res;
22223 }
22224
22225 // Set the insert point to the beginning of the basic block if the entry
22226 // should not be scheduled.
22227 auto FindScheduleBundle = [&](const TreeEntry *E) -> const ScheduleBundle * {
22228 if (E->isGather())
22229 return nullptr;
22230 // Found previously that the instruction do not need to be scheduled.
22231 const auto *It = BlocksSchedules.find(BB);
22232 if (It == BlocksSchedules.end())
22233 return nullptr;
22234 for (Instruction *I : make_isa_range<Instruction>(E->Scalars)) {
22235 if (isa<PHINode>(I) ||
22236 (!E->isCopyableElement(I) && doesNotNeedToBeScheduled(I)))
22237 continue;
22238 ArrayRef<ScheduleBundle *> Bundles = It->second->getScheduleBundles(I);
22239 if (Bundles.empty())
22240 continue;
22241 const auto *It = find_if(
22242 Bundles, [&](ScheduleBundle *B) { return B->getTreeEntry() == E; });
22243 if (It != Bundles.end())
22244 return *It;
22245 }
22246 return nullptr;
22247 };
22248 const ScheduleBundle *Bundle = FindScheduleBundle(E);
22249 if (!E->isGather() && !Bundle) {
22250 if ((Opcode == Instruction::GetElementPtr &&
22251 any_of(E->Scalars,
22252 [](Value *V) {
22253 return !isa<GetElementPtrInst>(V) && isa<Instruction>(V);
22254 })) ||
22255 (all_of(E->Scalars,
22256 [&](Value *V) {
22257 return isa<PoisonValue>(V) ||
22258 (E->Idx == 0 &&
22259 isa<InsertElementInst, InsertValueInst>(V)) ||
22260 E->isCopyableElement(V) ||
22261 (!isVectorLikeInstWithConstOps(V) &&
22262 isUsedOutsideBlock(V));
22263 }) &&
22264 (!E->doesNotNeedToSchedule() ||
22266 [&](Instruction *I) {
22267 if (E->hasCopyableElements() && E->isCopyableElement(I))
22268 return false;
22269 return !areAllOperandsNonInsts(I);
22270 }) ||
22271 none_of(make_isa_range<Instruction>(E->Scalars), [&](Instruction *I) {
22272 if (E->hasCopyableElements() && E->isCopyableElement(I))
22273 return false;
22274 return MustGather.contains(I);
22275 }))))
22276 Res = FindLastInst();
22277 else
22278 Res = FindFirstInst();
22279 EntryToLastInstruction.try_emplace(E, Res);
22280 return *Res;
22281 }
22282
22283 // Find the last instruction. The common case should be that BB has been
22284 // scheduled, and the last instruction is VL.back(). So we start with
22285 // VL.back() and iterate over schedule data until we reach the end of the
22286 // bundle. The end of the bundle is marked by null ScheduleData.
22287 if (Bundle) {
22288 assert(!E->isGather() && "Gathered instructions should not be scheduled");
22289 Res = Bundle->getBundle().back()->getInst();
22290 EntryToLastInstruction.try_emplace(E, Res);
22291 return *Res;
22292 }
22293
22294 // LastInst can still be null at this point if there's either not an entry
22295 // for BB in BlocksSchedules or there's no ScheduleData available for
22296 // VL.back(). This can be the case if buildTreeRec aborts for various
22297 // reasons (e.g., the maximum recursion depth is reached, the maximum region
22298 // size is reached, etc.). ScheduleData is initialized in the scheduling
22299 // "dry-run".
22300 //
22301 // If this happens, we can still find the last instruction by brute force. We
22302 // iterate forwards from Front (inclusive) until we either see all
22303 // instructions in the bundle or reach the end of the block. If Front is the
22304 // last instruction in program order, LastInst will be set to Front, and we
22305 // will visit all the remaining instructions in the block.
22306 //
22307 // One of the reasons we exit early from buildTreeRec is to place an upper
22308 // bound on compile-time. Thus, taking an additional compile-time hit here is
22309 // not ideal. However, this should be exceedingly rare since it requires that
22310 // we both exit early from buildTreeRec and that the bundle be out-of-order
22311 // (causing us to iterate all the way to the end of the block).
22312 if (!Res)
22313 Res = FindLastInst();
22314 assert(Res && "Failed to find last instruction in bundle");
22315 EntryToLastInstruction.try_emplace(E, Res);
22316 return *Res;
22317}
22318
22319void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
22320 auto *Front = E->getMainOp();
22321 Instruction *LastInst = &getLastInstructionInBundle(E);
22322 // Struct-call extractvalue entries may have scalars in different basic
22323 // blocks. The vector extractvalue depends only on the vectorized call, so
22324 // use the call bundle to set the insert point and dominate all uses.
22325 const bool UseCallBundleInsertPoint =
22326 E->getOpcode() == Instruction::ExtractValue &&
22327 !E->StructEVIndices.empty() &&
22328 any_of(E->Scalars, [BB = Front->getParent()](Value *V) {
22329 return cast<Instruction>(V)->getParent() != BB;
22330 });
22331 if (UseCallBundleInsertPoint)
22332 LastInst = &getLastInstructionInBundle(getOperandEntry(E, 0));
22333 assert(LastInst && "Failed to find last instruction in bundle");
22334 BasicBlock::iterator LastInstIt = LastInst->getIterator();
22335 // If the instruction is PHI, set the insert point after all the PHIs.
22336 bool IsPHI = isa<PHINode>(LastInst);
22337 if (IsPHI) {
22338 LastInstIt = LastInst->getParent()->getFirstNonPHIIt();
22339 if (LastInstIt != LastInst->getParent()->end() &&
22340 LastInstIt->getParent()->isLandingPad())
22341 LastInstIt = std::next(LastInstIt);
22342 }
22343 if (IsPHI ||
22344 (!E->isGather() && E->State != TreeEntry::SplitVectorize &&
22345 !UseCallBundleInsertPoint &&
22346 (E->doesNotNeedToSchedule() ||
22347 (E->hasCopyableElements() && !E->isCopyableElement(LastInst) &&
22348 isUsedOutsideBlock(LastInst)))) ||
22349 (GatheredLoadsEntriesFirst.has_value() &&
22350 E->Idx >= *GatheredLoadsEntriesFirst && !E->isGather() &&
22351 E->getOpcode() == Instruction::Load)) {
22352 Builder.SetInsertPoint(LastInstIt);
22353 } else {
22354 // Set the insertion point after the last instruction in the bundle. Set the
22355 // debug location to Front.
22356 Builder.SetInsertPoint(LastInst->getNextNode()->getIterator());
22357 if (Instruction *Res = LastInstructionToPos.lookup(LastInst)) {
22358 Builder.SetInsertPoint(Res->getIterator());
22359 } else {
22360 Res = Builder.CreateAlignedLoad(Builder.getPtrTy(),
22361 PoisonValue::get(Builder.getPtrTy()),
22362 MaybeAlign());
22363 Builder.SetInsertPoint(Res->getIterator());
22364 eraseInstruction(Res);
22365 if (E->State != TreeEntry::SplitVectorize)
22366 LastInstructionToPos.try_emplace(LastInst, Res);
22367 }
22368 }
22369 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
22370}
22371
22372Value *BoUpSLP::gather(
22373 ArrayRef<Value *> VL, Value *Root, Type *ScalarTy,
22374 function_ref<Value *(Value *, Value *, ArrayRef<int>)> CreateShuffle) {
22375 // List of instructions/lanes from current block and/or the blocks which are
22376 // part of the current loop. These instructions will be inserted at the end to
22377 // make it possible to optimize loops and hoist invariant instructions out of
22378 // the loops body with better chances for success.
22380 SmallSet<int, 4> PostponedIndices;
22381 Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
22382 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
22383 SmallPtrSet<BasicBlock *, 4> Visited;
22384 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
22385 InsertBB = InsertBB->getSinglePredecessor();
22386 return InsertBB && InsertBB == InstBB;
22387 };
22388 for (int I = 0, E = VL.size(); I < E; ++I) {
22389 if (auto *Inst = dyn_cast<Instruction>(VL[I]))
22390 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
22391 isVectorized(Inst) ||
22392 (L && (!Root || L->isLoopInvariant(Root)) && L->contains(Inst))) &&
22393 PostponedIndices.insert(I).second)
22394 PostponedInsts.emplace_back(Inst, I);
22395 }
22396
22397 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos,
22398 Type *Ty) {
22399 Value *Scalar = V;
22400 // Drop NUW from trunc to avoid incorrect codegen.
22401 Value *Trunced;
22402 if (match(Scalar, m_NUWTrunc(m_Value(Trunced))))
22403 cast<TruncInst>(Scalar)->setHasNoUnsignedWrap(/*B=*/false);
22404 if (Scalar->getType() != Ty) {
22405 assert(Scalar->getType()->isIntOrIntVectorTy() &&
22406 Ty->isIntOrIntVectorTy() && "Expected integer types only.");
22407 Value *V = Scalar;
22408 if (auto *CI = dyn_cast<CastInst>(Scalar);
22410 Value *Op = CI->getOperand(0);
22411 if (auto *IOp = dyn_cast<Instruction>(Op);
22412 !IOp || !(isDeleted(IOp) || isVectorized(IOp)))
22413 V = Op;
22414 }
22415 Scalar = Builder.CreateIntCast(
22416 V, Ty, !isKnownNonNegative(Scalar, SimplifyQuery(*DL)));
22417 }
22418
22419 Instruction *InsElt;
22420 if (auto *VecTy = dyn_cast<FixedVectorType>(Scalar->getType())) {
22421 assert(Opts.slp_revec && "FixedVectorType is not expected.");
22422 Vec =
22423 createInsertVector(Builder, Vec, Scalar, Pos * getNumElements(VecTy));
22424 auto *II = dyn_cast<Instruction>(Vec);
22425 if (!II)
22426 return Vec;
22427 InsElt = II;
22428 } else {
22429 Vec = Builder.CreateInsertElement(Vec, Scalar, Pos);
22430 InsElt = dyn_cast<InsertElementInst>(Vec);
22431 if (!InsElt)
22432 return Vec;
22433 }
22434 GatherShuffleExtractSeq.insert(InsElt);
22435 CSEBlocks.insert(InsElt->getParent());
22436 // Add to our 'need-to-extract' list.
22437 if (isa<Instruction>(V)) {
22438 ArrayRef<TreeEntry *> Entries = getTreeEntries(V);
22439 const auto *It = find_if(Entries, [&](const TreeEntry *E) {
22440 return !TransformedToGatherNodes.contains(E) &&
22441 !DeletedNodes.contains(E);
22442 });
22443 if (It != Entries.end()) {
22444 // Find which lane we need to extract.
22445 User *UserOp = nullptr;
22446 if (Scalar != V) {
22447 if (auto *SI = dyn_cast<Instruction>(Scalar))
22448 UserOp = SI;
22449 } else {
22450 if (V->getType()->isVectorTy()) {
22451 if (auto *SV = dyn_cast<ShuffleVectorInst>(InsElt);
22452 SV && SV->getOperand(0) != V && SV->getOperand(1) != V) {
22453 // Find shufflevector, caused by resize.
22454 auto FindOperand = [](Value *Vec, Value *V) -> Instruction * {
22455 if (auto *SV = dyn_cast<ShuffleVectorInst>(Vec)) {
22456 if (SV->getOperand(0) == V)
22457 return SV;
22458 if (SV->getOperand(1) == V)
22459 return SV;
22460 }
22461 return nullptr;
22462 };
22463 InsElt = nullptr;
22464 if (Instruction *User = FindOperand(SV->getOperand(0), V))
22465 InsElt = User;
22466 else if (Instruction *User = FindOperand(SV->getOperand(1), V))
22467 InsElt = User;
22468 assert(InsElt &&
22469 "Failed to find shufflevector, caused by resize.");
22470 } else if (Opts.slp_revec && isa<ShuffleVectorInst>(InsElt)) {
22471 // ReVec gather used V directly as a shufflevector operand.
22472 // Register a nullptr-User external use so all remaining
22473 // in-IR uses of V get rewritten via replaceAllUsesWith,
22474 // and track V in ExternalUsesWithNonUsers to match the
22475 // bookkeeping done by buildExternalUses.
22476 unsigned FoundLane = (*It)->findLaneForValue(V);
22477 ExternalUses.emplace_back(V, nullptr, **It, FoundLane);
22478 ExternalUsesWithNonUsers.insert(V);
22479 }
22480 }
22481 UserOp = InsElt;
22482 }
22483 if (UserOp) {
22484 unsigned FoundLane = (*It)->findLaneForValue(V);
22485 ExternalUses.emplace_back(V, UserOp, **It, FoundLane);
22486 }
22487 }
22488 }
22489 return Vec;
22490 };
22491 auto *VecTy = getWidenedType(ScalarTy, VL.size());
22492 Value *Vec = PoisonValue::get(VecTy);
22493 SmallVector<int> NonConsts;
22494 SmallVector<int> Mask(VL.size());
22495 std::iota(Mask.begin(), Mask.end(), 0);
22496 Value *OriginalRoot = Root;
22497 if (auto *SV = dyn_cast_if_present<ShuffleVectorInst>(Root);
22498 SV && isa<PoisonValue>(SV->getOperand(1)) &&
22499 SV->getOperand(0)->getType() == VecTy) {
22500 Root = SV->getOperand(0);
22501 Mask.assign(SV->getShuffleMask().begin(), SV->getShuffleMask().end());
22502 }
22503 // Insert constant values at first.
22504 for (int I = 0, E = VL.size(); I < E; ++I) {
22505 if (PostponedIndices.contains(I))
22506 continue;
22507 if (!isConstant(VL[I])) {
22508 NonConsts.push_back(I);
22509 continue;
22510 }
22511 if (isa<PoisonValue>(VL[I]))
22512 continue;
22513 Vec = CreateInsertElement(Vec, VL[I], I, ScalarTy);
22514 Mask[I] = I + E;
22515 }
22516 if (Root) {
22517 if (isa<PoisonValue>(Vec)) {
22518 Vec = OriginalRoot;
22519 } else {
22520 Vec = CreateShuffle(Root, Vec, Mask);
22521 if (auto *OI = dyn_cast<Instruction>(OriginalRoot);
22522 OI && OI->use_empty() &&
22523 none_of(VectorizableTree, [&](const std::unique_ptr<TreeEntry> &TE) {
22524 return TE->VectorizedValue == OI;
22525 }))
22526 eraseInstruction(OI);
22527 }
22528 }
22529 // Insert non-constant values.
22530 for (int I : NonConsts)
22531 Vec = CreateInsertElement(Vec, VL[I], I, ScalarTy);
22532 // Append instructions, which are/may be part of the loop, in the end to make
22533 // it possible to hoist non-loop-based instructions.
22534 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
22535 Vec = CreateInsertElement(Vec, Pair.first, Pair.second, ScalarTy);
22536
22537 return Vec;
22538}
22539
22540/// Merges shuffle masks and emits final shuffle instruction, if required. It
22541/// supports shuffling of 2 input vectors. It implements lazy shuffles emission,
22542/// when the actual shuffle instruction is generated only if this is actually
22543/// required. Otherwise, the shuffle instruction emission is delayed till the
22544/// end of the process, to reduce the number of emitted instructions and further
22545/// analysis/transformations.
22546/// The class also will look through the previously emitted shuffle instructions
22547/// and properly mark indices in mask as undef.
22548/// For example, given the code
22549/// \code
22550/// %s1 = shufflevector <2 x ty> %0, poison, <1, 0>
22551/// %s2 = shufflevector <2 x ty> %1, poison, <1, 0>
22552/// \endcode
22553/// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 3, 2>, it will
22554/// look through %s1 and %s2 and emit
22555/// \code
22556/// %res = shufflevector <2 x ty> %0, %1, <0, 1, 2, 3>
22557/// \endcode
22558/// instead.
22559/// If 2 operands are of different size, the smallest one will be resized and
22560/// the mask recalculated properly.
22561/// For example, given the code
22562/// \code
22563/// %s1 = shufflevector <2 x ty> %0, poison, <1, 0, 1, 0>
22564/// %s2 = shufflevector <2 x ty> %1, poison, <1, 0, 1, 0>
22565/// \endcode
22566/// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 5, 4>, it will
22567/// look through %s1 and %s2 and emit
22568/// \code
22569/// %res = shufflevector <2 x ty> %0, %1, <0, 1, 2, 3>
22570/// \endcode
22571/// instead.
22573 bool IsFinalized = false;
22574 /// Combined mask for all applied operands and masks. It is built during
22575 /// analysis and actual emission of shuffle vector instructions.
22576 SmallVector<int> CommonMask;
22577 /// List of operands for the shuffle vector instruction. It hold at max 2
22578 /// operands, if the 3rd is going to be added, the first 2 are combined into
22579 /// shuffle with \p CommonMask mask, the first operand sets to be the
22580 /// resulting shuffle and the second operand sets to be the newly added
22581 /// operand. The \p CommonMask is transformed in the proper way after that.
22582 SmallVector<Value *, 2> InVectors;
22583 IRBuilderBase &Builder;
22584 BoUpSLP &R;
22585
22586 class ShuffleIRBuilder {
22587 IRBuilderBase &Builder;
22588 /// Holds all of the instructions that we gathered.
22589 SetVector<Instruction *> &GatherShuffleExtractSeq;
22590 /// A list of blocks that we are going to CSE.
22591 DenseSet<BasicBlock *> &CSEBlocks;
22592 /// Data layout.
22593 const DataLayout &DL;
22594
22595 public:
22596 ShuffleIRBuilder(IRBuilderBase &Builder,
22597 SetVector<Instruction *> &GatherShuffleExtractSeq,
22598 DenseSet<BasicBlock *> &CSEBlocks, const DataLayout &DL)
22599 : Builder(Builder), GatherShuffleExtractSeq(GatherShuffleExtractSeq),
22600 CSEBlocks(CSEBlocks), DL(DL) {}
22601 ~ShuffleIRBuilder() = default;
22602 /// Creates shufflevector for the 2 operands with the given mask.
22603 Value *createShuffleVector(Value *V1, Value *V2, ArrayRef<int> Mask) {
22604 if (V1->getType() != V2->getType()) {
22605 assert(V1->getType()->isIntOrIntVectorTy() &&
22606 V1->getType()->isIntOrIntVectorTy() &&
22607 "Expected integer vector types only.");
22608 if (V1->getType() != V2->getType()) {
22609 if (cast<VectorType>(V2->getType())
22610 ->getElementType()
22611 ->getIntegerBitWidth() < cast<VectorType>(V1->getType())
22612 ->getElementType()
22613 ->getIntegerBitWidth())
22614 V2 = Builder.CreateIntCast(
22615 V2, V1->getType(), !isKnownNonNegative(V2, SimplifyQuery(DL)));
22616 else
22617 V1 = Builder.CreateIntCast(
22619 }
22620 }
22621 Value *Vec = Builder.CreateShuffleVector(V1, V2, Mask);
22622 if (auto *I = dyn_cast<Instruction>(Vec)) {
22623 GatherShuffleExtractSeq.insert(I);
22624 CSEBlocks.insert(I->getParent());
22625 }
22626 return Vec;
22627 }
22628 /// Creates permutation of the single vector operand with the given mask, if
22629 /// it is not identity mask.
22630 Value *createShuffleVector(Value *V1, ArrayRef<int> Mask) {
22631 if (Mask.empty())
22632 return V1;
22633 unsigned VF = Mask.size();
22634 unsigned LocalVF = cast<FixedVectorType>(V1->getType())->getNumElements();
22635 if (VF == LocalVF && ShuffleVectorInst::isIdentityMask(Mask, VF))
22636 return V1;
22637 Value *Vec = Builder.CreateShuffleVector(V1, Mask);
22638 if (auto *I = dyn_cast<Instruction>(Vec)) {
22639 GatherShuffleExtractSeq.insert(I);
22640 CSEBlocks.insert(I->getParent());
22641 }
22642 return Vec;
22643 }
22644 Value *createIdentity(Value *V) { return V; }
22645 Value *createPoison(Type *Ty, unsigned VF) {
22646 return PoisonValue::get(getWidenedType(Ty, VF));
22647 }
22648 /// Resizes 2 input vector to match the sizes, if the they are not equal
22649 /// yet. The smallest vector is resized to the size of the larger vector.
22650 void resizeToMatch(Value *&V1, Value *&V2) {
22651 if (V1->getType() == V2->getType())
22652 return;
22653 int V1VF = cast<FixedVectorType>(V1->getType())->getNumElements();
22654 int V2VF = cast<FixedVectorType>(V2->getType())->getNumElements();
22655 int VF = std::max(V1VF, V2VF);
22656 int MinVF = std::min(V1VF, V2VF);
22657 SmallVector<int> IdentityMask(VF, PoisonMaskElem);
22658 std::iota(IdentityMask.begin(), std::next(IdentityMask.begin(), MinVF),
22659 0);
22660 Value *&Op = MinVF == V1VF ? V1 : V2;
22661 Op = Builder.CreateShuffleVector(Op, IdentityMask);
22662 if (auto *I = dyn_cast<Instruction>(Op)) {
22663 GatherShuffleExtractSeq.insert(I);
22664 CSEBlocks.insert(I->getParent());
22665 }
22666 if (MinVF == V1VF)
22667 V1 = Op;
22668 else
22669 V2 = Op;
22670 }
22671 };
22672
22673 /// Smart shuffle instruction emission, walks through shuffles trees and
22674 /// tries to find the best matching vector for the actual shuffle
22675 /// instruction.
22676 Value *createShuffle(Value *V1, Value *V2, ArrayRef<int> Mask) {
22677 assert(V1 && "Expected at least one vector value.");
22678 ShuffleIRBuilder ShuffleBuilder(Builder, R.GatherShuffleExtractSeq,
22679 R.CSEBlocks, *R.DL);
22681 V1, V2, Mask, ShuffleBuilder, ScalarTy, R.Opts.slp_revec);
22682 }
22683
22684 /// Cast value \p V to the vector type with the same number of elements, but
22685 /// the base type \p ScalarTy.
22686 Value *castToScalarTyElem(Value *V,
22687 std::optional<bool> IsSigned = std::nullopt) {
22688 auto *VecTy = cast<VectorType>(V->getType());
22690 if (VecTy->getElementType() == ScalarTy->getScalarType())
22691 return V;
22692 return Builder.CreateIntCast(
22693 V, VectorType::get(ScalarTy->getScalarType(), VecTy->getElementCount()),
22694 IsSigned.value_or(!isKnownNonNegative(V, SimplifyQuery(*R.DL))));
22695 }
22696
22697 Value *getVectorizedValue(const TreeEntry &E) {
22698 Value *Vec = E.VectorizedValue;
22699 if (!Vec->getType()->isIntOrIntVectorTy())
22700 return Vec;
22701 return castToScalarTyElem(Vec, any_of(E.Scalars, [&](Value *V) {
22702 return !isa<PoisonValue>(V) &&
22703 !isKnownNonNegative(
22704 V, SimplifyQuery(*R.DL));
22705 }));
22706 }
22707
22708public:
22710 : BaseShuffleAnalysis(ScalarTy), Builder(Builder), R(R) {}
22711
22712 /// Adjusts extractelements after reusing them.
22713 Value *adjustExtracts(const TreeEntry *E, MutableArrayRef<int> Mask,
22714 ArrayRef<std::optional<TTI::ShuffleKind>> ShuffleKinds,
22715 unsigned NumParts, bool &UseVecBaseAsInput) {
22716 UseVecBaseAsInput = false;
22717 SmallPtrSet<Value *, 4> UniqueBases;
22718 Value *VecBase = nullptr;
22719 SmallVector<Value *> VL(E->Scalars.begin(), E->Scalars.end());
22720 if (!E->ReorderIndices.empty()) {
22721 SmallVector<int> ReorderMask(E->ReorderIndices.begin(),
22722 E->ReorderIndices.end());
22723 reorderScalars(VL, ReorderMask);
22724 }
22725 for (int I = 0, Sz = Mask.size(); I < Sz; ++I) {
22726 int Idx = Mask[I];
22727 if (Idx == PoisonMaskElem)
22728 continue;
22729 auto *EI = cast<ExtractElementInst>(VL[I]);
22730 VecBase = EI->getVectorOperand();
22731 if (ArrayRef<TreeEntry *> TEs = R.getTreeEntries(VecBase); !TEs.empty())
22732 VecBase = TEs.front()->VectorizedValue;
22733 assert(VecBase && "Expected vectorized value.");
22734 UniqueBases.insert(VecBase);
22735 // If the only one use is vectorized - can delete the extractelement
22736 // itself.
22737 if (!EI->hasOneUse() || R.ExternalUsesAsOriginalScalar.contains(EI) ||
22738 (E->UserTreeIndex && E->UserTreeIndex.EdgeIdx == UINT_MAX &&
22739 !R.isVectorized(EI) &&
22740 count_if(E->Scalars, [&](Value *V) { return V == EI; }) !=
22741 count_if(E->UserTreeIndex.UserTE->Scalars,
22742 [&](Value *V) { return V == EI; })) ||
22743 (NumParts != 1 && count(VL, EI) > 1) ||
22744 // Other gather nodes may still use the extractelement.
22745 any_of(R.ValueToGatherNodes.lookup(EI),
22746 [&](const TreeEntry *TE) {
22747 return TE != E && !R.DeletedNodes.contains(TE);
22748 }) ||
22749 any_of(EI->users(), [&](User *U) {
22750 ArrayRef<TreeEntry *> UTEs = R.getTreeEntries(U);
22751 return UTEs.empty() || UTEs.size() > 1 ||
22752 any_of(UTEs,
22753 [&](const TreeEntry *TE) {
22754 return R.DeletedNodes.contains(TE) ||
22755 R.TransformedToGatherNodes.contains(TE);
22756 }) ||
22758 !R.areAllUsersVectorized(cast<Instruction>(U))) ||
22759 (!UTEs.empty() &&
22760 count_if(R.VectorizableTree,
22761 [&](const std::unique_ptr<TreeEntry> &TE) {
22762 return TE->UserTreeIndex.UserTE ==
22763 UTEs.front() &&
22764 is_contained(VL, EI);
22765 }) != 1);
22766 }))
22767 continue;
22768 R.eraseInstruction(EI);
22769 }
22770 if (NumParts == 1 || UniqueBases.size() == 1) {
22771 assert(VecBase && "Expected vectorized value.");
22772 return castToScalarTyElem(VecBase);
22773 }
22774 UseVecBaseAsInput = true;
22775 auto TransformToIdentity = [](MutableArrayRef<int> Mask) {
22776 for (auto [I, Idx] : enumerate(Mask))
22777 if (Idx != PoisonMaskElem)
22778 Idx = I;
22779 };
22780 // Perform multi-register vector shuffle, joining them into a single virtual
22781 // long vector.
22782 // Need to shuffle each part independently and then insert all this parts
22783 // into a long virtual vector register, forming the original vector.
22784 Value *Vec = nullptr;
22785 SmallVector<int> VecMask(Mask.size(), PoisonMaskElem);
22786 unsigned SliceSize = getPartNumElems(VL.size(), NumParts);
22787 for (unsigned Part : seq<unsigned>(NumParts)) {
22788 unsigned Limit = getNumElems(VL.size(), SliceSize, Part);
22789 ArrayRef<Value *> SubVL = ArrayRef(VL).slice(Part * SliceSize, Limit);
22790 MutableArrayRef<int> SubMask = Mask.slice(Part * SliceSize, Limit);
22791 constexpr int MaxBases = 2;
22792 SmallVector<Value *, MaxBases> Bases(MaxBases);
22793 auto VLMask = zip(SubVL, SubMask);
22794 const unsigned VF =
22795 accumulate(VLMask, 0U, [&](unsigned S, const auto &D) {
22796 if (std::get<1>(D) == PoisonMaskElem)
22797 return S;
22798 Value *VecOp =
22799 cast<ExtractElementInst>(std::get<0>(D))->getVectorOperand();
22800 if (ArrayRef<TreeEntry *> TEs = R.getTreeEntries(VecOp);
22801 !TEs.empty())
22802 VecOp = TEs.front()->VectorizedValue;
22803 assert(VecOp && "Expected vectorized value.");
22804 const unsigned Size =
22805 cast<FixedVectorType>(VecOp->getType())->getNumElements();
22806 return std::max(S, Size);
22807 });
22808 for (const auto [V, I] : make_filter_range(VLMask, [](const auto &P) {
22809 return std::get<1>(P) != PoisonMaskElem;
22810 })) {
22811 Value *VecOp = cast<ExtractElementInst>(V)->getVectorOperand();
22812 if (ArrayRef<TreeEntry *> TEs = R.getTreeEntries(VecOp); !TEs.empty())
22813 VecOp = TEs.front()->VectorizedValue;
22814 assert(VecOp && "Expected vectorized value.");
22815 VecOp = castToScalarTyElem(VecOp);
22816 Bases[I / VF] = VecOp;
22817 }
22818 if (!Bases.front())
22819 continue;
22820 Value *SubVec;
22821 if (Bases.back()) {
22822 SubVec = createShuffle(Bases.front(), Bases.back(), SubMask);
22823 TransformToIdentity(SubMask);
22824 } else {
22825 SubVec = Bases.front();
22826 }
22827 if (!Vec) {
22828 Vec = SubVec;
22829 assert((Part == 0 || all_of(seq<unsigned>(0, Part),
22830 [&](unsigned P) {
22831 ArrayRef<int> SubMask =
22832 Mask.slice(P * SliceSize,
22833 getNumElems(Mask.size(),
22834 SliceSize, P));
22835 return all_of(SubMask, [](int Idx) {
22836 return Idx == PoisonMaskElem;
22837 });
22838 })) &&
22839 "Expected first part or all previous parts masked.");
22840 copy(SubMask, std::next(VecMask.begin(), Part * SliceSize));
22841 } else {
22842 unsigned NewVF =
22843 cast<FixedVectorType>(Vec->getType())->getNumElements();
22844 if (Vec->getType() != SubVec->getType()) {
22845 unsigned SubVecVF =
22846 cast<FixedVectorType>(SubVec->getType())->getNumElements();
22847 NewVF = std::max(NewVF, SubVecVF);
22848 }
22849 // Adjust SubMask.
22850 for (int &Idx : SubMask)
22851 if (Idx != PoisonMaskElem)
22852 Idx += NewVF;
22853 copy(SubMask, std::next(VecMask.begin(), Part * SliceSize));
22854 Vec = createShuffle(Vec, SubVec, VecMask);
22855 TransformToIdentity(VecMask);
22856 }
22857 }
22858 copy(VecMask, Mask.begin());
22859 return Vec;
22860 }
22861 /// Checks if the specified entry \p E needs to be delayed because of its
22862 /// dependency nodes.
22863 std::optional<Value *>
22864 needToDelay(const TreeEntry *E,
22866 // No need to delay emission if all deps are ready.
22867 if (all_of(Deps, [](ArrayRef<const TreeEntry *> TEs) {
22868 return all_of(
22869 TEs, [](const TreeEntry *TE) { return TE->VectorizedValue; });
22870 }))
22871 return std::nullopt;
22872 // Postpone gather emission, will be emitted after the end of the
22873 // process to keep correct order.
22874 auto *ResVecTy = getWidenedType(ScalarTy, E->getVectorFactor());
22875 return Builder.CreateAlignedLoad(
22876 ResVecTy,
22878 MaybeAlign());
22879 }
22880 /// Reset the builder to handle perfect diamond match.
22882 IsFinalized = false;
22883 CommonMask.clear();
22884 InVectors.clear();
22885 }
22886 /// Adds 2 input vectors (in form of tree entries) and the mask for their
22887 /// shuffling.
22888 void add(const TreeEntry &E1, const TreeEntry &E2, ArrayRef<int> Mask) {
22889 Value *V1 = getVectorizedValue(E1);
22890 Value *V2 = getVectorizedValue(E2);
22891 add(V1, V2, Mask);
22892 }
22893 /// Adds single input vector (in form of tree entry) and the mask for its
22894 /// shuffling.
22895 void add(const TreeEntry &E1, ArrayRef<int> Mask) {
22896 Value *V1 = getVectorizedValue(E1);
22897 add(V1, Mask);
22898 }
22899 /// Adds 2 input vectors and the mask for their shuffling.
22900 void add(Value *V1, Value *V2, ArrayRef<int> Mask) {
22901 assert(V1 && V2 && !Mask.empty() && "Expected non-empty input vectors.");
22902 assert(isa<FixedVectorType>(V1->getType()) &&
22904 "castToScalarTyElem expects V1 and V2 to be FixedVectorType");
22905 V1 = castToScalarTyElem(V1);
22906 V2 = castToScalarTyElem(V2);
22907 if (InVectors.empty()) {
22908 InVectors.push_back(V1);
22909 InVectors.push_back(V2);
22910 CommonMask.assign(Mask.begin(), Mask.end());
22911 return;
22912 }
22913 Value *Vec = InVectors.front();
22914 if (InVectors.size() == 2) {
22915 Vec = createShuffle(Vec, InVectors.back(), CommonMask);
22916 transformMaskAfterShuffle(CommonMask, CommonMask);
22917 } else if (cast<FixedVectorType>(Vec->getType())->getNumElements() !=
22918 Mask.size()) {
22919 Vec = createShuffle(Vec, nullptr, CommonMask);
22920 transformMaskAfterShuffle(CommonMask, CommonMask);
22921 }
22922 V1 = createShuffle(V1, V2, Mask);
22923 unsigned VF = std::max(getVF(V1), getVF(Vec));
22924 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
22925 if (Mask[Idx] != PoisonMaskElem)
22926 CommonMask[Idx] = Idx + VF;
22927 InVectors.front() = Vec;
22928 if (InVectors.size() == 2)
22929 InVectors.back() = V1;
22930 else
22931 InVectors.push_back(V1);
22932 }
22933 /// Adds another one input vector and the mask for the shuffling.
22934 void add(Value *V1, ArrayRef<int> Mask, bool = false,
22936 assert(isa<FixedVectorType>(V1->getType()) &&
22937 "castToScalarTyElem expects V1 to be FixedVectorType");
22938 V1 = castToScalarTyElem(V1);
22939 if (InVectors.empty()) {
22940 InVectors.push_back(V1);
22941 CommonMask.assign(Mask.begin(), Mask.end());
22942 return;
22943 }
22944 const auto *It = find(InVectors, V1);
22945 if (It == InVectors.end()) {
22946 if (InVectors.size() == 2 ||
22947 InVectors.front()->getType() != V1->getType()) {
22948 Value *V = InVectors.front();
22949 if (InVectors.size() == 2) {
22950 V = createShuffle(InVectors.front(), InVectors.back(), CommonMask);
22951 transformMaskAfterShuffle(CommonMask, CommonMask);
22952 } else if (cast<FixedVectorType>(V->getType())->getNumElements() !=
22953 CommonMask.size()) {
22954 V = createShuffle(InVectors.front(), nullptr, CommonMask);
22955 transformMaskAfterShuffle(CommonMask, CommonMask);
22956 }
22957 unsigned VF = std::max(CommonMask.size(), Mask.size());
22958 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
22959 if (CommonMask[Idx] == PoisonMaskElem && Mask[Idx] != PoisonMaskElem)
22960 CommonMask[Idx] = V->getType() != V1->getType()
22961 ? Idx + VF
22962 : Mask[Idx] + getVF(V1);
22963 if (V->getType() != V1->getType())
22964 V1 = createShuffle(V1, nullptr, Mask);
22965 InVectors.front() = V;
22966 if (InVectors.size() == 2)
22967 InVectors.back() = V1;
22968 else
22969 InVectors.push_back(V1);
22970 return;
22971 }
22972 // Check if second vector is required if the used elements are already
22973 // used from the first one.
22974 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
22975 if (Mask[Idx] != PoisonMaskElem && CommonMask[Idx] == PoisonMaskElem) {
22976 InVectors.push_back(V1);
22977 break;
22978 }
22979 }
22980 unsigned VF = 0;
22981 for (Value *V : InVectors)
22982 VF = std::max(VF, getVF(V));
22983 for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
22984 if (Mask[Idx] != PoisonMaskElem && CommonMask[Idx] == PoisonMaskElem)
22985 CommonMask[Idx] = Mask[Idx] + (It == InVectors.begin() ? 0 : VF);
22986 }
22987 /// Adds another one input vector and the mask for the shuffling.
22989 SmallVector<int> NewMask;
22990 inversePermutation(Order, NewMask);
22991 add(V1, NewMask);
22992 }
22993 Value *gather(ArrayRef<Value *> VL, unsigned MaskVF = 0,
22994 Value *Root = nullptr,
22996 return R.gather(VL, Root, ScalarTy,
22997 [&](Value *V1, Value *V2, ArrayRef<int> Mask) {
22998 return createShuffle(V1, V2, Mask);
22999 });
23000 }
23001 /// Emits the gather of zero-extended sub-fields of width \p FieldWidth of
23002 /// the same wider integer scalar \p Src, byte swapped if \p IsBSwap,
23003 /// permuted by \p Mask, as a bitcast to the field vector plus a permutation
23004 /// and an extension to the lane type.
23005 Value *createExtractedFieldsVector(Value *Src, unsigned FieldWidth,
23006 ArrayRef<int> Mask, bool IsBSwap,
23007 const TreeEntry &) {
23008 auto *FieldTy = IntegerType::get(Src->getContext(), FieldWidth);
23009 unsigned SrcWidth = Src->getType()->getIntegerBitWidth();
23010 assert(SrcWidth % FieldWidth == 0 &&
23011 "Expected the field width to divide the source width.");
23012 Value *Vec =
23013 IsBSwap ? Builder.CreateUnaryIntrinsic(Intrinsic::bswap, Src) : Src;
23014 Vec = Builder.CreateBitCast(Vec,
23015 getWidenedType(FieldTy, SrcWidth / FieldWidth));
23016 if (auto *I = dyn_cast<Instruction>(Vec)) {
23017 auto *SrcUser = IsBSwap ? cast<Instruction>(I->getOperand(0)) : I;
23018 R.GatherShuffleExtractSeq.insert(SrcUser);
23019 R.GatherShuffleExtractSeq.insert(I);
23020 R.CSEBlocks.insert(I->getParent());
23021 // A vectorized source scalar is erased; extract it for its user.
23022 ArrayRef<TreeEntry *> TEs = R.getTreeEntries(Src);
23023 const auto *It = find_if_not(TEs, [&](const TreeEntry *TE) {
23024 return R.TransformedToGatherNodes.contains(TE) ||
23025 R.DeletedNodes.contains(TE);
23026 });
23027 if (It != TEs.end())
23028 R.ExternalUses.emplace_back(Src, SrcUser, **It,
23029 (*It)->findLaneForValue(Src));
23030 }
23031 Vec = createShuffle(Vec, /*V2=*/nullptr, Mask);
23032 // The extracted fields are unsigned.
23033 Vec = castToScalarTyElem(Vec, /*IsSigned=*/false);
23034 return Vec;
23035 }
23036 Value *createFreeze(Value *V) { return Builder.CreateFreeze(V); }
23037 /// Finalize emission of the shuffles.
23038 /// \param Action the action (if any) to be performed before final applying of
23039 /// the \p ExtMask mask.
23041 ArrayRef<int> ExtMask,
23042 ArrayRef<std::pair<const TreeEntry *, unsigned>> SubVectors,
23043 ArrayRef<int> SubVectorsMask, unsigned VF = 0,
23046 Action = {}) {
23047 IsFinalized = true;
23048 if (Action) {
23049 Value *Vec = InVectors.front();
23050 if (InVectors.size() == 2) {
23051 Vec = createShuffle(Vec, InVectors.back(), CommonMask);
23052 InVectors.pop_back();
23053 } else {
23054 Vec = createShuffle(Vec, nullptr, CommonMask);
23055 }
23056 transformMaskAfterShuffle(CommonMask, CommonMask);
23057 assert(VF > 0 &&
23058 "Expected vector length for the final value before action.");
23059 unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements();
23060 if (VecVF < VF) {
23061 SmallVector<int> ResizeMask(VF, PoisonMaskElem);
23062 std::iota(ResizeMask.begin(), std::next(ResizeMask.begin(), VecVF), 0);
23063 Vec = createShuffle(Vec, nullptr, ResizeMask);
23064 }
23065 Action(Vec, CommonMask, [this](Value *V1, Value *V2, ArrayRef<int> Mask) {
23066 return createShuffle(V1, V2, Mask);
23067 });
23068 InVectors.front() = Vec;
23069 }
23070 if (!SubVectors.empty()) {
23071 Value *Vec = InVectors.front();
23072 if (InVectors.size() == 2) {
23073 Vec = createShuffle(Vec, InVectors.back(), CommonMask);
23074 InVectors.pop_back();
23075 } else {
23076 Vec = createShuffle(Vec, nullptr, CommonMask);
23077 }
23078 transformMaskAfterShuffle(CommonMask, CommonMask);
23079 auto CreateSubVectors = [&](Value *Vec,
23080 SmallVectorImpl<int> &CommonMask) {
23081 for (auto [E, Idx] : SubVectors) {
23082 Value *V = getVectorizedValue(*E);
23083 unsigned InsertionIndex = Idx * getNumElements(ScalarTy);
23084 // Use scalar version of the SCalarType to correctly handle shuffles
23085 // for revectorization. The revectorization mode operates by the
23086 // vectors, but here we need to operate on the scalars, because the
23087 // masks were already transformed for the vector elements and we don't
23088 // need doing this transformation again.
23089 Type *OrigScalarTy = ScalarTy;
23090 ScalarTy = ScalarTy->getScalarType();
23091 Vec = createInsertVector(
23092 Builder, Vec, V, InsertionIndex,
23093 std::bind(&ShuffleInstructionBuilder::createShuffle, this, _1, _2,
23094 _3));
23095 ScalarTy = OrigScalarTy;
23096 if (!CommonMask.empty()) {
23097 std::iota(std::next(CommonMask.begin(), Idx),
23098 std::next(CommonMask.begin(), Idx + E->getVectorFactor()),
23099 Idx);
23100 }
23101 }
23102 return Vec;
23103 };
23104 if (SubVectorsMask.empty()) {
23105 Vec = CreateSubVectors(Vec, CommonMask);
23106 } else {
23107 SmallVector<int> SVMask(CommonMask.size(), PoisonMaskElem);
23108 copy(SubVectorsMask, SVMask.begin());
23109 for (auto [I1, I2] : zip(SVMask, CommonMask)) {
23110 if (I2 != PoisonMaskElem) {
23111 assert(I1 == PoisonMaskElem && "Expected unused subvectors mask");
23112 I1 = I2 + CommonMask.size();
23113 }
23114 }
23115 Value *InsertVec =
23116 CreateSubVectors(PoisonValue::get(Vec->getType()), CommonMask);
23117 Vec = createShuffle(InsertVec, Vec, SVMask);
23118 transformMaskAfterShuffle(CommonMask, SVMask);
23119 }
23120 InVectors.front() = Vec;
23121 }
23122
23123 if (!ExtMask.empty()) {
23124 if (CommonMask.empty()) {
23125 CommonMask.assign(ExtMask.begin(), ExtMask.end());
23126 } else {
23127 SmallVector<int> NewMask(ExtMask.size(), PoisonMaskElem);
23128 for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
23129 if (ExtMask[I] == PoisonMaskElem)
23130 continue;
23131 NewMask[I] = CommonMask[ExtMask[I]];
23132 }
23133 CommonMask.swap(NewMask);
23134 }
23135 }
23136 if (CommonMask.empty()) {
23137 assert(InVectors.size() == 1 && "Expected only one vector with no mask");
23138 return InVectors.front();
23139 }
23140 if (InVectors.size() == 2)
23141 return createShuffle(InVectors.front(), InVectors.back(), CommonMask);
23142 return createShuffle(InVectors.front(), nullptr, CommonMask);
23143 }
23144
23146 assert((IsFinalized || CommonMask.empty()) &&
23147 "Shuffle construction must be finalized.");
23148 }
23149};
23150
23151Value *BoUpSLP::vectorizeOperand(TreeEntry *E, unsigned NodeIdx) {
23152 return vectorizeTree(getOperandEntry(E, NodeIdx));
23153}
23154
23155template <typename ResTy, typename BVTy>
23156std::optional<ResTy> BoUpSLP::processExtractedFieldsGather(
23157 BVTy &ShuffleBuilder, const TreeEntry *E, Type *ScalarTy,
23159 ArrayRef<std::pair<const TreeEntry *, unsigned>> SubVectors) {
23160 if (!SubVectors.empty() || !E->ReuseShuffleIndices.empty() ||
23161 !ScalarTy->isIntegerTy())
23162 return std::nullopt;
23163 std::optional<std::tuple<Value *, unsigned, SmallVector<int>>>
23164 ExtractedFields = matchGatheredExtractedFields(VL, *DL);
23165 if (!ExtractedFields ||
23166 ScalarTy->getIntegerBitWidth() < std::get<1>(*ExtractedFields))
23167 return std::nullopt;
23168 Value *Src = std::get<0>(*ExtractedFields);
23169 unsigned FieldWidth = std::get<1>(*ExtractedFields);
23170 SmallVector<int> &Mask = std::get<2>(*ExtractedFields);
23171 bool IsBSwap = E->CombinedOp == TreeEntry::ExtractedFieldsBSwap;
23172 assert((!IsBSwap ||
23173 (FieldWidth == 8 &&
23175 Mask, Src->getType()->getIntegerBitWidth() / FieldWidth))) &&
23176 "Expected the full reversal of the bytes.");
23177 if (IsBSwap)
23178 std::iota(Mask.begin(), Mask.end(), 0);
23179 return ShuffleBuilder.createExtractedFieldsVector(Src, FieldWidth, Mask,
23180 IsBSwap, *E);
23181}
23182
23183template <typename BVTy, typename ResTy, typename... Args>
23184ResTy BoUpSLP::processBuildVector(const TreeEntry *E, Type *ScalarTy,
23185 Args &...Params) {
23186 assert((E->isGather() || TransformedToGatherNodes.contains(E)) &&
23187 "Expected gather node.");
23188 unsigned VF = E->getVectorFactor();
23189
23190 bool NeedFreeze = false;
23191 SmallVector<Value *> GatheredScalars(E->Scalars.begin(), E->Scalars.end());
23192 // Do not process split vectorize node, marked to be gathers/buildvectors.
23194 E->CombinedEntriesWithIndices.size());
23195 if (E->State == TreeEntry::SplitVectorize &&
23196 TransformedToGatherNodes.contains(E)) {
23197 SubVectors.clear();
23198 } else {
23199 // Clear values, to be replaced by insertvector instructions.
23200 for (auto [EIdx, Idx] : E->CombinedEntriesWithIndices)
23201 for_each(MutableArrayRef(GatheredScalars)
23202 .slice(Idx, VectorizableTree[EIdx]->getVectorFactor()),
23203 [&](Value *&V) { V = PoisonValue::get(V->getType()); });
23204 transform(
23205 E->CombinedEntriesWithIndices, SubVectors.begin(), [&](const auto &P) {
23206 return std::make_pair(VectorizableTree[P.first].get(), P.second);
23207 });
23208 }
23209 // Build a mask out of the reorder indices and reorder scalars per this
23210 // mask.
23211 SmallVector<int> ReorderMask(E->ReorderIndices.begin(),
23212 E->ReorderIndices.end());
23213 if (!ReorderMask.empty())
23214 reorderScalars(GatheredScalars, ReorderMask);
23215 SmallVector<int> SubVectorsMask;
23216 inversePermutation(E->ReorderIndices, SubVectorsMask);
23217 // Transform non-clustered elements in the mask to poison (-1).
23218 // "Clustered" operations will be reordered using this mask later.
23219 if (!SubVectors.empty() && !SubVectorsMask.empty()) {
23220 for (unsigned I : seq<unsigned>(GatheredScalars.size()))
23221 if (E->Scalars[I] == GatheredScalars[ReorderMask[I]])
23222 SubVectorsMask[ReorderMask[I]] = PoisonMaskElem;
23223 } else {
23224 SubVectorsMask.clear();
23225 }
23226 SmallVector<Value *> StoredGS(GatheredScalars);
23227 auto FindReusedSplat = [&](MutableArrayRef<int> Mask, unsigned InputVF,
23228 unsigned I, unsigned SliceSize,
23229 bool IsNotPoisonous) {
23230 if (!isSplat(E->Scalars) || none_of(E->Scalars, [](Value *V) {
23231 return isa<UndefValue>(V) && !isa<PoisonValue>(V);
23232 }))
23233 return false;
23234 TreeEntry *UserTE = E->UserTreeIndex.UserTE;
23235 unsigned EdgeIdx = E->UserTreeIndex.EdgeIdx;
23236 if (UserTE->getNumOperands() != 2)
23237 return false;
23238 if (!IsNotPoisonous) {
23239 auto *It = find_if(ArrayRef(VectorizableTree).drop_front(UserTE->Idx + 1),
23240 [=](const std::unique_ptr<TreeEntry> &TE) {
23241 return TE->UserTreeIndex.UserTE == UserTE &&
23242 TE->UserTreeIndex.EdgeIdx != EdgeIdx;
23243 });
23244 if (It == VectorizableTree.end())
23245 return false;
23246 SmallVector<Value *> GS((*It)->Scalars.begin(), (*It)->Scalars.end());
23247 if (!(*It)->ReorderIndices.empty()) {
23248 inversePermutation((*It)->ReorderIndices, ReorderMask);
23249 reorderScalars(GS, ReorderMask);
23250 }
23251 if (!all_of(zip(GatheredScalars, GS), [&](const auto &P) {
23252 Value *V0 = std::get<0>(P);
23253 Value *V1 = std::get<1>(P);
23254 return !isa<UndefValue>(V0) || isa<PoisonValue>(V0) ||
23255 (isa<UndefValue>(V0) && !isa<PoisonValue>(V0) &&
23256 is_contained(E->Scalars, V1));
23257 }))
23258 return false;
23259 }
23260 int Idx;
23261 if ((Mask.size() < InputVF &&
23262 ShuffleVectorInst::isExtractSubvectorMask(Mask, InputVF, Idx) &&
23263 Idx == 0) ||
23264 (Mask.size() == InputVF &&
23265 ShuffleVectorInst::isIdentityMask(Mask, Mask.size()))) {
23266 std::iota(
23267 std::next(Mask.begin(), I * SliceSize),
23268 std::next(Mask.begin(),
23269 I * SliceSize + getNumElems(Mask.size(), SliceSize, I)),
23270 0);
23271 } else {
23272 unsigned IVal =
23273 *find_if_not(Mask, [](int Idx) { return Idx == PoisonMaskElem; });
23274 std::fill(
23275 std::next(Mask.begin(), I * SliceSize),
23276 std::next(Mask.begin(),
23277 I * SliceSize + getNumElems(Mask.size(), SliceSize, I)),
23278 IVal);
23279 }
23280 return true;
23281 };
23282 BVTy ShuffleBuilder(ScalarTy, Params...);
23283 ResTy Res = ResTy();
23284 SmallVector<int> Mask;
23285 SmallVector<int> ExtractMask(GatheredScalars.size(), PoisonMaskElem);
23287 Value *ExtractVecBase = nullptr;
23288 bool UseVecBaseAsInput = false;
23291 Type *OrigScalarTy = GatheredScalars.front()->getType();
23292 auto *VecTy = getWidenedType(ScalarTy, GatheredScalars.size());
23293 unsigned NumParts = getNumberOfParts(VecTy, ScalarTy, GatheredScalars.size());
23294 if (std::optional<ResTy> Res = processExtractedFieldsGather<ResTy>(
23295 ShuffleBuilder, E, ScalarTy, GatheredScalars, SubVectors))
23296 return *Res;
23297 if (!all_of(GatheredScalars, IsaPred<UndefValue>)) {
23298 // Check for gathered extracts.
23299 bool Resized = false;
23300 ExtractShuffles =
23301 tryToGatherExtractElements(GatheredScalars, ExtractMask, NumParts);
23302 if (!ExtractShuffles.empty()) {
23303 SmallVector<const TreeEntry *> ExtractEntries;
23304 for (const auto &P :
23305 make_filter_range(enumerate(ExtractMask), [](const auto &P) {
23306 return P.value() != PoisonMaskElem;
23307 })) {
23308 if (ArrayRef<TreeEntry *> TEs =
23309 getTreeEntries(cast<ExtractElementInst>(StoredGS[P.index()])
23310 ->getVectorOperand());
23311 !TEs.empty())
23312 ExtractEntries.append(TEs.begin(), TEs.end());
23313 }
23314 if (std::optional<ResTy> Delayed =
23315 ShuffleBuilder.needToDelay(E, ExtractEntries)) {
23316 // Delay emission of gathers which are not ready yet.
23317 PostponedGathers.insert(E);
23318 // Postpone gather emission, will be emitted after the end of the
23319 // process to keep correct order.
23320 return *Delayed;
23321 }
23322 if (Value *VecBase = ShuffleBuilder.adjustExtracts(
23323 E, ExtractMask, ExtractShuffles, NumParts, UseVecBaseAsInput)) {
23324 ExtractVecBase = VecBase;
23325 if (auto *VecBaseTy = dyn_cast<FixedVectorType>(VecBase->getType()))
23326 if (VF == VecBaseTy->getNumElements() &&
23327 GatheredScalars.size() != VF) {
23328 Resized = true;
23329 GatheredScalars.append(VF - GatheredScalars.size(),
23330 PoisonValue::get(OrigScalarTy));
23331 NumParts = getNumberOfParts(getWidenedType(OrigScalarTy, VF),
23332 OrigScalarTy, VF);
23333 }
23334 }
23335 }
23336 // Gather extracts after we check for full matched gathers only.
23337 if (!ExtractShuffles.empty() || !E->hasState() ||
23338 E->getOpcode() != Instruction::Load ||
23339 (((E->hasState() && E->getOpcode() == Instruction::Load) ||
23340 any_of(E->Scalars, IsaPred<LoadInst>)) &&
23341 any_of(make_isa_range<LoadInst>(E->Scalars),
23342 [this](LoadInst *LI) { return isVectorized(LI); })) ||
23343 (E->hasState() && E->isAltShuffle()) ||
23344 all_of(E->Scalars, [this](Value *V) { return isVectorized(V); }) ||
23345 isSplat(E->Scalars) ||
23346 (E->Scalars != GatheredScalars && GatheredScalars.size() <= 2)) {
23347 GatherShuffles = isGatherShuffledEntry(E, GatheredScalars, Mask, Entries,
23348 NumParts, ScalarTy);
23349 }
23350 // The splat gather subtrees are speculative: the keep/drop check may
23351 // delete them and does not track reuse of their internal gathers by other
23352 // gathers.
23353 if (hasSplatSubtreeGather(Entries)) {
23354 GatherShuffles.clear();
23355 Entries.clear();
23356 std::fill(Mask.begin(), Mask.end(), PoisonMaskElem);
23357 }
23358 if (!GatherShuffles.empty()) {
23359 if (std::optional<ResTy> Delayed =
23360 ShuffleBuilder.needToDelay(E, Entries)) {
23361 // Delay emission of gathers which are not ready yet.
23362 PostponedGathers.insert(E);
23363 // Postpone gather emission, will be emitted after the end of the
23364 // process to keep correct order.
23365 return *Delayed;
23366 }
23367 // Match against the expanded vector of the gather node, so that poison
23368 // lanes of the matched entry cannot wildcard-match its real scalars.
23369 auto IsFullVectorMatch = [&](const TreeEntry *FrontTE) {
23370 SmallVector<int> CommonMask = E->getCommonMask();
23371 SmallVector<Value *> Expanded(E->getVectorFactor());
23372 for (unsigned I : seq<unsigned>(E->getVectorFactor()))
23373 Expanded[I] = CommonMask.empty() ? E->Scalars[I]
23374 : CommonMask[I] == PoisonMaskElem
23375 ? PoisonValue::get(OrigScalarTy)
23376 : E->Scalars[CommonMask[I]];
23377 return FrontTE->isSame(Expanded);
23378 };
23379 if (GatherShuffles.size() == 1 &&
23380 *GatherShuffles.front() == TTI::SK_PermuteSingleSrc &&
23381 (Entries.front().front()->isSame(E->Scalars) ||
23382 IsFullVectorMatch(Entries.front().front()))) {
23383 // Perfect match in the graph, will reuse the previously vectorized
23384 // node. Cost is 0.
23385 LLVM_DEBUG(dbgs() << "SLP: perfect diamond match for gather bundle "
23386 << shortBundleName(E->Scalars, E->Idx) << ".\n");
23387 // Restore the mask for previous partially matched values.
23388 Mask.resize(E->Scalars.size());
23389 const TreeEntry *FrontTE = Entries.front().front();
23390 if (FrontTE->ReorderIndices.empty() && E->ReorderIndices.empty() &&
23391 ((FrontTE->ReuseShuffleIndices.empty() &&
23392 E->Scalars.size() == FrontTE->Scalars.size()) ||
23393 (E->Scalars.size() == FrontTE->ReuseShuffleIndices.size()))) {
23394 std::iota(Mask.begin(), Mask.end(), 0);
23395 } else {
23396 for (auto [I, V] : enumerate(E->Scalars)) {
23397 if (isa<PoisonValue>(V)) {
23398 Mask[I] = PoisonMaskElem;
23399 continue;
23400 }
23401 Mask[I] = FrontTE->findLaneForValue(V);
23402 }
23403 }
23404 // Reset the builder(s) to correctly handle perfect diamond matched
23405 // nodes.
23406 ShuffleBuilder.resetForSameNode();
23407 // Full matched entry found, no need to insert subvectors.
23408 if ((IsFullVectorMatch(FrontTE) &&
23409 FrontTE->ReuseShuffleIndices.empty() &&
23410 FrontTE->ReorderIndices.empty() &&
23411 E->getVectorFactor() == FrontTE->getVectorFactor()) ||
23412 (equal(E->Scalars, FrontTE->Scalars) &&
23413 equal(E->ReorderIndices, FrontTE->ReorderIndices) &&
23414 equal(E->ReuseShuffleIndices, FrontTE->ReuseShuffleIndices))) {
23415 Mask.resize(FrontTE->getVectorFactor());
23416 std::iota(Mask.begin(), Mask.end(), 0);
23417 ShuffleBuilder.add(*FrontTE, Mask);
23418 Res = ShuffleBuilder.finalize({}, {}, {});
23419 } else {
23420 ShuffleBuilder.add(*FrontTE, Mask);
23421 Res = ShuffleBuilder.finalize(E->getCommonMask(), {}, {});
23422 }
23423 return Res;
23424 }
23425 if (!Resized) {
23426 if (GatheredScalars.size() != VF &&
23427 any_of(Entries, [&](ArrayRef<const TreeEntry *> TEs) {
23428 return any_of(TEs, [&](const TreeEntry *TE) {
23429 return TE->getVectorFactor() == VF;
23430 });
23431 }))
23432 GatheredScalars.append(VF - GatheredScalars.size(),
23433 PoisonValue::get(OrigScalarTy));
23434 }
23435 // Remove shuffled elements from list of gathers.
23436 for (int I = 0, Sz = Mask.size(); I < Sz; ++I) {
23437 if (Mask[I] != PoisonMaskElem)
23438 GatheredScalars[I] = PoisonValue::get(OrigScalarTy);
23439 }
23440 }
23441 }
23442 auto TryPackScalars = [&](SmallVectorImpl<Value *> &Scalars,
23443 SmallVectorImpl<int> &ReuseMask,
23444 bool IsRootPoison) {
23445 // For splats with can emit broadcasts instead of gathers, so try to find
23446 // such sequences.
23447 bool IsSplat = IsRootPoison && isSplat(Scalars) &&
23448 (Scalars.size() > 2 || Scalars.front() == Scalars.back());
23449 Scalars.append(VF - Scalars.size(), PoisonValue::get(OrigScalarTy));
23450 SmallVector<int> UndefPos;
23451 DenseMap<Value *, unsigned> UniquePositions;
23452 // Gather unique non-const values and all constant values.
23453 // For repeated values, just shuffle them.
23454 int NumNonConsts = 0;
23455 int SinglePos = 0;
23456 for (auto [I, V] : enumerate(Scalars)) {
23457 if (isa<UndefValue>(V)) {
23458 if (!isa<PoisonValue>(V)) {
23459 ReuseMask[I] = I;
23460 UndefPos.push_back(I);
23461 }
23462 continue;
23463 }
23464 if (isConstant(V)) {
23465 ReuseMask[I] = I;
23466 continue;
23467 }
23468 ++NumNonConsts;
23469 SinglePos = I;
23470 Value *OrigV = V;
23471 Scalars[I] = PoisonValue::get(OrigScalarTy);
23472 if (IsSplat) {
23473 Scalars.front() = OrigV;
23474 ReuseMask[I] = 0;
23475 } else {
23476 const auto Res = UniquePositions.try_emplace(OrigV, I);
23477 Scalars[Res.first->second] = OrigV;
23478 ReuseMask[I] = Res.first->second;
23479 }
23480 }
23481 if (NumNonConsts == 1) {
23482 // Restore single insert element.
23483 if (IsSplat) {
23484 ReuseMask.assign(VF, PoisonMaskElem);
23485 std::swap(Scalars.front(), Scalars[SinglePos]);
23486 if (!UndefPos.empty() && UndefPos.front() == 0)
23487 Scalars.front() = UndefValue::get(OrigScalarTy);
23488 }
23489 ReuseMask[SinglePos] = SinglePos;
23490 } else if (!UndefPos.empty() && IsSplat) {
23491 // For undef values, try to replace them with the simple broadcast.
23492 // We can do it if the broadcasted value is guaranteed to be
23493 // non-poisonous, or by freezing the incoming scalar value first.
23494 auto *It = find_if(Scalars, [this, E](Value *V) {
23495 return !isa<UndefValue>(V) &&
23497 (E->UserTreeIndex && any_of(V->uses(), [E](const Use &U) {
23498 // Check if the value already used in the same operation in
23499 // one of the nodes already.
23500 return E->UserTreeIndex.EdgeIdx != U.getOperandNo() &&
23501 is_contained(E->UserTreeIndex.UserTE->Scalars,
23502 U.getUser());
23503 })));
23504 });
23505 if (It != Scalars.end()) {
23506 // Replace undefs by the non-poisoned scalars and emit broadcast.
23507 int Pos = std::distance(Scalars.begin(), It);
23508 for (int I : UndefPos) {
23509 // Set the undef position to the non-poisoned scalar.
23510 ReuseMask[I] = Pos;
23511 // Replace the undef by the poison, in the mask it is replaced by
23512 // non-poisoned scalar already.
23513 if (I != Pos)
23514 Scalars[I] = PoisonValue::get(OrigScalarTy);
23515 }
23516 } else {
23517 // Replace undefs by the poisons, emit broadcast and then emit
23518 // freeze.
23519 for (int I : UndefPos) {
23520 ReuseMask[I] = PoisonMaskElem;
23521 if (isa<UndefValue>(Scalars[I]))
23522 Scalars[I] = PoisonValue::get(OrigScalarTy);
23523 }
23524 NeedFreeze = true;
23525 }
23526 }
23527 };
23528 if (!ExtractShuffles.empty() || !GatherShuffles.empty()) {
23529 bool IsNonPoisoned = true;
23530 bool IsUsedInExpr = true;
23531 Value *Vec1 = nullptr;
23532 if (!ExtractShuffles.empty()) {
23533 // Gather of extractelements can be represented as just a shuffle of
23534 // a single/two vectors the scalars are extracted from.
23535 // Find input vectors.
23536 Value *Vec2 = nullptr;
23537 for (unsigned I = 0, Sz = ExtractMask.size(); I < Sz; ++I) {
23538 if (!Mask.empty() && Mask[I] != PoisonMaskElem)
23539 ExtractMask[I] = PoisonMaskElem;
23540 }
23541 if (UseVecBaseAsInput) {
23542 Vec1 = ExtractVecBase;
23543 } else {
23544 for (unsigned I = 0, Sz = ExtractMask.size(); I < Sz; ++I) {
23545 if (ExtractMask[I] == PoisonMaskElem)
23546 continue;
23547 if (isa<UndefValue>(StoredGS[I]))
23548 continue;
23549 auto *EI = cast<ExtractElementInst>(StoredGS[I]);
23550 Value *VecOp = EI->getVectorOperand();
23551 if (ArrayRef<TreeEntry *> TEs = getTreeEntries(VecOp);
23552 !TEs.empty() && TEs.front()->VectorizedValue)
23553 VecOp = TEs.front()->VectorizedValue;
23554 if (!Vec1) {
23555 Vec1 = VecOp;
23556 } else if (Vec1 != VecOp) {
23557 assert((!Vec2 || Vec2 == VecOp) &&
23558 "Expected only 1 or 2 vectors shuffle.");
23559 Vec2 = VecOp;
23560 }
23561 }
23562 }
23563 if (Vec2) {
23564 IsUsedInExpr = false;
23565 IsNonPoisoned &= isGuaranteedNotToBePoison(Vec1, AC) &&
23566 isGuaranteedNotToBePoison(Vec2, AC);
23567 ShuffleBuilder.add(Vec1, Vec2, ExtractMask);
23568 } else if (Vec1) {
23569 bool IsNotPoisonedVec = isGuaranteedNotToBePoison(Vec1, AC);
23570 IsUsedInExpr &= FindReusedSplat(
23571 ExtractMask,
23572 cast<FixedVectorType>(Vec1->getType())->getNumElements(), 0,
23573 ExtractMask.size(), IsNotPoisonedVec);
23574 ShuffleBuilder.add(Vec1, ExtractMask, /*ForExtracts=*/true);
23575 IsNonPoisoned &= IsNotPoisonedVec;
23576 } else {
23577 IsUsedInExpr = false;
23578 ShuffleBuilder.add(PoisonValue::get(VecTy), ExtractMask,
23579 /*ForExtracts=*/true);
23580 }
23581 }
23582 if (!GatherShuffles.empty()) {
23583 unsigned SliceSize = getPartNumElems(VF, NumParts);
23584 if (Mask.size() == E->Scalars.size())
23585 SliceSize = getPartNumElems(
23586 E->Scalars.size(),
23587 getNumberOfParts(VecTy, ScalarTy, E->Scalars.size()));
23588 SmallVector<int> VecMask(Mask.size(), PoisonMaskElem);
23589 for (const auto [I, TEs] : enumerate(Entries)) {
23590 if (TEs.empty()) {
23591 assert(!GatherShuffles[I] &&
23592 "No shuffles with empty entries list expected.");
23593 continue;
23594 }
23595 assert((TEs.size() == 1 || TEs.size() == 2) &&
23596 "Expected shuffle of 1 or 2 entries.");
23597 unsigned Limit = getNumElems(Mask.size(), SliceSize, I);
23598 auto SubMask = ArrayRef(Mask).slice(I * SliceSize, Limit);
23599 VecMask.assign(VecMask.size(), PoisonMaskElem);
23600 copy(SubMask, std::next(VecMask.begin(), I * SliceSize));
23601 if (TEs.size() == 1) {
23602 bool IsNotPoisonedVec =
23603 TEs.front()->VectorizedValue
23604 ? isGuaranteedNotToBePoison(TEs.front()->VectorizedValue, AC)
23605 : true;
23606 IsUsedInExpr &=
23607 FindReusedSplat(VecMask, TEs.front()->getVectorFactor(), I,
23608 SliceSize, IsNotPoisonedVec);
23609 ShuffleBuilder.add(*TEs.front(), VecMask);
23610 IsNonPoisoned &= IsNotPoisonedVec;
23611 } else {
23612 IsUsedInExpr = false;
23613 ShuffleBuilder.add(*TEs.front(), *TEs.back(), VecMask);
23614 if (TEs.front()->VectorizedValue && TEs.back()->VectorizedValue)
23615 IsNonPoisoned &=
23616 isGuaranteedNotToBePoison(TEs.front()->VectorizedValue, AC) &&
23617 isGuaranteedNotToBePoison(TEs.back()->VectorizedValue, AC);
23618 }
23619 }
23620 }
23621 // Try to figure out best way to combine values: build a shuffle and insert
23622 // elements or just build several shuffles.
23623 // Insert non-constant scalars.
23624 SmallVector<Value *> NonConstants(GatheredScalars);
23625 int EMSz = ExtractMask.size();
23626 int MSz = Mask.size();
23627 // Try to build constant vector and shuffle with it only if currently we
23628 // have a single permutation and more than 1 scalar constants.
23629 bool IsSingleShuffle = ExtractShuffles.empty() || GatherShuffles.empty();
23630 bool IsIdentityShuffle =
23631 ((UseVecBaseAsInput ||
23632 all_of(ExtractShuffles,
23633 [](const std::optional<TTI::ShuffleKind> &SK) {
23634 return SK.value_or(TTI::SK_PermuteTwoSrc) ==
23636 })) &&
23637 none_of(ExtractMask, [&](int I) { return I >= EMSz; }) &&
23638 ShuffleVectorInst::isIdentityMask(ExtractMask, EMSz)) ||
23639 (!GatherShuffles.empty() &&
23640 all_of(GatherShuffles,
23641 [](const std::optional<TTI::ShuffleKind> &SK) {
23642 return SK.value_or(TTI::SK_PermuteTwoSrc) ==
23644 }) &&
23645 none_of(Mask, [&](int I) { return I >= MSz; }) &&
23647 bool EnoughConstsForShuffle =
23648 IsSingleShuffle &&
23649 (none_of(GatheredScalars,
23650 [](Value *V) {
23651 return isa<UndefValue>(V) && !isa<PoisonValue>(V);
23652 }) ||
23653 any_of(GatheredScalars,
23654 [](Value *V) {
23655 return isa<Constant>(V) && !isa<UndefValue>(V);
23656 })) &&
23657 (!IsIdentityShuffle ||
23658 (GatheredScalars.size() == 2 &&
23659 any_of(GatheredScalars,
23660 [](Value *V) { return !isa<UndefValue>(V); })) ||
23661 count_if(GatheredScalars, [](Value *V) {
23662 return isa<Constant>(V) && !isa<PoisonValue>(V);
23663 }) > 1);
23664 // NonConstants array contains just non-constant values, GatheredScalars
23665 // contains only constant to build final vector and then shuffle.
23666 for (int I = 0, Sz = GatheredScalars.size(); I < Sz; ++I) {
23667 if (EnoughConstsForShuffle && isa<Constant>(GatheredScalars[I]))
23668 NonConstants[I] = PoisonValue::get(OrigScalarTy);
23669 else
23670 GatheredScalars[I] = PoisonValue::get(OrigScalarTy);
23671 }
23672 // Generate constants for final shuffle and build a mask for them.
23673 if (!all_of(GatheredScalars, IsaPred<PoisonValue>)) {
23674 SmallVector<int> BVMask(GatheredScalars.size(), PoisonMaskElem);
23675 TryPackScalars(GatheredScalars, BVMask, /*IsRootPoison=*/true);
23676 Value *BV = ShuffleBuilder.gather(GatheredScalars, BVMask.size());
23677 ShuffleBuilder.add(BV, BVMask);
23678 }
23679 if (all_of(NonConstants, [=](Value *V) {
23680 return isa<PoisonValue>(V) ||
23681 (IsSingleShuffle && ((IsIdentityShuffle &&
23682 IsNonPoisoned) || IsUsedInExpr) && isa<UndefValue>(V));
23683 }))
23684 Res = ShuffleBuilder.finalize(E->ReuseShuffleIndices, SubVectors,
23685 SubVectorsMask);
23686 else
23687 Res = ShuffleBuilder.finalize(
23688 E->ReuseShuffleIndices, SubVectors, SubVectorsMask, E->Scalars.size(),
23689 [&](Value *&Vec, SmallVectorImpl<int> &Mask, auto CreateShuffle) {
23690 bool IsSplat = isSplat(NonConstants);
23691 SmallVector<int> BVMask(Mask.size(), PoisonMaskElem);
23692 TryPackScalars(NonConstants, BVMask, /*IsRootPoison=*/false);
23693 auto CheckIfSplatIsProfitable = [&]() {
23694 // Estimate the cost of splatting + shuffle and compare with
23695 // insert + shuffle.
23696 Value *V = *find_if_not(NonConstants, IsaPred<UndefValue>);
23697 if (isa<ExtractElementInst>(V) || isVectorized(V))
23698 return false;
23699 InstructionCost SplatCost = TTI->getVectorInstrCost(
23700 Instruction::InsertElement, VecTy, CostKind, /*Index=*/0,
23701 PoisonValue::get(VecTy), V);
23702 SmallVector<int> NewMask(Mask.begin(), Mask.end());
23703 for (auto [Idx, I] : enumerate(BVMask))
23704 if (I != PoisonMaskElem)
23705 NewMask[Idx] = Mask.size();
23706 SplatCost +=
23707 getShuffleCost(*TTI, TTI::SK_PermuteTwoSrc,
23708 cast<VectorType>(VecTy), CostKind, NewMask);
23709 InstructionCost BVCost = TTI->getVectorInstrCost(
23710 Instruction::InsertElement, VecTy, CostKind,
23711 *find_if(Mask, not_equal_to(PoisonMaskElem)), Vec, V);
23712 // Shuffle required?
23713 if (count(BVMask, PoisonMaskElem) <
23714 static_cast<int>(BVMask.size() - 1)) {
23715 SmallVector<int> NewMask(Mask.begin(), Mask.end());
23716 for (auto [Idx, I] : enumerate(BVMask))
23717 if (I != PoisonMaskElem)
23718 NewMask[Idx] = I;
23719 BVCost +=
23720 getShuffleCost(*TTI, TTI::SK_PermuteSingleSrc,
23721 cast<VectorType>(VecTy), CostKind, NewMask);
23722 }
23723 return SplatCost <= BVCost;
23724 };
23725 if (!IsSplat || Mask.size() <= 2 || !CheckIfSplatIsProfitable()) {
23726 for (auto [Idx, I] : enumerate(BVMask))
23727 if (I != PoisonMaskElem)
23728 Mask[Idx] = I;
23729 Vec = ShuffleBuilder.gather(NonConstants, Mask.size(), Vec);
23730 } else {
23731 Value *V = *find_if_not(NonConstants, IsaPred<UndefValue>);
23732 // The splat replaces undefs by the splatted value, freeze it if
23733 // it may be poison.
23734 if constexpr (std::is_same_v<ResTy, Value *>)
23735 if (any_of(NonConstants,
23736 [](Value *U) {
23737 return isa<UndefValue>(U) && !isa<PoisonValue>(U);
23738 }) &&
23740 V = ShuffleBuilder.createFreeze(V);
23741 SmallVector<Value *> Values(NonConstants.size(),
23742 PoisonValue::get(ScalarTy));
23743 Values[0] = V;
23744 Value *BV = ShuffleBuilder.gather(Values, BVMask.size());
23745 SmallVector<int> SplatMask(BVMask.size(), PoisonMaskElem);
23746 transform(BVMask, SplatMask.begin(), [](int I) {
23747 return I == PoisonMaskElem ? PoisonMaskElem : 0;
23748 });
23749 if (!ShuffleVectorInst::isIdentityMask(SplatMask, VF))
23750 BV = CreateShuffle(BV, nullptr, SplatMask);
23751 for (auto [Idx, I] : enumerate(BVMask))
23752 if (I != PoisonMaskElem)
23753 Mask[Idx] = BVMask.size() + Idx;
23754 Vec = CreateShuffle(Vec, BV, Mask);
23755 for (auto [Idx, I] : enumerate(Mask))
23756 if (I != PoisonMaskElem)
23757 Mask[Idx] = Idx;
23758 }
23759 });
23760 } else if (!allConstant(GatheredScalars)) {
23761 // Gather unique scalars and all constants.
23762 SmallVector<int> ReuseMask(GatheredScalars.size(), PoisonMaskElem);
23763 TryPackScalars(GatheredScalars, ReuseMask, /*IsRootPoison=*/true);
23765 if constexpr (std::is_same_v<ResTy, InstructionCost>) {
23766 auto GatherUserOps =
23768 UserOps.clear();
23769 return !NeedFreeze && collectGatherUserOps(*E, UserOps);
23770 };
23771 ContextHint =
23772 TTI->getBuildVectorContextHint(ReuseMask, E->Scalars, GatherUserOps);
23773 }
23774 Value *BV = ShuffleBuilder.gather(GatheredScalars, ReuseMask.size(),
23775 /*Root*/ nullptr, ContextHint);
23776 ShuffleBuilder.add(BV, ReuseMask, /*ForExtract*/ false, ContextHint);
23777 Res = ShuffleBuilder.finalize(E->ReuseShuffleIndices, SubVectors,
23778 SubVectorsMask, /*VF*/ 0, /*Action*/ {});
23779 } else {
23780 // Gather all constants.
23781 SmallVector<int> Mask(GatheredScalars.size(), PoisonMaskElem);
23782 for (auto [I, V] : enumerate(GatheredScalars)) {
23783 if (!isa<PoisonValue>(V))
23784 Mask[I] = I;
23785 }
23786 Value *BV = ShuffleBuilder.gather(GatheredScalars);
23787 ShuffleBuilder.add(BV, Mask);
23788 Res = ShuffleBuilder.finalize(E->ReuseShuffleIndices, SubVectors,
23789 SubVectorsMask);
23790 }
23791
23792 if (NeedFreeze)
23793 Res = ShuffleBuilder.createFreeze(Res);
23794 return Res;
23795}
23796
23797Value *BoUpSLP::createBuildVector(const TreeEntry *E, Type *ScalarTy) {
23798 // Do not do this for split vectorize node, marked to be gathers/buildvectors.
23799 if (E->State != TreeEntry::SplitVectorize ||
23800 !TransformedToGatherNodes.contains(E)) {
23801 for (auto [EIdx, _] : E->CombinedEntriesWithIndices)
23802 (void)vectorizeTr