LLVM 24.0.0git
LoopVectorize.cpp
Go to the documentation of this file.
1//===- LoopVectorize.cpp - A Loop 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 is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
10// and generates target-independent LLVM-IR.
11// The vectorizer uses the TargetTransformInfo analysis to estimate the costs
12// of instructions in order to estimate the profitability of vectorization.
13//
14// The loop vectorizer combines consecutive loop iterations into a single
15// 'wide' iteration. After this transformation the index is incremented
16// by the SIMD vector width, and not by one.
17//
18// This pass has three parts:
19// 1. The main loop pass that drives the different parts.
20// 2. LoopVectorizationLegality - A unit that checks for the legality
21// of the vectorization.
22// 3. InnerLoopVectorizer - A unit that performs the actual
23// widening of instructions.
24// 4. LoopVectorizationCostModel - A unit that checks for the profitability
25// of vectorization. It decides on the optimal vector width, which
26// can be one, if vectorization is not profitable.
27//
28// There is a development effort going on to migrate loop vectorizer to the
29// VPlan infrastructure and to introduce outer loop vectorization support (see
30// docs/VectorizationPlan.rst and
31// http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
32// purpose, we temporarily introduced the VPlan-native vectorization path: an
33// alternative vectorization path that is natively implemented on top of the
34// VPlan infrastructure. See EnableVPlanNativePath for enabling.
35//
36//===----------------------------------------------------------------------===//
37//
38// The reduction-variable vectorization is based on the paper:
39// D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
40//
41// Variable uniformity checks are inspired by:
42// Karrenberg, R. and Hack, S. Whole Function Vectorization.
43//
44// The interleaved access vectorization is based on the paper:
45// Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
46// Data for SIMD
47//
48// Other ideas/concepts are from:
49// A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
50//
51// S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
52// Vectorizing Compilers.
53//
54//===----------------------------------------------------------------------===//
55
58#include "VPRecipeBuilder.h"
59#include "VPlan.h"
60#include "VPlanAnalysis.h"
61#include "VPlanCFG.h"
62#include "VPlanHelpers.h"
63#include "VPlanPatternMatch.h"
64#include "VPlanTransforms.h"
65#include "VPlanUtils.h"
66#include "VPlanVerifier.h"
67#include "llvm/ADT/APInt.h"
68#include "llvm/ADT/ArrayRef.h"
69#include "llvm/ADT/DenseMap.h"
70#include "llvm/ADT/Hashing.h"
71#include "llvm/ADT/MapVector.h"
72#include "llvm/ADT/STLExtras.h"
75#include "llvm/ADT/Statistic.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/Twine.h"
78#include "llvm/ADT/TypeSwitch.h"
83#include "llvm/Analysis/CFG.h"
101#include "llvm/IR/Attributes.h"
102#include "llvm/IR/BasicBlock.h"
103#include "llvm/IR/CFG.h"
104#include "llvm/IR/Constant.h"
105#include "llvm/IR/Constants.h"
106#include "llvm/IR/DataLayout.h"
107#include "llvm/IR/DebugInfo.h"
108#include "llvm/IR/DebugLoc.h"
109#include "llvm/IR/DerivedTypes.h"
111#include "llvm/IR/Dominators.h"
112#include "llvm/IR/Function.h"
113#include "llvm/IR/IRBuilder.h"
114#include "llvm/IR/InstrTypes.h"
115#include "llvm/IR/Instruction.h"
116#include "llvm/IR/Instructions.h"
118#include "llvm/IR/Intrinsics.h"
119#include "llvm/IR/MDBuilder.h"
120#include "llvm/IR/Metadata.h"
121#include "llvm/IR/Module.h"
122#include "llvm/IR/Operator.h"
123#include "llvm/IR/PatternMatch.h"
125#include "llvm/IR/Type.h"
126#include "llvm/IR/Use.h"
127#include "llvm/IR/User.h"
128#include "llvm/IR/Value.h"
129#include "llvm/IR/Verifier.h"
130#include "llvm/Support/Casting.h"
132#include "llvm/Support/Debug.h"
147#include <algorithm>
148#include <cassert>
149#include <cmath>
150#include <cstdint>
151#include <functional>
152#include <iterator>
153#include <memory>
154#include <string>
155#include <tuple>
156#include <utility>
157
158using namespace llvm;
159using namespace SCEVPatternMatch;
160using namespace LoopVectorizationUtils;
161
162#define LV_NAME "loop-vectorize"
163#define DEBUG_TYPE LV_NAME
164
165#ifndef NDEBUG
166const char VerboseDebug[] = DEBUG_TYPE "-verbose";
167#endif
168
169STATISTIC(LoopsVectorized, "Number of loops vectorized");
170STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
171STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
172STATISTIC(LoopsEarlyExitVectorized, "Number of early exit loops vectorized");
173STATISTIC(LoopsPartialAliasVectorized,
174 "Number of partial aliasing loops vectorized");
175
177 "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
178 cl::desc("Enable vectorization of epilogue loops."));
179
181 "epilogue-vectorization-force-VF", cl::init(ElementCount::getFixed(1)),
183 cl::desc("When epilogue vectorization is enabled, and a value greater than "
184 "1 is specified, forces the given VF for all applicable epilogue "
185 "loops. Note: This allows all scalable VFs >= vscale x 1."));
186
188 "epilogue-vectorization-minimum-VF", cl::Hidden,
189 cl::desc("Only loops with vectorization factor equal to or larger than "
190 "the specified value are considered for epilogue vectorization."));
191
192/// Loops with a known constant trip count below this number are vectorized only
193/// if no scalar iteration overheads are incurred.
195 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
196 cl::desc("Loops with a constant trip count that is smaller than this "
197 "value are vectorized only if no scalar iteration overheads "
198 "are incurred."));
199
201 "vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
202 cl::desc("The maximum allowed number of runtime memory checks"));
203
205 "force-partial-aliasing-vectorization", cl::init(false), cl::Hidden,
206 cl::desc("Replace pointer diff checks with alias masks."));
207
208/// Option tail-folding-policy controls the tail-folding strategy and lists all
209/// available options. The vectorizer will attempt to fold the tail-loop into
210/// the vector loop (main/epilogue loops) and predicate the instructions
211/// accordingly. If tail-folding fails, there are different fallback strategies
212/// depending on these values:
214
216 "tail-folding-policy", cl::init(TailFoldingPolicyTy::None), cl::Hidden,
217 cl::desc("Tail-folding preferences over creating an epilogue loop."),
219 clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail",
220 "Don't tail-fold loops."),
222 "prefer tail-folding, otherwise create an epilogue when "
223 "appropriate."),
225 "always tail-fold, don't attempt vectorization if "
226 "tail-folding fails.")));
227
229 "epilogue-tail-folding-policy", cl::Hidden,
230 cl::desc(
231 "Epilogue-tail-folding preferences over creating an epilogue loop."),
233 clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail",
234 "Don't tail-fold loops."),
236 "prefer tail-folding, otherwise create an epilogue when "
237 "appropriate.")));
238
240 "force-tail-folding-style", cl::desc("Force the tail folding style"),
243 clEnumValN(TailFoldingStyle::None, "none", "Disable tail folding"),
246 "Create lane mask for data only, using active.lane.mask intrinsic"),
248 "data-without-lane-mask",
249 "Create lane mask with compare/stepvector"),
251 "Create lane mask using active.lane.mask intrinsic, and use "
252 "it for both data and control flow"),
254 "Use predicated EVL instructions for tail folding. If EVL "
255 "is unsupported, fallback to data-without-lane-mask.")));
256
258 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
259 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
260
261/// An interleave-group may need masking if it resides in a block that needs
262/// predication, or in order to mask away gaps.
264 "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
265 cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
266
268 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
269 cl::desc("A flag that overrides the target's number of scalar registers."));
270
272 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
273 cl::desc("A flag that overrides the target's number of vector registers."));
274
276 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
277 cl::desc("A flag that overrides the target's max interleave factor for "
278 "scalar loops."));
279
281 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
282 cl::desc("A flag that overrides the target's max interleave factor for "
283 "vectorized loops."));
284
286 "force-target-instruction-cost", cl::init(0), cl::Hidden,
287 cl::desc("A flag that overrides the target's expected cost for "
288 "an instruction to a single constant value. Mostly "
289 "useful for getting consistent testing."));
290
292 "small-loop-cost", cl::init(20), cl::Hidden,
293 cl::desc(
294 "The cost of a loop that is considered 'small' by the interleaver."));
295
297 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
298 cl::desc("Enable the use of the block frequency analysis to access PGO "
299 "heuristics minimizing code growth in cold regions and being more "
300 "aggressive in hot regions."));
301
302// Runtime interleave loops for load/store throughput.
304 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
305 cl::desc(
306 "Enable runtime interleaving until load/store ports are saturated"));
307
308/// The number of stores in a loop that are allowed to need predication.
310 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
311 cl::desc("Max number of stores to be predicated behind an if."));
312
313// TODO: Move size-based thresholds out of legality checking, make cost based
314// decisions instead of hard thresholds.
316 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
317 cl::desc("The maximum number of SCEV checks allowed."));
318
320 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
321 cl::desc("The maximum number of SCEV checks allowed with a "
322 "vectorize(enable) pragma"));
323
325 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
326 cl::desc("Count the induction variable only once when interleaving"));
327
329 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
330 cl::desc("The maximum interleave count to use when interleaving a scalar "
331 "reduction in a nested loop."));
332
334 "force-ordered-reductions", cl::init(false), cl::Hidden,
335 cl::desc("Enable the vectorisation of loops with in-order (strict) "
336 "FP reductions"));
337
339 "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
340 cl::desc(
341 "Prefer predicating a reduction operation over an after loop select."));
342
344 "enable-vplan-native-path", cl::Hidden,
345 cl::desc("Enable VPlan-native vectorization path with "
346 "support for outer loop vectorization."));
347
349 llvm::VerifyEachVPlan("vplan-verify-each",
350#ifdef EXPENSIVE_CHECKS
351 cl::init(true),
352#else
353 cl::init(false),
354#endif
356 cl::desc("Verify VPlans after VPlan transforms."));
357
358#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
360 "vplan-print-before-all", cl::init(false), cl::Hidden,
361 cl::desc("Print VPlans before all VPlan transformations."));
362
364 "vplan-print-after-all", cl::init(false), cl::Hidden,
365 cl::desc("Print VPlans after all VPlan transformations."));
366
368 "vplan-print-before", cl::Hidden,
369 cl::desc("Print VPlans before specified VPlan transformations (regexp)."));
370
372 "vplan-print-after", cl::Hidden,
373 cl::desc("Print VPlans after specified VPlan transformations (regexp)."));
374
376 "vplan-print-vector-region-scope", cl::init(false), cl::Hidden,
377 cl::desc("Limit VPlan printing to vector loop region in "
378 "`-vplan-print-after*` if the plan has one."));
379#endif
380
381// This flag enables the stress testing of the VPlan H-CFG construction in the
382// VPlan-native vectorization path. It must be used in conjuction with
383// -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
384// verification of the H-CFGs built.
386 "vplan-build-outerloop-stress-test", cl::init(false), cl::Hidden,
387 cl::desc(
388 "Build VPlan for every supported loop nest in the function and bail "
389 "out right after the build (stress test the VPlan H-CFG construction "
390 "in the VPlan-native vectorization path)."));
391
393 "interleave-loops", cl::init(true), cl::Hidden,
394 cl::desc("Enable loop interleaving in Loop vectorization passes"));
396 "vectorize-loops", cl::init(true), cl::Hidden,
397 cl::desc("Run the Loop vectorization passes"));
398
400 ForceMaskedDivRem("force-widen-divrem-via-masked-intrinsic", cl::Hidden,
401 cl::desc("Override cost based masked intrinsic widening "
402 "for div/rem instructions"));
403
405 "enable-early-exit-vectorization", cl::init(true), cl::Hidden,
406 cl::desc(
407 "Enable vectorization of early exit loops with uncountable exits."));
408
410 "enable-early-exit-vectorization-with-side-effects", cl::init(false),
412 cl::desc("Enable vectorization of early exit loops with uncountable exits "
413 "and side effects"));
414
415// Returns true if the epilogue VF has been set to a non-zero value other than
416// VF=1 (scalar).
421
422// Likelyhood of bypassing the vectorized loop because there are zero trips left
423// after prolog. See `emitIterationCountCheck`.
424static constexpr uint32_t MinItersBypassWeights[] = {1, 127};
425
426/// A version of ScalarEvolution::getSmallConstantTripCount that returns an
427/// ElementCount to include loops whose trip count is a function of vscale.
429 const Loop *L) {
430 if (unsigned ExpectedTC = SE->getSmallConstantTripCount(L))
431 return ElementCount::getFixed(ExpectedTC);
432
433 const SCEV *BTC = SE->getBackedgeTakenCount(L);
435 return ElementCount::getFixed(0);
436
437 const SCEV *ExitCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
438 if (isa<SCEVVScale>(ExitCount))
440
441 const APInt *Scale;
442 if (match(ExitCount, m_scev_Mul(m_scev_APInt(Scale), m_SCEVVScale())))
443 if (cast<SCEVMulExpr>(ExitCount)->hasNoUnsignedWrap())
444 if (Scale->getActiveBits() <= 32)
446
447 return ElementCount::getFixed(0);
448}
449
450/// Get the maximum trip count for \p L from the SCEV unsigned range, excluding
451/// zero from the range. Only valid when not folding the tail, as the minimum
452/// iteration count check guards against a zero trip count. Returns 0 if
453/// unknown.
455 Loop *L) {
456 const SCEV *BTC = PSE.getBackedgeTakenCount();
458 return 0;
459 ScalarEvolution *SE = PSE.getSE();
460 const SCEV *TripCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
461 ConstantRange TCRange = SE->getUnsignedRange(TripCount);
462 APInt MaxTCFromRange = TCRange.getUnsignedMax();
463 if (!MaxTCFromRange.isZero() && MaxTCFromRange.getActiveBits() <= 32)
464 return MaxTCFromRange.getZExtValue();
465 return 0;
466}
467
468/// Returns "best known" trip count, which is either a valid positive trip count
469/// or std::nullopt when an estimate cannot be made (including when the trip
470/// count would overflow), for the specified loop \p L as defined by the
471/// following procedure:
472/// 1) Returns exact trip count if it is known.
473/// 2) Returns expected trip count according to profile data if any.
474/// 3) Returns upper bound estimate if known, if \p CanUseConstantMax, and
475/// if \p ComputeUpperBoundOnly is false.
476/// 4) Returns the maximum trip count from the SCEV range excluding zero,
477/// if \p CanUseConstantMax and \p CanExcludeZeroTrips.
478/// 5) Returns std::nullopt if all of the above failed.
479static std::optional<ElementCount> getSmallBestKnownTC(
480 PredicatedScalarEvolution &PSE, Loop *L, bool CanUseConstantMax = true,
481 bool CanExcludeZeroTrips = false, bool ComputeUpperBoundOnly = false) {
482 // Check if exact trip count is known.
483 if (auto ExpectedTC = getSmallConstantTripCount(PSE.getSE(), L))
484 return ExpectedTC;
485
486 // Check if there is an expected trip count available from profile data.
487 // An estimate of zero means the loop is estimated not to be entered; it is
488 // not a usable trip count for the profitability decisions below (and would
489 // e.g. divide by zero when scaling runtime check cost), so treat it as
490 // unknown.
491 if (LoopVectorizeWithBlockFrequency && !ComputeUpperBoundOnly)
492 if (unsigned EstimatedTC = getLoopEstimatedTripCount(L).value_or(0))
493 return ElementCount::getFixed(EstimatedTC);
494
495 if (!CanUseConstantMax)
496 return std::nullopt;
497
498 // Check if upper bound estimate is known.
499 if (unsigned ExpectedTC = PSE.getSmallConstantMaxTripCount())
500 return ElementCount::getFixed(ExpectedTC);
501
502 // Get the maximum trip count from the SCEV range excluding zero. This is
503 // only safe when not folding the tail, as the minimum iteration count check
504 // prevents entering the vector loop with a zero trip count.
505 if (CanUseConstantMax && CanExcludeZeroTrips)
506 if (unsigned RefinedTC = getMaxTCFromNonZeroRange(PSE, L))
507 return ElementCount::getFixed(RefinedTC);
508
509 return std::nullopt;
510}
511
512namespace {
513// Forward declare GeneratedRTChecks.
514class GeneratedRTChecks;
515
516using SCEV2ValueTy = DenseMap<const SCEV *, Value *>;
517} // namespace
518
519namespace llvm {
520
522
523/// InnerLoopVectorizer vectorizes loops which contain only one basic
524/// block to a specified vectorization factor (VF).
525/// This class performs the widening of scalars into vectors, or multiple
526/// scalars. This class also implements the following features:
527/// * It inserts an epilogue loop for handling loops that don't have iteration
528/// counts that are known to be a multiple of the vectorization factor.
529/// * It handles the code generation for reduction variables.
530/// * Scalarization (implementation using scalars) of un-vectorizable
531/// instructions.
532/// InnerLoopVectorizer does not perform any vectorization-legality
533/// checks, and relies on the caller to check for the different legality
534/// aspects. The InnerLoopVectorizer relies on the
535/// LoopVectorizationLegality class to provide information about the induction
536/// and reduction variables that were found to a given vectorization factor.
538public:
542 ElementCount VecWidth, unsigned UnrollFactor,
543 GeneratedRTChecks &RTChecks, VPlan &Plan)
544 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TTI(TTI), AC(AC),
545 VF(VecWidth), UF(UnrollFactor), Builder(PSE.getSE()->getContext()),
548 Plan.getVectorLoopRegion()->getSinglePredecessor())) {}
549
550 virtual ~InnerLoopVectorizer() = default;
551
552 /// Creates a basic block for the scalar preheader. Both
553 /// EpilogueVectorizerMainLoop and EpilogueVectorizerEpilogueLoop overwrite
554 /// the method to create additional blocks and checks needed for epilogue
555 /// vectorization.
557
558 /// Fix the vectorized code, taking care of header phi's, and more.
560
561protected:
563
564 /// Create and return a new IR basic block for the scalar preheader whose name
565 /// is prefixed with \p Prefix.
567
568 /// Allow subclasses to override and print debug traces before/after vplan
569 /// execution, when trace information is requested.
570 virtual void printDebugTracesAtStart() {}
571 virtual void printDebugTracesAtEnd() {}
572
573 /// The original loop.
575
576 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
577 /// dynamic knowledge to simplify SCEV expressions and converts them to a
578 /// more usable form.
580
581 /// Loop Info.
583
584 /// Dominator Tree.
586
587 /// Target Transform Info.
589
590 /// Assumption Cache.
592
593 /// The vectorization SIMD factor to use. Each vector will have this many
594 /// vector elements.
596
597 /// The vectorization unroll factor to use. Each scalar is vectorized to this
598 /// many different vector instructions.
599 unsigned UF;
600
601 /// The builder that we use
603
604 // --- Vectorization state ---
605
606 /// Structure to hold information about generated runtime checks, responsible
607 /// for cleaning the checks, if vectorization turns out unprofitable.
608 GeneratedRTChecks &RTChecks;
609
611
612 /// The vector preheader block of \p Plan, used as target for check blocks
613 /// introduced during skeleton creation.
615};
616
617/// Encapsulate information regarding vectorization of a loop and its epilogue.
618/// This information is meant to be updated and used across two stages of
619/// epilogue vectorization.
622 unsigned MainLoopUF = 0;
624 unsigned EpilogueUF = 0;
628
630 ElementCount EVF, unsigned EUF)
631 : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
632 assert(EUF == 1 &&
633 "A high UF for the epilogue loop is likely not beneficial.");
634 }
635};
636
637/// An extension of the inner loop vectorizer that creates a skeleton for a
638/// vectorized loop that has its epilogue (residual) also vectorized.
639/// The idea is to run the vplan on a given loop twice, firstly to setup the
640/// skeleton and vectorize the main loop, and secondly to complete the skeleton
641/// from the first step and vectorize the epilogue. This is achieved by
642/// deriving two concrete strategy classes from this base class and invoking
643/// them in succession from the loop vectorizer planner.
645public:
651 GeneratedRTChecks &Checks, VPlan &Plan,
652 ElementCount VecWidth, unsigned UnrollFactor)
653 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TTI, AC, VecWidth,
654 UnrollFactor, Checks, Plan),
655 EPI(EPI) {}
656
657 /// Holds and updates state information required to vectorize the main loop
658 /// and its epilogue in two separate passes. This setup helps us avoid
659 /// regenerating and recomputing runtime safety checks. It also helps us to
660 /// shorten the iteration-count-check path length for the cases where the
661 /// iteration count of the loop is so small that the main vector loop is
662 /// completely skipped.
664};
665
666/// A specialized derived class of inner loop vectorizer that performs
667/// vectorization of *main* loops in the process of vectorizing loops and their
668/// epilogues.
670public:
680
681protected:
682 void printDebugTracesAtStart() override;
683 void printDebugTracesAtEnd() override;
684};
685
686// A specialized derived class of inner loop vectorizer that performs
687// vectorization of *epilogue* loops in the process of vectorizing loops and
688// their epilogues.
690public:
700 /// Implements the interface for creating a vectorized skeleton using the
701 /// *epilogue loop* strategy (i.e., the second pass of VPlan execution).
703
704protected:
705 void printDebugTracesAtStart() override;
706 void printDebugTracesAtEnd() override;
707};
708} // end namespace llvm
709
710/// Look for a meaningful debug location on the instruction or its operands.
712 if (!I)
713 return DebugLoc::getUnknown();
714
716 if (I->getDebugLoc() != Empty)
717 return I->getDebugLoc();
718
719 for (Use &Op : I->operands()) {
720 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
721 if (OpInst->getDebugLoc() != Empty)
722 return OpInst->getDebugLoc();
723 }
724
725 return I->getDebugLoc();
726}
727
728namespace llvm {
729
730/// Return the runtime value for VF.
732 return B.CreateElementCount(Ty, VF);
733}
734
735} // end namespace llvm
736
737namespace llvm {
738
739// Loop vectorization cost-model hints how the epilogue/tail loop should be
740// lowered.
742
743 // The default: allowing epilogues.
745
746 // Vectorization with OptForSize: don't allow epilogues.
748
749 // A special case of vectorisation with OptForSize: loops with a very small
750 // trip count are considered for vectorization under OptForSize, thereby
751 // making sure the cost of their loop body is dominant, free of runtime
752 // guards and scalar iteration overheads.
754
755 // Loop hint indicating an epilogue is undesired, apply tail folding.
757
758 // Directive indicating we must either fold the epilogue/tail or not vectorize
760};
761
763
764/// LoopVectorizationCostModel - estimates the expected speedups due to
765/// vectorization.
766/// In many cases vectorization is not profitable. This can happen because of
767/// a number of reasons. In this class we mainly attempt to predict the
768/// expected speedup/slowdowns due to the supported instruction set. We use the
769/// TargetTransformInfo to query the different backends for the cost of
770/// different operations.
773
774public:
781 std::function<BlockFrequencyInfo &()> GetBFI,
782 const Function *F, InterleavedAccessInfo &IAI,
783 VFSelectionContext &Config)
784 : Config(Config), EpilogueLoweringStatus(SEL), TheLoop(L), PSE(PSE),
785 LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), AC(AC), ORE(ORE),
787
788 /// \return An upper bound for the vectorization factors (both fixed and
789 /// scalable). If the factors are 0, vectorization and interleaving should be
790 /// avoided up front.
791 FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
792
793 /// Memory access instruction may be vectorized in more than one way.
794 /// Form of instruction after vectorization depends on cost.
795 /// This function takes cost-based decisions for Load/Store instructions
796 /// and collects them in a map. This decisions map is used for building
797 /// the lists of loop-uniform and loop-scalar instructions.
798 /// The calculated cost is saved with widening decision in order to
799 /// avoid redundant calculations.
800 void setCostBasedWideningDecision(ElementCount VF);
801
802 /// Collect values we want to ignore in the cost model.
803 void collectValuesToIgnore();
804
805 /// \returns True if it is more profitable to scalarize instruction \p I for
806 /// vectorization factor \p VF.
808 assert(VF.isVector() &&
809 "Profitable to scalarize relevant only for VF > 1.");
810 assert(
811 TheLoop->isInnermost() &&
812 "cost-model should not be used for outer loops (in VPlan-native path)");
813
814 auto Scalars = InstsToScalarize.find(VF);
815 assert(Scalars != InstsToScalarize.end() &&
816 "VF not yet analyzed for scalarization profitability");
817 return Scalars->second.contains(I);
818 }
819
820 /// Returns true if \p I is known to be uniform after vectorization.
822 assert(
823 TheLoop->isInnermost() &&
824 "cost-model should not be used for outer loops (in VPlan-native path)");
825
826 // If VF is scalar, then all instructions are trivially uniform.
827 if (VF.isScalar())
828 return true;
829
830 // Pseudo probes must be duplicated per vector lane so that the
831 // profiled loop trip count is not undercounted.
833 return false;
834
835 auto UniformsPerVF = Uniforms.find(VF);
836 assert(UniformsPerVF != Uniforms.end() &&
837 "VF not yet analyzed for uniformity");
838 return UniformsPerVF->second.count(I);
839 }
840
841 /// Returns true if \p I is known to be scalar after vectorization.
843 assert(
844 TheLoop->isInnermost() &&
845 "cost-model should not be used for outer loops (in VPlan-native path)");
846 if (VF.isScalar())
847 return true;
848
849 auto ScalarsPerVF = Scalars.find(VF);
850 assert(ScalarsPerVF != Scalars.end() &&
851 "Scalar values are not calculated for VF");
852 return ScalarsPerVF->second.count(I);
853 }
854
855 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
856 /// for vectorization factor \p VF.
858 const auto &MinBWs = Config.getMinimalBitwidths();
859 // Truncs must truncate at most to their destination type.
860 if (isa_and_nonnull<TruncInst>(I) && MinBWs.contains(I) &&
861 I->getType()->getScalarSizeInBits() < MinBWs.lookup(I))
862 return false;
863 return VF.isVector() && MinBWs.contains(I) &&
866 }
867
868 /// Decision that was taken during cost calculation for memory instruction.
871 CM_Widen, // For consecutive accesses with stride +1.
872 CM_Widen_Reverse, // For consecutive accesses with stride -1.
876 /// A widening decision that has been invalidated after replacing the
877 /// corresponding recipe during VPlan transforms.
878 /// TODO: Remove once the legacy exit cost computation is retired.
880 };
881
882 /// Save vectorization decision \p W and \p Cost taken by the cost model for
883 /// instruction \p I and vector width \p VF.
886 assert(VF.isVector() && "Expected VF >=2");
887 WideningDecisions[{I, VF}] = {W, Cost};
888 }
889
890 /// Save vectorization decision \p W and \p Cost taken by the cost model for
891 /// interleaving group \p Grp and vector width \p VF.
895 assert(VF.isVector() && "Expected VF >=2");
896 /// Broadcast this decicion to all instructions inside the group.
897 /// When interleaving, the cost will only be assigned one instruction, the
898 /// insert position. For other cases, add the appropriate fraction of the
899 /// total cost to each instruction. This ensures accurate costs are used,
900 /// even if the insert position instruction is not used.
901 InstructionCost InsertPosCost = Cost;
902 InstructionCost OtherMemberCost = 0;
903 if (W != CM_Interleave)
904 OtherMemberCost = InsertPosCost = Cost / Grp->getNumMembers();
905 ;
906 for (auto *I : Grp->members()) {
907 if (Grp->getInsertPos() == I)
908 WideningDecisions[{I, VF}] = {W, InsertPosCost};
909 else
910 WideningDecisions[{I, VF}] = {W, OtherMemberCost};
911 }
912 }
913
914 /// Return the cost model decision for the given instruction \p I and vector
915 /// width \p VF. Return CM_Unknown if this instruction did not pass
916 /// through the cost modeling.
918 assert(VF.isVector() && "Expected VF to be a vector VF");
919 assert(
920 TheLoop->isInnermost() &&
921 "cost-model should not be used for outer loops (in VPlan-native path)");
922
923 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
924 auto Itr = WideningDecisions.find(InstOnVF);
925 if (Itr == WideningDecisions.end())
926 return CM_Unknown;
927 return Itr->second.first;
928 }
929
930 /// Return the vectorization cost for the given instruction \p I and vector
931 /// width \p VF.
933 assert(VF.isVector() && "Expected VF >=2");
934 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
935 assert(WideningDecisions.contains(InstOnVF) &&
936 "The cost is not calculated");
937 return WideningDecisions[InstOnVF].second;
938 }
939
940 /// Return True if instruction \p I is an optimizable truncate whose operand
941 /// is an induction variable. Such a truncate will be removed by adding a new
942 /// induction variable with the destination type.
944 // If the instruction is not a truncate, return false.
945 auto *Trunc = dyn_cast<TruncInst>(I);
946 if (!Trunc)
947 return false;
948
949 // Get the source and destination types of the truncate.
950 Type *SrcTy = toVectorTy(Trunc->getSrcTy(), VF);
951 Type *DestTy = toVectorTy(Trunc->getDestTy(), VF);
952
953 // If the truncate is free for the given types, return false. Replacing a
954 // free truncate with an induction variable would add an induction variable
955 // update instruction to each iteration of the loop. We exclude from this
956 // check the primary induction variable since it will need an update
957 // instruction regardless.
958 Value *Op = Trunc->getOperand(0);
959 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
960 return false;
961
962 // If the truncated value is not an induction variable, return false.
963 return Legal->isInductionPhi(Op);
964 }
965
966 /// Collects the instructions to scalarize for each predicated instruction in
967 /// the loop.
968 void collectInstsToScalarize(ElementCount VF);
969
970 /// Collect values that will not be widened, including Uniforms, Scalars, and
971 /// Instructions to Scalarize for the given \p VF.
972 /// The sets depend on CM decision for Load/Store instructions
973 /// that may be vectorized as interleave, gather-scatter or scalarized.
974 /// Also make a decision on what to do about call instructions in the loop
975 /// at that VF -- scalarize, call a known vector routine, or call a
976 /// vector intrinsic.
978 // Do the analysis once.
979 if (VF.isScalar() || Uniforms.contains(VF))
980 return;
982 collectLoopUniforms(VF);
983 collectLoopScalars(VF);
985 }
986
987 /// Given costs for both strategies, return true if the scalar predication
988 /// lowering should be used for div/rem. This incorporates an override
989 /// option so it is not simply a cost comparison.
991 InstructionCost MaskedCost) const {
992 switch (ForceMaskedDivRem) {
994 return ScalarCost < MaskedCost;
996 return false;
998 return true;
999 }
1000 llvm_unreachable("impossible case value");
1001 }
1002
1003 /// Returns true if \p I is an instruction which requires predication and
1004 /// for which our chosen predication strategy is scalarization (i.e. we
1005 /// don't have an alternate strategy such as masking available).
1006 /// \p VF is the vectorization factor that will be used to vectorize \p I.
1007 bool isScalarWithPredication(Instruction *I, ElementCount VF);
1008
1009 /// Wrapper function for LoopVectorizationLegality::isMaskRequired,
1010 /// that passes the Instruction \p I and if we fold tail.
1011 bool isMaskRequired(Instruction *I) const;
1012
1013 /// Returns true if \p I is an instruction that needs to be predicated
1014 /// at runtime. The result is independent of the predication mechanism.
1015 /// Superset of instructions that return true for isScalarWithPredication.
1016 bool isPredicatedInst(Instruction *I) const;
1017
1018 /// A helper function that returns how much we should divide the cost of a
1019 /// predicated block by. Typically this is the reciprocal of the block
1020 /// probability, i.e. if we return X we are assuming the predicated block will
1021 /// execute once for every X iterations of the loop header so the block should
1022 /// only contribute 1/X of its cost to the total cost calculation, but when
1023 /// optimizing for code size it will just be 1 as code size costs don't depend
1024 /// on execution probabilities.
1025 ///
1026 /// Note that if a block wasn't originally predicated but was predicated due
1027 /// to tail folding, the divisor will still be 1 because it will execute for
1028 /// every iteration of the loop header.
1029 inline uint64_t
1030 getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind,
1031 const BasicBlock *BB);
1032
1033 /// Returns true if an artificially high cost for emulated masked memrefs
1034 /// should be used.
1035 bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF) const;
1036
1037 /// Return the costs for our two available strategies for lowering a
1038 /// div/rem operation which requires speculating at least one lane.
1039 /// First result is for scalarization (will be invalid for scalable
1040 /// vectors); second is for the masked intrinsic strategy.
1041 std::pair<InstructionCost, InstructionCost>
1042 getDivRemSpeculationCost(Instruction *I, ElementCount VF);
1043
1044 /// If \p I is a memory instruction with a consecutive pointer that can be
1045 /// widened, returns the widening kind (CM_Widen or CM_Widen_Reverse) and
1046 /// std::nullopt otherwise.
1047 std::optional<InstWidening> memoryInstructionCanBeWidened(Instruction *I,
1048 ElementCount VF);
1049
1050 /// Returns true if \p I is a memory instruction in an interleaved-group
1051 /// of memory accesses that can be vectorized with wide vector loads/stores
1052 /// and shuffles.
1053 bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const;
1054
1055 /// Returns true if the target machine supports masked loads or stores
1056 /// for \p I's data type and alignment. The caller must ensure the access is
1057 /// consecutive or part of an interleave group.
1058 bool isLegalMaskedLoadOrStore(Instruction *I, ElementCount VF) const;
1059
1060 /// Returns true if the target machine supports gather or scatter for \p I's
1061 /// data type and alignment.
1062 bool isLegalGatherOrScatter(Instruction *I, ElementCount VF) const;
1063
1064 /// Check if \p Instr belongs to any interleaved access group.
1066 return InterleaveInfo.isInterleaved(Instr);
1067 }
1068
1069 /// Get the interleaved access group that \p Instr belongs to.
1072 return InterleaveInfo.getInterleaveGroup(Instr);
1073 }
1074
1075 /// Returns true if we're required to use a scalar epilogue for at least
1076 /// the final iteration of the original loop.
1077 bool requiresScalarEpilogue(bool IsVectorizing) const {
1078 if (!isEpilogueAllowed()) {
1079 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1080 return false;
1081 }
1082 // If we might exit from anywhere but the latch and early exit vectorization
1083 // is disabled, we must run the exiting iteration in scalar form.
1084 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
1085 !(EnableEarlyExitVectorization && Legal->hasUncountableEarlyExit())) {
1086 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: not exiting "
1087 "from latch block\n");
1088 return true;
1089 }
1090 if (IsVectorizing && InterleaveInfo.requiresScalarEpilogue()) {
1091 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: "
1092 "interleaved group requires scalar epilogue\n");
1093 return true;
1094 }
1095 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1096 return false;
1097 }
1098
1099 /// Returns true if an epilogue is allowed (e.g., not prevented by
1100 /// optsize or a loop hint annotation).
1101 bool isEpilogueAllowed() const {
1102 return EpilogueLoweringStatus == CM_EpilogueAllowed;
1103 }
1104
1105 /// Returns true if tail-folding is preferred over an epilogue.
1107 return EpilogueLoweringStatus == CM_EpilogueNotNeededFoldTail ||
1108 EpilogueLoweringStatus == CM_EpilogueNotAllowedFoldTail;
1109 }
1110
1111 /// Returns the TailFoldingStyle that is best for the current loop.
1113 return ChosenTailFoldingStyle;
1114 }
1115
1116 /// Selects and saves TailFoldingStyle.
1117 /// \param IsScalableVF true if scalable vector factors enabled.
1118 /// \param UserIC User specific interleave count.
1119 void setTailFoldingStyle(bool IsScalableVF, unsigned UserIC) {
1120 assert(ChosenTailFoldingStyle == TailFoldingStyle::None &&
1121 "Tail folding must not be selected yet.");
1122 if (!Legal->canFoldTailByMasking()) {
1123 ChosenTailFoldingStyle = TailFoldingStyle::None;
1124 return;
1125 }
1126
1127 // Default to TTI preference, but allow command line override.
1128 ChosenTailFoldingStyle = TTI.getPreferredTailFoldingStyle();
1129 if (ForceTailFoldingStyle.getNumOccurrences())
1130 ChosenTailFoldingStyle = ForceTailFoldingStyle.getValue();
1131
1132 if (ChosenTailFoldingStyle != TailFoldingStyle::DataWithEVL)
1133 return;
1134 // Override EVL styles if needed.
1135 // FIXME: Investigate opportunity for fixed vector factor.
1136 bool EVLIsLegal = UserIC <= 1 && IsScalableVF &&
1137 TTI.hasActiveVectorLength() && !EnableVPlanNativePath;
1138 if (EVLIsLegal)
1139 return;
1140 // If for some reason EVL mode is unsupported, fallback to an epilogue
1141 // if it's allowed, or DataWithoutLaneMask otherwise.
1142 if (EpilogueLoweringStatus == CM_EpilogueAllowed ||
1143 EpilogueLoweringStatus == CM_EpilogueNotNeededFoldTail)
1144 ChosenTailFoldingStyle = TailFoldingStyle::None;
1145 else
1146 ChosenTailFoldingStyle = TailFoldingStyle::DataWithoutLaneMask;
1147
1148 LLVM_DEBUG(
1149 dbgs() << "LV: Preference for VP intrinsics indicated. Will "
1150 "not try to generate VP Intrinsics "
1151 << (UserIC > 1
1152 ? "since interleave count specified is greater than 1.\n"
1153 : "due to non-interleaving reasons.\n"));
1154 }
1155
1156 /// Returns true if all loop blocks should be masked to fold tail loop.
1157 bool foldTailByMasking() const {
1159 }
1160
1162 assert(foldTailByMasking() && "Expected tail folding to be enabled!");
1164 "Did not expect to enable alias masking with EVL!");
1165 assert(PartialAliasMaskingStatus == AliasMaskingStatus::NotDecided);
1166
1167 // Assume we fail to enable alias masking (in case we early exit).
1168 PartialAliasMaskingStatus = AliasMaskingStatus::Disabled;
1169
1170 // Note: FixedOrderRecurrences are not supported yet as we cannot handle
1171 // the required `splice.right` with the alias-mask.
1173 !Legal->getFixedOrderRecurrences().empty())
1174 return;
1175
1176 const RuntimePointerChecking *Checks = Legal->getRuntimePointerChecking();
1177 if (!Checks)
1178 return;
1179
1180 auto DiffChecks = Checks->getDiffChecks();
1181 if (!DiffChecks || DiffChecks->empty())
1182 return;
1183
1184 [[maybe_unused]] auto HasPointerArgs = [](CallBase *CB) {
1185 return any_of(CB->args(), [](Value const *Arg) {
1186 return Arg->getType()->isPointerTy();
1187 });
1188 };
1189
1190 for (BasicBlock *BB : TheLoop->blocks()) {
1191 for (Instruction &I : *BB) {
1193 [[maybe_unused]] auto *Call = dyn_cast<CallInst>(&I);
1194 assert(
1195 (!I.mayReadOrWriteMemory() || (Call && !HasPointerArgs(Call))) &&
1196 "Skipped unexpected memory access");
1197 continue;
1198 }
1199
1200 Type *ScalarTy = getLoadStoreType(&I);
1202
1203 // Currently, we can't handle alias masking in reverse. Reversing the
1204 // alias mask is not correct (or necessary). When combined with
1205 // tail-folding the active lane mask should only be reversed where the
1206 // alias-mask is true.
1207 if (Legal->isConsecutivePtr(ScalarTy, Ptr) == -1)
1208 return;
1209 }
1210 }
1211
1212 PartialAliasMaskingStatus = AliasMaskingStatus::Enabled;
1213 }
1214
1215 /// Returns true if all loop blocks should have partial aliases masked.
1216 bool maskPartialAliasing() const {
1217 return PartialAliasMaskingStatus == AliasMaskingStatus::Enabled;
1218 }
1219
1220 /// Returns true if the instructions in this block requires predication
1221 /// for any reason, e.g. because tail folding now requires a predicate
1222 /// or because the block in the original loop was predicated.
1224 return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1225 }
1226
1227 /// Returns true if VP intrinsics with explicit vector length support should
1228 /// be generated in the tail folded loop.
1232
1233 /// Returns true if the predicated reduction select should be used to set the
1234 /// incoming value for the reduction phi.
1235 bool usePredicatedReductionSelect(RecurKind RecurrenceKind) const {
1236 // Force to use predicated reduction select since the EVL of the
1237 // second-to-last iteration might not be VF*UF.
1238 if (foldTailWithEVL())
1239 return true;
1240
1241 // Force a predicated select with alias-masking to avoid propagating poison
1242 // values to the header phi for lanes outside the alias-mask.
1243 if (maskPartialAliasing())
1244 return true;
1245
1246 // Note: For FindLast recurrences we prefer a predicated select to simplify
1247 // matching in handleFindLastReductions(), rather than handle multiple
1248 // cases.
1250 return true;
1251
1253 TTI.preferPredicatedReductionSelect();
1254 }
1255
1256 /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1257 /// with factor VF. Return the cost of the instruction, including
1258 /// scalarization overhead if it's needed.
1259 InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1260
1261 /// Estimate cost of a call instruction CI if it were vectorized with factor
1262 /// VF. Return the cost of the instruction, including scalarization overhead
1263 /// if it's needed.
1264 InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const;
1265
1266 /// Invalidates decisions already taken by the cost model.
1268 WideningDecisions.clear();
1269 Uniforms.clear();
1270 Scalars.clear();
1271 }
1272
1273 /// Returns the expected execution cost. The unit of the cost does
1274 /// not matter because we use the 'cost' units to compare different
1275 /// vector widths. The cost that is returned is *not* normalized by
1276 /// the factor width.
1277 InstructionCost expectedCost(ElementCount VF);
1278
1279 /// Returns the execution time cost of an instruction for a given vector
1280 /// width. Vector width of one means scalar.
1281 InstructionCost getInstructionCost(Instruction *I, ElementCount VF);
1282
1283 /// Returns true if \p Op should be considered invariant and if it is
1284 /// trivially hoistable.
1285 bool shouldConsiderInvariant(Value *Op);
1286
1287 /// Returns true if \p I has been forced to be scalarized at \p VF.
1289 auto FS = ForcedScalars.find(VF);
1290 return FS != ForcedScalars.end() && FS->second.contains(I);
1291 }
1292
1293private:
1294 unsigned NumPredStores = 0;
1295
1296 /// VF selection state independent of cost-modeling decisions.
1297 VFSelectionContext &Config;
1298
1299 /// Wrapper around LoopVectorizationLegality::isUniform() that takes into
1300 /// account if alias-masking is enabled. We consider the VF to be unknown when
1301 /// alias masking.
1302 bool isUniform(Value *V, ElementCount VF) const {
1303 // With alias-masking our runtime VF is [2, VF] (and not necessarily a
1304 // power-of-two). Something that is uniform for VF may not be for the full
1305 // range.
1306 assert(PartialAliasMaskingStatus != AliasMaskingStatus::NotDecided &&
1307 "alias-mask status must be decided already");
1308 return Legal->isUniform(V, PartialAliasMaskingStatus ==
1310 ? std::optional(VF)
1311 : std::nullopt);
1312 }
1313
1314 /// Wrapper around LoopVectorizationLegality::isUniformMemOp() that takes into
1315 /// account if alias-masking is enabled. We consider the VF to be unknown when
1316 /// alias masking.
1317 bool isUniformMemOp(Instruction &I, ElementCount VF) const {
1318 assert(PartialAliasMaskingStatus != AliasMaskingStatus::NotDecided &&
1319 "alias-mask status must be decided already");
1320 return Legal->isUniformMemOp(I, PartialAliasMaskingStatus ==
1322 ? std::optional(VF)
1323 : std::nullopt);
1324 }
1325
1326 /// Calculate vectorization cost of memory instruction \p I.
1327 InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1328
1329 /// The cost computation for scalarized memory instruction.
1330 InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1331
1332 /// The cost computation for interleaving group of memory instructions.
1333 InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF) const;
1334
1335 /// The cost computation for Gather/Scatter instruction.
1336 InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF) const;
1337
1338 /// The cost computation for widening instruction \p I with consecutive
1339 /// memory access.
1340 InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF,
1341 InstWidening Kind);
1342
1343 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1344 /// Load: scalar load + broadcast.
1345 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1346 /// element)
1347 InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF) const;
1348
1349 /// Estimate the overhead of scalarizing an instruction. This is a
1350 /// convenience wrapper for the type-based getScalarizationOverhead API.
1352 ElementCount VF) const;
1353
1354 /// A type representing the costs for instructions if they were to be
1355 /// scalarized rather than vectorized. The entries are Instruction-Cost
1356 /// pairs.
1357 using ScalarCostsTy = MapVector<Instruction *, InstructionCost>;
1358
1359 /// A set containing all BasicBlocks that are known to present after
1360 /// vectorization as a predicated block.
1361 DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
1362 PredicatedBBsAfterVectorization;
1363
1364 /// Records whether it is allowed to have the original scalar loop execute at
1365 /// least once. This may be needed as a fallback loop in case runtime
1366 /// aliasing/dependence checks fail, or to handle the tail/remainder
1367 /// iterations when the trip count is unknown or doesn't divide by the VF,
1368 /// or as a peel-loop to handle gaps in interleave-groups.
1369 /// Under optsize and when the trip count is very small we don't allow any
1370 /// iterations to execute in the scalar loop.
1371 EpilogueLowering EpilogueLoweringStatus = CM_EpilogueAllowed;
1372
1373 /// Control finally chosen tail folding style.
1374 TailFoldingStyle ChosenTailFoldingStyle = TailFoldingStyle::None;
1375
1376 /// If partial alias masking is enabled/disabled or not decided.
1377 AliasMaskingStatus PartialAliasMaskingStatus = AliasMaskingStatus::NotDecided;
1378
1379 /// A map holding scalar costs for different vectorization factors. The
1380 /// presence of a cost for an instruction in the mapping indicates that the
1381 /// instruction will be scalarized when vectorizing with the associated
1382 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1383 MapVector<ElementCount, ScalarCostsTy> InstsToScalarize;
1384
1385 /// Holds the instructions known to be uniform after vectorization.
1386 /// The data is collected per VF.
1387 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1388
1389 /// Holds the instructions known to be scalar after vectorization.
1390 /// The data is collected per VF.
1391 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1392
1393 /// Holds the instructions (address computations) that are forced to be
1394 /// scalarized.
1395 DenseMap<ElementCount, SmallSetVector<Instruction *, 4>> ForcedScalars;
1396
1397 /// Returns the expected difference in cost from scalarizing the expression
1398 /// feeding a predicated instruction \p PredInst. The instructions to
1399 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1400 /// non-negative return value implies the expression will be scalarized.
1401 /// Currently, only single-use chains are considered for scalarization.
1402 InstructionCost computePredInstDiscount(Instruction *PredInst,
1403 ScalarCostsTy &ScalarCosts,
1404 ElementCount VF);
1405
1406 /// Collect the instructions that are uniform after vectorization. An
1407 /// instruction is uniform if we represent it with a single scalar value in
1408 /// the vectorized loop corresponding to each vector iteration. Examples of
1409 /// uniform instructions include pointer operands of consecutive or
1410 /// interleaved memory accesses. Note that although uniformity implies an
1411 /// instruction will be scalar, the reverse is not true. In general, a
1412 /// scalarized instruction will be represented by VF scalar values in the
1413 /// vectorized loop, each corresponding to an iteration of the original
1414 /// scalar loop.
1415 void collectLoopUniforms(ElementCount VF);
1416
1417 /// Collect the instructions that are scalar after vectorization. An
1418 /// instruction is scalar if it is known to be uniform or will be scalarized
1419 /// during vectorization. collectLoopScalars should only add non-uniform nodes
1420 /// to the list if they are used by a load/store instruction that is marked as
1421 /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1422 /// VF values in the vectorized loop, each corresponding to an iteration of
1423 /// the original scalar loop.
1424 void collectLoopScalars(ElementCount VF);
1425
1426 /// Keeps cost model vectorization decision and cost for instructions.
1427 /// Right now it is used for memory instructions only.
1428 using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1429 std::pair<InstWidening, InstructionCost>>;
1430
1431 DecisionList WideningDecisions;
1432
1433 /// Returns true if \p V is expected to be vectorized and it needs to be
1434 /// extracted.
1435 bool needsExtract(Value *V, ElementCount VF) const {
1437 if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1438 TheLoop->isLoopInvariant(I) ||
1439 getWideningDecision(I, VF) == CM_Scalarize)
1440 return false;
1441
1442 // Assume we can vectorize V (and hence we need extraction) if the
1443 // scalars are not computed yet. This can happen, because it is called
1444 // via getScalarizationOverhead from setCostBasedWideningDecision, before
1445 // the scalars are collected. That should be a safe assumption in most
1446 // cases, because we check if the operands have vectorizable types
1447 // beforehand in LoopVectorizationLegality.
1448 return !Scalars.contains(VF) || !isScalarAfterVectorization(I, VF);
1449 };
1450
1451 /// Returns a range containing only operands needing to be extracted.
1452 SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1453 ElementCount VF) const {
1454
1455 SmallPtrSet<const Value *, 4> UniqueOperands;
1456 SmallVector<Value *, 4> Res;
1457 for (Value *Op : Ops) {
1458 if (isa<Constant>(Op) || !UniqueOperands.insert(Op).second ||
1459 !needsExtract(Op, VF))
1460 continue;
1461 Res.push_back(Op);
1462 }
1463 return Res;
1464 }
1465
1466public:
1467 /// The loop that we evaluate.
1469
1470 /// Predicated scalar evolution analysis.
1472
1473 /// Loop Info analysis.
1475
1476 /// Vectorization legality.
1478
1479 /// Vector target information.
1481
1482 /// Target Library Info.
1484
1485 /// Assumption cache.
1487
1488 /// Interface to emit optimization remarks.
1490
1491 /// A function to lazily fetch BlockFrequencyInfo. This avoids computing it
1492 /// unless necessary, e.g. when the loop isn't legal to vectorize or when
1493 /// there is no predication.
1494 std::function<BlockFrequencyInfo &()> GetBFI;
1495 /// The BlockFrequencyInfo returned from GetBFI.
1497 /// Returns the BlockFrequencyInfo for the function if cached, otherwise
1498 /// fetches it via GetBFI. Avoids an indirect call to the std::function.
1500 if (!BFI)
1501 BFI = &GetBFI();
1502 return *BFI;
1503 }
1504
1506
1507 /// The interleave access information contains groups of interleaved accesses
1508 /// with the same stride and close to each other.
1510
1511 /// Values to ignore in the cost model.
1513
1514 /// Values to ignore in the cost model when VF > 1.
1516};
1517} // end namespace llvm
1518
1519namespace {
1520/// Helper struct to manage generating runtime checks for vectorization.
1521///
1522/// The runtime checks are created up-front in temporary blocks to allow better
1523/// estimating the cost and un-linked from the existing IR. After deciding to
1524/// vectorize, the checks are moved back. If deciding not to vectorize, the
1525/// temporary blocks are completely removed.
1526class GeneratedRTChecks {
1527 /// Basic block which contains the generated SCEV checks, if any.
1528 BasicBlock *SCEVCheckBlock = nullptr;
1529
1530 /// The value representing the result of the generated SCEV checks. If it is
1531 /// nullptr no SCEV checks have been generated.
1532 Value *SCEVCheckCond = nullptr;
1533
1534 /// Basic block which contains the generated memory runtime checks, if any.
1535 BasicBlock *MemCheckBlock = nullptr;
1536
1537 /// The value representing the result of the generated memory runtime checks.
1538 /// If it is nullptr no memory runtime checks have been generated.
1539 Value *MemRuntimeCheckCond = nullptr;
1540
1541 DominatorTree *DT;
1542 LoopInfo *LI;
1544
1545 SCEVExpander SCEVExp;
1546 SCEVExpander MemCheckExp;
1547
1548 bool CostTooHigh = false;
1549
1550 Loop *OuterLoop = nullptr;
1551
1553
1554 /// The kind of cost that we are calculating
1556
1557 /// True if the loop is alias-masked (which allows us to omit diff checks).
1558 bool LoopUsesPartialAliasMasking = false;
1559
1560public:
1561 GeneratedRTChecks(PredicatedScalarEvolution &PSE, DominatorTree *DT,
1564 bool LoopUsesPartialAliasMasking)
1565 : DT(DT), LI(LI), TTI(TTI),
1566 SCEVExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1567 MemCheckExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1568 PSE(PSE), CostKind(CostKind),
1569 LoopUsesPartialAliasMasking(LoopUsesPartialAliasMasking) {}
1570
1571 /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1572 /// accurately estimate the cost of the runtime checks. The blocks are
1573 /// un-linked from the IR and are added back during vector code generation. If
1574 /// there is no vector code generation, the check blocks are removed
1575 /// completely.
1576 void create(Loop *L, const LoopAccessInfo &LAI,
1577 const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC,
1578 OptimizationRemarkEmitter &ORE) {
1579
1580 // Hard cutoff to limit compile-time increase in case a very large number of
1581 // runtime checks needs to be generated.
1582 // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1583 // profile info.
1584 CostTooHigh =
1586 if (CostTooHigh) {
1587 // Mark runtime checks as never succeeding when they exceed the threshold.
1588 MemRuntimeCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1589 SCEVCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1590 ORE.emit([&]() {
1591 return OptimizationRemarkAnalysisAliasing(
1592 DEBUG_TYPE, "TooManyMemoryRuntimeChecks", L->getStartLoc(),
1593 L->getHeader())
1594 << "loop not vectorized: too many memory checks needed";
1595 });
1596 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1597 return;
1598 }
1599
1600 BasicBlock *LoopHeader = L->getHeader();
1601 BasicBlock *Preheader = L->getLoopPreheader();
1602
1603 // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1604 // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1605 // may be used by SCEVExpander. The blocks will be un-linked from their
1606 // predecessors and removed from LI & DT at the end of the function.
1607 if (!UnionPred.isAlwaysTrue()) {
1608 SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1609 nullptr, "vector.scevcheck");
1610
1611 SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1612 &UnionPred, SCEVCheckBlock->getTerminator());
1613 if (isa<Constant>(SCEVCheckCond)) {
1614 // Clean up directly after expanding the predicate to a constant, to
1615 // avoid further expansions re-using anything left over from SCEVExp.
1616 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1617 SCEVCleaner.cleanup();
1618 }
1619 }
1620
1621 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1622 // TODO: We need to estimate the cost of alias-masking in
1623 // GeneratedRTChecks::getCost(). We can't check the MemCheckBlock as the
1624 // alias-mask is generated later in VPlan.
1625 if (RtPtrChecking.Need && !LoopUsesPartialAliasMasking) {
1626 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1627 MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1628 "vector.memcheck");
1629
1630 auto DiffChecks = RtPtrChecking.getDiffChecks();
1631 if (DiffChecks) {
1632 MemRuntimeCheckCond = addDiffRuntimeChecks(
1633 MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp, VF, IC);
1634 } else {
1635 MemRuntimeCheckCond = addRuntimeChecks(
1636 MemCheckBlock->getTerminator(), L, RtPtrChecking.getChecks(),
1638 }
1639 assert(MemRuntimeCheckCond &&
1640 "no RT checks generated although RtPtrChecking "
1641 "claimed checks are required");
1642 }
1643
1644 SCEVExp.eraseDeadInstructions(SCEVCheckCond);
1645
1646 if (!MemCheckBlock && !SCEVCheckBlock)
1647 return;
1648
1649 // Unhook the temporary block with the checks, update various places
1650 // accordingly.
1651 if (SCEVCheckBlock)
1652 SCEVCheckBlock->replaceAllUsesWith(Preheader);
1653 if (MemCheckBlock)
1654 MemCheckBlock->replaceAllUsesWith(Preheader);
1655
1656 if (SCEVCheckBlock) {
1657 SCEVCheckBlock->getTerminator()->moveBefore(
1658 Preheader->getTerminator()->getIterator());
1659 auto *UI = new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1660 UI->setDebugLoc(DebugLoc::getTemporary());
1661 Preheader->getTerminator()->eraseFromParent();
1662 }
1663 if (MemCheckBlock) {
1664 MemCheckBlock->getTerminator()->moveBefore(
1665 Preheader->getTerminator()->getIterator());
1666 auto *UI = new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1667 UI->setDebugLoc(DebugLoc::getTemporary());
1668 Preheader->getTerminator()->eraseFromParent();
1669 }
1670
1671 DT->changeImmediateDominator(LoopHeader, Preheader);
1672 if (MemCheckBlock) {
1673 DT->eraseNode(MemCheckBlock);
1674 LI->removeBlock(MemCheckBlock);
1675 }
1676 if (SCEVCheckBlock) {
1677 DT->eraseNode(SCEVCheckBlock);
1678 LI->removeBlock(SCEVCheckBlock);
1679 }
1680
1681 // Outer loop is used as part of the later cost calculations.
1682 OuterLoop = L->getParentLoop();
1683 }
1684
1686 if (SCEVCheckBlock || MemCheckBlock)
1687 LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1688
1689 if (CostTooHigh) {
1691 Cost.setInvalid();
1692 LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
1693 return Cost;
1694 }
1695
1696 InstructionCost RTCheckCost = 0;
1697 if (SCEVCheckBlock)
1698 for (Instruction &I : *SCEVCheckBlock) {
1699 if (SCEVCheckBlock->getTerminator() == &I)
1700 continue;
1702 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1703 RTCheckCost += C;
1704 }
1705 if (MemCheckBlock) {
1706 InstructionCost MemCheckCost = 0;
1707 for (Instruction &I : *MemCheckBlock) {
1708 if (MemCheckBlock->getTerminator() == &I)
1709 continue;
1711 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1712 MemCheckCost += C;
1713 }
1714
1715 // If the runtime memory checks are being created inside an outer loop
1716 // we should find out if these checks are outer loop invariant. If so,
1717 // the checks will likely be hoisted out and so the effective cost will
1718 // reduce according to the outer loop trip count.
1719 if (OuterLoop) {
1720 ScalarEvolution *SE = MemCheckExp.getSE();
1721 // TODO: If profitable, we could refine this further by analysing every
1722 // individual memory check, since there could be a mixture of loop
1723 // variant and invariant checks that mean the final condition is
1724 // variant.
1725 const SCEV *Cond = SE->getSCEV(MemRuntimeCheckCond);
1726 if (SE->isLoopInvariant(Cond, OuterLoop)) {
1727 // It seems reasonable to assume that we can reduce the effective
1728 // cost of the checks even when we know nothing about the trip
1729 // count. Assume that the outer loop executes at least twice.
1730 unsigned BestTripCount = 2;
1731
1732 // Get the best known TC estimate.
1733 if (auto EstimatedTC = getSmallBestKnownTC(
1734 PSE, OuterLoop, /* CanUseConstantMax = */ false))
1735 if (EstimatedTC->isFixed())
1736 BestTripCount = EstimatedTC->getFixedValue();
1737
1738 InstructionCost NewMemCheckCost = MemCheckCost / BestTripCount;
1739
1740 // Let's ensure the cost is always at least 1.
1741 NewMemCheckCost = std::max(NewMemCheckCost.getValue(),
1742 (InstructionCost::CostType)1);
1743
1744 if (BestTripCount > 1)
1746 << "We expect runtime memory checks to be hoisted "
1747 << "out of the outer loop. Cost reduced from "
1748 << MemCheckCost << " to " << NewMemCheckCost << '\n');
1749
1750 MemCheckCost = NewMemCheckCost;
1751 }
1752 }
1753
1754 RTCheckCost += MemCheckCost;
1755 }
1756
1757 if (SCEVCheckBlock || MemCheckBlock)
1758 LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
1759 << "\n");
1760
1761 return RTCheckCost;
1762 }
1763
1764 /// Remove the created SCEV & memory runtime check blocks & instructions, if
1765 /// unused.
1766 ~GeneratedRTChecks() {
1767 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1768 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
1769 bool SCEVChecksUsed = !SCEVCheckBlock || !pred_empty(SCEVCheckBlock);
1770 bool MemChecksUsed = !MemCheckBlock || !pred_empty(MemCheckBlock);
1771 if (SCEVChecksUsed)
1772 SCEVCleaner.markResultUsed();
1773
1774 if (MemChecksUsed) {
1775 MemCheckCleaner.markResultUsed();
1776 } else {
1777 auto &SE = *MemCheckExp.getSE();
1778 // Memory runtime check generation creates compares that use expanded
1779 // values. Remove them before running the SCEVExpanderCleaners.
1780 for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
1781 if (MemCheckExp.isInsertedInstruction(&I))
1782 continue;
1783 SE.forgetValue(&I);
1784 I.eraseFromParent();
1785 }
1786 }
1787 MemCheckCleaner.cleanup();
1788 SCEVCleaner.cleanup();
1789
1790 if (!SCEVChecksUsed)
1791 SCEVCheckBlock->eraseFromParent();
1792 if (!MemChecksUsed)
1793 MemCheckBlock->eraseFromParent();
1794 }
1795
1796 /// Retrieves the SCEVCheckCond and SCEVCheckBlock that were generated as IR
1797 /// outside VPlan.
1798 std::pair<Value *, BasicBlock *> getSCEVChecks() const {
1799 using namespace llvm::PatternMatch;
1800 if (!SCEVCheckCond || match(SCEVCheckCond, m_ZeroInt()))
1801 return {nullptr, nullptr};
1802
1803 return {SCEVCheckCond, SCEVCheckBlock};
1804 }
1805
1806 /// Retrieves the MemCheckCond and MemCheckBlock that were generated as IR
1807 /// outside VPlan.
1808 std::pair<Value *, BasicBlock *> getMemRuntimeChecks() const {
1809 using namespace llvm::PatternMatch;
1810 if (MemRuntimeCheckCond && match(MemRuntimeCheckCond, m_ZeroInt()))
1811 return {nullptr, nullptr};
1812 return {MemRuntimeCheckCond, MemCheckBlock};
1813 }
1814
1815 /// Return true if any runtime checks have been added
1816 bool hasChecks() const {
1817 return getSCEVChecks().first || getMemRuntimeChecks().first;
1818 }
1819};
1820} // namespace
1821
1823 return Style == TailFoldingStyle::Data ||
1825}
1826
1830
1831// Return true if \p OuterLp is an outer loop annotated with hints for explicit
1832// vectorization. The loop needs to be annotated with #pragma omp simd
1833// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
1834// vector length information is not provided, vectorization is not considered
1835// explicit. Interleave hints are not allowed either. These limitations will be
1836// relaxed in the future.
1837// Please, note that we are currently forced to abuse the pragma 'clang
1838// vectorize' semantics. This pragma provides *auto-vectorization hints*
1839// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
1840// provides *explicit vectorization hints* (LV can bypass legal checks and
1841// assume that vectorization is legal). However, both hints are implemented
1842// using the same metadata (llvm.loop.vectorize, processed by
1843// LoopVectorizeHints). This will be fixed in the future when the native IR
1844// representation for pragma 'omp simd' is introduced.
1845static bool isExplicitVecOuterLoop(Loop *OuterLp,
1847 assert(!OuterLp->isInnermost() && "This is not an outer loop");
1848 LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
1849
1850 // Only outer loops with an explicit vectorization hint are supported.
1851 // Unannotated outer loops are ignored.
1853 return false;
1854
1855 Function *Fn = OuterLp->getHeader()->getParent();
1856 if (!Hints.allowVectorization(Fn, OuterLp,
1857 true /*VectorizeOnlyWhenForced*/)) {
1858 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
1859 return false;
1860 }
1861
1862 if (Hints.getInterleave() > 1) {
1863 // TODO: Interleave support is future work.
1864 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
1865 "outer loops.\n");
1866 Hints.emitRemarkWithHints();
1867 return false;
1868 }
1869
1870 return true;
1871}
1872
1876 // Collect inner loops and outer loops without irreducible control flow. For
1877 // now, only collect outer loops that have explicit vectorization hints. If we
1878 // are stress testing the VPlan H-CFG construction, we collect the outermost
1879 // loop of every loop nest.
1880 if (L.isInnermost() || VPlanBuildOuterloopStressTest ||
1882 LoopBlocksRPO RPOT(&L);
1883 RPOT.perform(LI);
1885 V.push_back(&L);
1886 // TODO: Collect inner loops inside marked outer loops in case
1887 // vectorization fails for the outer loop. Do not invoke
1888 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
1889 // already known to be reducible. We can use an inherited attribute for
1890 // that.
1891 return;
1892 }
1893 }
1894 for (Loop *InnerL : L)
1895 collectSupportedLoops(*InnerL, LI, ORE, V);
1896}
1897
1898//===----------------------------------------------------------------------===//
1899// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1900// LoopVectorizationCostModel and LoopVectorizationPlanner.
1901//===----------------------------------------------------------------------===//
1902
1903/// For the given VF and UF and maximum trip count computed for the loop, return
1904/// whether the induction variable might overflow in the vectorized loop. If not,
1905/// then we know a runtime overflow check always evaluates to false and can be
1906/// removed.
1908 const LoopVectorizationCostModel *Cost,
1909 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
1910 // Always be conservative if we don't know the exact unroll factor.
1911 uint64_t MaxUF = UF ? *UF
1912 : std::max(Cost->TTI.getMaxInterleaveFactor(VF, false),
1913 Cost->TTI.getMaxInterleaveFactor(VF, true));
1914
1915 IntegerType *IdxTy = Cost->Legal->getWidestInductionType();
1916 APInt MaxUIntTripCount = IdxTy->getMask();
1917
1918 // We know the runtime overflow check is known false iff the (max) trip-count
1919 // is known and (max) trip-count + (VF * UF) does not overflow in the type of
1920 // the vector loop induction variable.
1921 if (std::optional<ElementCount> TC = getSmallBestKnownTC(
1922 Cost->PSE, Cost->TheLoop,
1923 /*CanUseConstantMax=*/true, /*CanExcludeZeroTrips=*/false,
1924 /*ComputeUpperBoundOnly=*/true)) {
1925 // Compute the maximum runtime values of VF and the trip count.
1926 std::optional<uint64_t> MaxStep =
1927 getMaxRuntimeElementCount(VF * MaxUF, *Cost->TheFunction);
1928 std::optional<uint64_t> MaxTC =
1929 getMaxRuntimeElementCount(*TC, *Cost->TheFunction);
1930 if (!MaxStep || !MaxTC)
1931 return false;
1932
1933 // Bail out if the maximum trip count is not representable in the induction
1934 // variable's type.
1935 if (MaxUIntTripCount.ult(*MaxTC))
1936 return false;
1937
1938 return (MaxUIntTripCount - *MaxTC).ugt(*MaxStep);
1939 }
1940
1941 return false;
1942}
1943
1944// Return whether we allow using masked interleave-groups (for dealing with
1945// strided loads/stores that reside in predicated blocks, or for dealing
1946// with gaps).
1948 // If an override option has been passed in for interleaved accesses, use it.
1949 if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
1951
1952 return TTI.enableMaskedInterleavedAccessVectorization();
1953}
1954
1955/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
1956/// VPBB are moved to the end of the newly created VPIRBasicBlock. All
1957/// predecessors and successors of VPBB, if any, are rewired to the new
1958/// VPIRBasicBlock. If \p VPBB may be unreachable, \p Plan must be passed.
1960 BasicBlock *IRBB,
1961 VPlan *Plan = nullptr) {
1962 if (!Plan)
1963 Plan = VPBB->getPlan();
1964 VPIRBasicBlock *IRVPBB = Plan->createVPIRBasicBlock(IRBB);
1965 auto IP = IRVPBB->begin();
1966 for (auto &R : make_early_inc_range(VPBB->phis()))
1967 R.moveBefore(*IRVPBB, IP);
1968
1969 for (auto &R :
1971 R.moveBefore(*IRVPBB, IRVPBB->end());
1972
1973 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB);
1974 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
1975 return IRVPBB;
1976}
1977
1979 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
1980 assert(VectorPH && "Invalid loop structure");
1981
1982 // NOTE: The Plan's scalar preheader VPBB isn't replaced with a VPIRBasicBlock
1983 // wrapping the newly created scalar preheader here at the moment, because the
1984 // Plan's scalar preheader may be unreachable at this point. Instead it is
1985 // replaced in executePlan.
1986 return SplitBlock(VectorPH, VectorPH->getTerminator(), DT, LI, nullptr,
1987 Twine(Prefix) + "scalar.ph");
1988}
1989
1990/// Knowing that loop \p L executes a single vector iteration, add instructions
1991/// that will get simplified and thus should not have any cost to \p
1992/// InstsToIgnore.
1995 SmallPtrSetImpl<Instruction *> &InstsToIgnore) {
1996 auto *Cmp = L->getLatchCmpInst();
1997 if (Cmp)
1998 InstsToIgnore.insert(Cmp);
1999 for (const auto &KV : IL) {
2000 // Extract the key by hand so that it can be used in the lambda below. Note
2001 // that captured structured bindings are a C++20 extension.
2002 PHINode *IV = KV.first;
2003
2004 // The induction is free: a widened induction generates a vector phi with
2005 // its start value and an increment that is dead without a backedge.
2006 InstsToIgnore.insert(IV);
2007
2008 // Get next iteration value of the induction variable.
2009 Instruction *IVInst =
2010 cast<Instruction>(IV->getIncomingValueForBlock(L->getLoopLatch()));
2011 if (all_of(IVInst->users(),
2012 [&](const User *U) { return U == IV || U == Cmp; }))
2013 InstsToIgnore.insert(IVInst);
2014 }
2015}
2016
2018 // Create a new IR basic block for the scalar preheader.
2019 BasicBlock *ScalarPH = createScalarPreheader("");
2020 return ScalarPH->getSinglePredecessor();
2021}
2022
2023namespace {
2024
2025struct CSEDenseMapInfo {
2026 static bool canHandle(const Instruction *I) {
2029 }
2030
2031 static unsigned getHashValue(const Instruction *I) {
2032 assert(canHandle(I) && "Unknown instruction!");
2033 return hash_combine(I->getOpcode(),
2034 hash_combine_range(I->operand_values()));
2035 }
2036
2037 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
2038 return LHS->isIdenticalTo(RHS);
2039 }
2040};
2041
2042} // end anonymous namespace
2043
2044/// FIXME: This legacy common-subexpression-elimination routine is scheduled for
2045/// removal, in favor of the VPlan-based one.
2046static void legacyCSE(BasicBlock *BB) {
2047 // Perform simple cse.
2049 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
2050 if (!CSEDenseMapInfo::canHandle(&In))
2051 continue;
2052
2053 // Check if we can replace this instruction with any of the
2054 // visited instructions.
2055 if (Instruction *V = CSEMap.lookup(&In)) {
2056 In.replaceAllUsesWith(V);
2057 In.eraseFromParent();
2058 continue;
2059 }
2060
2061 CSEMap[&In] = &In;
2062 }
2063}
2064
2065/// This function attempts to return a value that represents the ElementCount
2066/// at runtime. For fixed-width VFs we know this precisely at compile
2067/// time, but for scalable VFs we calculate it based on an estimate of the
2068/// vscale value.
2070 std::optional<unsigned> VScale) {
2071 unsigned EstimatedVF = VF.getKnownMinValue();
2072 if (VF.isScalable())
2073 if (VScale)
2074 EstimatedVF *= *VScale;
2075 assert(EstimatedVF >= 1 && "Estimated VF shouldn't be less than 1");
2076 return EstimatedVF;
2077}
2078
2079/// Returns the vector library variant function of \p CI usable at \p VF,
2080/// respecting \p MaskRequired, or nullptr if none is found: a mapping with
2081/// matching VF, masked if required, whose vector function is declared in the
2082/// module.
2084 bool MaskRequired,
2085 const TargetLibraryInfo *TLI) {
2086 if (!TLI || CI.isNoBuiltin())
2087 return nullptr;
2088 for (const VFInfo &Info : VFDatabase::getMappings(CI))
2089 if (Info.Shape.VF == VF && (!MaskRequired || Info.isMasked()))
2090 if (Function *F = CI.getModule()->getFunction(Info.VectorName))
2091 return F;
2092 return nullptr;
2093}
2094
2095/// Returns true iff \p CI has a library vector variant usable at \p VF.
2097 bool MaskRequired,
2098 const TargetLibraryInfo *TLI) {
2099 return getVectorLibraryVariantFor(CI, VF, MaskRequired, TLI) != nullptr;
2100}
2101
2104 ElementCount VF) const {
2105 Type *RetTy = CI->getType();
2107 for (auto &ArgOp : CI->args())
2108 Tys.push_back(ArgOp->getType());
2109
2110 InstructionCost ScalarCallCost = TTI.getCallInstrCost(
2111 CI->getCalledFunction(), RetTy, Tys, Config.CostKind);
2112
2113 // Cost of the scalar call (scalar VF) or its scalarization (vector VF). The
2114 // scalarization cost is only meaningful for fixed VFs.
2117 : ScalarCallCost * VF.getKnownMinValue() +
2118 getScalarizationOverhead(CI, VF);
2119
2120 // The call may be vectorized at this VF, via a vector intrinsic or a vector
2121 // library variant.
2123 Cost = std::min(Cost, getVectorIntrinsicCost(CI, VF));
2124
2125 if (Function *Variant =
2127 Cost = std::min(Cost,
2128 TTI.getCallInstrCost(
2129 /*F=*/nullptr, Variant->getReturnType(),
2130 Variant->getFunctionType()->params(), Config.CostKind));
2131
2132 return Cost;
2133}
2134
2136 if (VF.isScalar() || !canVectorizeTy(Ty))
2137 return Ty;
2138 return toVectorizedTy(Ty, VF);
2139}
2140
2143 ElementCount VF) const {
2145 assert(ID && "Expected intrinsic call!");
2146 Type *RetTy = maybeVectorizeType(CI->getType(), VF);
2147 FastMathFlags FMF;
2148 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2149 FMF = FPMO->getFastMathFlags();
2150
2153 SmallVector<Type *> ParamTys;
2154 std::transform(FTy->param_begin(), FTy->param_end(),
2155 std::back_inserter(ParamTys),
2156 [&](Type *Ty) { return maybeVectorizeType(Ty, VF); });
2157
2158 IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
2161 return TTI.getIntrinsicInstrCost(CostAttrs, Config.CostKind);
2162}
2163
2165 // Don't apply optimizations below when no (vector) loop remains, as they all
2166 // require one at the moment.
2167 VPBasicBlock *HeaderVPBB =
2168 vputils::getFirstLoopHeader(*State.Plan, State.VPDT);
2169 if (!HeaderVPBB)
2170 return;
2171
2172 BasicBlock *HeaderBB = State.CFG.VPBB2IRBB[HeaderVPBB];
2173
2174 // Remove redundant induction instructions.
2175 legacyCSE(HeaderBB);
2176}
2177
2178void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
2179 // We should not collect Scalars more than once per VF. Right now, this
2180 // function is called from collectUniformsAndScalars(), which already does
2181 // this check. Collecting Scalars for VF=1 does not make any sense.
2182 assert(VF.isVector() && !Scalars.contains(VF) &&
2183 "This function should not be visited twice for the same VF");
2184
2185 // This avoids any chances of creating a REPLICATE recipe during planning
2186 // since that would result in generation of scalarized code during execution,
2187 // which is not supported for scalable vectors.
2188 if (VF.isScalable()) {
2189 Scalars[VF].insert_range(Uniforms[VF]);
2190 return;
2191 }
2192
2194
2195 // These sets are used to seed the analysis with pointers used by memory
2196 // accesses that will remain scalar.
2198 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
2199 auto *Latch = TheLoop->getLoopLatch();
2200
2201 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
2202 // The pointer operands of loads and stores will be scalar as long as the
2203 // memory access is not a gather/scatter or histogram operation. The value
2204 // operand of a store will remain scalar if the store is scalarized.
2205 auto IsScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
2206 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
2207 assert(WideningDecision != CM_Unknown &&
2208 "Widening decision should be ready at this moment");
2209 auto *Store = dyn_cast<StoreInst>(MemAccess);
2210 if (Store && Ptr == Store->getValueOperand())
2211 return WideningDecision == CM_Scalarize;
2212 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
2213 "Ptr is neither a value or pointer operand");
2214 return WideningDecision != CM_GatherScatter &&
2215 !(Store && Legal->getHistogramInfo(Store));
2216 };
2217
2218 // A helper that returns true if the given value is a getelementptr
2219 // instruction contained in the loop.
2220 auto IsLoopVaryingGEP = [&](Value *V) {
2221 return isa<GetElementPtrInst>(V) && !TheLoop->isLoopInvariant(V);
2222 };
2223
2224 // A helper that evaluates a memory access's use of a pointer. If the use will
2225 // be a scalar use and the pointer is only used by memory accesses, we place
2226 // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
2227 // PossibleNonScalarPtrs.
2228 auto EvaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
2229 // We only care about bitcast and getelementptr instructions contained in
2230 // the loop.
2231 if (!IsLoopVaryingGEP(Ptr))
2232 return;
2233
2234 // If the pointer has already been identified as scalar (e.g., if it was
2235 // also identified as uniform), there's nothing to do.
2236 auto *I = cast<Instruction>(Ptr);
2237 if (Worklist.count(I))
2238 return;
2239
2240 // If the use of the pointer will be a scalar use, and all users of the
2241 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
2242 // place the pointer in PossibleNonScalarPtrs.
2243 if (IsScalarUse(MemAccess, Ptr) &&
2245 ScalarPtrs.insert(I);
2246 else
2247 PossibleNonScalarPtrs.insert(I);
2248 };
2249
2250 // We seed the scalars analysis with three classes of instructions: (1)
2251 // instructions marked uniform-after-vectorization and (2) bitcast,
2252 // getelementptr and (pointer) phi instructions used by memory accesses
2253 // requiring a scalar use.
2254 //
2255 // (1) Add to the worklist all instructions that have been identified as
2256 // uniform-after-vectorization.
2257 Worklist.insert_range(Uniforms[VF]);
2258
2259 // (2) Add to the worklist all bitcast and getelementptr instructions used by
2260 // memory accesses requiring a scalar use. The pointer operands of loads and
2261 // stores will be scalar unless the operation is a gather or scatter.
2262 // The value operand of a store will remain scalar if the store is scalarized.
2263 for (auto *BB : TheLoop->blocks())
2264 for (auto &I : *BB) {
2265 if (auto *Load = dyn_cast<LoadInst>(&I)) {
2266 EvaluatePtrUse(Load, Load->getPointerOperand());
2267 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
2268 EvaluatePtrUse(Store, Store->getPointerOperand());
2269 EvaluatePtrUse(Store, Store->getValueOperand());
2270 }
2271 }
2272 for (auto *I : ScalarPtrs)
2273 if (!PossibleNonScalarPtrs.count(I)) {
2274 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
2275 Worklist.insert(I);
2276 }
2277
2278 // Insert the forced scalars.
2279 // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
2280 // induction variable when the PHI user is scalarized.
2281 auto ForcedScalar = ForcedScalars.find(VF);
2282 if (ForcedScalar != ForcedScalars.end())
2283 for (auto *I : ForcedScalar->second) {
2284 LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
2285 Worklist.insert(I);
2286 }
2287
2288 // Expand the worklist by looking through any bitcasts and getelementptr
2289 // instructions we've already identified as scalar. This is similar to the
2290 // expansion step in collectLoopUniforms(); however, here we're only
2291 // expanding to include additional bitcasts and getelementptr instructions.
2292 unsigned Idx = 0;
2293 while (Idx != Worklist.size()) {
2294 Instruction *Dst = Worklist[Idx++];
2295 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
2296 continue;
2297 auto *Src = cast<Instruction>(Dst->getOperand(0));
2298 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
2299 auto *J = cast<Instruction>(U);
2300 return !TheLoop->contains(J) || Worklist.count(J) ||
2301 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
2302 IsScalarUse(J, Src));
2303 })) {
2304 Worklist.insert(Src);
2305 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
2306 }
2307 }
2308
2309 // An induction variable will remain scalar if all users of the induction
2310 // variable and induction variable update remain scalar.
2311 for (const auto &Induction : Legal->getInductionVars()) {
2312 auto *Ind = Induction.first;
2313 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2314
2315 // If tail-folding is applied, the primary induction variable will be used
2316 // to feed a vector compare.
2317 if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
2318 continue;
2319
2320 // Returns true if \p Indvar is a pointer induction that is used directly by
2321 // load/store instruction \p I.
2322 auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
2323 Instruction *I) {
2324 return Induction.second.getKind() ==
2327 Indvar == getLoadStorePointerOperand(I) && IsScalarUse(I, Indvar);
2328 };
2329
2330 // Determine if all users of the induction variable are scalar after
2331 // vectorization.
2332 bool ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
2333 auto *I = cast<Instruction>(U);
2334 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2335 IsDirectLoadStoreFromPtrIndvar(Ind, I);
2336 });
2337 if (!ScalarInd)
2338 continue;
2339
2340 // If the induction variable update is a fixed-order recurrence, neither the
2341 // induction variable or its update should be marked scalar after
2342 // vectorization.
2343 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
2344 if (IndUpdatePhi && Legal->isFixedOrderRecurrence(IndUpdatePhi))
2345 continue;
2346
2347 // Determine if all users of the induction variable update instruction are
2348 // scalar after vectorization.
2349 bool ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2350 auto *I = cast<Instruction>(U);
2351 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
2352 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
2353 });
2354 if (!ScalarIndUpdate)
2355 continue;
2356
2357 // The induction variable and its update instruction will remain scalar.
2358 Worklist.insert(Ind);
2359 Worklist.insert(IndUpdate);
2360 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
2361 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
2362 << "\n");
2363 }
2364
2365 Scalars[VF].insert_range(Worklist);
2366}
2367
2375
2377 ElementCount VF) const {
2379 return Config.isLegalGatherOrScatter(isa<LoadInst>(I), getLoadStoreType(I),
2381}
2382
2384 ElementCount VF) {
2385 if (!isPredicatedInst(I))
2386 return false;
2387
2388 // Do we have a non-scalar lowering for this predicated
2389 // instruction? No - it is scalar with predication.
2390 switch(I->getOpcode()) {
2391 default:
2392 return true;
2393 case Instruction::Call: {
2394 if (VF.isScalar())
2395 return true;
2396 auto *CI = cast<CallInst>(I);
2397 // A vector intrinsic or library variant lowering avoids scalarization.
2398 return !getVectorIntrinsicIDForCall(CI, TLI) &&
2400 }
2401 case Instruction::Load:
2402 case Instruction::Store: {
2403 bool IsConsecutive = Legal->isConsecutivePtr(getLoadStoreType(I),
2405 return !(IsConsecutive && isLegalMaskedLoadOrStore(I, VF)) &&
2407 }
2408 case Instruction::UDiv:
2409 case Instruction::SDiv:
2410 case Instruction::SRem:
2411 case Instruction::URem: {
2412 // We have the option to use the llvm.masked.udiv intrinsics to avoid
2413 // predication. The cost based decision here will always select the masked
2414 // intrinsics for scalable vectors as scalarization isn't legal.
2415 const auto [ScalarCost, MaskedCost] = getDivRemSpeculationCost(I, VF);
2416 return isDivRemScalarWithPredication(ScalarCost, MaskedCost);
2417 }
2418 }
2419}
2420
2422 return Legal->isMaskRequired(I, foldTailByMasking());
2423}
2424
2425// TODO: Fold into LoopVectorizationLegality::isMaskRequired.
2427 // TODO: We can use the loop-preheader as context point here and get
2428 // context sensitive reasoning for isSafeToSpeculativelyExecute.
2432 return false;
2433
2434 // If the instruction was executed conditionally in the original scalar loop,
2435 // predication is needed with a mask whose lanes are all possibly inactive.
2436 if (Legal->blockNeedsPredication(I->getParent()))
2437 return true;
2438
2439 // If we're not folding the tail by masking and not vectorizing a loop with
2440 // uncountable exits and side effects, predication is unnecessary.
2441 if (!foldTailByMasking() && !Legal->hasUncountableExitWithSideEffects())
2442 return false;
2443
2444 // All that remain are instructions with side-effects originally executed in
2445 // the loop unconditionally, but now execute under a tail-fold mask (only)
2446 // having at least one active lane (the first). If the side-effects of the
2447 // instruction are invariant, executing it w/o (the tail-folding) mask is safe
2448 // - it will cause the same side-effects as when masked.
2449 switch(I->getOpcode()) {
2450 default:
2452 "instruction should have been considered by earlier checks");
2453 case Instruction::Call:
2454 // Side-effects of a Call are assumed to be non-invariant, needing a
2455 // (fold-tail) mask.
2457 "should have returned earlier for calls not needing a mask");
2458 return true;
2459 case Instruction::Load:
2460 // If the address is loop invariant no predication is needed.
2461 return !Legal->isInvariant(getLoadStorePointerOperand(I));
2462 case Instruction::Store: {
2463 // For stores, we need to prove both speculation safety (which follows from
2464 // the same argument as loads), but also must prove the value being stored
2465 // is correct. The easiest form of the later is to require that all values
2466 // stored are the same.
2467 return !(Legal->isInvariant(getLoadStorePointerOperand(I)) &&
2468 TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()));
2469 }
2470 case Instruction::UDiv:
2471 case Instruction::URem:
2472 // If the divisor is loop-invariant no predication is needed.
2473 return !Legal->isInvariant(I->getOperand(1));
2474 case Instruction::SDiv:
2475 case Instruction::SRem:
2476 // Conservative for now, since masked-off lanes may be poison and could
2477 // trigger signed overflow.
2478 return true;
2479 }
2480}
2481
2485 return 1;
2486 // If the block wasn't originally predicated then return early to avoid
2487 // computing BlockFrequencyInfo unnecessarily.
2488 if (!Legal->blockNeedsPredication(BB))
2489 return 1;
2490
2491 uint64_t HeaderFreq =
2492 getBFI().getBlockFreq(TheLoop->getHeader()).getFrequency();
2493 uint64_t BBFreq = getBFI().getBlockFreq(BB).getFrequency();
2494 assert(HeaderFreq >= BBFreq &&
2495 "Header has smaller block freq than dominated BB?");
2496 return std::round((double)HeaderFreq / BBFreq);
2497}
2498
2500 switch (Opcode) {
2501 case Instruction::UDiv:
2502 return Intrinsic::masked_udiv;
2503 case Instruction::SDiv:
2504 return Intrinsic::masked_sdiv;
2505 case Instruction::URem:
2506 return Intrinsic::masked_urem;
2507 case Instruction::SRem:
2508 return Intrinsic::masked_srem;
2509 default:
2510 llvm_unreachable("Unexpected opcode");
2511 }
2512}
2513
2514std::pair<InstructionCost, InstructionCost>
2516 ElementCount VF) {
2517 assert(I->getOpcode() == Instruction::UDiv ||
2518 I->getOpcode() == Instruction::SDiv ||
2519 I->getOpcode() == Instruction::SRem ||
2520 I->getOpcode() == Instruction::URem);
2522
2523 // Scalarization isn't legal for scalable vector types
2524 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
2525 if (!VF.isScalable()) {
2526 // Get the scalarization cost and scale this amount by the probability of
2527 // executing the predicated block. If the instruction is not predicated,
2528 // we fall through to the next case.
2529 ScalarizationCost = 0;
2530
2531 // These instructions have a non-void type, so account for the phi nodes
2532 // that we will create. This cost is likely to be zero. The phi node
2533 // cost, if any, should be scaled by the block probability because it
2534 // models a copy at the end of each predicated block.
2535 ScalarizationCost += VF.getFixedValue() *
2536 TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
2537
2538 // The cost of the non-predicated instruction.
2539 ScalarizationCost +=
2540 VF.getFixedValue() * TTI.getArithmeticInstrCost(
2541 I->getOpcode(), I->getType(), Config.CostKind);
2542
2543 // The cost of insertelement and extractelement instructions needed for
2544 // scalarization.
2545 ScalarizationCost += getScalarizationOverhead(I, VF);
2546
2547 // Scale the cost by the probability of executing the predicated blocks.
2548 // This assumes the predicated block for each vector lane is equally
2549 // likely.
2550 ScalarizationCost =
2551 ScalarizationCost /
2552 getPredBlockCostDivisor(Config.CostKind, I->getParent());
2553 }
2554
2555 auto *VecTy = toVectorTy(I->getType(), VF);
2556 auto *MaskTy = toVectorTy(Type::getInt1Ty(I->getContext()), VF);
2557 IntrinsicCostAttributes ICA(getMaskedDivRemIntrinsic(I->getOpcode()), VecTy,
2558 {VecTy, VecTy, MaskTy});
2559 InstructionCost MaskedCost = TTI.getIntrinsicInstrCost(ICA, Config.CostKind);
2560 return {ScalarizationCost, MaskedCost};
2561}
2562
2564 Instruction *I, ElementCount VF) const {
2565 assert(isAccessInterleaved(I) && "Expecting interleaved access.");
2567 "Decision should not be set yet.");
2568 auto *Group = getInterleavedAccessGroup(I);
2569 assert(Group && "Must have a group.");
2570 unsigned InterleaveFactor = Group->getFactor();
2571
2572 // If the instruction's allocated size doesn't equal its type size, it
2573 // requires padding and will be scalarized.
2574 auto &DL = I->getDataLayout();
2575 auto *ScalarTy = getLoadStoreType(I);
2576 if (hasIrregularType(ScalarTy, DL))
2577 return false;
2578
2579 // For scalable vectors, the interleave factors must be <= 8 since we require
2580 // the (de)interleaveN intrinsics instead of shufflevectors.
2581 if (VF.isScalable() && InterleaveFactor > 8)
2582 return false;
2583
2584 // If the group involves a non-integral pointer, we may not be able to
2585 // losslessly cast all values to a common type.
2586 bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
2587 for (Instruction *Member : Group->members()) {
2588 auto *MemberTy = getLoadStoreType(Member);
2589 bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
2590 // Don't coerce non-integral pointers to integers or vice versa.
2591 if (MemberNI != ScalarNI)
2592 // TODO: Consider adding special nullptr value case here
2593 return false;
2594 if (MemberNI && ScalarNI &&
2595 ScalarTy->getPointerAddressSpace() !=
2596 MemberTy->getPointerAddressSpace())
2597 return false;
2598 }
2599
2600 // Check if masking is required.
2601 // A Group may need masking for one of two reasons: it resides in a block that
2602 // needs predication, or it was decided to use masking to deal with gaps
2603 // (either a gap at the end of a load-access that may result in a speculative
2604 // load, or any gaps in a store-access).
2605 bool PredicatedAccessRequiresMasking =
2607 bool LoadAccessWithGapsRequiresEpilogMasking =
2608 isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
2610 bool StoreAccessWithGapsRequiresMasking =
2611 isa<StoreInst>(I) && !Group->isFull();
2612 if (!PredicatedAccessRequiresMasking &&
2613 !LoadAccessWithGapsRequiresEpilogMasking &&
2614 !StoreAccessWithGapsRequiresMasking)
2615 return true;
2616
2617 // If masked interleaving is required, we expect that the user/target had
2618 // enabled it, because otherwise it either wouldn't have been created or
2619 // it should have been invalidated by the CostModel.
2621 "Masked interleave-groups for predicated accesses are not enabled.");
2622
2623 if (Group->isReverse())
2624 return false;
2625
2626 // TODO: Support interleaved access that requires a gap mask for scalable VFs.
2627 bool NeedsMaskForGaps = LoadAccessWithGapsRequiresEpilogMasking ||
2628 StoreAccessWithGapsRequiresMasking;
2629 if (VF.isScalable() && NeedsMaskForGaps)
2630 return false;
2631
2632 return isLegalMaskedLoadOrStore(I, VF);
2633}
2634
2635std::optional<LoopVectorizationCostModel::InstWidening>
2637 ElementCount VF) {
2638 // Get and ensure we have a valid memory instruction.
2639 assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
2640
2641 auto *Ptr = getLoadStorePointerOperand(I);
2642 auto *ScalarTy = getLoadStoreType(I);
2643
2644 // In order to be widened, the pointer should be consecutive, first of all.
2645 int Stride = Legal->isConsecutivePtr(ScalarTy, Ptr);
2646 if (!Stride)
2647 return std::nullopt;
2648
2649 // If the instruction is a store located in a predicated block, it will be
2650 // scalarized.
2651 if (isScalarWithPredication(I, VF))
2652 return std::nullopt;
2653
2654 // If the instruction's allocated size doesn't equal it's type size, it
2655 // requires padding and will be scalarized.
2656 auto &DL = I->getDataLayout();
2657 if (hasIrregularType(ScalarTy, DL))
2658 return std::nullopt;
2659
2660 return Stride == 1 ? CM_Widen : CM_Widen_Reverse;
2661}
2662
2663void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
2664 // We should not collect Uniforms more than once per VF. Right now,
2665 // this function is called from collectUniformsAndScalars(), which
2666 // already does this check. Collecting Uniforms for VF=1 does not make any
2667 // sense.
2668
2669 assert(VF.isVector() && !Uniforms.contains(VF) &&
2670 "This function should not be visited twice for the same VF");
2671
2672 // Visit the list of Uniforms. If we find no uniform value, we won't
2673 // analyze again. Uniforms.count(VF) will return 1.
2674 Uniforms[VF].clear();
2675
2676 // Now we know that the loop is vectorizable!
2677 // Collect instructions inside the loop that will remain uniform after
2678 // vectorization.
2679
2680 // Global values, params and instructions outside of current loop are out of
2681 // scope.
2682 auto IsOutOfScope = [&](Value *V) -> bool {
2684 return (!I || !TheLoop->contains(I));
2685 };
2686
2687 // Worklist containing uniform instructions demanding lane 0.
2688 SetVector<Instruction *> Worklist;
2689
2690 // Add uniform instructions demanding lane 0 to the worklist. Instructions
2691 // that require predication must not be considered uniform after
2692 // vectorization, because that would create an erroneous replicating region
2693 // where only a single instance out of VF should be formed.
2694 auto AddToWorklistIfAllowed = [&](Instruction *I) -> void {
2695 if (IsOutOfScope(I)) {
2696 LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
2697 << *I << "\n");
2698 return;
2699 }
2700 if (isPredicatedInst(I)) {
2701 LLVM_DEBUG(
2702 dbgs() << "LV: Found not uniform due to requiring predication: " << *I
2703 << "\n");
2704 return;
2705 }
2706 LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
2707 Worklist.insert(I);
2708 };
2709
2710 // Start with the conditional branches exiting the loop. If the branch
2711 // condition is an instruction contained in the loop that is only used by the
2712 // branch, it is uniform. Note conditions from uncountable early exits are not
2713 // uniform.
2715 TheLoop->getExitingBlocks(Exiting);
2716 for (BasicBlock *E : Exiting) {
2717 if (Legal->hasUncountableEarlyExit() && TheLoop->getLoopLatch() != E)
2718 continue;
2719 auto *Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
2720 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
2721 AddToWorklistIfAllowed(Cmp);
2722 }
2723
2724 auto PrevVF = VF.divideCoefficientBy(2);
2725 // Return true if all lanes perform the same memory operation, and we can
2726 // thus choose to execute only one.
2727 auto IsUniformMemOpUse = [&](Instruction *I) {
2728 // If the value was already known to not be uniform for the previous
2729 // (smaller VF), it cannot be uniform for the larger VF.
2730 if (PrevVF.isVector()) {
2731 auto Iter = Uniforms.find(PrevVF);
2732 if (Iter != Uniforms.end() && !Iter->second.contains(I))
2733 return false;
2734 }
2735 if (!isUniformMemOp(*I, VF))
2736 return false;
2737 if (isa<LoadInst>(I))
2738 // Loading the same address always produces the same result - at least
2739 // assuming aliasing and ordering which have already been checked.
2740 return true;
2741 // Storing the same value on every iteration.
2742 return TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand());
2743 };
2744
2745 auto IsUniformDecision = [&](Instruction *I, ElementCount VF) {
2746 InstWidening WideningDecision = getWideningDecision(I, VF);
2747 assert(WideningDecision != CM_Unknown &&
2748 "Widening decision should be ready at this moment");
2749
2750 if (IsUniformMemOpUse(I))
2751 return true;
2752
2753 return (WideningDecision == CM_Widen ||
2754 WideningDecision == CM_Widen_Reverse ||
2755 WideningDecision == CM_Interleave);
2756 };
2757
2758 // Returns true if Ptr is the pointer operand of a memory access instruction
2759 // I, I is known to not require scalarization, and the pointer is not also
2760 // stored.
2761 auto IsVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
2762 if (isa<StoreInst>(I) && I->getOperand(0) == Ptr)
2763 return false;
2764 return getLoadStorePointerOperand(I) == Ptr &&
2765 (IsUniformDecision(I, VF) || Legal->isInvariant(Ptr));
2766 };
2767
2768 // Holds a list of values which are known to have at least one uniform use.
2769 // Note that there may be other uses which aren't uniform. A "uniform use"
2770 // here is something which only demands lane 0 of the unrolled iterations;
2771 // it does not imply that all lanes produce the same value (e.g. this is not
2772 // the usual meaning of uniform)
2773 SetVector<Value *> HasUniformUse;
2774
2775 // Scan the loop for instructions which are either a) known to have only
2776 // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
2777 for (auto *BB : TheLoop->blocks())
2778 for (auto &I : *BB) {
2779 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
2780 switch (II->getIntrinsicID()) {
2781 case Intrinsic::sideeffect:
2782 case Intrinsic::experimental_noalias_scope_decl:
2783 case Intrinsic::assume:
2784 case Intrinsic::lifetime_start:
2785 case Intrinsic::lifetime_end:
2786 if (TheLoop->hasLoopInvariantOperands(&I))
2787 AddToWorklistIfAllowed(&I);
2788 break;
2789 default:
2790 break;
2791 }
2792 }
2793
2794 if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
2795 if (IsOutOfScope(EVI->getAggregateOperand())) {
2796 AddToWorklistIfAllowed(EVI);
2797 continue;
2798 }
2799 // Only ExtractValue instructions where the aggregate value comes from a
2800 // call are allowed to be non-uniform.
2801 assert(isa<CallInst>(EVI->getAggregateOperand()) &&
2802 "Expected aggregate value to be call return value");
2803 }
2804
2805 // If there's no pointer operand, there's nothing to do.
2806 auto *Ptr = getLoadStorePointerOperand(&I);
2807 if (!Ptr)
2808 continue;
2809
2810 // If the pointer can be proven to be uniform, always add it to the
2811 // worklist.
2812 if (isa<Instruction>(Ptr) && isUniform(Ptr, VF))
2813 AddToWorklistIfAllowed(cast<Instruction>(Ptr));
2814
2815 if (IsUniformMemOpUse(&I))
2816 AddToWorklistIfAllowed(&I);
2817
2818 if (IsVectorizedMemAccessUse(&I, Ptr))
2819 HasUniformUse.insert(Ptr);
2820 }
2821
2822 // Add to the worklist any operands which have *only* uniform (e.g. lane 0
2823 // demanding) users. Since loops are assumed to be in LCSSA form, this
2824 // disallows uses outside the loop as well.
2825 for (auto *V : HasUniformUse) {
2826 if (IsOutOfScope(V))
2827 continue;
2828 auto *I = cast<Instruction>(V);
2829 bool UsersAreMemAccesses = all_of(I->users(), [&](User *U) -> bool {
2830 auto *UI = cast<Instruction>(U);
2831 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
2832 });
2833 if (UsersAreMemAccesses)
2834 AddToWorklistIfAllowed(I);
2835 }
2836
2837 // Expand Worklist in topological order: whenever a new instruction
2838 // is added , its users should be already inside Worklist. It ensures
2839 // a uniform instruction will only be used by uniform instructions.
2840 unsigned Idx = 0;
2841 while (Idx != Worklist.size()) {
2842 Instruction *I = Worklist[Idx++];
2843
2844 for (auto *OV : I->operand_values()) {
2845 // isOutOfScope operands cannot be uniform instructions.
2846 if (IsOutOfScope(OV))
2847 continue;
2848 // First order recurrence Phi's should typically be considered
2849 // non-uniform.
2850 auto *OP = dyn_cast<PHINode>(OV);
2851 if (OP && Legal->isFixedOrderRecurrence(OP))
2852 continue;
2853 // If all the users of the operand are uniform, then add the
2854 // operand into the uniform worklist.
2855 auto *OI = cast<Instruction>(OV);
2856 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
2857 auto *J = cast<Instruction>(U);
2858 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
2859 }))
2860 AddToWorklistIfAllowed(OI);
2861 }
2862 }
2863
2864 // For an instruction to be added into Worklist above, all its users inside
2865 // the loop should also be in Worklist. However, this condition cannot be
2866 // true for phi nodes that form a cyclic dependence. We must process phi
2867 // nodes separately. An induction variable will remain uniform if all users
2868 // of the induction variable and induction variable update remain uniform.
2869 // The code below handles both pointer and non-pointer induction variables.
2870 BasicBlock *Latch = TheLoop->getLoopLatch();
2871 for (const auto &Induction : Legal->getInductionVars()) {
2872 auto *Ind = Induction.first;
2873 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2874
2875 // Determine if all users of the induction variable are uniform after
2876 // vectorization.
2877 bool UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
2878 auto *I = cast<Instruction>(U);
2879 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2880 IsVectorizedMemAccessUse(I, Ind);
2881 });
2882 if (!UniformInd)
2883 continue;
2884
2885 // Determine if all users of the induction variable update instruction are
2886 // uniform after vectorization.
2887 bool UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2888 auto *I = cast<Instruction>(U);
2889 return I == Ind || Worklist.count(I) ||
2890 IsVectorizedMemAccessUse(I, IndUpdate);
2891 });
2892 if (!UniformIndUpdate)
2893 continue;
2894
2895 // The induction variable and its update instruction will remain uniform.
2896 AddToWorklistIfAllowed(Ind);
2897 AddToWorklistIfAllowed(IndUpdate);
2898 }
2899
2900 Uniforms[VF].insert_range(Worklist);
2901}
2902
2903FixedScalableVFPair
2905 // Make sure once we return PartialAliasMaskingStatus is not "NotDecided".
2906 scope_exit EnsureAliasMaskingStatusIsDecidedOnReturn([this] {
2907 if (PartialAliasMaskingStatus == AliasMaskingStatus::NotDecided)
2908 PartialAliasMaskingStatus = AliasMaskingStatus::Disabled;
2909 });
2910
2911 // For outer loops, use simple type-based heuristic VF. No cost model or
2912 // memory dependence analysis is available.
2913 if (!TheLoop->isInnermost()) {
2914 return Config.computeVPlanOuterloopVF(UserVF);
2915 }
2916
2917 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
2918 // TODO: It may be useful to do since it's still likely to be dynamically
2919 // uniform if the target can skip.
2921 "Not inserting runtime ptr check for divergent target",
2922 "runtime pointer checks needed. Not enabled for divergent target",
2923 "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
2925 }
2926
2927 ScalarEvolution *SE = PSE.getSE();
2929 unsigned MaxTC = PSE.getSmallConstantMaxTripCount();
2930 if (!MaxTC && EpilogueLoweringStatus == CM_EpilogueAllowed)
2932 LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
2933 if (TC != ElementCount::getFixed(MaxTC))
2934 LLVM_DEBUG(dbgs() << "LV: Found maximum trip count: " << MaxTC << '\n');
2935 if (TC.isScalar()) {
2937 "Single iteration (non) loop",
2938 "loop trip count is one, irrelevant for vectorization",
2939 "SingleIterationLoop", ORE, TheLoop);
2941 }
2942
2943 // If BTC matches the widest induction type and is -1 then the trip count
2944 // computation will wrap to 0 and the vector trip count will be 0. Do not try
2945 // to vectorize.
2946 const SCEV *BTC = SE->getBackedgeTakenCount(TheLoop);
2947 if (!isa<SCEVCouldNotCompute>(BTC) &&
2948 BTC->getType()->getScalarSizeInBits() >=
2949 Legal->getWidestInductionType()->getScalarSizeInBits() &&
2951 SE->getMinusOne(BTC->getType()))) {
2953 "Trip count computation wrapped",
2954 "backedge-taken count is -1, loop trip count wrapped to 0",
2955 "TripCountWrapped", ORE, TheLoop);
2957 }
2958
2959 assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
2960 "No cost-modeling decisions should have been taken at this point");
2961
2962 switch (EpilogueLoweringStatus) {
2963 case CM_EpilogueAllowed:
2964 return Config.computeFeasibleMaxVF(MaxTC, UserVF, UserIC, false,
2967 [[fallthrough]];
2969 LLVM_DEBUG(dbgs() << "LV: tail-folding hint/switch found.\n"
2970 << "LV: Not allowing epilogue, creating tail-folded "
2971 << "vector loop.\n");
2972 break;
2974 // fallthrough as a special case of OptForSize
2976 if (EpilogueLoweringStatus == CM_EpilogueNotAllowedOptSize)
2977 LLVM_DEBUG(dbgs() << "LV: Not allowing epilogue due to -Os/-Oz.\n");
2978 else
2979 LLVM_DEBUG(dbgs() << "LV: Not allowing epilogue due to low trip "
2980 << "count.\n");
2981
2982 // Bail if runtime checks are required, which are not good when optimising
2983 // for size.
2984 if (Config.runtimeChecksRequired())
2986
2987 break;
2988 }
2989
2990 // Now try the tail folding
2991
2992 // Invalidate interleave groups that require an epilogue if we can't mask
2993 // the interleave-group.
2995 // Note: There is no need to invalidate any cost modeling decisions here, as
2996 // none were taken so far (see assertion above).
2997 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
2998 }
2999
3000 FixedScalableVFPair MaxFactors = Config.computeFeasibleMaxVF(
3001 MaxTC, UserVF, UserIC, true, requiresScalarEpilogue(true));
3002
3003 // Avoid tail folding if the trip count is known to be a multiple of any VF
3004 // we choose.
3005 std::optional<uint64_t> MaxPowerOf2RuntimeVF =
3006 MaxFactors.FixedVF.getFixedValue();
3007 if (MaxFactors.ScalableVF) {
3008 if (std::optional<uint64_t> MaxRuntimeScalableVF =
3010 MaxPowerOf2RuntimeVF =
3011 std::max(*MaxPowerOf2RuntimeVF, *MaxRuntimeScalableVF);
3012 else
3013 MaxPowerOf2RuntimeVF = std::nullopt; // Stick with tail-folding for now.
3014 }
3015
3016 auto NoScalarEpilogueNeeded = [this, &UserIC](uint64_t MaxRuntimeVF) {
3017 // Return false if the loop is neither a single-latch-exit loop nor an
3018 // early-exit loop as tail-folding is not supported in that case.
3019 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
3020 !Legal->hasUncountableEarlyExit())
3021 return false;
3022 uint64_t MaxVFtimesIC = MaxRuntimeVF * std::max<uint64_t>(UserIC, 1);
3023 ScalarEvolution *SE = PSE.getSE();
3024 // Calling getSymbolicMaxBackedgeTakenCount enables support for loops
3025 // with uncountable exits. For countable loops, the symbolic maximum must
3026 // remain identical to the known back-edge taken count.
3027 const SCEV *BackedgeTakenCount = PSE.getSymbolicMaxBackedgeTakenCount();
3028 assert((Legal->hasUncountableEarlyExit() ||
3029 BackedgeTakenCount == PSE.getBackedgeTakenCount()) &&
3030 "Invalid loop count");
3031 const SCEV *ExitCount = SE->getAddExpr(
3032 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3033 const SCEV *Rem = SE->getURemExpr(
3034 SE->applyLoopGuards(ExitCount, TheLoop),
3035 SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
3036 return Rem->isZero();
3037 };
3038
3039 if (MaxPowerOf2RuntimeVF > 0u) {
3040 assert((UserVF.isNonZero() || isPowerOf2_64(*MaxPowerOf2RuntimeVF)) &&
3041 "MaxFixedVF must be a power of 2");
3042 if (NoScalarEpilogueNeeded(*MaxPowerOf2RuntimeVF)) {
3043 // Accept MaxFixedVF if we do not have a tail.
3044 LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
3045 return MaxFactors;
3046 }
3047 }
3048
3049 auto ExpectedTC = getSmallBestKnownTC(PSE, TheLoop);
3050 if (ExpectedTC && ExpectedTC->isFixed() &&
3051 ExpectedTC->getFixedValue() <=
3052 TTI.getMinTripCountTailFoldingThreshold()) {
3053 if (MaxPowerOf2RuntimeVF > 0u) {
3054 // If we have a low-trip-count, and the fixed-width VF is known to divide
3055 // the trip count but the scalable factor does not, use the fixed-width
3056 // factor in preference to allow the generation of a non-predicated loop.
3057 if (EpilogueLoweringStatus == CM_EpilogueNotAllowedLowTripLoop &&
3058 NoScalarEpilogueNeeded(MaxFactors.FixedVF.getFixedValue())) {
3059 LLVM_DEBUG(dbgs() << "LV: Picking a fixed-width so that no tail will "
3060 "remain for any chosen VF.\n");
3061 MaxFactors.ScalableVF = ElementCount::getScalable(0);
3062 return MaxFactors;
3063 }
3064 }
3065
3067 "The trip count is below the minial threshold value.",
3068 "loop trip count is too low, avoiding vectorization", "LowTripCount",
3069 ORE, TheLoop);
3071 }
3072
3073 // If we don't know the precise trip count, or if the trip count that we
3074 // found modulo the vectorization factor is not zero, try to fold the tail
3075 // by masking.
3076 // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
3077 bool ContainsScalableVF = MaxFactors.ScalableVF.isNonZero();
3078 setTailFoldingStyle(ContainsScalableVF, UserIC);
3079 if (foldTailByMasking()) {
3080 if (foldTailWithEVL()) {
3081 LLVM_DEBUG(
3082 dbgs()
3083 << "LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
3084 "try to generate VP Intrinsics with scalable vector "
3085 "factors only.\n");
3086 // Tail folded loop using VP intrinsics restricts the VF to be scalable
3087 // for now.
3088 // TODO: extend it for fixed vectors, if required.
3089 assert(ContainsScalableVF && "Expected scalable vector factor.");
3090
3091 MaxFactors.FixedVF = ElementCount::getFixed(1);
3092 } else {
3094 }
3095 return MaxFactors;
3096 }
3097
3098 // If there was a tail-folding hint/switch, but we can't fold the tail by
3099 // masking, fallback to a vectorization with an epilogue.
3100 if (EpilogueLoweringStatus == CM_EpilogueNotNeededFoldTail) {
3101 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with an "
3102 "epilogue instead.\n");
3103 EpilogueLoweringStatus = CM_EpilogueAllowed;
3104 return MaxFactors;
3105 }
3106
3107 if (EpilogueLoweringStatus == CM_EpilogueNotAllowedFoldTail) {
3108 LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
3110 }
3111
3112 if (TC.isZero()) {
3114 "unable to calculate the loop count due to complex control flow",
3115 "UnknownLoopCountComplexCFG", ORE, TheLoop);
3117 }
3118
3120 "Cannot optimize for size and vectorize at the same time.",
3121 "cannot optimize for size and vectorize at the same time. "
3122 "Enable vectorization of this loop with '#pragma clang loop "
3123 "vectorize(enable)' when compiling with -Os/-Oz",
3124 "NoTailLoopWithOptForSize", ORE, TheLoop);
3126}
3127
3130 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
3131 SmallVector<RecipeVFPair> InvalidCosts;
3132 for (const auto &Plan : VPlans) {
3133 for (ElementCount VF : Plan->vectorFactors()) {
3134 // The VPlan-based cost model is designed for computing vector cost.
3135 // Querying VPlan-based cost model with a scarlar VF will cause some
3136 // errors because we expect the VF is vector for most of the widen
3137 // recipes.
3138 if (VF.isScalar())
3139 continue;
3140
3141 VPCostContext CostCtx(*TLI, *Plan, *CM, Config,
3142 /*ReusePrintingSlotTracker=*/true);
3143 precomputeCosts(*Plan, VF, CostCtx);
3144 auto Iter = vp_depth_first_deep(Plan->getVectorLoopRegion()->getEntry());
3146 for (auto &R : *VPBB) {
3147 if (!R.cost(VF, CostCtx).isValid())
3148 InvalidCosts.emplace_back(&R, VF);
3149 }
3150 }
3151 }
3152 }
3153 if (InvalidCosts.empty())
3154 return;
3155
3156 // Emit a report of VFs with invalid costs in the loop.
3157
3158 // Group the remarks per recipe, keeping the recipe order from InvalidCosts.
3160 unsigned I = 0;
3161 for (auto &Pair : InvalidCosts)
3162 if (Numbering.try_emplace(Pair.first, I).second)
3163 ++I;
3164
3165 // Sort the list, first on recipe(number) then on VF.
3166 sort(InvalidCosts, [&Numbering](RecipeVFPair &A, RecipeVFPair &B) {
3167 unsigned NA = Numbering[A.first];
3168 unsigned NB = Numbering[B.first];
3169 if (NA != NB)
3170 return NA < NB;
3171 return ElementCount::isKnownLT(A.second, B.second);
3172 });
3173
3174 // For a list of ordered recipe-VF pairs:
3175 // [(load, VF1), (load, VF2), (store, VF1)]
3176 // group the recipes together to emit separate remarks for:
3177 // load (VF1, VF2)
3178 // store (VF1)
3179 auto Tail = ArrayRef<RecipeVFPair>(InvalidCosts);
3180 auto Subset = ArrayRef<RecipeVFPair>();
3181 do {
3182 if (Subset.empty())
3183 Subset = Tail.take_front(1);
3184
3185 VPRecipeBase *R = Subset.front().first;
3186
3187 unsigned Opcode =
3189 .Case([](const VPHeaderPHIRecipe *R) { return Instruction::PHI; })
3190 .Case(
3191 [](const VPWidenStoreRecipe *R) { return Instruction::Store; })
3192 .Case([](const VPWidenLoadRecipe *R) { return Instruction::Load; })
3193 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
3194 [](const auto *R) { return Instruction::Call; })
3197 [](const auto *R) { return R->getOpcode(); })
3198 .Case([](const VPInterleaveRecipe *R) {
3199 return R->getStoredValues().empty() ? Instruction::Load
3200 : Instruction::Store;
3201 })
3202 .Case([](const VPReductionRecipe *R) {
3203 return RecurrenceDescriptor::getOpcode(R->getRecurrenceKind());
3204 });
3205
3206 // If the next recipe is different, or if there are no other pairs,
3207 // emit a remark for the collated subset. e.g.
3208 // [(load, VF1), (load, VF2))]
3209 // to emit:
3210 // remark: invalid costs for 'load' at VF=(VF1, VF2)
3211 if (Subset == Tail || Tail[Subset.size()].first != R) {
3212 std::string OutString;
3213 raw_string_ostream OS(OutString);
3214 assert(!Subset.empty() && "Unexpected empty range");
3215 OS << "Recipe with invalid costs prevented vectorization at VF=(";
3216 for (const auto &Pair : Subset)
3217 OS << (Pair.second == Subset.front().second ? "" : ", ") << Pair.second;
3218 OS << "):";
3219 if (Opcode == Instruction::Call) {
3220 StringRef Name = "";
3221 if (auto *Int = dyn_cast<VPWidenIntrinsicRecipe>(R)) {
3222 Name = Int->getIntrinsicName();
3223 } else {
3224 auto *WidenCall = dyn_cast<VPWidenCallRecipe>(R);
3225 Function *CalledFn =
3226 WidenCall ? WidenCall->getCalledScalarFunction()
3227 : cast<Function>(R->getOperand(R->getNumOperands() - 1)
3228 ->getLiveInIRValue());
3229 Name = CalledFn->getName();
3230 }
3231 OS << " call to " << Name;
3232 } else
3233 OS << " " << Instruction::getOpcodeName(Opcode);
3234 reportVectorizationInfo(OutString, "InvalidCost", ORE, OrigLoop, nullptr,
3235 R->getDebugLoc());
3236 Tail = Tail.drop_front(Subset.size());
3237 Subset = {};
3238 } else
3239 // Grow the subset by one element
3240 Subset = Tail.take_front(Subset.size() + 1);
3241 } while (!Tail.empty());
3242}
3243
3244/// Check if any recipe of \p Plan will generate a vector value, which will be
3245/// assigned a vector register.
3247 const TargetTransformInfo &TTI) {
3248 assert(VF.isVector() && "Checking a scalar VF?");
3249 DenseSet<VPRecipeBase *> EphemeralRecipes;
3250 collectEphemeralRecipesForVPlan(Plan, EphemeralRecipes);
3251 // Set of already visited types.
3252 DenseSet<Type *> Visited;
3255 for (VPRecipeBase &R : *VPBB) {
3256 if (EphemeralRecipes.contains(&R))
3257 continue;
3258 // Continue early if the recipe is considered to not produce a vector
3259 // result. Note that this includes VPInstruction where some opcodes may
3260 // produce a vector, to preserve existing behavior as VPInstructions model
3261 // aspects not directly mapped to existing IR instructions.
3262 switch (R.getVPRecipeID()) {
3263 case VPRecipeBase::VPDerivedIVSC:
3264 case VPRecipeBase::VPScalarIVStepsSC:
3265 case VPRecipeBase::VPReplicateSC:
3266 case VPRecipeBase::VPInstructionSC:
3267 case VPRecipeBase::VPCurrentIterationPHISC:
3268 case VPRecipeBase::VPVectorPointerSC:
3269 case VPRecipeBase::VPVectorEndPointerSC:
3270 case VPRecipeBase::VPExpandSCEVSC:
3271 case VPRecipeBase::VPPredInstPHISC:
3272 case VPRecipeBase::VPBranchOnMaskSC:
3273 continue;
3274 case VPRecipeBase::VPReductionSC:
3275 case VPRecipeBase::VPActiveLaneMaskPHISC:
3276 case VPRecipeBase::VPWidenCallSC:
3277 case VPRecipeBase::VPWidenCanonicalIVSC:
3278 case VPRecipeBase::VPWidenCastSC:
3279 case VPRecipeBase::VPWidenGEPSC:
3280 case VPRecipeBase::VPWidenIntrinsicSC:
3281 case VPRecipeBase::VPWidenMemIntrinsicSC:
3282 case VPRecipeBase::VPWidenSC:
3283 case VPRecipeBase::VPBlendSC:
3284 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
3285 case VPRecipeBase::VPHistogramSC:
3286 case VPRecipeBase::VPWidenPHISC:
3287 case VPRecipeBase::VPWidenIntOrFpInductionSC:
3288 case VPRecipeBase::VPWidenPointerInductionSC:
3289 case VPRecipeBase::VPReductionPHISC:
3290 case VPRecipeBase::VPInterleaveEVLSC:
3291 case VPRecipeBase::VPInterleaveSC:
3292 case VPRecipeBase::VPWidenLoadEVLSC:
3293 case VPRecipeBase::VPWidenLoadSC:
3294 case VPRecipeBase::VPWidenStoreEVLSC:
3295 case VPRecipeBase::VPWidenStoreSC:
3296 break;
3297 default:
3298 llvm_unreachable("unhandled recipe");
3299 }
3300
3301 auto WillGenerateTargetVectors = [&TTI, VF](Type *VectorTy) {
3302 unsigned NumLegalParts = TTI.getNumberOfParts(VectorTy);
3303 if (!NumLegalParts)
3304 return false;
3305 if (VF.isScalable()) {
3306 // <vscale x 1 x iN> is assumed to be profitable over iN because
3307 // scalable registers are a distinct register class from scalar
3308 // ones. If we ever find a target which wants to lower scalable
3309 // vectors back to scalars, we'll need to update this code to
3310 // explicitly ask TTI about the register class uses for each part.
3311 return NumLegalParts <= VF.getKnownMinValue();
3312 }
3313 // Two or more elements that share a register - are vectorized.
3314 return NumLegalParts < VF.getFixedValue();
3315 };
3316
3317 // If no def nor is a store, e.g., branches, continue - no value to check.
3318 if (R.getNumDefinedValues() == 0 &&
3320 continue;
3321 // For multi-def recipes, currently only interleaved loads, suffice to
3322 // check first def only.
3323 // For stores check their stored value; for interleaved stores suffice
3324 // the check first stored value only. In all cases this is the second
3325 // operand.
3326 VPValue *ToCheck =
3327 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
3328 Type *ScalarTy = ToCheck->getScalarType();
3329 if (!Visited.insert({ScalarTy}).second)
3330 continue;
3331 Type *WideTy = toVectorizedTy(ScalarTy, VF);
3332 if (any_of(getContainedTypes(WideTy), WillGenerateTargetVectors))
3333 return true;
3334 }
3335 }
3336
3337 return false;
3338}
3339
3340static bool hasReplicatorRegion(VPlan &Plan) {
3342 Plan.getVectorLoopRegion()->getEntry())),
3343 [](auto *VPRB) { return VPRB->isReplicator(); });
3344}
3345
3346/// Returns true if the VPlan contains a VPReductionPHIRecipe with
3347/// FindLast recurrence kind.
3348static bool hasFindLastReductionPhi(VPlan &Plan) {
3350 [](VPRecipeBase &R) {
3351 auto *RedPhi = dyn_cast<VPReductionPHIRecipe>(&R);
3352 return RedPhi &&
3353 RecurrenceDescriptor::isFindLastRecurrenceKind(
3354 RedPhi->getRecurrenceKind());
3355 });
3356}
3358 const ElementCount VF, const unsigned IC) const {
3359 // FIXME: We need a much better cost-model to take different parameters such
3360 // as register pressure, code size increase and cost of extra branches into
3361 // account. For now we apply a very crude heuristic and only consider loops
3362 // with vectorization factors larger than a certain value.
3363
3364 // Allow the target to opt out.
3365 if (!TTI.preferEpilogueVectorization(VF * IC))
3366 return false;
3367
3368 unsigned MinVFThreshold = EpilogueVectorizationMinVF.getNumOccurrences() > 0
3370 : TTI.getEpilogueVectorizationMinVF();
3371 return estimateElementCount(VF * IC, getVScaleForTuning()) >= MinVFThreshold;
3372}
3373
3375 VPlan &MainPlan, ElementCount MainLoopVF, unsigned IC,
3376 bool ScalarEpilogueAllowed) {
3378 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n");
3379 return nullptr;
3380 }
3381
3382 if (!ScalarEpilogueAllowed) {
3383 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because no "
3384 "epilogue is allowed.\n");
3385 return nullptr;
3386 }
3387
3388 if (vputils::findIncomingAliasMask(MainPlan)) {
3389 LLVM_DEBUG(
3390 dbgs()
3391 << "LEV: Epilogue vectorization not supported with alias masking.\n");
3392 return nullptr;
3393 }
3394
3395 // Not really a cost consideration, but check for unsupported cases here to
3396 // simplify the logic.
3397 if (!isCandidateForEpilogueVectorization(MainPlan)) {
3398 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because the loop "
3399 "is not a supported candidate.\n");
3400 return nullptr;
3401 }
3402
3403 if (hasForcedEpilogueVF()) {
3405 Config.getVScaleForTuning()) >=
3406 IC * estimateElementCount(MainLoopVF, Config.getVScaleForTuning())) {
3407 // Note that the main loop leaves IC * MainLoopVF iterations iff a scalar
3408 // epilogue is required, but then the epilogue loop also requires a scalar
3409 // epilogue.
3410 LLVM_DEBUG(dbgs() << "LEV: Forced epilogue VF results in dead epilogue "
3411 "vector loop, skipping vectorizing epilogue.\n");
3412 return nullptr;
3413 }
3414
3415 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n");
3417 std::unique_ptr<VPlan> Clone(
3419 Clone->setVF(EpilogueVectorizationForceVF);
3420 return Clone;
3421 }
3422
3423 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization forced factor is not "
3424 "viable.\n");
3425 return nullptr;
3426 }
3427
3428 if (OrigLoop->getHeader()->getParent()->hasOptSize()) {
3429 LLVM_DEBUG(
3430 dbgs() << "LEV: Epilogue vectorization skipped due to opt for size.\n");
3431 return nullptr;
3432 }
3433
3434 if (!Config.isEpilogueVectorizationProfitable(MainLoopVF, IC)) {
3435 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
3436 "this loop\n");
3437 return nullptr;
3438 }
3439
3440 // Check if a plan's vector loop processes fewer iterations than VF (e.g. when
3441 // interleave groups have been narrowed) narrowInterleaveGroups) and return
3442 // the adjusted, effective VF.
3443 using namespace VPlanPatternMatch;
3444 auto GetEffectiveVF = [](VPlan &Plan, ElementCount VF) -> ElementCount {
3445 auto *Exiting = Plan.getVectorLoopRegion()->getExitingBasicBlock();
3446 if (match(&Exiting->back(),
3447 m_BranchOnCount(m_Add(m_CanonicalIV(), m_Specific(&Plan.getUF())),
3448 m_VPValue())))
3449 return ElementCount::get(1, VF.isScalable());
3450 return VF;
3451 };
3452
3453 // Check if the main loop processes fewer than MainLoopVF elements per
3454 // iteration (e.g. due to narrowing interleave groups). Adjust MainLoopVF
3455 // as needed.
3456 MainLoopVF = GetEffectiveVF(MainPlan, MainLoopVF);
3457
3458 // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
3459 // the main loop handles 8 lanes per iteration. We could still benefit from
3460 // vectorizing the epilogue loop with VF=4.
3461 ElementCount EstimatedRuntimeVF = ElementCount::getFixed(
3462 estimateElementCount(MainLoopVF, Config.getVScaleForTuning()));
3463
3464 Type *TCType = Legal->getWidestInductionType();
3465 const SCEV *RemainingIterations = nullptr;
3466 unsigned MaxTripCount = 0;
3467 const SCEV *TC = vputils::getSCEVExprForVPValue(MainPlan.getTripCount(), PSE);
3468 assert(!isa<SCEVCouldNotCompute>(TC) && "Trip count SCEV must be computable");
3469 const SCEV *KnownMinTC;
3470 bool ScalableTC = match(TC, m_scev_c_Mul(m_SCEV(KnownMinTC), m_SCEVVScale()));
3471 bool ScalableRemIter = false;
3472 ScalarEvolution &SE = *PSE.getSE();
3473 // Use versions of TC and VF in which both are either scalable or fixed.
3474 if (ScalableTC == MainLoopVF.isScalable()) {
3475 ScalableRemIter = ScalableTC;
3476 RemainingIterations =
3477 SE.getURemExpr(TC, SE.getElementCount(TCType, MainLoopVF * IC));
3478 } else if (ScalableTC) {
3479 const SCEV *EstimatedTC = SE.getMulExpr(
3480 KnownMinTC,
3481 SE.getConstant(TCType, Config.getVScaleForTuning().value_or(1)));
3482 RemainingIterations = SE.getURemExpr(
3483 EstimatedTC, SE.getElementCount(TCType, MainLoopVF * IC));
3484 } else
3485 RemainingIterations =
3486 SE.getURemExpr(TC, SE.getElementCount(TCType, EstimatedRuntimeVF * IC));
3487
3488 // No iterations left to process in the epilogue.
3489 if (RemainingIterations->isZero())
3490 return nullptr;
3491
3492 if (MainLoopVF.isFixed()) {
3493 MaxTripCount = MainLoopVF.getFixedValue() * IC - 1;
3494 if (SE.isKnownPredicate(CmpInst::ICMP_ULT, RemainingIterations,
3495 SE.getConstant(TCType, MaxTripCount))) {
3496 MaxTripCount = SE.getUnsignedRangeMax(RemainingIterations).getZExtValue();
3497 }
3498 LLVM_DEBUG(dbgs() << "LEV: Maximum Trip Count for Epilogue: "
3499 << MaxTripCount << "\n");
3500 }
3501
3502 auto SkipVF = [&](const SCEV *VF, const SCEV *RemIter) -> bool {
3503 return SE.isKnownPredicate(CmpInst::ICMP_UGT, VF, RemIter);
3504 };
3506 VPlan *BestPlan = nullptr;
3507 for (auto &NextVF : ProfitableVFs) {
3508 // Skip candidate VFs without a corresponding VPlan.
3509 if (!hasPlanWithVF(NextVF.Width))
3510 continue;
3511
3512 VPlan &CurrentPlan = getPlanFor(NextVF.Width);
3513 ElementCount EffectiveVF = GetEffectiveVF(CurrentPlan, NextVF.Width);
3514 // Skip fixed vector VFs > than the estimated runtime VF, or any VF > than
3515 // the VF of the main loop.
3516 if ((!EffectiveVF.isScalable() && MainLoopVF.isScalable() &&
3517 ElementCount::isKnownGT(EffectiveVF, EstimatedRuntimeVF)) ||
3518 ElementCount::isKnownGT(EffectiveVF, MainLoopVF))
3519 continue;
3520
3521 // If EffectiveVF is greater than the number of remaining iterations, the
3522 // epilogue loop would be dead. Skip such factors. If the epilogue plan
3523 // also has narrowed interleave groups, use the effective VF since
3524 // the epilogue step will be reduced to its IC.
3525 // TODO: We should also consider comparing against a scalable
3526 // RemainingIterations when SCEV be able to evaluate non-canonical
3527 // vscale-based expressions.
3528 if (!ScalableRemIter) {
3529 // Handle the case where EffectiveVF and RemainingIterations are in
3530 // different numerical spaces.
3531 if (EffectiveVF.isScalable())
3532 EffectiveVF = ElementCount::getFixed(
3533 estimateElementCount(EffectiveVF, Config.getVScaleForTuning()));
3534 if (SkipVF(SE.getElementCount(TCType, EffectiveVF), RemainingIterations))
3535 continue;
3536 }
3537
3538 if (Result.Width.isScalar() ||
3539 isMoreProfitable(NextVF, Result, MaxTripCount,
3540 !MainPlan.hasTailFolded(),
3541 /*IsEpilogue*/ true)) {
3542 Result = NextVF;
3543 BestPlan = &CurrentPlan;
3544 }
3545 }
3546
3547 if (!BestPlan)
3548 return nullptr;
3549
3550 LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
3551 << Result.Width << "\n");
3552 std::unique_ptr<VPlan> Clone(BestPlan->duplicate());
3553 Clone->setVF(Result.Width);
3554 return Clone;
3555}
3556
3557unsigned
3559 InstructionCost LoopCost) {
3560 // -- The interleave heuristics --
3561 // We interleave the loop in order to expose ILP and reduce the loop overhead.
3562 // There are many micro-architectural considerations that we can't predict
3563 // at this level. For example, frontend pressure (on decode or fetch) due to
3564 // code size, or the number and capabilities of the execution ports.
3565 //
3566 // We use the following heuristics to select the interleave count:
3567 // 1. If the code has reductions, then we interleave to break the cross
3568 // iteration dependency.
3569 // 2. If the loop is really small, then we interleave to reduce the loop
3570 // overhead.
3571 // 3. We don't interleave if we think that we will spill registers to memory
3572 // due to the increased register pressure.
3573
3574 // Do not interleave tail-folded loops, as the overhead of multiple
3575 // instructions to calculate the predicate is likely not beneficial.
3576 // If an epilogue is not allowed for any other reason, do not interleave.
3577 if (!CM->isEpilogueAllowed())
3578 return 1;
3579
3582 LLVM_DEBUG(dbgs() << "LV: Loop requires variable-length step. "
3583 "Unroll factor forced to be 1.\n");
3584 return 1;
3585 }
3586
3587 // We used the distance for the interleave count.
3588 if (!Legal->isSafeForAnyVectorWidth())
3589 return 1;
3590
3591 // We don't attempt to perform interleaving for loops with uncountable early
3592 // exits because the VPInstruction::AnyOf code cannot currently handle
3593 // multiple parts.
3594 if (Plan.hasEarlyExit())
3595 return 1;
3596
3597 const bool HasReductions =
3600
3601 // FIXME: implement interleaving for FindLast transform correctly.
3602 if (hasFindLastReductionPhi(Plan))
3603 return 1;
3604
3605 VPRegisterUsage R = calculateRegisterUsageForPlan(Plan, {VF}, TTI)[0];
3606
3607 // If we did not calculate the cost for VF (because the user selected the VF)
3608 // then we calculate the cost of VF here.
3609 if (LoopCost == 0) {
3610 if (VF.isScalar())
3611 LoopCost = CM->expectedCost(VF);
3612 else
3613 LoopCost = cost(Plan, VF, &R);
3614 assert(LoopCost.isValid() && "Expected to have chosen a VF with valid cost");
3615
3616 // Loop body is free and there is no need for interleaving.
3617 if (LoopCost == 0)
3618 return 1;
3619 }
3620
3621 // We divide by these constants so assume that we have at least one
3622 // instruction that uses at least one register.
3623 for (auto &Pair : R.MaxLocalUsers) {
3624 Pair.second = std::max(Pair.second, 1U);
3625 }
3626
3627 // We calculate the interleave count using the following formula.
3628 // Subtract the number of loop invariants from the number of available
3629 // registers. These registers are used by all of the interleaved instances.
3630 // Next, divide the remaining registers by the number of registers that is
3631 // required by the loop, in order to estimate how many parallel instances
3632 // fit without causing spills. All of this is rounded down if necessary to be
3633 // a power of two. We want power of two interleave count to simplify any
3634 // addressing operations or alignment considerations.
3635 // We also want power of two interleave counts to ensure that the induction
3636 // variable of the vector loop wraps to zero, when tail is folded by masking;
3637 // this currently happens when OptForSize, in which case IC is set to 1 above.
3638 unsigned IC = UINT_MAX;
3639
3640 for (const auto &Pair : R.MaxLocalUsers) {
3641 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(Pair.first);
3642 LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
3643 << " registers of "
3644 << TTI.getRegisterClassName(Pair.first)
3645 << " register class\n");
3646 if (VF.isScalar()) {
3647 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
3648 TargetNumRegisters = ForceTargetNumScalarRegs;
3649 } else {
3650 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
3651 TargetNumRegisters = ForceTargetNumVectorRegs;
3652 }
3653 unsigned MaxLocalUsers = Pair.second;
3654 unsigned LoopInvariantRegs = 0;
3655 if (R.LoopInvariantRegs.contains(Pair.first))
3656 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
3657
3658 unsigned TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
3659 MaxLocalUsers);
3660 // Don't count the induction variable as interleaved.
3662 TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
3663 std::max(1U, (MaxLocalUsers - 1)));
3664 }
3665
3666 IC = std::min(IC, TmpIC);
3667 }
3668
3669 // Clamp the interleave ranges to reasonable counts.
3670 bool HasUnorderedReductions =
3671 HasReductions &&
3673 [](VPRecipeBase &R) {
3674 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
3675 return RedR && RedR->isOrdered();
3676 });
3677 unsigned MaxInterleaveCount =
3678 TTI.getMaxInterleaveFactor(VF, HasUnorderedReductions);
3679 LLVM_DEBUG(dbgs() << "LV: MaxInterleaveFactor for the target is "
3680 << MaxInterleaveCount << "\n");
3681
3682 // Check if the user has overridden the max.
3683 if (VF.isScalar()) {
3684 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
3685 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
3686 } else {
3687 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
3688 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
3689 }
3690
3691 // Try to get the exact trip count, or an estimate based on profiling data or
3692 // ConstantMax from PSE, failing that.
3693 auto BestKnownTC =
3694 getSmallBestKnownTC(PSE, OrigLoop,
3695 /*CanUseConstantMax=*/true,
3696 /*CanExcludeZeroTrips=*/CM->isEpilogueAllowed());
3697
3698 // For fixed length VFs treat a scalable trip count as unknown.
3699 if (BestKnownTC && (BestKnownTC->isFixed() || VF.isScalable())) {
3700 // Re-evaluate trip counts and VFs to be in the same numerical space.
3701 unsigned AvailableTC =
3702 estimateElementCount(*BestKnownTC, Config.getVScaleForTuning());
3703 unsigned EstimatedVF =
3704 estimateElementCount(VF, Config.getVScaleForTuning());
3705
3706 // At least one iteration must be scalar when this constraint holds. So the
3707 // maximum available iterations for interleaving is one less.
3708 if (Plan.requiresScalarEpilogue())
3709 --AvailableTC;
3710
3711 unsigned InterleaveCountLB = bit_floor(std::max(
3712 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
3713
3714 if (getSmallConstantTripCount(PSE.getSE(), OrigLoop).isNonZero()) {
3715 // If the best known trip count is exact, we select between two
3716 // prospective ICs, where
3717 //
3718 // 1) the aggressive IC is capped by the trip count divided by VF
3719 // 2) the conservative IC is capped by the trip count divided by (VF * 2)
3720 //
3721 // The final IC is selected in a way that the epilogue loop trip count is
3722 // minimized while maximizing the IC itself, so that we either run the
3723 // vector loop at least once if it generates a small epilogue loop, or
3724 // else we run the vector loop at least twice.
3725
3726 unsigned InterleaveCountUB = bit_floor(std::max(
3727 1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
3728 MaxInterleaveCount = InterleaveCountLB;
3729
3730 if (InterleaveCountUB != InterleaveCountLB) {
3731 unsigned TailTripCountUB =
3732 (AvailableTC % (EstimatedVF * InterleaveCountUB));
3733 unsigned TailTripCountLB =
3734 (AvailableTC % (EstimatedVF * InterleaveCountLB));
3735 // If both produce same scalar tail, maximize the IC to do the same work
3736 // in fewer vector loop iterations
3737 if (TailTripCountUB == TailTripCountLB)
3738 MaxInterleaveCount = InterleaveCountUB;
3739 }
3740 } else {
3741 // If trip count is an estimated compile time constant, limit the
3742 // IC to be capped by the trip count divided by VF * 2, such that the
3743 // vector loop runs at least twice to make interleaving seem profitable
3744 // when there is an epilogue loop present. Since exact Trip count is not
3745 // known we choose to be conservative in our IC estimate.
3746 MaxInterleaveCount = InterleaveCountLB;
3747 }
3748 }
3749
3750 assert(MaxInterleaveCount > 0 &&
3751 "Maximum interleave count must be greater than 0");
3752
3753 // Clamp the calculated IC to be between the 1 and the max interleave count
3754 // that the target and trip count allows.
3755 if (IC > MaxInterleaveCount)
3756 IC = MaxInterleaveCount;
3757 else
3758 // Make sure IC is greater than 0.
3759 IC = std::max(1u, IC);
3760
3761 assert(IC > 0 && "Interleave count must be greater than 0.");
3762
3763 // Interleave if we vectorized this loop and there is a reduction that could
3764 // benefit from interleaving.
3765 if (VF.isVector() && HasReductions) {
3766 LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
3767 return IC;
3768 }
3769
3770 // For any scalar loop that either requires runtime checks or tail-folding we
3771 // are better off leaving this to the unroller. Note that if we've already
3772 // vectorized the loop we will have done the runtime check and so interleaving
3773 // won't require further checks.
3774 bool ScalarInterleavingRequiresPredication =
3775 (VF.isScalar() && any_of(OrigLoop->blocks(), [this](BasicBlock *BB) {
3776 return Legal->blockNeedsPredication(BB);
3777 }));
3778 bool ScalarInterleavingRequiresRuntimePointerCheck =
3779 (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
3780
3781 // We want to interleave small loops in order to reduce the loop overhead and
3782 // potentially expose ILP opportunities.
3783 LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
3784 << "LV: IC is " << IC << '\n'
3785 << "LV: VF is " << VF << '\n');
3786 const bool AggressivelyInterleave =
3787 TTI.enableAggressiveInterleaving(HasReductions);
3788 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
3789 !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
3790 // We assume that the cost overhead is 1 and we use the cost model
3791 // to estimate the cost of the loop and interleave until the cost of the
3792 // loop overhead is about 5% of the cost of the loop.
3793 unsigned SmallIC = std::min(IC, (unsigned)llvm::bit_floor<uint64_t>(
3794 SmallLoopCost / LoopCost.getValue()));
3795
3796 // Interleave until store/load ports (estimated by max interleave count) are
3797 // saturated.
3798 unsigned NumStores = 0;
3799 unsigned NumLoads = 0;
3802 for (VPRecipeBase &R : *VPBB) {
3804 NumLoads++;
3805 continue;
3806 }
3808 NumStores++;
3809 continue;
3810 }
3811
3812 if (auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R)) {
3813 if (unsigned StoreOps = InterleaveR->getNumStoreOperands())
3814 NumStores += StoreOps;
3815 else
3816 NumLoads += InterleaveR->getNumDefinedValues();
3817 continue;
3818 }
3819 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
3820 NumLoads += isa<LoadInst>(RepR->getUnderlyingInstr());
3821 NumStores += isa<StoreInst>(RepR->getUnderlyingInstr());
3822 continue;
3823 }
3824 if (isa<VPHistogramRecipe>(&R)) {
3825 NumLoads++;
3826 NumStores++;
3827 continue;
3828 }
3829 }
3830 }
3831 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
3832 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
3833
3834 // There is little point in interleaving for reductions containing selects
3835 // and compares when VF=1 since it may just create more overhead than it's
3836 // worth for loops with small trip counts. This is because we still have to
3837 // do the final reduction after the loop.
3838 bool HasSelectCmpReductions =
3839 HasReductions &&
3841 [](VPRecipeBase &R) {
3842 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
3843 return RedR && (RecurrenceDescriptor::isAnyOfRecurrenceKind(
3844 RedR->getRecurrenceKind()) ||
3845 RecurrenceDescriptor::isFindIVRecurrenceKind(
3846 RedR->getRecurrenceKind()));
3847 });
3848 if (HasSelectCmpReductions) {
3849 LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
3850 return 1;
3851 }
3852
3853 // If we have a scalar reduction (vector reductions are already dealt with
3854 // by this point), we can increase the critical path length if the loop
3855 // we're interleaving is inside another loop. For tree-wise reductions
3856 // set the limit to 2, and for ordered reductions it's best to disable
3857 // interleaving entirely.
3858 if (HasReductions && OrigLoop->getLoopDepth() > 1) {
3859 bool HasOrderedReductions =
3861 [](VPRecipeBase &R) {
3862 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
3863
3864 return RedR && RedR->isOrdered();
3865 });
3866 if (HasOrderedReductions) {
3867 LLVM_DEBUG(
3868 dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
3869 return 1;
3870 }
3871
3872 unsigned F = MaxNestedScalarReductionIC;
3873 SmallIC = std::min(SmallIC, F);
3874 StoresIC = std::min(StoresIC, F);
3875 LoadsIC = std::min(LoadsIC, F);
3876 }
3877
3879 std::max(StoresIC, LoadsIC) > SmallIC) {
3880 LLVM_DEBUG(
3881 dbgs() << "LV: Interleaving to saturate store or load ports.\n");
3882 return std::max(StoresIC, LoadsIC);
3883 }
3884
3885 // If there are scalar reductions and TTI has enabled aggressive
3886 // interleaving for reductions, we will interleave to expose ILP.
3887 if (VF.isScalar() && AggressivelyInterleave) {
3888 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
3889 // Interleave no less than SmallIC but not as aggressive as the normal IC
3890 // to satisfy the rare situation when resources are too limited.
3891 return std::max(IC / 2, SmallIC);
3892 }
3893
3894 LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
3895 return SmallIC;
3896 }
3897
3898 // Interleave if this is a large loop (small loops are already dealt with by
3899 // this point) that could benefit from interleaving.
3900 if (AggressivelyInterleave) {
3901 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
3902 return IC;
3903 }
3904
3905 LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
3906 return 1;
3907}
3908
3910 Instruction *I, ElementCount VF) const {
3911 // TODO: Cost model for emulated masked load/store is completely
3912 // broken. This hack guides the cost model to use an artificially
3913 // high enough value to practically disable vectorization with such
3914 // operations, except where previously deployed legality hack allowed
3915 // using very low cost values. This is to avoid regressions coming simply
3916 // from moving "masked load/store" check from legality to cost model.
3917 // Masked Load/Gather emulation was previously never allowed.
3918 // Limited number of Masked Store/Scatter emulation was allowed.
3920 "Expecting a scalar emulated instruction");
3921 return isa<LoadInst>(I) ||
3922 (isa<StoreInst>(I) &&
3923 NumPredStores > NumberOfStoresToPredicate);
3924}
3925
3927 assert(VF.isVector() && "Expected VF >= 2");
3928
3929 // If we've already collected the instructions to scalarize or the predicated
3930 // BBs after vectorization, there's nothing to do. Collection may already have
3931 // occurred if we have a user-selected VF and are now computing the expected
3932 // cost for interleaving.
3933 if (InstsToScalarize.contains(VF) ||
3934 PredicatedBBsAfterVectorization.contains(VF))
3935 return;
3936
3937 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
3938 // not profitable to scalarize any instructions, the presence of VF in the
3939 // map will indicate that we've analyzed it already.
3940 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
3941
3942 // Find all the instructions that are scalar with predication in the loop and
3943 // determine if it would be better to not if-convert the blocks they are in.
3944 // If so, we also record the instructions to scalarize.
3945 for (BasicBlock *BB : TheLoop->blocks()) {
3947 continue;
3948 for (Instruction &I : *BB)
3949 if (isScalarWithPredication(&I, VF)) {
3950 ScalarCostsTy ScalarCosts;
3951 // Do not apply discount logic for:
3952 // 1. Scalars after vectorization, as there will only be a single copy
3953 // of the instruction.
3954 // 2. Scalable VF, as that would lead to invalid scalarization costs.
3955 // 3. Emulated masked memrefs, if a hacked cost is needed.
3956 if (!isScalarAfterVectorization(&I, VF) && !VF.isScalable() &&
3958 computePredInstDiscount(&I, ScalarCosts, VF) >= 0) {
3959 for (const auto &[I, IC] : ScalarCosts)
3960 ScalarCostsVF.insert({I, IC});
3961 }
3962 // Remember that BB will remain after vectorization.
3963 PredicatedBBsAfterVectorization[VF].insert(BB);
3964 for (auto *Pred : predecessors(BB)) {
3965 if (Pred->getSingleSuccessor() == BB)
3966 PredicatedBBsAfterVectorization[VF].insert(Pred);
3967 }
3968 }
3969 }
3970}
3971
3972InstructionCost LoopVectorizationCostModel::computePredInstDiscount(
3973 Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
3974 assert(!isUniformAfterVectorization(PredInst, VF) &&
3975 "Instruction marked uniform-after-vectorization will be predicated");
3976
3977 // Initialize the discount to zero, meaning that the scalar version and the
3978 // vector version cost the same.
3979 InstructionCost Discount = 0;
3980
3981 // Holds instructions to analyze. The instructions we visit are mapped in
3982 // ScalarCosts. Those instructions are the ones that would be scalarized if
3983 // we find that the scalar version costs less.
3985
3986 // Returns true if the given instruction can be scalarized.
3987 auto CanBeScalarized = [&](Instruction *I) -> bool {
3988 // We only attempt to scalarize instructions forming a single-use chain
3989 // from the original predicated block that would otherwise be vectorized.
3990 // Although not strictly necessary, we give up on instructions we know will
3991 // already be scalar to avoid traversing chains that are unlikely to be
3992 // beneficial.
3993 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
3994 isScalarAfterVectorization(I, VF))
3995 return false;
3996
3997 // If the instruction is scalar with predication, it will be analyzed
3998 // separately. We ignore it within the context of PredInst.
3999 if (isScalarWithPredication(I, VF))
4000 return false;
4001
4002 // If any of the instruction's operands are uniform after vectorization,
4003 // the instruction cannot be scalarized. This prevents, for example, a
4004 // masked load from being scalarized.
4005 //
4006 // We assume we will only emit a value for lane zero of an instruction
4007 // marked uniform after vectorization, rather than VF identical values.
4008 // Thus, if we scalarize an instruction that uses a uniform, we would
4009 // create uses of values corresponding to the lanes we aren't emitting code
4010 // for. This behavior can be changed by allowing getScalarValue to clone
4011 // the lane zero values for uniforms rather than asserting.
4012 for (Use &U : I->operands())
4013 if (auto *J = dyn_cast<Instruction>(U.get()))
4014 if (isUniformAfterVectorization(J, VF))
4015 return false;
4016
4017 // Otherwise, we can scalarize the instruction.
4018 return true;
4019 };
4020
4021 // Compute the expected cost discount from scalarizing the entire expression
4022 // feeding the predicated instruction. We currently only consider expressions
4023 // that are single-use instruction chains.
4024 Worklist.push_back(PredInst);
4025 while (!Worklist.empty()) {
4026 Instruction *I = Worklist.pop_back_val();
4027
4028 // If we've already analyzed the instruction, there's nothing to do.
4029 if (ScalarCosts.contains(I))
4030 continue;
4031
4032 // Cannot scalarize fixed-order recurrence phis at the moment.
4033 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
4034 continue;
4035
4036 // Compute the cost of the vector instruction. Note that this cost already
4037 // includes the scalarization overhead of the predicated instruction.
4038 InstructionCost VectorCost = getInstructionCost(I, VF);
4039
4040 // Compute the cost of the scalarized instruction. This cost is the cost of
4041 // the instruction as if it wasn't if-converted and instead remained in the
4042 // predicated block. We will scale this cost by block probability after
4043 // computing the scalarization overhead.
4044 InstructionCost ScalarCost =
4045 VF.getFixedValue() * getInstructionCost(I, ElementCount::getFixed(1));
4046
4047 // Compute the scalarization overhead of needed insertelement instructions
4048 // and phi nodes.
4049 if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
4050 Type *WideTy = toVectorizedTy(I->getType(), VF);
4051 for (Type *VectorTy : getContainedTypes(WideTy)) {
4052 ScalarCost += TTI.getScalarizationOverhead(
4054 /*Insert=*/true,
4055 /*Extract=*/false, Config.CostKind);
4056 }
4057 ScalarCost += VF.getFixedValue() *
4058 TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
4059 }
4060
4061 // Compute the scalarization overhead of needed extractelement
4062 // instructions. For each of the instruction's operands, if the operand can
4063 // be scalarized, add it to the worklist; otherwise, account for the
4064 // overhead.
4065 for (Use &U : I->operands())
4066 if (auto *J = dyn_cast<Instruction>(U.get())) {
4067 assert(canVectorizeTy(J->getType()) &&
4068 "Instruction has non-scalar type");
4069 if (CanBeScalarized(J))
4070 Worklist.push_back(J);
4071 else if (needsExtract(J, VF)) {
4072 Type *WideTy = toVectorizedTy(J->getType(), VF);
4073 for (Type *VectorTy : getContainedTypes(WideTy)) {
4074 ScalarCost += TTI.getScalarizationOverhead(
4075 cast<VectorType>(VectorTy),
4076 APInt::getAllOnes(VF.getFixedValue()), /*Insert*/ false,
4077 /*Extract*/ true, Config.CostKind);
4078 }
4079 }
4080 }
4081
4082 // Scale the total scalar cost by block probability.
4083 ScalarCost /= getPredBlockCostDivisor(Config.CostKind, I->getParent());
4084
4085 // Compute the discount. A non-negative discount means the vector version
4086 // of the instruction costs more, and scalarizing would be beneficial.
4087 Discount += VectorCost - ScalarCost;
4088 ScalarCosts[I] = ScalarCost;
4089 }
4090
4091 return Discount;
4092}
4093
4096 assert(VF.isScalar() && "must only be called for scalar VFs");
4097
4098 // For each block.
4099 for (BasicBlock *BB : TheLoop->blocks()) {
4100 InstructionCost BlockCost;
4101
4102 // For each instruction in the old loop.
4103 for (Instruction &I : *BB) {
4104 // Skip ignored values.
4105 if (ValuesToIgnore.count(&I) ||
4106 (VF.isVector() && VecValuesToIgnore.count(&I)))
4107 continue;
4108
4110
4111 // Check if we should override the cost.
4112 if (C.isValid() && ForceTargetInstructionCost.getNumOccurrences() > 0)
4114
4115 BlockCost += C;
4116 LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF "
4117 << VF << " For instruction: " << I << '\n');
4118 }
4119
4120 // In the scalar loop, we may not always execute the predicated block, if it
4121 // is an if-else block. Thus, scale the block's cost by the probability of
4122 // executing it. getPredBlockCostDivisor will return 1 for blocks that are
4123 // only predicated by the header mask when folding the tail.
4124 Cost += BlockCost / getPredBlockCostDivisor(Config.CostKind, BB);
4125 }
4126
4127 return Cost;
4128}
4129
4130/// Gets the address access SCEV for Ptr, if it should be used for cost modeling
4131/// according to isAddressSCEVForCost.
4132///
4133/// This SCEV can be sent to the Target in order to estimate the address
4134/// calculation cost.
4136 Value *Ptr,
4138 const Loop *TheLoop) {
4139 const SCEV *Addr = PSE.getSCEV(Ptr);
4140 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), TheLoop) ? Addr
4141 : nullptr;
4142}
4143
4145LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
4146 ElementCount VF) {
4147 assert(VF.isVector() &&
4148 "Scalarization cost of instruction implies vectorization.");
4149 if (VF.isScalable())
4150 return InstructionCost::getInvalid();
4151
4152 Type *ValTy = getLoadStoreType(I);
4153 auto *SE = PSE.getSE();
4154
4155 unsigned AS = getLoadStoreAddressSpace(I);
4157 Type *PtrTy = toVectorTy(Ptr->getType(), VF);
4158 // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
4159 // that it is being called from this specific place.
4160
4161 // Figure out whether the access is strided and get the stride value
4162 // if it's known in compile time
4163 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, PSE, TheLoop);
4164
4165 // Get the cost of the scalar memory instruction and address computation.
4167 VF.getFixedValue() *
4168 TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV, Config.CostKind);
4169
4170 // Don't pass *I here, since it is scalar but will actually be part of a
4171 // vectorized loop where the user of it is a vectorized instruction.
4173 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
4174 Cost += VF.getFixedValue() *
4175 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
4176 AS, Config.CostKind, OpInfo);
4177
4178 // Get the overhead of the extractelement and insertelement instructions
4179 // we might create due to scalarization.
4181
4182 // If we have a predicated load/store, it will need extra i1 extracts and
4183 // conditional branches, but may not be executed for each vector lane. Scale
4184 // the cost by the probability of executing the predicated block.
4185 if (isPredicatedInst(I)) {
4186 Cost /= getPredBlockCostDivisor(Config.CostKind, I->getParent());
4187
4188 // Add the cost of an i1 extract and a branch
4189 auto *VecI1Ty =
4190 VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
4192 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4193 /*Insert=*/false, /*Extract=*/true, Config.CostKind);
4194 Cost += TTI.getCFInstrCost(Instruction::CondBr, Config.CostKind);
4195
4196 if (useEmulatedMaskMemRefHack(I, VF))
4197 // Artificially setting to a high enough value to practically disable
4198 // vectorization with such operations.
4199 Cost = 3000000;
4200 }
4201
4202 return Cost;
4203}
4204
4205InstructionCost LoopVectorizationCostModel::getConsecutiveMemOpCost(
4206 Instruction *I, ElementCount VF, InstWidening Kind) {
4207 assert((Kind == CM_Widen || Kind == CM_Widen_Reverse) &&
4208 "Expected a consecutive widening decision");
4209 Type *ValTy = getLoadStoreType(I);
4210 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4211 unsigned AS = getLoadStoreAddressSpace(I);
4212
4215 if (isMaskRequired(I)) {
4216 unsigned IID = I->getOpcode() == Instruction::Load
4217 ? Intrinsic::masked_load
4218 : Intrinsic::masked_store;
4220 MemIntrinsicCostAttributes(IID, VectorTy, Alignment, AS),
4221 Config.CostKind);
4222 } else {
4223 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
4224 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
4225 Config.CostKind, OpInfo, I);
4226 }
4227
4228 if (Kind == CM_Widen_Reverse)
4230 VectorTy, Config.CostKind, {}, 0);
4231 return Cost;
4232}
4233
4235LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
4236 ElementCount VF) const {
4237 assert(isUniformMemOp(*I, VF));
4238
4239 Type *ValTy = getLoadStoreType(I);
4241 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4243 unsigned AS = getLoadStoreAddressSpace(I);
4244 if (isa<LoadInst>(I)) {
4245 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4246 Config.CostKind) +
4247 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
4248 Config.CostKind) +
4250 VectorTy, Config.CostKind);
4251 }
4252 StoreInst *SI = cast<StoreInst>(I);
4253
4254 bool IsLoopInvariantStoreValue = Legal->isInvariant(SI->getValueOperand());
4255 // TODO: We have existing tests that request the cost of extracting element
4256 // VF.getKnownMinValue() - 1 from a scalable vector. This does not represent
4257 // the actual generated code, which involves extracting the last element of
4258 // a scalable vector where the lane to extract is unknown at compile time.
4260 TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, Config.CostKind) +
4261 TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
4262 Config.CostKind);
4263 if (!IsLoopInvariantStoreValue)
4264 Cost += TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
4265 VectorTy, Config.CostKind, 0);
4266 return Cost;
4267}
4268
4270LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
4271 ElementCount VF) const {
4272 Type *ValTy = getLoadStoreType(I);
4273 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4276 Type *PtrTy = Ptr->getType();
4277
4278 if (!isUniform(Ptr, VF))
4279 PtrTy = toVectorTy(PtrTy, VF);
4280
4281 unsigned IID = I->getOpcode() == Instruction::Load
4282 ? Intrinsic::masked_gather
4283 : Intrinsic::masked_scatter;
4284 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4285 Config.CostKind) +
4287 MemIntrinsicCostAttributes(IID, VectorTy, Ptr, isMaskRequired(I),
4288 Alignment, I),
4289 Config.CostKind);
4290}
4291
4293LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
4294 ElementCount VF) const {
4295 const auto *Group = getInterleavedAccessGroup(I);
4296 assert(Group && "Fail to get an interleaved access group.");
4297
4298 Instruction *InsertPos = Group->getInsertPos();
4299 Type *ValTy = getLoadStoreType(InsertPos);
4300 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4301 unsigned AS = getLoadStoreAddressSpace(InsertPos);
4302
4303 unsigned InterleaveFactor = Group->getFactor();
4304 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4305
4306 // Holds the indices of existing members in the interleaved group.
4307 SmallVector<unsigned, 4> Indices;
4308 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4309 if (Group->getMember(IF))
4310 Indices.push_back(IF);
4311
4312 // Calculate the cost of the whole interleaved group.
4313 bool UseMaskForGaps =
4314 (Group->requiresScalarEpilogue() && !isEpilogueAllowed()) ||
4315 (isa<StoreInst>(I) && !Group->isFull());
4317 InsertPos->getOpcode(), WideVecTy, Group->getFactor(), Indices,
4318 Group->getAlign(), AS, Config.CostKind, isMaskRequired(I),
4319 UseMaskForGaps);
4320
4321 if (Group->isReverse()) {
4322 // TODO: Add support for reversed masked interleaved access.
4323 assert(!isMaskRequired(I) &&
4324 "Reverse masked interleaved access not supported.");
4325 Cost += Group->getNumMembers() *
4327 VectorTy, Config.CostKind, {}, 0);
4328 }
4329 return Cost;
4330}
4331
4333LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
4334 ElementCount VF) {
4335 // Calculate scalar cost only. Vectorization cost should be ready at this
4336 // moment.
4337 if (VF.isScalar()) {
4338 Type *ValTy = getLoadStoreType(I);
4341 unsigned AS = getLoadStoreAddressSpace(I);
4342
4343 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
4344 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4345 Config.CostKind) +
4346 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
4347 Config.CostKind, OpInfo, I);
4348 }
4349 return getWideningCost(I, VF);
4350}
4351
4353LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
4354 ElementCount VF) const {
4355
4356 // There is no mechanism yet to create a scalable scalarization loop,
4357 // so this is currently Invalid.
4358 if (VF.isScalable())
4359 return InstructionCost::getInvalid();
4360
4361 if (VF.isScalar())
4362 return 0;
4363
4365 Type *RetTy = toVectorizedTy(I->getType(), VF);
4366 if (!RetTy->isVoidTy() &&
4368
4370 if (isa<LoadInst>(I))
4371 VIC = TTI::VectorInstrContext::Load;
4372 else if (isa<StoreInst>(I))
4373 VIC = TTI::VectorInstrContext::Store;
4374
4375 for (Type *VectorTy : getContainedTypes(RetTy)) {
4378 /*Insert=*/true, /*Extract=*/false, Config.CostKind,
4379 /*ForPoisonSrc=*/true, {}, VIC);
4380 }
4381 }
4382
4383 // Some targets keep addresses scalar.
4385 return Cost;
4386
4387 // Some targets support efficient element stores.
4389 return Cost;
4390
4391 // Collect operands to consider.
4392 CallInst *CI = dyn_cast<CallInst>(I);
4393 Instruction::op_range Ops = CI ? CI->args() : I->operands();
4394
4395 // Skip operands that do not require extraction/scalarization and do not incur
4396 // any overhead.
4398 for (auto *V : filterExtractingOperands(Ops, VF))
4399 Tys.push_back(maybeVectorizeType(V->getType(), VF));
4400
4402 ? TTI::VectorInstrContext::Store
4404 return Cost +
4405 TTI.getOperandsScalarizationOverhead(Tys, Config.CostKind, OperandVIC);
4406}
4407
4409 if (VF.isScalar())
4410 return;
4411
4412 // TODO: We should generate better code and update the cost model for
4413 // predicated uniform stores. Today they are treated as any other
4414 // predicated store (see added test cases in
4415 // invariant-store-vectorization.ll).
4416 NumPredStores = 0;
4417 for (BasicBlock *BB : TheLoop->blocks())
4418 for (Instruction &I : *BB)
4420 ++NumPredStores;
4421
4422 for (BasicBlock *BB : TheLoop->blocks()) {
4423 // For each instruction in the old loop.
4424 for (Instruction &I : *BB) {
4426 if (!Ptr)
4427 continue;
4428
4429 if (isUniformMemOp(I, VF)) {
4430 auto IsLegalToScalarize = [&]() {
4431 if (!VF.isScalable())
4432 // Scalarization of fixed length vectors "just works".
4433 return true;
4434
4435 // We have dedicated lowering for unpredicated uniform loads and
4436 // stores. Note that even with tail folding we know that at least
4437 // one lane is active (i.e. generalized predication is not possible
4438 // here), and the logic below depends on this fact.
4439 if (!foldTailByMasking())
4440 return true;
4441
4442 // For scalable vectors, a uniform memop load is always
4443 // uniform-by-parts and we know how to scalarize that.
4444 if (isa<LoadInst>(I))
4445 return true;
4446
4447 // A uniform store isn't neccessarily uniform-by-part
4448 // and we can't assume scalarization.
4449 auto &SI = cast<StoreInst>(I);
4450 return TheLoop->isLoopInvariant(SI.getValueOperand());
4451 };
4452
4453 const InstructionCost GatherScatterCost =
4454 isLegalGatherOrScatter(&I, VF) ? getGatherScatterCost(&I, VF)
4456
4457 // Load: Scalar load + broadcast
4458 // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
4459 // FIXME: This cost is a significant under-estimate for tail folded
4460 // memory ops.
4461 const InstructionCost ScalarizationCost =
4462 IsLegalToScalarize() ? getUniformMemOpCost(&I, VF)
4464
4465 // Choose better solution for the current VF, Note that Invalid
4466 // costs compare as maximumal large. If both are invalid, we get
4467 // scalable invalid which signals a failure and a vectorization abort.
4468 if (GatherScatterCost < ScalarizationCost)
4469 setWideningDecision(&I, VF, CM_GatherScatter, GatherScatterCost);
4470 else
4471 setWideningDecision(&I, VF, CM_Scalarize, ScalarizationCost);
4472 continue;
4473 }
4474
4475 // We assume that widening is the best solution when possible.
4476 if (std::optional<InstWidening> Decision =
4478 setWideningDecision(&I, VF, *Decision,
4479 getConsecutiveMemOpCost(&I, VF, *Decision));
4480 continue;
4481 }
4482
4483 // Choose between Interleaving, Gather/Scatter or Scalarization.
4485 unsigned NumAccesses = 1;
4486 if (isAccessInterleaved(&I)) {
4487 const auto *Group = getInterleavedAccessGroup(&I);
4488 assert(Group && "Fail to get an interleaved access group.");
4489
4490 // Make one decision for the whole group.
4491 if (getWideningDecision(&I, VF) != CM_Unknown)
4492 continue;
4493
4494 NumAccesses = Group->getNumMembers();
4496 InterleaveCost = getInterleaveGroupCost(&I, VF);
4497 }
4498
4499 InstructionCost GatherScatterCost =
4501 ? getGatherScatterCost(&I, VF) * NumAccesses
4503
4504 InstructionCost ScalarizationCost =
4505 getMemInstScalarizationCost(&I, VF) * NumAccesses;
4506
4507 // Choose better solution for the current VF,
4508 // write down this decision and use it during vectorization.
4510 InstWidening Decision;
4511 if (InterleaveCost <= GatherScatterCost &&
4512 InterleaveCost < ScalarizationCost) {
4513 Decision = CM_Interleave;
4514 Cost = InterleaveCost;
4515 } else if (GatherScatterCost < ScalarizationCost) {
4516 Decision = CM_GatherScatter;
4517 Cost = GatherScatterCost;
4518 } else {
4519 Decision = CM_Scalarize;
4520 Cost = ScalarizationCost;
4521 }
4522 // If the instructions belongs to an interleave group, the whole group
4523 // receives the same decision. The whole group receives the cost, but
4524 // the cost will actually be assigned to one instruction.
4525 if (const auto *Group = getInterleavedAccessGroup(&I)) {
4526 if (Decision == CM_Scalarize) {
4527 for (Instruction *I : Group->members())
4528 setWideningDecision(I, VF, Decision,
4529 getMemInstScalarizationCost(I, VF));
4530 } else {
4531 setWideningDecision(Group, VF, Decision, Cost);
4532 }
4533 } else
4534 setWideningDecision(&I, VF, Decision, Cost);
4535 }
4536 }
4537
4538 // Make sure that any load of address and any other address computation
4539 // remains scalar unless there is gather/scatter support. This avoids
4540 // inevitable extracts into address registers, and also has the benefit of
4541 // activating LSR more, since that pass can't optimize vectorized
4542 // addresses.
4543 if (TTI.prefersVectorizedAddressing())
4544 return;
4545
4546 // Start with all scalar pointer uses.
4548 for (BasicBlock *BB : TheLoop->blocks())
4549 for (Instruction &I : *BB) {
4550 Instruction *PtrDef =
4552 if (PtrDef && TheLoop->contains(PtrDef) &&
4554 AddrDefs.insert(PtrDef);
4555 }
4556
4557 // Add all instructions used to generate the addresses.
4559 append_range(Worklist, AddrDefs);
4560 while (!Worklist.empty()) {
4561 Instruction *I = Worklist.pop_back_val();
4562 for (auto &Op : I->operands())
4563 if (auto *InstOp = dyn_cast<Instruction>(Op))
4564 if (TheLoop->contains(InstOp) && !isa<PHINode>(InstOp) &&
4565 AddrDefs.insert(InstOp))
4566 Worklist.push_back(InstOp);
4567 }
4568
4569 auto UpdateMemOpUserCost = [this, VF](LoadInst *LI) {
4570 // If there are direct memory op users of the newly scalarized load,
4571 // their cost may have changed because there's no scalarization
4572 // overhead for the operand. Update it.
4573 for (User *U : LI->users()) {
4575 continue;
4577 continue;
4580 getMemInstScalarizationCost(cast<Instruction>(U), VF));
4581 }
4582 };
4583 for (auto *I : AddrDefs) {
4584 if (isa<LoadInst>(I)) {
4585 // Setting the desired widening decision should ideally be handled in
4586 // by cost functions, but since this involves the task of finding out
4587 // if the loaded register is involved in an address computation, it is
4588 // instead changed here when we know this is the case.
4589 InstWidening Decision = getWideningDecision(I, VF);
4590 if (!isPredicatedInst(I) &&
4591 (Decision == CM_Widen || Decision == CM_Widen_Reverse ||
4592 (!isUniformMemOp(*I, VF) && Decision == CM_Scalarize))) {
4593 // Scalarize a widened load of address or update the cost of a scalar
4594 // load of an address.
4596 I, VF, CM_Scalarize,
4597 (VF.getKnownMinValue() *
4598 getMemoryInstructionCost(I, ElementCount::getFixed(1))));
4599 UpdateMemOpUserCost(cast<LoadInst>(I));
4600 } else if (const auto *Group = getInterleavedAccessGroup(I)) {
4601 // Scalarize all members of this interleaved group when any member
4602 // is used as an address. The address-used load skips scalarization
4603 // overhead, other members include it.
4604 for (Instruction *Member : Group->members()) {
4605 InstructionCost Cost = AddrDefs.contains(Member)
4606 ? (VF.getKnownMinValue() *
4607 getMemoryInstructionCost(
4608 Member, ElementCount::getFixed(1)))
4609 : getMemInstScalarizationCost(Member, VF);
4611 UpdateMemOpUserCost(cast<LoadInst>(Member));
4612 }
4613 }
4614 } else {
4615 // Cannot scalarize fixed-order recurrence phis at the moment.
4616 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
4617 continue;
4618
4619 // Make sure I gets scalarized and a cost estimate without
4620 // scalarization overhead.
4621 ForcedScalars[VF].insert(I);
4622 }
4623 }
4624}
4625
4627 if (!Legal->isInvariant(Op))
4628 return false;
4629 // Consider Op invariant, if it or its operands aren't predicated
4630 // instruction in the loop. In that case, it is not trivially hoistable.
4631 auto *OpI = dyn_cast<Instruction>(Op);
4632 return !OpI || !TheLoop->contains(OpI) ||
4633 (!isPredicatedInst(OpI) &&
4634 (!isa<PHINode>(OpI) || OpI->getParent() != TheLoop->getHeader()) &&
4635 all_of(OpI->operands(),
4636 [this](Value *Op) { return shouldConsiderInvariant(Op); }));
4637}
4638
4641 ElementCount VF) {
4642 // If we know that this instruction will remain uniform, check the cost of
4643 // the scalar version.
4645 VF = ElementCount::getFixed(1);
4646
4647 if (VF.isVector() && isProfitableToScalarize(I, VF))
4648 return InstsToScalarize[VF][I];
4649
4650 // Forced scalars do not have any scalarization overhead.
4651 auto ForcedScalar = ForcedScalars.find(VF);
4652 if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
4653 auto InstSet = ForcedScalar->second;
4654 if (InstSet.count(I))
4656 VF.getKnownMinValue();
4657 }
4658
4659 const auto &MinBWs = Config.getMinimalBitwidths();
4660 uint64_t InstrMinBWs = MinBWs.lookup(I);
4661 Type *RetTy = I->getType();
4663 RetTy = IntegerType::get(RetTy->getContext(), InstrMinBWs);
4664 auto *SE = PSE.getSE();
4665
4666 Type *VectorTy;
4667 if (isScalarAfterVectorization(I, VF)) {
4668 [[maybe_unused]] auto HasSingleCopyAfterVectorization =
4669 [this](Instruction *I, ElementCount VF) -> bool {
4670 if (VF.isScalar())
4671 return true;
4672
4673 auto Scalarized = InstsToScalarize.find(VF);
4674 assert(Scalarized != InstsToScalarize.end() &&
4675 "VF not yet analyzed for scalarization profitability");
4676 return !Scalarized->second.count(I) &&
4677 llvm::all_of(I->users(), [&](User *U) {
4678 auto *UI = cast<Instruction>(U);
4679 return !Scalarized->second.count(UI);
4680 });
4681 };
4682
4683 // With the exception of GEPs and PHIs, after scalarization there should
4684 // only be one copy of the instruction generated in the loop. This is
4685 // because the VF is either 1, or any instructions that need scalarizing
4686 // have already been dealt with by the time we get here. As a result,
4687 // it means we don't have to multiply the instruction cost by VF.
4688 assert(I->getOpcode() == Instruction::GetElementPtr ||
4689 I->getOpcode() == Instruction::PHI ||
4690 (I->getOpcode() == Instruction::BitCast &&
4691 I->getType()->isPointerTy()) ||
4692 HasSingleCopyAfterVectorization(I, VF));
4693 VectorTy = RetTy;
4694 } else
4695 VectorTy = toVectorizedTy(RetTy, VF);
4696
4697 if (VF.isVector() && VectorTy->isVectorTy() &&
4698 !TTI.getNumberOfParts(VectorTy))
4700
4701 // TODO: We need to estimate the cost of intrinsic calls.
4702 switch (I->getOpcode()) {
4703 case Instruction::GetElementPtr:
4704 // We mark this instruction as zero-cost because the cost of GEPs in
4705 // vectorized code depends on whether the corresponding memory instruction
4706 // is scalarized or not. Therefore, we handle GEPs with the memory
4707 // instruction cost.
4708 return 0;
4709 case Instruction::UncondBr:
4710 case Instruction::CondBr: {
4711 // In cases of scalarized and predicated instructions, there will be VF
4712 // predicated blocks in the vectorized loop. Each branch around these
4713 // blocks requires also an extract of its vector compare i1 element.
4714 // Note that the conditional branch from the loop latch will be replaced by
4715 // a single branch controlling the loop, so there is no extra overhead from
4716 // scalarization.
4717 bool ScalarPredicatedBB = false;
4719 if (VF.isVector() && BI &&
4720 (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
4721 PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))) &&
4722 BI->getParent() != TheLoop->getLoopLatch())
4723 ScalarPredicatedBB = true;
4724
4725 if (ScalarPredicatedBB) {
4726 // Not possible to scalarize scalable vector with predicated instructions.
4727 if (VF.isScalable())
4729 // Return cost for branches around scalarized and predicated blocks.
4730 auto *VecI1Ty =
4732 return (TTI.getScalarizationOverhead(
4733 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4734 /*Insert*/ false, /*Extract*/ true, Config.CostKind) +
4735 (TTI.getCFInstrCost(Instruction::CondBr, Config.CostKind) *
4736 VF.getFixedValue()));
4737 }
4738
4739 if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
4740 // The back-edge branch will remain, as will all scalar branches.
4741 return TTI.getCFInstrCost(Instruction::UncondBr, Config.CostKind);
4742
4743 // This branch will be eliminated by if-conversion.
4744 return 0;
4745 // Note: We currently assume zero cost for an unconditional branch inside
4746 // a predicated block since it will become a fall-through, although we
4747 // may decide in the future to call TTI for all branches.
4748 }
4749 case Instruction::Switch: {
4750 if (VF.isScalar())
4751 return TTI.getCFInstrCost(Instruction::Switch, Config.CostKind);
4752 auto *Switch = cast<SwitchInst>(I);
4753 return Switch->getNumCases() *
4754 TTI.getCmpSelInstrCost(
4755 Instruction::ICmp,
4756 toVectorTy(Switch->getCondition()->getType(), VF),
4757 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
4758 CmpInst::ICMP_EQ, Config.CostKind);
4759 }
4760 case Instruction::PHI: {
4761 auto *Phi = cast<PHINode>(I);
4762
4763 // First-order recurrences are replaced by vector shuffles inside the loop.
4764 if (VF.isVector() && Legal->isFixedOrderRecurrence(Phi)) {
4765 return TTI.getShuffleCost(
4767 cast<VectorType>(VectorTy), Config.CostKind, {}, -1);
4768 }
4769
4770 // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
4771 // converted into select instructions. We require N - 1 selects per phi
4772 // node, where N is the number of incoming values.
4773 if (VF.isVector() && Phi->getParent() != TheLoop->getHeader()) {
4774 Type *ResultTy = Phi->getType();
4775
4776 // All instructions in an Any-of reduction chain are narrowed to bool.
4777 // Check if that is the case for this phi node.
4778 auto *HeaderUser = cast_if_present<PHINode>(
4779 find_singleton<User>(Phi->users(), [this](User *U, bool) -> User * {
4780 auto *Phi = dyn_cast<PHINode>(U);
4781 if (Phi && Phi->getParent() == TheLoop->getHeader())
4782 return Phi;
4783 return nullptr;
4784 }));
4785 if (HeaderUser) {
4786 auto &ReductionVars = Legal->getReductionVars();
4787 auto Iter = ReductionVars.find(HeaderUser);
4788 if (Iter != ReductionVars.end() &&
4790 Iter->second.getRecurrenceKind()))
4791 ResultTy = Type::getInt1Ty(Phi->getContext());
4792 }
4793 return (Phi->getNumIncomingValues() - 1) *
4794 TTI.getCmpSelInstrCost(
4795 Instruction::Select, toVectorTy(ResultTy, VF),
4796 toVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
4797 CmpInst::BAD_ICMP_PREDICATE, Config.CostKind);
4798 }
4799
4800 // When tail folding with EVL, if the phi is part of an out of loop
4801 // reduction then it will be transformed into a wide vp_merge.
4802 if (VF.isVector() && foldTailWithEVL() &&
4803 Legal->getReductionVars().contains(Phi) &&
4804 !Config.isInLoopReduction(Phi)) {
4806 Intrinsic::vp_merge, toVectorTy(Phi->getType(), VF),
4807 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
4808 return TTI.getIntrinsicInstrCost(ICA, Config.CostKind);
4809 }
4810
4811 return TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
4812 }
4813 case Instruction::UDiv:
4814 case Instruction::SDiv:
4815 case Instruction::URem:
4816 case Instruction::SRem:
4817 if (VF.isVector() && isPredicatedInst(I)) {
4818 const auto [ScalarCost, MaskedCost] = getDivRemSpeculationCost(I, VF);
4819 return isDivRemScalarWithPredication(ScalarCost, MaskedCost) ? ScalarCost
4820 : MaskedCost;
4821 }
4822 // We've proven all lanes safe to speculate, fall through.
4823 [[fallthrough]];
4824 case Instruction::Add:
4825 case Instruction::Sub: {
4826 auto Info = Legal->getHistogramInfo(I);
4827 if (Info && VF.isVector()) {
4828 const HistogramInfo *HGram = Info.value();
4829 // Assume that a non-constant update value (or a constant != 1) requires
4830 // a multiply, and add that into the cost.
4832 ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1));
4833 if (!RHS || RHS->getZExtValue() != 1)
4834 MulCost = TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
4835 Config.CostKind);
4836
4837 // Find the cost of the histogram operation itself.
4838 Type *PtrTy = VectorType::get(HGram->Load->getPointerOperandType(), VF);
4839 Type *ScalarTy = I->getType();
4840 Type *MaskTy = VectorType::get(Type::getInt1Ty(I->getContext()), VF);
4841 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
4842 Type::getVoidTy(I->getContext()),
4843 {PtrTy, ScalarTy, MaskTy});
4844
4845 // Add the costs together with the add/sub operation.
4846 return TTI.getIntrinsicInstrCost(ICA, Config.CostKind) + MulCost +
4847 TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy,
4848 Config.CostKind);
4849 }
4850 [[fallthrough]];
4851 }
4852 case Instruction::FAdd:
4853 case Instruction::FSub:
4854 case Instruction::Mul:
4855 case Instruction::FMul:
4856 case Instruction::FDiv:
4857 case Instruction::FRem:
4858 case Instruction::Shl:
4859 case Instruction::LShr:
4860 case Instruction::AShr:
4861 case Instruction::And:
4862 case Instruction::Or:
4863 case Instruction::Xor: {
4864 // If we're speculating on the stride being 1, the multiplication may
4865 // fold away. We can generalize this for all operations using the notion
4866 // of neutral elements. (TODO)
4867 if (I->getOpcode() == Instruction::Mul &&
4868 ((TheLoop->isLoopInvariant(I->getOperand(0)) &&
4869 PSE.getSCEV(I->getOperand(0))->isOne()) ||
4870 (TheLoop->isLoopInvariant(I->getOperand(1)) &&
4871 PSE.getSCEV(I->getOperand(1))->isOne())))
4872 return 0;
4873
4874 // Certain instructions can be cheaper to vectorize if they have a constant
4875 // second vector operand. One example of this are shifts on x86.
4876 Value *Op2 = I->getOperand(1);
4877 if (!isa<Constant>(Op2) && TheLoop->isLoopInvariant(Op2) &&
4878 PSE.getSE()->isSCEVable(Op2->getType()) &&
4879 isa<SCEVConstant>(PSE.getSCEV(Op2))) {
4880 Op2 = cast<SCEVConstant>(PSE.getSCEV(Op2))->getValue();
4881 }
4882 auto Op2Info = TTI.getOperandInfo(Op2);
4883 if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue &&
4886
4887 SmallVector<const Value *, 4> Operands(I->operand_values());
4888 return TTI.getArithmeticInstrCost(
4889 I->getOpcode(), VectorTy, Config.CostKind,
4890 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
4891 Op2Info, Operands, I, TLI);
4892 }
4893 case Instruction::FNeg: {
4894 return TTI.getArithmeticInstrCost(
4895 I->getOpcode(), VectorTy, Config.CostKind,
4896 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
4897 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
4898 I->getOperand(0), I);
4899 }
4900 case Instruction::Select: {
4902 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4903 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4904
4905 const Value *Op0, *Op1;
4906 using namespace llvm::PatternMatch;
4907 if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
4908 match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
4909 // select x, y, false --> x & y
4910 // select x, true, y --> x | y
4911 const auto [Op1VK, Op1VP] = TTI::getOperandInfo(Op0);
4912 const auto [Op2VK, Op2VP] = TTI::getOperandInfo(Op1);
4913 assert(Op0->getType()->getScalarSizeInBits() == 1 &&
4914 Op1->getType()->getScalarSizeInBits() == 1);
4915
4916 return TTI.getArithmeticInstrCost(
4917 match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And,
4918 VectorTy, Config.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, {Op0, Op1},
4919 I);
4920 }
4921
4922 Type *CondTy = SI->getCondition()->getType();
4923 if (!ScalarCond)
4924 CondTy = VectorType::get(CondTy, VF);
4925
4927 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
4928 Pred = Cmp->getPredicate();
4929 return TTI.getCmpSelInstrCost(
4930 I->getOpcode(), VectorTy, CondTy, Pred, Config.CostKind,
4931 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
4932 }
4933 case Instruction::ICmp:
4934 case Instruction::FCmp: {
4935 Type *ValTy = I->getOperand(0)->getType();
4936
4938 [[maybe_unused]] Instruction *Op0AsInstruction =
4939 dyn_cast<Instruction>(I->getOperand(0));
4940 assert((!canTruncateToMinimalBitwidth(Op0AsInstruction, VF) ||
4941 InstrMinBWs == MinBWs.lookup(Op0AsInstruction)) &&
4942 "if both the operand and the compare are marked for "
4943 "truncation, they must have the same bitwidth");
4944 ValTy = IntegerType::get(ValTy->getContext(), InstrMinBWs);
4945 }
4946
4947 VectorTy = toVectorTy(ValTy, VF);
4948 return TTI.getCmpSelInstrCost(
4949 I->getOpcode(), VectorTy, CmpInst::makeCmpResultType(VectorTy),
4950 cast<CmpInst>(I)->getPredicate(), Config.CostKind,
4951 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
4952 }
4953 case Instruction::Store:
4954 case Instruction::Load: {
4955 ElementCount Width = VF;
4956 if (Width.isVector()) {
4957 InstWidening Decision = getWideningDecision(I, Width);
4958 assert(Decision != CM_Unknown &&
4959 "CM decision should be taken at this point");
4962 if (Decision == CM_Scalarize)
4963 Width = ElementCount::getFixed(1);
4964 }
4965 VectorTy = toVectorTy(getLoadStoreType(I), Width);
4966 return getMemoryInstructionCost(I, VF);
4967 }
4968 case Instruction::BitCast:
4969 if (I->getType()->isPointerTy())
4970 return 0;
4971 [[fallthrough]];
4972 case Instruction::ZExt:
4973 case Instruction::SExt:
4974 case Instruction::FPToUI:
4975 case Instruction::FPToSI:
4976 case Instruction::FPExt:
4977 case Instruction::PtrToInt:
4978 case Instruction::IntToPtr:
4979 case Instruction::SIToFP:
4980 case Instruction::UIToFP:
4981 case Instruction::Trunc:
4982 case Instruction::FPTrunc: {
4983 // Computes the CastContextHint from a Load/Store instruction.
4984 auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
4986 "Expected a load or a store!");
4987
4988 if (VF.isScalar() || !TheLoop->contains(I))
4990
4991 switch (getWideningDecision(I, VF)) {
5003 llvm_unreachable("Instr did not go through cost modelling?");
5006 }
5007
5008 llvm_unreachable("Unhandled case!");
5009 };
5010
5011 unsigned Opcode = I->getOpcode();
5013 // For Trunc, the context is the only user, which must be a StoreInst.
5014 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
5015 if (I->hasOneUse())
5016 if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
5017 CCH = ComputeCCH(Store);
5018 }
5019 // For Z/Sext, the context is the operand, which must be a LoadInst.
5020 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
5021 Opcode == Instruction::FPExt) {
5022 if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
5023 CCH = ComputeCCH(Load);
5024 }
5025
5026 // We optimize the truncation of induction variables having constant
5027 // integer steps. The cost of these truncations is the same as the scalar
5028 // operation.
5029 if (isOptimizableIVTruncate(I, VF)) {
5030 auto *Trunc = cast<TruncInst>(I);
5031 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
5032 Trunc->getSrcTy(), CCH, Config.CostKind,
5033 Trunc);
5034 }
5035
5036 Type *SrcScalarTy = I->getOperand(0)->getType();
5037 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
5038 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
5039 SrcScalarTy = IntegerType::get(SrcScalarTy->getContext(),
5040 MinBWs.lookup(Op0AsInstruction));
5041 Type *SrcVecTy =
5042 VectorTy->isVectorTy() ? toVectorTy(SrcScalarTy, VF) : SrcScalarTy;
5043
5045 // If the result type is <= the source type, there will be no extend
5046 // after truncating the users to the minimal required bitwidth.
5047 if (VectorTy->getScalarSizeInBits() <= SrcVecTy->getScalarSizeInBits() &&
5048 (I->getOpcode() == Instruction::ZExt ||
5049 I->getOpcode() == Instruction::SExt))
5050 return 0;
5051 }
5052
5053 return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH,
5054 Config.CostKind, I);
5055 }
5056 case Instruction::Call:
5057 return getVectorCallCost(cast<CallInst>(I), VF);
5058 case Instruction::ExtractValue:
5059 return TTI.getInstructionCost(I, Config.CostKind);
5060 case Instruction::Alloca:
5061 // We cannot easily widen alloca to a scalable alloca, as
5062 // the result would need to be a vector of pointers.
5063 if (VF.isScalable())
5065 return TTI.getArithmeticInstrCost(Instruction::Mul, RetTy, Config.CostKind);
5066 case Instruction::Freeze:
5067 return TTI::TCC_Free;
5068 default:
5069 // This opcode is unknown. Assume that it is the same as 'mul'.
5070 return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
5071 Config.CostKind);
5072 } // end of switch.
5073}
5074
5076 // Ignore ephemeral values.
5078
5079 SmallVector<Value *, 4> DeadInterleavePointerOps;
5081
5082 // If a scalar epilogue is required, users outside the loop won't use
5083 // live-outs from the vector loop but from the scalar epilogue. Ignore them if
5084 // that is the case.
5085 bool RequiresScalarEpilogue = requiresScalarEpilogue(true);
5086 auto IsLiveOutDead = [this, RequiresScalarEpilogue](User *U) {
5087 return RequiresScalarEpilogue &&
5088 !TheLoop->contains(cast<Instruction>(U)->getParent());
5089 };
5090
5092 DFS.perform(LI);
5093 for (BasicBlock *BB : reverse(make_range(DFS.beginRPO(), DFS.endRPO())))
5094 for (Instruction &I : reverse(*BB)) {
5095 if (VecValuesToIgnore.contains(&I) || ValuesToIgnore.contains(&I))
5096 continue;
5097
5098 // Add instructions that would be trivially dead and are only used by
5099 // values already ignored to DeadOps to seed worklist.
5101 all_of(I.users(), [this, IsLiveOutDead](User *U) {
5102 return VecValuesToIgnore.contains(U) ||
5103 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
5104 }))
5105 DeadOps.push_back(&I);
5106
5107 // For interleave groups, we only create a pointer for the start of the
5108 // interleave group. Queue up addresses of group members except the insert
5109 // position for further processing.
5110 if (isAccessInterleaved(&I)) {
5111 auto *Group = getInterleavedAccessGroup(&I);
5112 if (Group->getInsertPos() == &I)
5113 continue;
5114 Value *PointerOp = getLoadStorePointerOperand(&I);
5115 DeadInterleavePointerOps.push_back(PointerOp);
5116 }
5117
5118 // Queue branches for analysis. They are dead, if their successors only
5119 // contain dead instructions.
5120 if (isa<CondBrInst>(&I))
5121 DeadOps.push_back(&I);
5122 }
5123
5124 // Mark ops feeding interleave group members as free, if they are only used
5125 // by other dead computations.
5126 for (unsigned I = 0; I != DeadInterleavePointerOps.size(); ++I) {
5127 auto *Op = dyn_cast<Instruction>(DeadInterleavePointerOps[I]);
5128 if (!Op || !TheLoop->contains(Op) || any_of(Op->users(), [this](User *U) {
5129 Instruction *UI = cast<Instruction>(U);
5130 return !VecValuesToIgnore.contains(U) &&
5131 (!isAccessInterleaved(UI) ||
5132 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
5133 }))
5134 continue;
5135 VecValuesToIgnore.insert(Op);
5136 append_range(DeadInterleavePointerOps, Op->operands());
5137 }
5138
5139 // Mark ops that would be trivially dead and are only used by ignored
5140 // instructions as free.
5141 BasicBlock *Header = TheLoop->getHeader();
5142
5143 // Returns true if the block contains only dead instructions. Such blocks will
5144 // be removed by VPlan-to-VPlan transforms and won't be considered by the
5145 // VPlan-based cost model, so skip them in the legacy cost-model as well.
5146 auto IsEmptyBlock = [this](BasicBlock *BB) {
5147 return all_of(*BB, [this](Instruction &I) {
5148 return ValuesToIgnore.contains(&I) || VecValuesToIgnore.contains(&I) ||
5150 });
5151 };
5152 for (unsigned I = 0; I != DeadOps.size(); ++I) {
5153 auto *Op = dyn_cast<Instruction>(DeadOps[I]);
5154
5155 // Check if the branch should be considered dead.
5156 if (auto *Br = dyn_cast_or_null<CondBrInst>(Op)) {
5157 BasicBlock *ThenBB = Br->getSuccessor(0);
5158 BasicBlock *ElseBB = Br->getSuccessor(1);
5159 // Don't considers branches leaving the loop for simplification.
5160 if (!TheLoop->contains(ThenBB) || !TheLoop->contains(ElseBB))
5161 continue;
5162 bool ThenEmpty = IsEmptyBlock(ThenBB);
5163 bool ElseEmpty = IsEmptyBlock(ElseBB);
5164 if ((ThenEmpty && ElseEmpty) ||
5165 (ThenEmpty && ThenBB->getSingleSuccessor() == ElseBB &&
5166 ElseBB->phis().empty()) ||
5167 (ElseEmpty && ElseBB->getSingleSuccessor() == ThenBB &&
5168 ThenBB->phis().empty())) {
5169 VecValuesToIgnore.insert(Br);
5170 DeadOps.push_back(Br->getCondition());
5171 }
5172 continue;
5173 }
5174
5175 // Skip any op that shouldn't be considered dead.
5176 if (!Op || !TheLoop->contains(Op) ||
5177 (isa<PHINode>(Op) && Op->getParent() == Header) ||
5179 any_of(Op->users(), [this, IsLiveOutDead](User *U) {
5180 return !VecValuesToIgnore.contains(U) &&
5181 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
5182 }))
5183 continue;
5184
5185 // If all of Op's users are in ValuesToIgnore, add it to ValuesToIgnore
5186 // which applies for both scalar and vector versions. Otherwise it is only
5187 // dead in vector versions, so only add it to VecValuesToIgnore.
5188 if (all_of(Op->users(),
5189 [this](User *U) { return ValuesToIgnore.contains(U); }))
5190 ValuesToIgnore.insert(Op);
5191
5192 VecValuesToIgnore.insert(Op);
5193 append_range(DeadOps, Op->operands());
5194 }
5195
5196 // Ignore type-promoting instructions we identified during reduction
5197 // detection.
5198 for (const auto &Reduction : Legal->getReductionVars()) {
5199 const RecurrenceDescriptor &RedDes = Reduction.second;
5200 const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
5201 VecValuesToIgnore.insert_range(Casts);
5202 }
5203 // Ignore type-casting instructions we identified during induction
5204 // detection.
5205 for (const auto &Induction : Legal->getInductionVars()) {
5206 const InductionDescriptor &IndDes = Induction.second;
5207 VecValuesToIgnore.insert_range(IndDes.getCastInsts());
5208 }
5209}
5210
5211void LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
5212 CM->collectValuesToIgnore();
5213 Config.collectElementTypesForWidening(&CM->ValuesToIgnore);
5214
5215 FixedScalableVFPair MaxFactors = CM->computeMaxVF(UserVF, UserIC);
5216 if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
5217 return;
5218
5219 Config.collectInLoopReductions();
5220 // Cases that may be vectorized may be optimized by unit stride predicates.
5221 // TODO: Currently unit stride predicates are added unconditionally, even if
5222 // they are not used for the selected VF (e.g. when only interleaving).
5223 if (MaxFactors.FixedVF.isVector() || MaxFactors.ScalableVF.isVector())
5224 Legal->collectUnitStridePredicates();
5225
5226 auto VPlan1 = tryToBuildVPlan1();
5227 if (!VPlan1)
5228 return;
5229
5230 if (!OrigLoop->isInnermost()) {
5231 // For outer loops, computeMaxVF returns a single non-scalar VF; build a
5232 // plan for that VF only.
5233 ElementCount VF =
5234 MaxFactors.FixedVF ? MaxFactors.FixedVF : MaxFactors.ScalableVF;
5235 buildVPlans(*VPlan1, VF, VF);
5237 return;
5238 }
5239
5240 // Compute the minimal bitwidths required for integer operations in the loop
5241 // for later use by the cost model.
5242 Config.computeMinimalBitwidths();
5243
5244 // Invalidate interleave groups if all blocks of loop will be predicated.
5245 if (CM->blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
5247 LLVM_DEBUG(
5248 dbgs()
5249 << "LV: Invalidate all interleaved groups due to fold-tail by masking "
5250 "which requires masked-interleaved support.\n");
5251 if (CM->InterleaveInfo.invalidateGroups())
5252 // Invalidating interleave groups also requires invalidating all decisions
5253 // based on them, which includes widening decisions and uniform and scalar
5254 // values.
5255 CM->invalidateCostModelingDecisions();
5256 }
5257
5258 if (CM->foldTailByMasking())
5259 Legal->prepareToFoldTailByMasking();
5260
5261 ElementCount MaxUserVF =
5262 UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
5263 if (UserVF) {
5264 if (!ElementCount::isKnownLE(UserVF, MaxUserVF)) {
5266 "UserVF ignored because it may be larger than the maximal safe VF",
5267 "InvalidUserVF", ORE, OrigLoop);
5268 } else {
5270 "VF needs to be a power of two");
5271 // Collect the instructions (and their associated costs) that will be more
5272 // profitable to scalarize.
5273 CM->collectNonVectorizedAndSetWideningDecisions(UserVF);
5274 buildVPlans(*VPlan1, UserVF, UserVF);
5276 if (EpilogueUserVF.isVector() &&
5277 ElementCount::isKnownLT(EpilogueUserVF, UserVF)) {
5278 CM->collectNonVectorizedAndSetWideningDecisions(EpilogueUserVF);
5279 buildVPlans(*VPlan1, EpilogueUserVF, EpilogueUserVF);
5280 }
5281 if (!VPlans.empty() && VPlans.front()->getSingleVF() == UserVF) {
5282 // For scalar VF, skip VPlan cost check as VPlan cost is designed for
5283 // vector VFs only.
5284 if (UserVF.isScalar() ||
5285 cost(*VPlans.front(), UserVF, /*RU=*/nullptr).isValid()) {
5286 LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5288 return;
5289 }
5290 }
5291 VPlans.clear();
5292 reportVectorizationInfo("UserVF ignored because of invalid costs.",
5293 "InvalidCost", ORE, OrigLoop);
5294 }
5295 }
5296
5297 // Collect the Vectorization Factor Candidates.
5298 SmallVector<ElementCount> VFCandidates;
5299 for (auto VF = ElementCount::getFixed(1);
5300 ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
5301 VFCandidates.push_back(VF);
5302 for (auto VF = ElementCount::getScalable(1);
5303 ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
5304 VFCandidates.push_back(VF);
5305
5306 for (const auto &VF : VFCandidates) {
5307 // Collect Uniform and Scalar instructions after vectorization with VF.
5308 CM->collectNonVectorizedAndSetWideningDecisions(VF);
5309 }
5310
5311 buildVPlans(*VPlan1, ElementCount::getFixed(1), MaxFactors.FixedVF);
5312 buildVPlans(*VPlan1, ElementCount::getScalable(1), MaxFactors.ScalableVF);
5313
5315}
5316
5320 bool ReusePrintingSlotTracker)
5321 : TTI(Config.getTTI()), TLI(TLI), LLVMCtx(Plan.getContext()), CM(CM),
5323 L(Config.getLoop()) {
5324#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5325 if (ReusePrintingSlotTracker)
5326 PlanForSlotTracker = &Plan;
5327#endif
5328}
5329
5331 ElementCount VF) const {
5332 InstructionCost Cost = CM.getInstructionCost(UI, VF);
5333 if (Cost.isValid() && ForceTargetInstructionCost.getNumOccurrences())
5335 return Cost;
5336}
5337
5338bool VPCostContext::skipCostComputation(Instruction *UI, bool IsVector) const {
5339 return CM.ValuesToIgnore.contains(UI) ||
5340 (IsVector && CM.VecValuesToIgnore.contains(UI)) ||
5341 SkipCostComputation.contains(UI);
5342}
5343
5349
5351 return CM.getPredBlockCostDivisor(CostKind, BB);
5352}
5353
5355 return CM.isScalarWithPredication(I, VF) ||
5356 CM.isUniformAfterVectorization(I, VF) || CM.isForcedScalar(I, VF) ||
5357 (VF.isVector() && CM.isProfitableToScalarize(I, VF));
5358}
5359
5361 return CM.isMaskRequired(I);
5362}
5363
5367 return TC && TC->getValue().ule(VF.getKnownMinValue());
5368}
5369
5371LoopVectorizationPlanner::precomputeCosts(VPlan &Plan, ElementCount VF,
5372 VPCostContext &CostCtx) const {
5374 // Cost modeling for inductions is inaccurate in the legacy cost model
5375 // compared to the recipes that are generated. To match here initially during
5376 // VPlan cost model bring up directly use the induction costs from the legacy
5377 // cost model. Note that we do this as pre-processing; the VPlan may not have
5378 // any recipes associated with the original induction increment instruction
5379 // and may replace truncates with VPWidenIntOrFpInductionRecipe. We precompute
5380 // the cost of induction phis and increments (both that are represented by
5381 // recipes and those that are not), to avoid distinguishing between them here,
5382 // and skip all recipes that represent induction phis and increments (the
5383 // former case) later on, if they exist, to avoid counting them twice.
5384 // Similarly we pre-compute the cost of any optimized truncates.
5385 // Inductions that are represented by a VPWidenIntOrFpInductionRecipe are an
5386 // exception: their cost is computed by the recipe's computeCost (see below),
5387 // so they are not precomputed here.
5388 // TODO: Switch to more accurate costing based on VPlan.
5389
5390 // If the vector loop gets executed exactly once with the given VF, ignore the
5391 // costs of comparison and induction instructions, as they'll get simplified
5392 // away.
5393 // TODO: Remove this code after stepping away from the legacy cost model and
5394 // adding code to simplify VPlans before calculating their costs.
5395 auto TC = getSmallConstantTripCount(PSE.getSE(), OrigLoop);
5397 if (TC == VF && !Plan.hasTailFolded()) {
5398 addFullyUnrolledInstructionsToIgnore(OrigLoop, Legal->getInductionVars(),
5399 CostCtx.SkipCostComputation);
5400 } else {
5401 // Inductions represented by a VPWidenIntOrFpInductionRecipe have their cost
5402 // computed by the recipe, so collect their phis to skip the legacy
5403 // increment cost below.
5404 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
5405 for (VPRecipeBase &R : *LoopRegion->getEntryBasicBlock())
5406 if (auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) {
5407 if (PHINode *IVPhi = WideIV->getPHINode())
5408 WidenedIVs.insert(IVPhi);
5409 }
5410 }
5411
5412 for (const auto &[IV, IndDesc] : Legal->getInductionVars()) {
5413 // Integer inductions are always costed via the VPlan-based cost model.
5414 // TODO: Also migrate FP and pointer inductions.
5415 if (IndDesc.getKind() == InductionDescriptor::IK_IntInduction)
5416 continue;
5417 if (WidenedIVs.contains(IV))
5418 continue;
5420 IV->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
5421 SmallVector<Instruction *> IVInsts = {IVInc};
5422 for (unsigned I = 0; I != IVInsts.size(); I++) {
5423 for (Value *Op : IVInsts[I]->operands()) {
5424 auto *OpI = dyn_cast<Instruction>(Op);
5425 if (Op == IV || !OpI || !OrigLoop->contains(OpI) || !Op->hasOneUse())
5426 continue;
5427 IVInsts.push_back(OpI);
5428 }
5429 }
5430 IVInsts.push_back(IV);
5431 for (User *U : IV->users()) {
5432 auto *CI = cast<Instruction>(U);
5433 if (!CostCtx.CM.isOptimizableIVTruncate(CI, VF))
5434 continue;
5435 IVInsts.push_back(CI);
5436 }
5437
5438 for (Instruction *IVInst : IVInsts) {
5439 if (CostCtx.skipCostComputation(IVInst, VF.isVector()))
5440 continue;
5441 InstructionCost InductionCost = CostCtx.getLegacyCost(IVInst, VF);
5442 LLVM_DEBUG({
5443 dbgs() << "Cost of " << InductionCost << " for VF " << VF
5444 << ": induction instruction " << *IVInst << "\n";
5445 });
5446 Cost += InductionCost;
5447 CostCtx.SkipCostComputation.insert(IVInst);
5448 }
5449 }
5450
5451 // Pre-compute the costs for branches except for the backedge, as the number
5452 // of replicate regions in a VPlan may not directly match the number of
5453 // branches, which would lead to different decisions.
5454 // TODO: Compute cost of branches for each replicate region in the VPlan,
5455 // which is more accurate than the legacy cost model.
5456 for (BasicBlock *BB : OrigLoop->blocks()) {
5457 if (CostCtx.skipCostComputation(BB->getTerminator(), VF.isVector()))
5458 continue;
5459 CostCtx.SkipCostComputation.insert(BB->getTerminator());
5460 if (BB == OrigLoop->getLoopLatch())
5461 continue;
5462 auto BranchCost = CostCtx.getLegacyCost(BB->getTerminator(), VF);
5463 Cost += BranchCost;
5464 }
5465
5466 // Don't apply special costs when instruction cost is forced to make sure the
5467 // forced cost is used for each recipe.
5468 if (ForceTargetInstructionCost.getNumOccurrences())
5469 return Cost;
5470
5471 // Pre-compute costs for instructions that are forced-scalar or profitable to
5472 // scalarize. For most such instructions, their scalarization costs are
5473 // accounted for here using the legacy cost model. However, some opcodes
5474 // are excluded from these precomputed scalarization costs and are instead
5475 // modeled later by the VPlan cost model (see UseVPlanCostModel below).
5476 for (Instruction *ForcedScalar : CostCtx.CM.ForcedScalars[VF]) {
5477 if (CostCtx.skipCostComputation(ForcedScalar, VF.isVector()))
5478 continue;
5479 CostCtx.SkipCostComputation.insert(ForcedScalar);
5480 InstructionCost ForcedCost = CostCtx.getLegacyCost(ForcedScalar, VF);
5481 LLVM_DEBUG({
5482 dbgs() << "Cost of " << ForcedCost << " for VF " << VF
5483 << ": forced scalar " << *ForcedScalar << "\n";
5484 });
5485 Cost += ForcedCost;
5486 }
5487
5488 // Don't apply legacy scalarization costs if nothing remains scalar &
5489 // predicated.
5490 if (!hasReplicatorRegion(Plan))
5491 return Cost;
5492
5493 auto UseVPlanCostModel = [](Instruction *I) -> bool {
5494 switch (I->getOpcode()) {
5495 case Instruction::SDiv:
5496 case Instruction::UDiv:
5497 case Instruction::SRem:
5498 case Instruction::URem:
5499 return true;
5500 default:
5501 return false;
5502 }
5503 };
5504 for (const auto &[Scalarized, ScalarCost] : CostCtx.CM.InstsToScalarize[VF]) {
5505 if (UseVPlanCostModel(Scalarized) ||
5506 CostCtx.skipCostComputation(Scalarized, VF.isVector()))
5507 continue;
5508 CostCtx.SkipCostComputation.insert(Scalarized);
5509 LLVM_DEBUG({
5510 dbgs() << "Cost of " << ScalarCost << " for VF " << VF
5511 << ": profitable to scalarize " << *Scalarized << "\n";
5512 });
5513 Cost += ScalarCost;
5514 }
5515
5516 return Cost;
5517}
5518
5519InstructionCost LoopVectorizationPlanner::cost(VPlan &Plan, ElementCount VF,
5520 VPRegisterUsage *RU) const {
5521 VPCostContext CostCtx(*TLI, Plan, *CM, Config,
5522 /*ReusePrintingSlotTracker=*/true);
5523 InstructionCost Cost = precomputeCosts(Plan, VF, CostCtx);
5524
5525 // Now compute and add the VPlan-based cost.
5526 Cost += Plan.cost(VF, CostCtx);
5527
5528 // Add the cost of spills due to excess register usage
5529 if (RU && Config.shouldConsiderRegPressureForVF(VF))
5530 Cost += RU->spillCost(TTI, Config.CostKind, ForceTargetNumVectorRegs);
5531
5532#ifndef NDEBUG
5533 unsigned EstimatedWidth =
5534 estimateElementCount(VF, Config.getVScaleForTuning());
5535 LLVM_DEBUG(dbgs() << "Cost for VF " << VF << ": " << Cost
5536 << " (Estimated cost per lane: ");
5537 if (Cost.isValid()) {
5538 APFloat CostPerLane(APFloat::IEEEdouble());
5539 APFloat EstimatedWidthAsAPFloat(APFloat::IEEEdouble());
5540 (void)CostPerLane.convertFromAPInt(APInt(64, (uint64_t)Cost.getValue()),
5541 false, APFloat::rmTowardZero);
5542 (void)EstimatedWidthAsAPFloat.convertFromAPInt(
5543 APInt(64, (uint64_t)EstimatedWidth), false, APFloat::rmTowardZero);
5544 (void)CostPerLane.divide(EstimatedWidthAsAPFloat, APFloat::rmTowardZero);
5545
5546 SmallString<16> Str;
5547 CostPerLane.toString(Str, 3);
5548 LLVM_DEBUG(dbgs() << Str);
5549 } else /* No point dividing an invalid cost - it will still be invalid */
5550 LLVM_DEBUG(dbgs() << "Invalid");
5551 LLVM_DEBUG(dbgs() << ")\n");
5552#endif
5553 return Cost;
5554}
5555
5556std::pair<VectorizationFactor, VPlan *>
5558 if (VPlans.empty())
5559 return {VectorizationFactor::Disabled(), nullptr};
5560 // If there is a single VPlan with a single VF, return it directly.
5561 VPlan &FirstPlan = *VPlans[0];
5562
5563 ElementCount UserVF = Config.getHints().getWidth();
5564 if (VPlans.size() == 1) {
5565 // For outer loops, the plan has a single vector VF determined by the
5566 // heuristic.
5567 assert((FirstPlan.hasScalarVFOnly() || hasPlanWithVF(UserVF) ||
5568 FirstPlan.isOuterLoop()) &&
5569 "must have a single scalar VF, UserVF or an outer loop");
5570 return {VectorizationFactor(FirstPlan.getSingleVF(), 0, 0), &FirstPlan};
5571 }
5572
5573 if (hasPlanWithVF(UserVF) && hasForcedEpilogueVF() && VPlans.size() == 2) {
5574 assert(VPlans[0]->getSingleVF() == UserVF &&
5575 "expected second plan to be for the forced UserVF");
5576 assert(VPlans[1]->getSingleVF() == EpilogueVectorizationForceVF &&
5577 "expected first plan to be for the forced epilogue VF");
5578 return {VectorizationFactor(UserVF, 0, 0), VPlans[0].get()};
5579 }
5580
5581 LLVM_DEBUG(dbgs() << "LV: Computing best VF using cost kind: "
5582 << (Config.CostKind == TTI::TCK_RecipThroughput
5583 ? "Reciprocal Throughput\n"
5584 : Config.CostKind == TTI::TCK_Latency
5585 ? "Instruction Latency\n"
5586 : Config.CostKind == TTI::TCK_CodeSize ? "Code Size\n"
5587 : Config.CostKind == TTI::TCK_SizeAndLatency
5588 ? "Code Size and Latency\n"
5589 : "Unknown\n"));
5590
5592 assert(FirstPlan.hasVF(ScalarVF) &&
5593 "More than a single plan/VF w/o any plan having scalar VF");
5594
5595 // TODO: Compute scalar cost using VPlan-based cost model.
5596 InstructionCost ScalarCost = CM->expectedCost(ScalarVF);
5597 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ScalarCost << ".\n");
5598 VectorizationFactor ScalarFactor(ScalarVF, ScalarCost, ScalarCost);
5599 VectorizationFactor BestFactor = ScalarFactor;
5600
5601 bool ForceVectorization =
5602 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled;
5603 if (ForceVectorization) {
5604 // Ignore scalar width, because the user explicitly wants vectorization.
5605 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5606 // evaluation.
5607 BestFactor.Cost = InstructionCost::getMax();
5608 }
5609
5610 VPlan *PlanForBestVF = &FirstPlan;
5611
5612 for (auto &P : VPlans) {
5613 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
5614 P->vectorFactors().end());
5615
5617 bool ConsiderRegPressure = any_of(VFs, [this](ElementCount VF) {
5618 return Config.shouldConsiderRegPressureForVF(VF);
5619 });
5621 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI);
5622
5623 for (unsigned I = 0; I < VFs.size(); I++) {
5624 ElementCount VF = VFs[I];
5625 if (VF.isScalar())
5626 continue;
5627 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
5628 LLVM_DEBUG(
5629 dbgs()
5630 << "LV: Not considering vector loop of width " << VF
5631 << " because it will not generate any vector instructions.\n");
5632 continue;
5633 }
5634 if (Config.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
5635 LLVM_DEBUG(
5636 dbgs()
5637 << "LV: Not considering vector loop of width " << VF
5638 << " because it would cause replicated blocks to be generated,"
5639 << " which isn't allowed when optimizing for size.\n");
5640 continue;
5641 }
5642
5644 cost(*P, VF, ConsiderRegPressure ? &RUs[I] : nullptr);
5645 VectorizationFactor CurrentFactor(VF, Cost, ScalarCost);
5646
5647 if (isMoreProfitable(CurrentFactor, BestFactor, P->hasScalarTail())) {
5648 BestFactor = CurrentFactor;
5649 PlanForBestVF = P.get();
5650 }
5651
5652 // If profitable add it to ProfitableVF list.
5653 if (isMoreProfitable(CurrentFactor, ScalarFactor, P->hasScalarTail()))
5654 ProfitableVFs.push_back(CurrentFactor);
5655 }
5656 }
5657
5658 VPlan &BestPlan = *PlanForBestVF;
5659
5660 assert((BestFactor.Width.isScalar() || BestFactor.ScalarCost > 0) &&
5661 "when vectorizing, the scalar cost must be computed.");
5662
5663 LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << BestFactor.Width << ".\n");
5664 return {BestFactor, &BestPlan};
5665}
5666
5668 Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
5670 std::unique_ptr<LoopVectorizationCostModel> CM, VFSelectionContext &Config,
5673 : OrigLoop(L), LI(LI), DT(DT), TLI(TLI), TTI(TTI), Legal(Legal),
5674 CM(std::move(CM)), Config(Config), IAI(IAI), PSE(PSE), ORE(ORE) {}
5675
5677
5679
5681 ElementCount BestVF, unsigned BestUF, VPlan &BestVPlan,
5683 EpilogueVectorizationKind EpilogueVecKind) {
5684 assert(BestVPlan.hasVF(BestVF) &&
5685 "Trying to execute plan with unsupported VF");
5686 assert(BestVPlan.hasUF(BestUF) &&
5687 "Trying to execute plan with unsupported UF");
5688 if (BestVPlan.hasEarlyExit())
5689 ++LoopsEarlyExitVectorized;
5690
5692 *PSE.getSE(), TTI, Config.CostKind, BestVF, BestUF);
5693 // TODO: Move to VPlan transform stage once the transition to the VPlan-based
5694 // cost model is complete for better cost estimates.
5695 RUN_VPLAN_PASS(VPlanTransforms::unrollByUF, BestVPlan, BestUF);
5699 bool HasBranchWeights =
5700 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator());
5701 if (HasBranchWeights) {
5702 std::optional<unsigned> VScale = Config.getVScaleForTuning();
5704 BestVPlan, BestVF, VScale);
5705 }
5706
5707 if (vputils::findIncomingAliasMask(BestVPlan)) {
5708 assert(BestVPlan.hasTailFolded() && "Expected tail folding to be enabled");
5710 *Legal->getRuntimePointerChecking()->getDiffChecks(),
5711 HasBranchWeights);
5712 ++LoopsPartialAliasVectorized;
5713 }
5714
5715 // Retrieving VectorPH now when it's easier while VPlan still has Regions.
5716 VPBasicBlock *VectorPH = cast<VPBasicBlock>(BestVPlan.getVectorPreheader());
5717
5719 BestVF, BestUF, PSE);
5720 RUN_VPLAN_PASS(VPlanTransforms::optimizeForVFAndUF, BestVPlan, BestVF, BestUF,
5721 PSE);
5723 // Check if scalar epilogue is required, before simplifying constant branches.
5724 const bool RequiresScalarEpilogue = BestVPlan.requiresScalarEpilogue();
5725 if (EpilogueVecKind == EpilogueVectorizationKind::None)
5727 /*OnlyLatches=*/false);
5728 if (BestVPlan.getEntry()->getSingleSuccessor() ==
5729 BestVPlan.getScalarPreheader()) {
5730 // TODO: The vector loop would be dead, should not even try to vectorize.
5731 ORE->emit([&]() {
5732 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationDead",
5733 OrigLoop->getStartLoc(),
5734 OrigLoop->getHeader())
5735 << "Created vector loop never executes due to insufficient trip "
5736 "count.";
5737 });
5739 }
5740
5742
5744 // Convert the exit condition to AVLNext == 0 for EVL tail folded loops.
5746 // Regions are dissolved after optimizing for VF and UF, which completely
5747 // removes unneeded loop regions first.
5748 const bool HasTailFolded = BestVPlan.hasTailFolded();
5750 // Expand BranchOnTwoConds after dissolution, when latch has direct access to
5751 // its successors.
5753 // Convert loops with variable-length stepping after regions are dissolved.
5755 // Remove dead back-edges for single-iteration loops with BranchOnCond(true).
5756 // Only process loop latches to avoid removing edges from the middle block,
5757 // which may be needed for epilogue vectorization.
5759 /*OnlyLatches=*/true);
5761 VectorPH);
5762 std::optional<uint64_t> MaxRuntimeStep = getMaxRuntimeElementCount(
5763 BestVF * BestUF, *OrigLoop->getHeader()->getParent());
5764
5765 assert((LI->getUniqueLatchExitBlock(*OrigLoop) || RequiresScalarEpilogue) &&
5766 "loops not exiting via the latch without required epilogue?");
5768 VectorPH, HasTailFolded, RequiresScalarEpilogue,
5769 &BestVPlan.getVFxUF(), MaxRuntimeStep);
5771 BestVF);
5772 // Limit expansions to VPInstruction to when not vectorizing the epilogue.
5773 // Currently this code path still relies on code re-using SCEVs expanded
5774 // directly to IR instructions.
5775 if (EpilogueVecKind == EpilogueVectorizationKind::None)
5777 *PSE.getSE());
5780 // Removing branches and incoming values may expose additional simplification
5781 // opportunities.
5783 /*OnlyLatches=*/EpilogueVecKind !=
5786 RUN_VPLAN_PASS(VPlanTransforms::simplifyKnownEVL, BestVPlan, BestVF, PSE);
5787
5788 // 0. Generate SCEV-dependent code in the entry, including TripCount, before
5789 // making any changes to the CFG.
5790 DenseMap<const SCEV *, Value *> ExpandedSCEVs =
5791 RUN_VPLAN_PASS(VPlanTransforms::expandSCEVs, BestVPlan, *PSE.getSE());
5792
5793 // Perform the actual loop transformation.
5794 VPTransformState State(&TTI, BestVF, LI, DT, ILV.AC, ILV.Builder, &BestVPlan,
5795 OrigLoop->getParentLoop());
5796
5797#ifdef EXPENSIVE_CHECKS
5798 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
5799#endif
5800
5801 // 1. Set up the skeleton for vectorization, including vector pre-header and
5802 // middle block. The vector loop is created during VPlan execution.
5803 State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
5804 if (VPBasicBlock *ScalarPH = BestVPlan.getScalarPreheader())
5805 replaceVPBBWithIRVPBB(ScalarPH, State.CFG.PrevBB->getSingleSuccessor(),
5806 &BestVPlan);
5808
5809 assert(verifyVPlanIsValid(BestVPlan) && "final VPlan is invalid");
5810
5811 // After vectorization, the exit blocks of the original loop will have
5812 // additional predecessors. Invalidate SCEVs for the exit phis in case SE
5813 // looked through single-entry phis.
5814 ScalarEvolution &SE = *PSE.getSE();
5815 for (VPIRBasicBlock *Exit : BestVPlan.getExitBlocks()) {
5816 if (!Exit->hasPredecessors())
5817 continue;
5818 for (VPRecipeBase &PhiR : Exit->phis())
5820 &cast<VPIRPhi>(PhiR).getIRPhi());
5821 }
5822
5823 // Query whether the target wants loops it vectorizes to remain eligible for
5824 // runtime unrolling. Do this here, on the original loop and before its SCEV
5825 // is forgotten below.
5827 TTI.getUnrollingPreferences(OrigLoop, SE, UP, ORE);
5828 bool UnrollVectorizedLoop = UP.UnrollVectorizedLoop;
5829
5830 // Forget the original loop and block dispositions.
5831 SE.forgetLoop(OrigLoop);
5833
5835
5836 //===------------------------------------------------===//
5837 //
5838 // Notice: any optimization or new instruction that go
5839 // into the code below should also be implemented in
5840 // the cost-model.
5841 //
5842 //===------------------------------------------------===//
5843
5844 // Retrieve loop information before executing the plan, which may remove the
5845 // original loop, if it becomes unreachable.
5846 MDNode *LID = OrigLoop->getLoopID();
5847 unsigned OrigLoopInvocationWeight = 0;
5848 std::optional<unsigned> OrigAverageTripCount =
5849 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
5850
5851 BestVPlan.execute(&State);
5852
5853 // 2.6. Maintain Loop Hints
5854 // Keep all loop hints from the original loop on the vector loop (we'll
5855 // replace the vectorizer-specific hints below).
5856 VPBasicBlock *HeaderVPBB = vputils::getFirstLoopHeader(BestVPlan, State.VPDT);
5857 // Add metadata to disable runtime unrolling a scalar loop when there
5858 // are no runtime checks about strides and memory. A scalar loop that is
5859 // rarely used is not worth unrolling.
5860 bool DisableRuntimeUnroll = !ILV.RTChecks.hasChecks() && !BestVF.isScalar();
5862 HeaderVPBB ? LI->getLoopFor(State.CFG.VPBB2IRBB.lookup(HeaderVPBB))
5863 : nullptr,
5864 HeaderVPBB, BestVPlan,
5865 EpilogueVecKind == EpilogueVectorizationKind::Epilogue, LID,
5866 OrigAverageTripCount, OrigLoopInvocationWeight,
5867 estimateElementCount(BestVF * BestUF, Config.getVScaleForTuning()),
5868 DisableRuntimeUnroll, UnrollVectorizedLoop);
5869
5870 // 3. Fix the vectorized code: take care of header phi's, live-outs,
5871 // predication, updating analyses.
5872 ILV.fixVectorizedLoop(State);
5873
5875
5876 return ExpandedSCEVs;
5877}
5878
5879//===--------------------------------------------------------------------===//
5880// EpilogueVectorizerMainLoop
5881//===--------------------------------------------------------------------===//
5882
5884 LLVM_DEBUG({
5885 dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
5886 << "Main Loop VF:" << EPI.MainLoopVF
5887 << ", Main Loop UF:" << EPI.MainLoopUF
5888 << ", Epilogue Loop VF:" << EPI.EpilogueVF
5889 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
5890 });
5891}
5892
5895 dbgs() << "intermediate fn:\n"
5896 << *OrigLoop->getHeader()->getParent() << "\n";
5897 });
5898}
5899
5900//===--------------------------------------------------------------------===//
5901// EpilogueVectorizerEpilogueLoop
5902//===--------------------------------------------------------------------===//
5903
5904/// This function creates a new scalar preheader, using the previous one as
5905/// entry block to the epilogue VPlan. The minimum iteration check is being
5906/// represented in VPlan.
5908 BasicBlock *NewScalarPH = createScalarPreheader("vec.epilog.");
5909 BasicBlock *OriginalScalarPH = NewScalarPH->getSinglePredecessor();
5910 OriginalScalarPH->setName("vec.epilog.iter.check");
5911 VPIRBasicBlock *NewEntry = Plan.createVPIRBasicBlock(OriginalScalarPH);
5912 VPBasicBlock *OldEntry = Plan.getEntry();
5913 for (auto &R : make_early_inc_range(*OldEntry)) {
5914 // Skip moving VPIRInstructions (including VPIRPhis), which are unmovable by
5915 // defining.
5916 if (isa<VPIRInstruction>(&R))
5917 continue;
5918 R.moveBefore(*NewEntry, NewEntry->end());
5919 }
5920
5921 VPBlockUtils::reassociateBlocks(OldEntry, NewEntry);
5922 Plan.setEntry(NewEntry);
5923 // OldEntry is now dead and will be cleaned up when the plan gets destroyed.
5924
5925 return OriginalScalarPH;
5926}
5927
5929 LLVM_DEBUG({
5930 dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
5931 << "Epilogue Loop VF:" << EPI.EpilogueVF
5932 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
5933 });
5934}
5935
5938 dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
5939 });
5940}
5941
5943 return CM.isPredicatedInst(I);
5944}
5945
5947 return CM.TTI.prefersVectorizedAddressing();
5948}
5949
5951 VFRange &Range) {
5952 assert((VPI->getOpcode() == Instruction::Load ||
5953 VPI->getOpcode() == Instruction::Store) &&
5954 "Must be called with either a load or store");
5956
5957 auto WillWiden = [&](ElementCount VF) -> bool {
5959 CM.getWideningDecision(I, VF);
5961 "CM decision should be taken at this point.");
5963 return true;
5964 if (CM.isScalarAfterVectorization(I, VF) ||
5965 CM.isProfitableToScalarize(I, VF))
5966 return false;
5968 };
5969
5971 return nullptr;
5972
5973 // If a mask is not required, drop it - use unmasked version for safe loads.
5974 // TODO: Determine if mask is needed in VPlan.
5975 VPValue *Mask = CM.isMaskRequired(I) ? VPI->getMask() : nullptr;
5976
5977 // Determine if the pointer operand of the access is either consecutive or
5978 // reverse consecutive.
5980 CM.getWideningDecision(I, Range.Start);
5982 bool Consecutive =
5984
5985 VPValue *Ptr = VPI->getOpcode() == Instruction::Load ? VPI->getOperand(0)
5986 : VPI->getOperand(1);
5987 Builder.setInsertPoint(VPI);
5988 if (Consecutive) {
5989 Ptr = Builder.createConsecutiveVectorPointer(Ptr, getLoadStoreType(I),
5990 Reverse, VPI->getDebugLoc());
5991 }
5992
5993 if (Reverse && Mask)
5994 Mask = Builder.createNaryOp(VPInstruction::Reverse, Mask, I->getDebugLoc());
5995
5996 if (VPI->getOpcode() == Instruction::Load) {
5997 auto *Load = cast<LoadInst>(I);
5998 auto *LoadR = Builder.createWidenLoad(*Load, Ptr, Mask, Consecutive, *VPI,
5999 Load->getDebugLoc());
6000 if (Reverse)
6001 return Builder.createNaryOp(VPInstruction::Reverse, LoadR,
6002 LoadR->getDebugLoc());
6003 return LoadR;
6004 }
6005
6007 VPValue *StoredVal = VPI->getOperand(0);
6008 if (Reverse)
6009 StoredVal = Builder.createNaryOp(VPInstruction::Reverse, StoredVal,
6010 Store->getDebugLoc());
6011 return Builder.createWidenStore(*Store, Ptr, StoredVal, Mask, Consecutive,
6012 *VPI, Store->getDebugLoc());
6013}
6014
6016VPRecipeBuilder::tryToOptimizeInductionTruncate(VPInstruction *VPI,
6017 VFRange &Range) {
6018 auto *I = cast<TruncInst>(VPI->getUnderlyingInstr());
6019 // Optimize the special case where the source is a constant integer
6020 // induction variable. Notice that we can only optimize the 'trunc' case
6021 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
6022 // (c) other casts depend on pointer size.
6023
6024 // Determine whether \p K is a truncation based on an induction variable that
6025 // can be optimized.
6028 I),
6029 Range))
6030 return nullptr;
6031
6033 VPI->getOperand(0)->getDefiningRecipe());
6034 PHINode *Phi = WidenIV->getPHINode();
6035 VPValue *Start = WidenIV->getStartValue();
6036 const InductionDescriptor &IndDesc = WidenIV->getInductionDescriptor();
6037
6038 // Wrap flags from the original induction do not apply to the truncated type,
6039 // so do not propagate them.
6040 VPIRFlags Flags = VPIRFlags::WrapFlagsTy(false, false);
6041 VPValue *Step =
6044 Phi, Start, Step, &Plan.getVF(), IndDesc, I, Flags, VPI->getDebugLoc());
6045}
6046
6047bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
6049 "Instruction should have been handled earlier");
6050 // Instruction should be widened, unless it is scalar after vectorization,
6051 // scalarization is profitable or it is predicated.
6052 auto WillScalarize = [this, I](ElementCount VF) -> bool {
6053 return CM.isScalarAfterVectorization(I, VF) ||
6054 CM.isProfitableToScalarize(I, VF) ||
6055 CM.isScalarWithPredication(I, VF);
6056 };
6058 Range);
6059}
6060
6061VPRecipeWithIRFlags *VPRecipeBuilder::tryToWiden(VPInstruction *VPI) {
6062 auto *I = VPI->getUnderlyingInstr();
6063 switch (VPI->getOpcode()) {
6064 default:
6065 return nullptr;
6066 case Instruction::SDiv:
6067 case Instruction::UDiv:
6068 case Instruction::SRem:
6069 case Instruction::URem:
6070 // If not provably safe, use a masked intrinsic.
6071 if (CM.isPredicatedInst(I))
6072 return new VPWidenIntrinsicRecipe(
6074 I->getType(), {}, {}, VPI->getDebugLoc());
6075 [[fallthrough]];
6076 case Instruction::Add:
6077 case Instruction::And:
6078 case Instruction::AShr:
6079 case Instruction::FAdd:
6080 case Instruction::FCmp:
6081 case Instruction::FDiv:
6082 case Instruction::FMul:
6083 case Instruction::FNeg:
6084 case Instruction::FRem:
6085 case Instruction::FSub:
6086 case Instruction::ICmp:
6087 case Instruction::LShr:
6088 case Instruction::Mul:
6089 case Instruction::Or:
6090 case Instruction::Select:
6091 case Instruction::Shl:
6092 case Instruction::Sub:
6093 case Instruction::Xor:
6094 case Instruction::Freeze:
6095 return new VPWidenRecipe(*I, VPI->operandsWithoutMask(), *VPI, *VPI,
6096 VPI->getDebugLoc());
6097 case Instruction::ExtractValue: {
6099 auto *EVI = cast<ExtractValueInst>(I);
6100 assert(EVI->getNumIndices() == 1 && "Expected one extractvalue index");
6101 unsigned Idx = EVI->getIndices()[0];
6102 NewOps.push_back(Plan.getConstantInt(32, Idx));
6103 return new VPWidenRecipe(*I, NewOps, *VPI, *VPI, VPI->getDebugLoc());
6104 }
6105 };
6106}
6107
6109 if (VPI->getOpcode() != Instruction::Store)
6110 return nullptr;
6111
6112 auto HistInfo =
6113 Legal->getHistogramInfo(cast<StoreInst>(VPI->getUnderlyingInstr()));
6114 if (!HistInfo)
6115 return nullptr;
6116
6117 const HistogramInfo *HI = *HistInfo;
6118 // FIXME: Support other operations.
6119 unsigned Opcode = HI->Update->getOpcode();
6120 assert((Opcode == Instruction::Add || Opcode == Instruction::Sub) &&
6121 "Histogram update operation must be an Add or Sub");
6122
6124 // Bucket address.
6125 HGramOps.push_back(VPI->getOperand(1));
6126 // Increment value.
6127 HGramOps.push_back(Plan.getOrAddLiveIn(HI->Update->getOperand(1)));
6128
6129 // In case of predicated execution (due to tail-folding, or conditional
6130 // execution, or both), pass the relevant mask.
6131 if (CM.isMaskRequired(HI->Store))
6132 HGramOps.push_back(VPI->getMask());
6133
6134 return new VPHistogramRecipe(Opcode, HGramOps, cast<VPIRMetadata>(*VPI),
6135 VPI->getDebugLoc());
6136}
6137
6139 VPInstruction *VPI, VPBuilder &FinalRedStoresBuilder) {
6140 StoreInst *SI;
6141 if ((SI = dyn_cast<StoreInst>(VPI->getUnderlyingInstr())) &&
6142 Legal->isInvariantAddressOfReduction(SI->getPointerOperand())) {
6143 // Only create recipe for the final invariant store of the reduction.
6144 if (Legal->isInvariantStoreOfReduction(SI)) {
6145 VPValue *Val = VPI->getOperand(0);
6146 VPValue *Addr = VPI->getOperand(1);
6147 // We need to store the exiting value of the reduction, so use the blend
6148 // if tail folded.
6149 if (auto *Blend = VPlanPatternMatch::findUserOf<VPBlendRecipe>(Val))
6150 Val = Blend;
6151 [[maybe_unused]] auto *Rdx =
6153 assert((isa<VPIRValue>(Val) || !Rdx || Rdx->getBackedgeValue() == Val) &&
6154 "Store of reduction thats not the backedge value?");
6155 auto *Recipe = new VPReplicateRecipe(
6156 SI, {Val, Addr}, true /* IsUniform */, nullptr /*Mask*/, *VPI, *VPI,
6157 VPI->getDebugLoc());
6158 FinalRedStoresBuilder.insert(Recipe);
6159 }
6160 VPI->eraseFromParent();
6161 return true;
6162 }
6163
6164 return false;
6165}
6166
6168 VFRange &Range) {
6169 auto *I = VPI->getUnderlyingInstr();
6171 [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
6172 Range);
6173
6174 bool IsPredicated = CM.isPredicatedInst(I);
6175
6176 // Even if the instruction is not marked as uniform, there are certain
6177 // intrinsic calls that can be effectively treated as such, so we check for
6178 // them here. Conservatively, we only do this for scalable vectors, since
6179 // for fixed-width VFs we can always fall back on full scalarization.
6180 if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
6181 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
6182 case Intrinsic::assume:
6183 case Intrinsic::lifetime_start:
6184 case Intrinsic::lifetime_end:
6185 // For scalable vectors if one of the operands is variant then we still
6186 // want to mark as uniform, which will generate one instruction for just
6187 // the first lane of the vector. We can't scalarize the call in the same
6188 // way as for fixed-width vectors because we don't know how many lanes
6189 // there are.
6190 //
6191 // The reasons for doing it this way for scalable vectors are:
6192 // 1. For the assume intrinsic generating the instruction for the first
6193 // lane is still be better than not generating any at all. For
6194 // example, the input may be a splat across all lanes.
6195 // 2. For the lifetime start/end intrinsics the pointer operand only
6196 // does anything useful when the input comes from a stack object,
6197 // which suggests it should always be uniform. For non-stack objects
6198 // the effect is to poison the object, which still allows us to
6199 // remove the call.
6200 IsUniform = true;
6201 break;
6202 default:
6203 break;
6204 }
6205 }
6206 VPValue *BlockInMask = nullptr;
6207 if (!IsPredicated) {
6208 // Finalize the recipe for Instr, first if it is not predicated.
6209 LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
6210 } else {
6211 LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
6212 // Instructions marked for predication are replicated and a mask operand is
6213 // added initially. Masked replicate recipes will later be placed under an
6214 // if-then construct to prevent side-effects. Generate recipes to compute
6215 // the block mask for this region.
6216 BlockInMask = VPI->getMask();
6217 }
6218
6219 // Note that there is some custom logic to mark some intrinsics as uniform
6220 // manually above for scalable vectors, which this assert needs to account for
6221 // as well.
6222 assert((Range.Start.isScalar() || !IsUniform || !IsPredicated ||
6223 (Range.Start.isScalable() && isa<IntrinsicInst>(I))) &&
6224 "Should not predicate a uniform recipe");
6225 if (IsUniform) {
6227 VPI->getOpcode(), VPI->operandsWithoutMask(), BlockInMask, *VPI, *VPI,
6228 VPI->getDebugLoc(), I);
6229 }
6230 auto *Recipe = new VPReplicateRecipe(I, VPI->operandsWithoutMask(),
6231 /*IsSingleScalar=*/false, BlockInMask,
6232 *VPI, *VPI, VPI->getDebugLoc());
6233 return Recipe;
6234}
6235
6238 VFRange &Range) {
6239 assert(!R->isPhi() && "phis must be handled earlier");
6240 // First, check for specific widening recipes that deal with optimizing
6241 // truncates and memory operations.
6242 auto *VPI = cast<VPInstruction>(R);
6243 assert(VPI->getOpcode() != Instruction::Call &&
6244 "Call should have been handled by makeCallWideningDecisions");
6245
6246 VPRecipeBase *Recipe;
6247 if (VPI->getOpcode() == Instruction::Trunc &&
6248 (Recipe = tryToOptimizeInductionTruncate(VPI, Range)))
6249 return Recipe;
6250
6251 // All widen recipes below deal only with VF > 1.
6253 [&](ElementCount VF) { return VF.isScalar(); }, Range))
6254 return nullptr;
6255
6256 Instruction *Instr = R->getUnderlyingInstr();
6257 assert(!is_contained({Instruction::Load, Instruction::Store},
6258 VPI->getOpcode()) &&
6259 "Should have been handled prior to this!");
6260
6261 // We can only replicate an extractvalue if its operand generates per lane in
6262 // the same block, otherwise we would need to extract a lane from its struct
6263 // operand which is invalid.
6264 if (VPI->getOpcode() == Instruction::ExtractValue &&
6266 if (VPRecipeBase *OpR = VPI->getOperand(0)->getDefiningRecipe())
6268 OpR->getParent() != VPI->getParent())
6269 return tryToWiden(VPI);
6270
6271 if (!shouldWiden(Instr, Range))
6272 return nullptr;
6273
6274 if (VPI->getOpcode() == Instruction::GetElementPtr) {
6275 auto *GEP = cast<GetElementPtrInst>(Instr);
6276 return new VPWidenGEPRecipe(GEP->getSourceElementType(),
6277 VPI->operandsWithoutMask(), *VPI,
6278 VPI->getDebugLoc(), GEP);
6279 }
6280
6281 if (Instruction::isCast(VPI->getOpcode())) {
6282 auto *CI = cast<CastInst>(Instr);
6283 auto *CastR = cast<VPInstructionWithType>(VPI);
6284 return new VPWidenCastRecipe(CI->getOpcode(), VPI->getOperand(0),
6285 CastR->getResultType(), CI, *VPI, *VPI,
6286 VPI->getDebugLoc());
6287 }
6288
6289 return tryToWiden(VPI);
6290}
6291
6292// To allow RUN_VPLAN_PASS to print the VPlan after VF/UF independent
6293// optimizations.
6295
6296#ifndef NDEBUG
6297/// Cross-check vputils::computeExecutionFrequencies for the loop region of
6298/// \p Plan against BlockFrequencyInfo for the blocks of \p OrigLoop.
6299/// FIXME: Temporary verification aid, to be removed.
6300static bool verifyExecutionFrequenciesMatchBFI(VPlan &Plan, Loop *OrigLoop,
6301 LoopInfo *LI,
6303 // Limited to inner loops with the latch as only exiting block and no extra
6304 // VPBBs without a matching IR BB (as introduced by tail folding).
6305 if (Plan.isOuterLoop() ||
6306 OrigLoop->getExitingBlock() != OrigLoop->getLoopLatch() ||
6307 Plan.hasTailFolded())
6308 return true;
6309
6310 // Visit the region's blocks in the same order as introduceMasksAndLinearize.
6311 // Both are reverse post-orders of the same CFG, so indices correspond.
6315 assert(Blocks.size() == OrigLoop->getNumBlocks() &&
6316 "loop region and original loop must have the same blocks");
6317
6318 LoopBlocksRPO OrigRPO(OrigLoop);
6319 OrigRPO.perform(LI);
6320
6321 // Only request the expensive BFI once the cheap bail-outs are past.
6322 BlockFrequencyInfo &BFI = CM.getBFI();
6323 uint64_t HeaderFreq = BFI.getBlockFreq(OrigLoop->getHeader()).getFrequency();
6324 if (HeaderFreq == 0)
6325 return true;
6326
6327 // BFI's fixed-point mass propagation loses up to 1 ULP per edge, so bound the
6328 // error by the number of edges in the region.
6329 uint64_t Edges = 0;
6330 for (const VPBasicBlock *VPBB : Blocks)
6331 Edges += VPBB->getNumSuccessors();
6332 uint64_t Tolerance = Edges + BranchProbability::getDenominator() / HeaderFreq;
6333
6336 for (const auto &[VPBB, BB] :
6337 zip_equal(drop_begin(Blocks), drop_begin(OrigRPO))) {
6338 // Compare at BranchProbability's coarser resolution, which is as precise as
6339 // BFI's frequencies get.
6340 std::optional<BlockFrequency> Freq = Frequencies.lookup(VPBB);
6341 if (!Freq)
6342 continue;
6344
6345 // Clamp to the header's frequency, which BFI's rounding may exceed.
6348 std::min(BBFreq, HeaderFreq), HeaderFreq);
6349 if (AbsoluteDifference(Computed.getNumerator(), Expected.getNumerator()) <=
6350 Tolerance)
6351 continue;
6352
6353 errs() << "Block frequency mismatch for " << VPBB->getName() << ": VPlan "
6354 << Computed << ", BlockFrequencyInfo " << Expected << "\n";
6355 return false;
6356 }
6357 return true;
6358}
6359#endif
6360
6361VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan1() {
6362 bool IsInnerLoop = OrigLoop->isInnermost();
6363
6364 // Set up loop versioning for inner loops with memory runtime checks.
6365 // Outer loops don't have LoopAccessInfo since canVectorizeMemory() is not
6366 // called for them.
6367 std::optional<LoopVersioning> LVer;
6368 if (IsInnerLoop) {
6369 const LoopAccessInfo *LAI = Legal->getLAI();
6370 LVer.emplace(*LAI, LAI->getRuntimePointerChecking()->getChecks(), OrigLoop,
6371 LI, DT, PSE.getSE());
6372 if (!LAI->getRuntimePointerChecking()->getChecks().empty() &&
6374 // Only use noalias metadata when using memory checks guaranteeing no
6375 // overlap across all iterations.
6376 LVer->prepareNoAliasMetadata();
6377 }
6378 }
6379
6380 // Create initial base VPlan0, to serve as common starting point for all
6381 // candidates built later for specific VF ranges.
6382 auto VPlan0 = VPlanTransforms::buildVPlan0(OrigLoop, *LI,
6383 Legal->getWidestInductionType(),
6384 PSE, LVer ? &*LVer : nullptr);
6385
6386 VPDominatorTree VPDT(*VPlan0);
6387 if (const LoopAccessInfo *LAI = Legal->getLAI())
6389 LAI->getSymbolicStrides(), VPDT);
6392
6393 // Create recipes for header phis. For outer loops, reductions, recurrences
6394 // and in-loop reductions are empty since legality doesn't detect them.
6395 if (!RUN_VPLAN_PASS(
6396 VPlanTransforms::createHeaderPhiRecipes, *VPlan0, PSE, *OrigLoop,
6397 VPDT, Legal->getInductionVars(), Legal->getReductionVars(),
6398 Legal->getFixedOrderRecurrences(), Config.getInLoopReductions(),
6399 Config.getHints().allowReordering())) {
6400 return nullptr;
6401 }
6402
6403 if (const LoopAccessInfo *LAI = Legal->getLAI())
6405 LAI->getSymbolicStrides(), VPDT);
6406
6407 // Add surviving induction predicates to PSE and check constraints.
6408 bool ForceVectorization =
6409 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled;
6410 bool OptForSize =
6411 !ForceVectorization &&
6412 (CM->EpilogueLoweringStatus == CM_EpilogueNotAllowedOptSize ||
6413 CM->EpilogueLoweringStatus == CM_EpilogueNotAllowedLowTripLoop);
6414 unsigned SCEVCheckThreshold = ForceVectorization
6418 OptForSize, SCEVCheckThreshold, ORE, OrigLoop))
6419 return nullptr;
6420
6422
6423 // If we're vectorizing a loop with an uncountable exit, make sure that the
6424 // recipes are safe to handle.
6425 // TODO: Remove this once we can properly check the VPlan itself for both
6426 // the presence of an uncountable exit and the presence of stores in
6427 // the loop inside handleUncountableEarlyExits itself.
6428 if (Legal->hasUncountableEarlyExit()) {
6429 // TODO: Check target preference for style.
6430 UncountableExitStyle EEStyle =
6431 Legal->hasUncountableExitWithSideEffects()
6435 OrigLoop, PSE, *DT, Legal->getAssumptionCache(),
6436 EEStyle))
6437 return nullptr;
6438 } else {
6440 }
6441
6443 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()));
6444 if (CM->foldTailByMasking())
6446
6447 assert(verifyExecutionFrequenciesMatchBFI(*VPlan0, OrigLoop, LI, *CM) &&
6448 "execution frequencies do not match the loop's block frequencies");
6450
6451 return VPlan0;
6452}
6453
6454void LoopVectorizationPlanner::buildVPlans(VPlan &VPlan1, ElementCount MinVF,
6455 ElementCount MaxVF) {
6456 if (ElementCount::isKnownGT(MinVF, MaxVF))
6457 return;
6458
6459 auto MaxVFTimes2 = MaxVF * 2;
6460 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
6461 VFRange SubRange = {VF, MaxVFTimes2};
6462 auto Plan =
6463 tryToBuildVPlan(std::unique_ptr<VPlan>(VPlan1.duplicate()), SubRange);
6464 VF = SubRange.End;
6465
6466 if (!Plan)
6467 continue;
6468
6469 // Now optimize the initial VPlan.
6473 Config.getMinimalBitwidths());
6475 // TODO: try to put addExplicitVectorLength close to addActiveLaneMask
6476 if (CM->foldTailWithEVL()) {
6478 Config.getMaxSafeElements());
6480 }
6481
6482 if (auto P =
6484 VPlans.push_back(std::move(P));
6485
6486 TailFoldingStyle Style = CM->getTailFoldingStyle();
6488 useActiveLaneMask(Style),
6490
6492 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
6493 VPlans.push_back(std::move(Plan));
6494 }
6495}
6496
6497VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan(VPlanPtr Plan,
6498 VFRange &Range) {
6499
6500 // For outer loops, the plan only needs basic recipe conversion and induction
6501 // live-out optimization; the full inner-loop recipe building below does not
6502 // apply (no widening decisions, interleave groups, reductions, etc.).
6503 if (Plan->isOuterLoop()) {
6504 for (ElementCount VF : Range)
6505 Plan->addVF(VF);
6507 *Plan, *TLI, PSE, OrigLoop))
6508 return nullptr;
6510 OrigLoop);
6511 return Plan;
6512 }
6513
6514 using namespace llvm::VPlanPatternMatch;
6515 SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
6516
6517 // ---------------------------------------------------------------------------
6518 // Build initial VPlan: Scan the body of the loop in a topological order to
6519 // visit each basic block after having visited its predecessor basic blocks.
6520 // ---------------------------------------------------------------------------
6521
6522 bool RequiresScalarEpilogueCheck =
6524 [this](ElementCount VF) {
6525 return !CM->requiresScalarEpilogue(VF.isVector());
6526 },
6527 Range);
6528 // Update the branch in the middle block if a scalar epilogue is required.
6529 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
6530 if (!RequiresScalarEpilogueCheck && MiddleVPBB->getNumSuccessors() == 2) {
6531 auto *BranchOnCond = cast<VPInstruction>(MiddleVPBB->getTerminator());
6532 assert(MiddleVPBB->getSuccessors()[1] == Plan->getScalarPreheader() &&
6533 "second successor must be scalar preheader");
6534 BranchOnCond->setOperand(0, Plan->getFalse());
6535 }
6536
6537 // Don't use getDecisionAndClampRange here, because we don't know the UF
6538 // so this function is better to be conservative, rather than to split
6539 // it up into different VPlans.
6540 // TODO: Consider using getDecisionAndClampRange here to split up VPlans.
6541 bool IVUpdateMayOverflow = false;
6542 for (ElementCount VF : Range)
6543 IVUpdateMayOverflow |= !isIndvarOverflowCheckKnownFalse(CM.get(), VF);
6544
6545 TailFoldingStyle Style = CM->getTailFoldingStyle();
6546 // Use NUW for the induction increment if we proved that it won't overflow in
6547 // the vector loop or when not folding the tail. In the later case, we know
6548 // that the canonical induction increment will not overflow as the vector trip
6549 // count is >= increment and a multiple of the increment.
6550 VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
6551 bool HasNUW = !IVUpdateMayOverflow || Style == TailFoldingStyle::None;
6552 if (!HasNUW) {
6553 auto *IVInc =
6554 LoopRegion->getExitingBasicBlock()->getTerminator()->getOperand(0);
6555 assert(match(IVInc,
6556 m_VPInstruction<Instruction::Add>(
6557 m_Specific(LoopRegion->getCanonicalIV()), m_VPValue())) &&
6558 "Did not find the canonical IV increment");
6559 LoopRegion->clearCanonicalIVNUW(cast<VPInstruction>(IVInc));
6560 }
6561
6562 // ---------------------------------------------------------------------------
6563 // Pre-construction: record ingredients whose recipes we'll need to further
6564 // process after constructing the initial VPlan.
6565 // ---------------------------------------------------------------------------
6566
6567 // For each interleave group which is relevant for this (possibly trimmed)
6568 // Range, add it to the set of groups to be later applied to the VPlan and add
6569 // placeholders for its members' Recipes which we'll be replacing with a
6570 // single VPInterleaveRecipe.
6571 for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
6572 auto ApplyIG = [IG, this](ElementCount VF) -> bool {
6573 bool Result = (VF.isVector() && // Query is illegal for VF == 1
6574 CM->getWideningDecision(IG->getInsertPos(), VF) ==
6576 // For scalable vectors, the interleave factors must be <= 8 since we
6577 // require the (de)interleaveN intrinsics instead of shufflevectors.
6578 assert((!Result || !VF.isScalable() || IG->getFactor() <= 8) &&
6579 "Unsupported interleave factor for scalable vectors");
6580 return Result;
6581 };
6582 if (!getDecisionAndClampRange(ApplyIG, Range))
6583 continue;
6584 InterleaveGroups.insert(IG);
6585 }
6586
6587 // ---------------------------------------------------------------------------
6588 // Construct wide recipes and apply predication for original scalar
6589 // VPInstructions in the loop.
6590 // ---------------------------------------------------------------------------
6591 VPRecipeBuilder RecipeBuilder(*Plan, Legal, *CM, Builder);
6592
6593 // Scan the body of the loop in a topological order to visit each basic block
6594 // after having visited its predecessor basic blocks.
6595 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
6596 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> RPOT(
6597 HeaderVPBB);
6598
6600 Range.Start);
6601
6602 VPCostContext CostCtx(*TLI, *Plan, *CM, Config);
6603
6605 RecipeBuilder, CostCtx);
6606
6608
6610 RecipeBuilder, CostCtx);
6611
6612 // Now process all other blocks and instructions.
6613 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
6614 // Convert input VPInstructions to widened recipes.
6615 for (VPRecipeBase &R : make_early_inc_range(
6616 make_range(VPBB->getFirstNonPhi(), VPBB->end()))) {
6617 // Skip recipes that do not need transforming or have already been
6618 // transformed.
6619 if (isa<VPWidenCanonicalIVRecipe, VPBlendRecipe, VPReductionRecipe,
6620 VPReplicateRecipe, VPWidenLoadRecipe, VPWidenStoreRecipe,
6621 VPWidenCallRecipe, VPWidenIntrinsicRecipe, VPVectorPointerRecipe,
6622 VPVectorEndPointerRecipe, VPHistogramRecipe>(&R) ||
6625 vputils::onlyFirstLaneUsed(R.getVPSingleValue())))
6626 continue;
6627 auto *VPI = cast<VPInstruction>(&R);
6628 if (!VPI->getUnderlyingValue())
6629 continue;
6630
6631 // TODO: Gradually replace uses of underlying instruction by analyses on
6632 // VPlan. Migrate code relying on the underlying instruction from VPlan0
6633 // to construct recipes below to not use the underlying instruction.
6635 Builder.setInsertPoint(VPI);
6636
6637 VPRecipeBase *Recipe =
6638 RecipeBuilder.tryToCreateWidenNonPhiRecipe(VPI, Range);
6639 if (!Recipe)
6640 Recipe =
6641 RecipeBuilder.handleReplication(cast<VPInstruction>(VPI), Range);
6642
6643 if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) && isa<TruncInst>(Instr)) {
6644 // Optimized a truncate to VPWidenIntOrFpInductionRecipe. It needs to be
6645 // moved to the phi section in the header.
6646 Recipe->insertBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
6647 } else {
6648 Builder.insert(Recipe);
6649 }
6650 if (Recipe->getNumDefinedValues() == 1) {
6651 VPI->replaceAllUsesWith(Recipe->getVPSingleValue());
6652 } else {
6653 assert(Recipe->getNumDefinedValues() == 0 &&
6654 "Unexpected multidef recipe");
6655 }
6656 R.eraseFromParent();
6657 }
6658 }
6659
6660 assert(isa<VPRegionBlock>(LoopRegion) &&
6661 !LoopRegion->getEntryBasicBlock()->empty() &&
6662 "entry block must be set to a VPRegionBlock having a non-empty entry "
6663 "VPBasicBlock");
6664
6666 Range);
6667
6668 // ---------------------------------------------------------------------------
6669 // Transform initial VPlan: Apply previously taken decisions, in order, to
6670 // bring the VPlan to its final state.
6671 // ---------------------------------------------------------------------------
6672
6673 addReductionResultComputation(Plan, RecipeBuilder, Range.Start);
6674
6675 // Optimize FindIV reductions to use sentinel-based approach when possible.
6677 *OrigLoop);
6679 OrigLoop);
6680
6681 // Apply mandatory transformation to handle reductions with multiple in-loop
6682 // uses if possible, bail out otherwise.
6684 OrigLoop))
6685 return nullptr;
6686 // Apply mandatory transformation to handle FP maxnum/minnum reduction with
6687 // NaNs if possible, bail out otherwise.
6689 return nullptr;
6690
6691 // Create whole-vector selects for find-last recurrences.
6693 return nullptr;
6694
6696
6697 // Create partial reduction recipes for scaled reductions and transform
6698 // recipes to abstract recipes if it is legal and beneficial and clamp the
6699 // range for better cost estimation.
6701 Range);
6703 Range);
6704
6705 // Interleave memory: for each Interleave Group we marked earlier as relevant
6706 // for this VPlan, replace the Recipes widening its memory instructions with a
6707 // single VPInterleaveRecipe at its insertion point.
6709 InterleaveGroups, CM->isEpilogueAllowed());
6710
6711 // Convert memory recipes to strided access recipes if the strided access is
6712 // legal and profitable.
6714 *OrigLoop, CostCtx, Range);
6715
6716 // Ensure scalar VF plans only contain VF=1, as required by hasScalarVFOnly.
6717 if (Range.Start.isScalar())
6718 Range.End = Range.Start * 2;
6719
6720 for (ElementCount VF : Range)
6721 Plan->addVF(VF);
6722 Plan->setName("Initial VPlan");
6723
6725
6726 if (CM->maskPartialAliasing())
6728
6729 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
6730 return Plan;
6731}
6732
6733void LoopVectorizationPlanner::addReductionResultComputation(
6734 VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
6735 using namespace VPlanPatternMatch;
6736 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
6737 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
6738 VPBasicBlock *LatchVPBB = VectorLoopRegion->getExitingBasicBlock();
6739 Builder.setInsertPoint(&*std::prev(std::prev(LatchVPBB->end())));
6740 VPBasicBlock::iterator IP = MiddleVPBB->getFirstNonPhi();
6741 VPValue *HeaderMask = Plan->getVectorLoopRegion()->getHeaderMask();
6742 for (VPRecipeBase &R :
6743 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
6744 VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
6745 if (!PhiR)
6746 continue;
6747
6748 RecurKind RecurrenceKind = PhiR->getRecurrenceKind();
6749 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(
6751 Type *PhiTy = PhiR->getScalarType();
6752
6753 // Convert a VPBlendRecipe backedge to a select.
6754 if (auto *Blend = dyn_cast<VPBlendRecipe>(PhiR->getBackedgeValue())) {
6755 if (Blend->getNumIncomingValues() == 2 &&
6756 Blend->getMask(0) == HeaderMask) {
6757 auto *Sel = VPBuilder(Blend).createSelect(
6758 Blend->getMask(0), Blend->getIncomingValue(0),
6759 Blend->getIncomingValue(1), {}, "", *Blend);
6760 Blend->replaceAllUsesWith(Sel);
6761 Blend->eraseFromParent();
6762 }
6763 }
6764
6765 auto *OrigExitingVPV = PhiR->getBackedgeValue();
6766 auto *NewExitingVPV = OrigExitingVPV;
6767
6768 // Remove the predicated select if the target doesn't want it.
6769 VPValue *V;
6770 if (!CM->usePredicatedReductionSelect(RecurrenceKind) &&
6771 match(PhiR->getBackedgeValue(),
6772 m_Select(m_Specific(HeaderMask), m_VPValue(V), m_Specific(PhiR))))
6773 PhiR->setBackedgeValue(V);
6774
6775 // We want code in the middle block to appear to execute on the location of
6776 // the scalar loop's latch terminator because: (a) it is all compiler
6777 // generated, (b) these instructions are always executed after evaluating
6778 // the latch conditional branch, and (c) other passes may add new
6779 // predecessors which terminate on this line. This is the easiest way to
6780 // ensure we don't accidentally cause an extra step back into the loop while
6781 // debugging.
6782 DebugLoc ExitDL = OrigLoop->getLoopLatch()->getTerminator()->getDebugLoc();
6783
6784 // TODO: At the moment ComputeReductionResult also drives creation of the
6785 // bc.merge.rdx phi nodes, hence it needs to be created unconditionally here
6786 // even for in-loop reductions, until the reduction resume value handling is
6787 // also modeled in VPlan.
6788 VPInstruction *FinalReductionResult;
6789 VPBuilder::InsertPointGuard Guard(Builder);
6790 Builder.setInsertPoint(MiddleVPBB, IP);
6791 // For AnyOf reductions, find the select among PhiR's users and convert
6792 // the reduction phi to operate on bools before creating the final
6793 // reduction result.
6794 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
6795 auto *AnyOfSelect = cast<VPSingleDefRecipe>(
6797 VPValue *Start = PhiR->getStartValue();
6798 bool TrueValIsPhi = AnyOfSelect->getOperand(1) == PhiR;
6799 // NewVal is the non-phi operand of the select.
6800 VPValue *NewVal = TrueValIsPhi ? AnyOfSelect->getOperand(2)
6801 : AnyOfSelect->getOperand(1);
6802
6803 // Adjust AnyOf reductions; replace the reduction phi for the selected
6804 // value with a boolean reduction phi node to check if the condition is
6805 // true in any iteration. The final value is selected by the final
6806 // ComputeReductionResult.
6807 VPValue *Cmp = AnyOfSelect->getOperand(0);
6808 // If the compare is checking the reduction PHI node, adjust it to check
6809 // the start value.
6810 if (VPRecipeBase *CmpR = Cmp->getDefiningRecipe())
6811 CmpR->replaceUsesOfWith(PhiR, PhiR->getStartValue());
6812 Builder.setInsertPoint(AnyOfSelect);
6813
6814 // If the true value of the select is the reduction phi, the new value
6815 // is selected if the negated condition is true in any iteration.
6816 if (TrueValIsPhi)
6817 Cmp = Builder.createNot(Cmp);
6818
6819 // Build a fresh i1 chain (phi, or, and i1 versions of any blend/select
6820 // the exiting value flows through).
6821 auto *NewPhiR =
6822 PhiR->cloneWithOperands(Plan->getFalse(), Plan->getFalse());
6823 NewPhiR->insertBefore(PhiR);
6824 VPValue *NewExiting = Builder.createOr(NewPhiR, Cmp);
6825
6826 // The exiting value may flow through a chain of VPBlendRecipes and
6827 // select recipes (VPInstruction, VPWidenRecipe or VPReplicateRecipe with
6828 // Select opcode) before reaching OrigExitingVPV. Clone each chain link
6829 // in topological order so each clone refers to the already-rewritten i1
6830 // operands via Substitutions.
6831 DenseMap<VPValue *, VPValue *> Substitutions = {{AnyOfSelect, NewExiting},
6832 {PhiR, NewPhiR}};
6833 std::function<void(VPSingleDefRecipe *)> CloneChain =
6834 [&](VPSingleDefRecipe *Old) {
6835 if (Substitutions.contains(Old))
6836 return;
6838 for (VPValue *Op : Old->operands()) {
6839 if (isa<VPBlendRecipe>(Op) ||
6841 CloneChain(cast<VPSingleDefRecipe>(Op));
6842 NewOps.push_back(Substitutions.lookup_or(Op, Op));
6843 }
6844 VPSingleDefRecipe *New;
6845 if (auto *B = dyn_cast<VPBlendRecipe>(Old))
6846 New = B->cloneWithOperands(NewOps);
6847 else if (auto *W = dyn_cast<VPWidenRecipe>(Old))
6848 New = W->cloneWithOperands(NewOps);
6849 else if (auto *Rep = dyn_cast<VPReplicateRecipe>(Old))
6850 New = Rep->cloneWithOperands(NewOps);
6851 else
6852 New = cast<VPInstruction>(Old)->cloneWithOperands(NewOps);
6853 New->insertBefore(Old);
6854 Substitutions[Old] = New;
6855 };
6856
6857 if (OrigExitingVPV != AnyOfSelect) {
6858 CloneChain(cast<VPSingleDefRecipe>(OrigExitingVPV));
6859 NewExiting = Substitutions.lookup(OrigExitingVPV);
6860 }
6861 NewPhiR->setOperand(1, NewExiting);
6862 PhiR->replaceAllUsesWith(Plan->getPoison(PhiR->getScalarType()));
6863
6864 Builder.setInsertPoint(MiddleVPBB, IP);
6865 FinalReductionResult =
6866 Builder.createAnyOfReduction(NewExiting, NewVal, Start, ExitDL);
6867 } else {
6868 // If the vector reduction can be performed in a smaller type, we
6869 // truncate then extend the loop exit value to enable InstCombine to
6870 // evaluate the entire expression in the smaller type.
6871 VPValue *ReductionOp = NewExitingVPV;
6872 Instruction::CastOps ExtendOpc = Instruction::CastOpsEnd;
6873 if (MinVF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
6874 assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
6876 "Unexpected truncated min-max recurrence!");
6877 Type *RdxTy = RdxDesc.getRecurrenceType();
6878 ExtendOpc = RdxDesc.isSigned() ? Instruction::SExt : Instruction::ZExt;
6879 {
6880 VPBuilder::InsertPointGuard Guard(Builder);
6881 Builder.setInsertPoint(
6882 NewExitingVPV->getDefiningRecipe()->getParent(),
6883 std::next(NewExitingVPV->getDefiningRecipe()->getIterator()));
6884 ReductionOp =
6885 Builder.createWidenCast(Instruction::Trunc, NewExitingVPV, RdxTy);
6886 VPWidenCastRecipe *Extnd =
6887 Builder.createWidenCast(ExtendOpc, ReductionOp, PhiTy);
6888 if (PhiR->getOperand(1) == NewExitingVPV)
6889 PhiR->setOperand(1, Extnd);
6890 }
6891 }
6892
6893 VPIRFlags Flags(RecurrenceKind, PhiR->isOrdered(), PhiR->isInLoop(),
6894 PhiR->getFastMathFlagsOrNone());
6895 FinalReductionResult = Builder.createNaryOp(
6896 VPInstruction::ComputeReductionResult, {ReductionOp}, Flags, ExitDL);
6897 if (ExtendOpc != Instruction::CastOpsEnd)
6898 FinalReductionResult = Builder.createScalarCast(
6899 ExtendOpc, FinalReductionResult, PhiTy, {});
6900 }
6901
6902 // Update all users outside the vector region. Also replace redundant
6903 // extracts.
6904 for (auto *U : to_vector(OrigExitingVPV->users())) {
6905 auto *Parent = cast<VPRecipeBase>(U)->getParent();
6906 if (FinalReductionResult == U || Parent->getParent())
6907 continue;
6908 // Skip ComputeReductionResult and FindIV reductions when they are not the
6909 // final result.
6910 if (match(U, m_VPInstruction<VPInstruction::ComputeReductionResult>()) ||
6912 match(U, m_VPInstruction<Instruction::ICmp>())))
6913 continue;
6914 U->replaceUsesOfWith(OrigExitingVPV, FinalReductionResult);
6915
6916 // Look through ExtractLastPart.
6918 U = cast<VPInstruction>(U)->getSingleUser();
6919
6922 cast<VPInstruction>(U)->replaceAllUsesWith(FinalReductionResult);
6923 }
6924
6925 RecurKind RK = PhiR->getRecurrenceKind();
6930 VPBuilder PHBuilder(Plan->getVectorPreheader());
6931 VPValue *Iden = Plan->getOrAddLiveIn(
6932 getRecurrenceIdentity(RK, PhiTy, PhiR->getFastMathFlagsOrNone()));
6933 auto *ScaleFactorVPV = Plan->getConstantInt(32, 1);
6934 VPValue *StartV = PHBuilder.createNaryOp(
6936 {PhiR->getStartValue(), Iden, ScaleFactorVPV}, *PhiR);
6937 PhiR->setOperand(0, StartV);
6938 }
6939 }
6940
6942}
6943
6945 VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const {
6946 const auto &[SCEVCheckCond, SCEVCheckBlock] = RTChecks.getSCEVChecks();
6947 if (SCEVCheckBlock && SCEVCheckBlock->hasNPredecessors(0)) {
6948 assert((!Config.OptForSize ||
6949 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled) &&
6950 "Cannot SCEV check stride or overflow when optimizing for size");
6952 SCEVCheckBlock, HasBranchWeights);
6953 }
6954 const auto &[MemCheckCond, MemCheckBlock] = RTChecks.getMemRuntimeChecks();
6955 if (MemCheckBlock && MemCheckBlock->hasNPredecessors(0)) {
6956 // VPlan-native path does not do any analysis for runtime checks
6957 // currently.
6959 "Runtime checks are not supported for outer loops yet");
6960
6961 if (Config.OptForSize) {
6962 assert(
6963 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled &&
6964 "Cannot emit memory checks when optimizing for size, unless forced "
6965 "to vectorize.");
6966 ORE->emit([&]() {
6967 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
6968 OrigLoop->getStartLoc(),
6969 OrigLoop->getHeader())
6970 << "Code-size may be reduced by not forcing "
6971 "vectorization, or by source-code modifications "
6972 "eliminating the need for runtime checks "
6973 "(e.g., adding 'restrict').";
6974 });
6975 }
6977 MemCheckBlock, HasBranchWeights);
6978 }
6979}
6980
6982 VPlan &Plan, ElementCount VF, unsigned UF,
6983 ElementCount MinProfitableTripCount) const {
6984 const uint32_t *BranchWeights =
6985 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator())
6987 : nullptr;
6989 MinProfitableTripCount, Plan.requiresScalarEpilogue(),
6990 Plan.hasTailFolded(), OrigLoop, BranchWeights,
6991 OrigLoop->getLoopPredecessor()->getTerminator()->getDebugLoc(),
6992 PSE, Plan.getEntry());
6993}
6994
6995// Determine how to lower the epilogue, which depends on 1) optimising
6996// for minimum code-size, 2) tail-folding compiler options, 3) loop
6997// hints forcing tail-folding, and 4) a TTI hook that analyses whether the loop
6998// is suitable for tail-folding.
6999// This function determines epilogue lowering for the main vector loop while
7000// epilogue lowering for the tail-folded epilogue path will be handled
7001// separately in getEpilogueTailLowering.
7002static EpilogueLowering
7004 bool OptForSize, TargetTransformInfo *TTI,
7006 InterleavedAccessInfo *IAI) {
7007 // 1) OptSize takes precedence over all other options, i.e. if this is set,
7008 // don't look at hints or options, and don't request an epilogue.
7009 if (F->hasOptSize() ||
7010 (OptForSize && Hints.getForce() != LoopVectorizeHints::FK_Enabled))
7012
7013 // 2) If set, obey the directives
7014 if (TailFoldingPolicy.getNumOccurrences()) {
7015 switch (TailFoldingPolicy) {
7017 return CM_EpilogueAllowed;
7022 };
7023 }
7024
7025 // 3) If set, obey the hints
7026 switch (Hints.getPredicate()) {
7030 return CM_EpilogueAllowed;
7031 };
7032
7033 // 4) if the TTI hook indicates this is profitable, request tail-folding.
7034 TailFoldingInfo TFI(TLI, &LVL, IAI);
7035 if (TTI->preferTailFoldingOverEpilogue(&TFI))
7037
7038 return CM_EpilogueAllowed;
7039}
7040
7041/// Determine how to lower the epilogue for the vector epilogue loop.
7042/// Check if there are any conflicts that prevent tail-folding the epilogue.
7043/// \return CM_EpilogueNotNeededFoldTail if epilogue tail-folding is possible,
7044/// otherwise CM_EpilogueAllowed.
7045static EpilogueLowering
7049 LoopVectorizeHints &Hints) {
7050 // Epilogue TF is only enabled when explicitly requested via command line.
7051 if (!EpilogueTailFoldingPolicy.getNumOccurrences() ||
7053 return CM_EpilogueAllowed;
7054
7057 "Options conflict, epilogue vectorization is disallowed while "
7058 "epilogue tail-folding allowed!",
7059 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
7060 return CM_EpilogueAllowed;
7061 }
7062
7063 if (!Hints.getWidth() || !hasForcedEpilogueVF()) {
7064 reportVectorizationInfo("For now, epilogue tail-folding can't be "
7065 "applied without forced main/epilogue loop VF",
7066 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
7067 return CM_EpilogueAllowed;
7068 }
7069
7071 reportVectorizationInfo("For now, epilogue tail-folding can't be applied "
7072 "when VF of the main loop <= VF of the epilogue",
7073 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
7074 return CM_EpilogueAllowed;
7075 }
7076
7077 if (!L->isInnermost()) {
7079 "Epilogue tail-folding is not supported for outer loop",
7080 "InvalidTailFoldedEpilogue", ORE, L);
7081 return CM_EpilogueAllowed;
7082 }
7083
7084 // If scalar epilogue is explicitly required, we can't apply TF.
7085 if (MainCM.requiresScalarEpilogue(/*IsVectorizing*/ true)) {
7087 "Epilogue tail-folding can't be applied because scalar epilogue is "
7088 "required. Fall back to a normal epilogue",
7089 "InvalidTailFoldedEpilogue", ORE, L);
7090 return CM_EpilogueAllowed;
7091 }
7092
7093 // If having epilogue is NOT allowed, then no epilogue to apply TF for.
7094 if (!MainCM.isEpilogueAllowed()) {
7095 reportVectorizationInfo("Not applying tail-folding to the epilogue, since "
7096 "no epilogue is allowed.",
7097 "InvalidTailFoldedEpilogue", ORE, L);
7098 return CM_EpilogueAllowed;
7099 }
7100
7101 if (L->getExitingBlock() != L->getLoopLatch() ||
7104 "Epilogue tail-folding is not supported yet for early-exit loops",
7105 "InvalidTailFoldedEpilogue", ORE, L);
7106 return CM_EpilogueAllowed;
7107 }
7108
7109 // We can apply tail-folding on the vectorized epilogue loop.
7111}
7112
7113// Emit a remark if there are stores to floats that required a floating point
7114// extension. If the vectorized loop was generated with floating point there
7115// will be a performance penalty from the conversion overhead and the change in
7116// the vector width.
7119 for (BasicBlock *BB : L->getBlocks()) {
7120 for (Instruction &Inst : *BB) {
7121 if (auto *S = dyn_cast<StoreInst>(&Inst)) {
7122 if (S->getValueOperand()->getType()->isFloatTy())
7123 Worklist.push_back(S);
7124 }
7125 }
7126 }
7127
7128 // Traverse the floating point stores upwards searching, for floating point
7129 // conversions.
7132 while (!Worklist.empty()) {
7133 auto *I = Worklist.pop_back_val();
7134 if (!L->contains(I))
7135 continue;
7136 if (!Visited.insert(I).second)
7137 continue;
7138
7139 // Emit a remark if the floating point store required a floating
7140 // point conversion.
7141 // TODO: More work could be done to identify the root cause such as a
7142 // constant or a function return type and point the user to it.
7143 if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
7144 ORE->emit([&]() {
7145 return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
7146 I->getDebugLoc(), L->getHeader())
7147 << "floating point conversion changes vector width. "
7148 << "Mixed floating point precision requires an up/down "
7149 << "cast that will negatively impact performance.";
7150 });
7151
7152 for (Use &Op : I->operands())
7153 if (auto *OpI = dyn_cast<Instruction>(Op))
7154 Worklist.push_back(OpI);
7155 }
7156}
7157
7158/// For loops with uncountable early exits, find the cost of doing work when
7159/// exiting the loop early, such as calculating the final exit values of
7160/// variables used outside the loop.
7161/// TODO: This is currently overly pessimistic because the loop may not take
7162/// the early exit, but better to keep this conservative for now. In future,
7163/// it might be possible to relax this by using branch probabilities.
7165 VPlan &Plan, ElementCount VF) {
7166 InstructionCost Cost = 0;
7167 for (auto *ExitVPBB : Plan.getExitBlocks()) {
7168 for (auto *PredVPBB : ExitVPBB->getPredecessors()) {
7169 // If the predecessor is not the middle.block, then it must be the
7170 // vector.early.exit block, which may contain work to calculate the exit
7171 // values of variables used outside the loop.
7172 if (PredVPBB != Plan.getMiddleBlock()) {
7173 LLVM_DEBUG(dbgs() << "Calculating cost of work in exit block "
7174 << PredVPBB->getName() << ":\n");
7175 Cost += PredVPBB->cost(VF, CostCtx);
7176 }
7177 }
7178 }
7179 return Cost;
7180}
7181
7182/// This function determines whether or not it's still profitable to vectorize
7183/// the loop given the extra work we have to do outside of the loop:
7184/// 1. Perform the runtime checks before entering the loop to ensure it's safe
7185/// to vectorize.
7186/// 2. In the case of loops with uncountable early exits, we may have to do
7187/// extra work when exiting the loop early, such as calculating the final
7188/// exit values of variables used outside the loop.
7189/// 3. The middle block.
7190static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks,
7191 VectorizationFactor &VF, Loop *L,
7193 VPCostContext &CostCtx, VPlan &Plan,
7194 EpilogueLowering SEL,
7195 std::optional<unsigned> VScale) {
7196 InstructionCost RtC = Checks.getCost();
7197 if (!RtC.isValid())
7198 return false;
7199
7200 // When interleaving only scalar and vector cost will be equal, which in turn
7201 // would lead to a divide by 0. Fall back to hard threshold.
7202 if (VF.Width.isScalar()) {
7203 // TODO: Should we rename VectorizeMemoryCheckThreshold?
7205 LLVM_DEBUG(
7206 dbgs()
7207 << "LV: Interleaving only is not profitable due to runtime checks\n");
7208 return false;
7209 }
7210 return true;
7211 }
7212
7213 // The scalar cost should only be 0 when vectorizing with a user specified
7214 // VF/IC. In those cases, runtime checks should always be generated.
7215 uint64_t ScalarC = VF.ScalarCost.getValue();
7216 if (ScalarC == 0)
7217 return true;
7218
7219 InstructionCost TotalCost = RtC;
7220 // Add on the cost of any work required in the vector early exit block, if
7221 // one exists.
7222 TotalCost += calculateEarlyExitCost(CostCtx, Plan, VF.Width);
7223 TotalCost += Plan.getMiddleBlock()->cost(VF.Width, CostCtx);
7224
7225 // First, compute the minimum iteration count required so that the vector
7226 // loop outperforms the scalar loop.
7227 // The total cost of the scalar loop is
7228 // ScalarC * TC
7229 // where
7230 // * TC is the actual trip count of the loop.
7231 // * ScalarC is the cost of a single scalar iteration.
7232 //
7233 // The total cost of the vector loop is
7234 // TotalCost + VecC * (TC / VF) + EpiC
7235 // where
7236 // * TotalCost is the sum of the costs cost of
7237 // - the generated runtime checks, i.e. RtC
7238 // - performing any additional work in the vector.early.exit block for
7239 // loops with uncountable early exits.
7240 // - the middle block, if ExpectedTC <= VF.Width.
7241 // * VecC is the cost of a single vector iteration.
7242 // * TC is the actual trip count of the loop
7243 // * VF is the vectorization factor
7244 // * EpiCost is the cost of the generated epilogue, including the cost
7245 // of the remaining scalar operations.
7246 //
7247 // Vectorization is profitable once the total vector cost is less than the
7248 // total scalar cost:
7249 // TotalCost + VecC * (TC / VF) + EpiC < ScalarC * TC
7250 //
7251 // Now we can compute the minimum required trip count TC as
7252 // VF * (TotalCost + EpiC) / (ScalarC * VF - VecC) < TC
7253 //
7254 // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
7255 // the computations are performed on doubles, not integers and the result
7256 // is rounded up, hence we get an upper estimate of the TC.
7257 unsigned IntVF = estimateElementCount(VF.Width, VScale);
7258 uint64_t Div = ScalarC * IntVF - VF.Cost.getValue();
7259 uint64_t MinTC1 =
7260 Div == 0 ? 0 : divideCeil(TotalCost.getValue() * IntVF, Div);
7261
7262 // Second, compute a minimum iteration count so that the cost of the
7263 // runtime checks is only a fraction of the total scalar loop cost. This
7264 // adds a loop-dependent bound on the overhead incurred if the runtime
7265 // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
7266 // * TC. To bound the runtime check to be a fraction 1/X of the scalar
7267 // cost, compute
7268 // RtC < ScalarC * TC * (1 / X) ==> RtC * X / ScalarC < TC
7269 uint64_t MinTC2 = divideCeil(RtC.getValue() * 10, ScalarC);
7270
7271 // Now pick the larger minimum. If it is not a multiple of VF and an epilogue
7272 // is allowed, choose the next closest multiple of VF. This should partly
7273 // compensate for ignoring the epilogue cost.
7274 uint64_t MinTC = std::max(MinTC1, MinTC2);
7275 if (SEL == CM_EpilogueAllowed)
7276 MinTC = alignTo(MinTC, IntVF);
7278
7279 LLVM_DEBUG(
7280 dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
7281 << VF.MinProfitableTripCount << "\n");
7282
7283 // Skip vectorization if the expected trip count is less than the minimum
7284 // required trip count.
7285 if (auto ExpectedTC = getSmallBestKnownTC(PSE, L)) {
7286 if (ElementCount::isKnownLT(*ExpectedTC, VF.MinProfitableTripCount)) {
7287 LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
7288 "trip count < minimum profitable VF ("
7289 << *ExpectedTC << " < " << VF.MinProfitableTripCount
7290 << ")\n");
7291
7292 return false;
7293 }
7294 }
7295 return true;
7296}
7297
7299 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
7301 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
7303
7304/// Prepare \p MainPlan for vectorizing the main vector loop during epilogue
7305/// vectorization.
7308 using namespace VPlanPatternMatch;
7309 // When vectorizing the epilogue, FindFirstIV & FindLastIV reductions can
7310 // introduce multiple uses of undef/poison. If the reduction start value may
7311 // be undef or poison it needs to be frozen and the frozen start has to be
7312 // used when computing the reduction result. We also need to use the frozen
7313 // value in the resume phi generated by the main vector loop, as this is also
7314 // used to compute the reduction result after the epilogue vector loop.
7315 auto AddFreezeForFindLastIVReductions = [](VPlan &Plan,
7316 bool UpdateResumePhis) {
7317 VPBuilder Builder(Plan.getEntry());
7318 for (VPRecipeBase &R : *Plan.getMiddleBlock()) {
7319 auto *VPI = dyn_cast<VPInstruction>(&R);
7320 if (!VPI)
7321 continue;
7322 VPValue *OrigStart;
7323 if (!matchFindIVResult(VPI, m_VPValue(), m_VPValue(OrigStart)))
7324 continue;
7326 continue;
7327 VPInstruction *Freeze =
7328 Builder.createNaryOp(Instruction::Freeze, {OrigStart}, {}, "fr");
7329 VPI->setOperand(2, Freeze);
7330 if (UpdateResumePhis)
7331 OrigStart->replaceUsesWithIf(Freeze, [Freeze](VPUser &U, unsigned) {
7332 return Freeze != &U && isa<VPPhi>(&U);
7333 });
7334 }
7335 };
7336 AddFreezeForFindLastIVReductions(MainPlan, true);
7337 AddFreezeForFindLastIVReductions(EpiPlan, false);
7338
7339 VPValue *VectorTC = nullptr;
7340 auto *Term =
7342 [[maybe_unused]] bool MatchedTC =
7343 match(Term, m_BranchOnCount(m_VPValue(), m_VPValue(VectorTC)));
7344 assert(MatchedTC && "must match vector trip count");
7345
7346 // If there is a suitable resume value for the canonical induction in the
7347 // scalar (which will become vector) epilogue loop, use it and move it to the
7348 // beginning of the scalar preheader. Otherwise create it below.
7349 VPBasicBlock *MainScalarPH = MainPlan.getScalarPreheader();
7350 auto ResumePhiIter =
7351 find_if(MainScalarPH->phis(), [VectorTC](VPRecipeBase &R) {
7352 return match(&R, m_VPInstruction<Instruction::PHI>(m_Specific(VectorTC),
7353 m_ZeroInt()));
7354 });
7355 VPPhi *ResumePhi = nullptr;
7356 if (ResumePhiIter == MainScalarPH->phis().end()) {
7358 "canonical IV must exist");
7359 Type *Ty = VectorTC->getScalarType();
7360 VPBuilder ScalarPHBuilder(MainScalarPH, MainScalarPH->begin());
7361 ResumePhi = ScalarPHBuilder.createScalarPhi(
7362 {VectorTC, MainPlan.getZero(Ty)}, {}, "vec.epilog.resume.val");
7363 } else {
7364 ResumePhi = cast<VPPhi>(&*ResumePhiIter);
7365 ResumePhi->setName("vec.epilog.resume.val");
7366 if (&MainScalarPH->front() != ResumePhi)
7367 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->begin());
7368 }
7369
7370 // Create a ResumeForEpilogue for the canonical IV resume and its bypass value
7371 // as the first non-phi, to keep them alive for the epilogue.
7372 VPBuilder ResumeBuilder(MainScalarPH);
7374 {ResumePhi, ResumePhi->getOperand(1)});
7375
7376 // Create ResumeForEpilogue instructions for the resume phis of the
7377 // VPIRPhis and their bypass values in the scalar header of the main plan and
7378 // return them so they can be used as resume values when vectorizing the
7379 // epilogue.
7380 return to_vector(
7381 map_range(MainPlan.getScalarHeader()->phis(), [&](VPRecipeBase &R) {
7382 assert(isa<VPIRPhi>(R) &&
7383 "only VPIRPhis expected in the scalar header");
7384 VPValue *MainResumePhi = R.getOperand(0);
7385 VPValue *Bypass = MainResumePhi->getDefiningRecipe()->getOperand(1);
7386 return ResumeBuilder.createNaryOp(VPInstruction::ResumeForEpilogue,
7387 {MainResumePhi, Bypass});
7388 }));
7389}
7390
7391/// Prepare \p Plan for vectorizing the epilogue loop. That is, re-use expanded
7392/// SCEVs from \p ExpandedSCEVs and set resume values for header recipes. Some
7393/// reductions require creating new instructions to compute the resume values.
7394/// They are collected in a vector and returned. They must be moved to the
7395/// preheader of the vector epilogue loop, after created by the execution of \p
7396/// Plan.
7398 VPlan &MainPlan, VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs,
7401 ArrayRef<VPInstruction *> ResumeValues) {
7402 // Build a map from the scalar-header PHI to the ResumeForEpilogue markers
7403 // from the main plan.
7404 // TODO: Replace the IR PHI key.
7405 DenseMap<PHINode *, VPInstruction *> IRPhiToResumeForEpi;
7406 for (auto [HeaderPhi, ResumeForEpi] :
7407 zip_equal(MainPlan.getScalarHeader()->phis(), ResumeValues))
7408 IRPhiToResumeForEpi[&cast<VPIRPhi>(HeaderPhi).getIRPhi()] = ResumeForEpi;
7409 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
7410 VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
7411 Header->setName("vec.epilog.vector.body");
7412
7413 VPValue *IV = VectorLoop->getCanonicalIV();
7414 // When vectorizing the epilogue loop, the canonical induction needs to start
7415 // at the resume value from the main vector loop. Find the resume value
7416 // created during execution of the main VPlan. Add this resume value as an
7417 // offset to the canonical IV of the epilogue loop.
7418 using namespace llvm::PatternMatch;
7419 VPInstruction *ResumeForEpilogue =
7421 Value *EPResumeVal = ResumeForEpilogue->getUnderlyingValue();
7422 if (auto *ResumePhi = dyn_cast<PHINode>(EPResumeVal)) {
7423 for (Value *Inc : ResumePhi->incoming_values()) {
7424 if (match(Inc, m_SpecificInt(0)))
7425 continue;
7426 assert(!EPI.VectorTripCount &&
7427 "Must only have a single non-zero incoming value");
7428 EPI.VectorTripCount = Inc;
7429 }
7430 // If we didn't find a non-zero vector trip count, all incoming values
7431 // must be zero, which also means the vector trip count is zero.
7432 if (!EPI.VectorTripCount) {
7433 assert(ResumePhi->getNumIncomingValues() > 0 &&
7434 all_of(ResumePhi->incoming_values(), match_fn(m_SpecificInt(0))) &&
7435 "all incoming values must be 0");
7436 EPI.VectorTripCount = ResumePhi->getIncomingValue(0);
7437 }
7438 } else {
7439 EPI.VectorTripCount = EPResumeVal;
7440 }
7441 VPValue *VPV = Plan.getOrAddLiveIn(EPResumeVal);
7442 assert(all_of(IV->users(),
7443 [](const VPUser *U) {
7444 if (isa<VPScalarIVStepsRecipe, VPDerivedIVRecipe>(U))
7445 return true;
7446 unsigned Opc = cast<VPInstruction>(U)->getOpcode();
7447 return Instruction::isCast(Opc) || Opc == Instruction::Add;
7448 }) &&
7449 "the canonical IV should only be used by its increment or "
7450 "ScalarIVSteps when resetting the start value");
7451 VPBuilder Builder(Header, Header->getFirstNonPhi());
7452 VPInstruction *Add = Builder.createAdd(IV, VPV);
7453 // Replace all users of the canonical IV and its increment with the offset
7454 // version, except for the Add itself and the canonical IV increment.
7456 assert(Increment && "Must have a canonical IV increment at this point");
7457 IV->replaceUsesWithIf(Add, [Add, Increment](VPUser &U, unsigned) {
7458 return &U != Add && &U != Increment;
7459 });
7460 VPInstruction *OffsetIVInc =
7462 Increment->replaceAllUsesWith(OffsetIVInc);
7463 OffsetIVInc->setOperand(0, Increment);
7464
7466 SmallVector<Instruction *> InstsToMove;
7467 // Ensure that the start values for all header phi recipes are updated before
7468 // vectorizing the epilogue loop.
7469 for (VPRecipeBase &R : Header->phis()) {
7470 Value *ResumeV = nullptr;
7471 // TODO: Move setting of resume values to prepareToExecute.
7472 if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
7473 // Find the reduction result by searching users of the phi or its backedge
7474 // value.
7475 auto IsReductionResult = [](VPRecipeBase *R) {
7476 auto *VPI = dyn_cast<VPInstruction>(R);
7477 return VPI && VPI->getOpcode() == VPInstruction::ComputeReductionResult;
7478 };
7479 auto *RdxResult = cast<VPInstruction>(
7480 vputils::findRecipe(ReductionPhi->getBackedgeValue(), IsReductionResult));
7481 assert(RdxResult && "expected to find reduction result");
7482
7483 VPInstruction *ResumeForEpi = IRPhiToResumeForEpi.at(
7484 cast<PHINode>(ReductionPhi->getUnderlyingInstr()));
7485 ResumeV = ResumeForEpi->getUnderlyingValue();
7486
7487 // Check for FindIV pattern by looking for icmp user of RdxResult.
7488 // The pattern is: select(icmp ne RdxResult, Sentinel), RdxResult, Start
7489 using namespace VPlanPatternMatch;
7490 VPValue *SentinelVPV = nullptr;
7491 bool IsFindIV = any_of(RdxResult->users(), [&](VPUser *U) {
7492 return match(U, VPlanPatternMatch::m_SpecificICmp(
7493 ICmpInst::ICMP_NE, m_Specific(RdxResult),
7494 m_VPValue(SentinelVPV)));
7495 });
7496
7497 RecurKind RK = ReductionPhi->getRecurrenceKind();
7498 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RK) || IsFindIV) {
7499 auto *ResumePhi = cast<PHINode>(ResumeV);
7500 VPValue *BypassOp = ResumeForEpi->getOperand(1);
7501 assert((isa<VPIRValue>(BypassOp) ||
7503 BypassOp,
7505 "expected live-in or Freeze");
7506 Value *StartV = BypassOp->getUnderlyingValue();
7507 IRBuilder<> Builder(ResumePhi->getParent(),
7508 ResumePhi->getParent()->getFirstNonPHIIt());
7509
7511 // VPReductionPHIRecipes for AnyOf reductions expect a boolean as
7512 // start value; compare the final value from the main vector loop
7513 // to the start value.
7514 ResumeV = Builder.CreateICmpNE(ResumeV, StartV);
7515 if (auto *I = dyn_cast<Instruction>(ResumeV))
7516 InstsToMove.push_back(I);
7517 } else {
7518 assert(SentinelVPV && "expected to find icmp using RdxResult");
7519 if (auto *FreezeI = dyn_cast<FreezeInst>(StartV))
7520 ToFrozen[FreezeI->getOperand(0)] = StartV;
7521
7522 // Adjust resume: select(icmp eq ResumeV, StartV), Sentinel, ResumeV
7523 Value *Cmp = Builder.CreateICmpEQ(ResumeV, StartV);
7524 if (auto *I = dyn_cast<Instruction>(Cmp))
7525 InstsToMove.push_back(I);
7526 ResumeV = Builder.CreateSelect(Cmp, SentinelVPV->getLiveInIRValue(),
7527 ResumeV);
7528 if (auto *I = dyn_cast<Instruction>(ResumeV))
7529 InstsToMove.push_back(I);
7530 }
7531 } else {
7532 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
7533 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
7534 if (auto *VPI = dyn_cast<VPInstruction>(PhiR->getStartValue())) {
7536 "unexpected start value");
7537 // Partial sub-reductions always start at 0 and account for the
7538 // reduction start value in a final subtraction. Update it to use the
7539 // resume value from the main vector loop.
7540 if (PhiR->getVFScaleFactor() > 1 &&
7542 PhiR->getRecurrenceKind())) {
7543 auto *Sub = cast<VPInstruction>(RdxResult->getSingleUser());
7544 assert((Sub->getOpcode() == Instruction::Sub ||
7545 Sub->getOpcode() == Instruction::FSub) &&
7546 "Unexpected opcode");
7547 assert(isa<VPIRValue>(Sub->getOperand(0)) &&
7548 "Expected operand to match the original start value of the "
7549 "reduction");
7550 // For integer sub-reductions, verify start value is zero.
7551 // For FP sub-reductions, verify start value is negative zero.
7552 [[maybe_unused]] auto StartValueIsIdentity = [&] {
7553 Value *IdentityValue = getRecurrenceIdentity(
7554 PhiR->getRecurrenceKind(), ResumeV->getType(),
7555 PhiR->getFastMathFlagsOrNone());
7556 auto *StartValue = dyn_cast<VPIRValue>(VPI->getOperand(0));
7557 return StartValue && StartValue->getValue() == IdentityValue;
7558 };
7559 assert(StartValueIsIdentity() &&
7560 "Expected start value for partial sub-reduction to be zero "
7561 "(or negative zero)");
7562
7563 Sub->setOperand(0, StartVal);
7564 } else
7565 VPI->setOperand(0, StartVal);
7566 continue;
7567 }
7568 }
7569 } else {
7570 // Retrieve the induction resume value via ResumeForEpilogue.
7571 PHINode *IndPhi = cast<VPWidenInductionRecipe>(&R)->getPHINode();
7572 ResumeV = IRPhiToResumeForEpi.at(IndPhi)->getUnderlyingValue();
7573 }
7574 assert(ResumeV && "Must have a resume value");
7575 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
7576 cast<VPHeaderPHIRecipe>(&R)->setStartValue(StartVal);
7577 }
7578
7579 // For some VPValues in the epilogue plan we must re-use the generated IR
7580 // values from the main plan. Replace them with live-in VPValues.
7581 // TODO: This is a workaround needed for epilogue vectorization and it
7582 // should be removed once induction resume value creation is done
7583 // directly in VPlan.
7584 for (auto &R : make_early_inc_range(*Plan.getEntry())) {
7585 // Re-use frozen values from the main plan for Freeze VPInstructions in the
7586 // epilogue plan. This ensures all users use the same frozen value.
7587 auto *VPI = dyn_cast<VPInstruction>(&R);
7588 if (VPI && VPI->getOpcode() == Instruction::Freeze) {
7590 ToFrozen.lookup(VPI->getOperand(0)->getLiveInIRValue())));
7591 continue;
7592 }
7593
7594 // Re-use the trip count and steps expanded for the main loop, as
7595 // skeleton creation needs it as a value that dominates both the scalar
7596 // and vector epilogue loops
7597 auto *ExpandR = dyn_cast<VPExpandSCEVRecipe>(&R);
7598 if (!ExpandR)
7599 continue;
7600 assert(ExpandedSCEVs.contains(ExpandR->getSCEV()) &&
7601 "Epilogue plan needs a SCEV not expanded for the main loop");
7602 VPValue *ExpandedVal =
7603 Plan.getOrAddLiveIn(ExpandedSCEVs.lookup(ExpandR->getSCEV()));
7604 ExpandR->replaceAllUsesWith(ExpandedVal);
7605 if (Plan.getTripCount() == ExpandR)
7606 Plan.resetTripCount(ExpandedVal);
7607 ExpandR->eraseFromParent();
7608 }
7609
7610 auto VScale = Config.getVScaleForTuning();
7611 unsigned MainLoopStep =
7612 estimateElementCount(EPI.MainLoopVF * EPI.MainLoopUF, VScale);
7613 unsigned EpilogueLoopStep =
7614 estimateElementCount(EPI.EpilogueVF * EPI.EpilogueUF, VScale);
7617 EPI.EpilogueVF, EPI.EpilogueUF, MainLoopStep, EpilogueLoopStep,
7618 SE);
7619
7620 return InstsToMove;
7621}
7622
7623static void
7625 VPlan &BestEpiPlan,
7626 ArrayRef<VPInstruction *> ResumeValues) {
7627 // Fix resume values from the additional bypass block.
7628 BasicBlock *PH = L->getLoopPreheader();
7629 for (auto *Pred : predecessors(PH)) {
7630 for (PHINode &Phi : PH->phis()) {
7631 if (Phi.getBasicBlockIndex(Pred) != -1)
7632 continue;
7633 Phi.addIncoming(Phi.getIncomingValueForBlock(BypassBlock), Pred);
7634 }
7635 }
7636 auto *ScalarPH = cast<VPIRBasicBlock>(BestEpiPlan.getScalarPreheader());
7637 if (ScalarPH->hasPredecessors()) {
7638 // Fix resume values for inductions and reductions from the additional
7639 // bypass block using the incoming values from the main loop's resume phis.
7640 // ResumeValues correspond 1:1 with the scalar loop header phis.
7641 for (auto [ResumeV, HeaderPhi] :
7642 zip(ResumeValues, BestEpiPlan.getScalarHeader()->phis())) {
7643 auto *HeaderPhiR = cast<VPIRPhi>(&HeaderPhi);
7644 auto *EpiResumePhi =
7645 cast<PHINode>(HeaderPhiR->getIRPhi().getIncomingValueForBlock(PH));
7646 if (EpiResumePhi->getBasicBlockIndex(BypassBlock) == -1)
7647 continue;
7648 auto *MainResumePhi = cast<PHINode>(ResumeV->getUnderlyingValue());
7649 EpiResumePhi->setIncomingValueForBlock(
7650 BypassBlock, MainResumePhi->getIncomingValueForBlock(BypassBlock));
7651 }
7652 }
7653}
7654
7655/// Connect the epilogue vector loop generated for \p EpiPlan to the main vector
7656/// loop, after both plans have executed, updating branches from the iteration
7657/// and runtime checks of the main loop, as well as updating various phis. \p
7658/// InstsToMove contains instructions that need to be moved to the preheader of
7659/// the epilogue vector loop.
7660static void connectEpilogueVectorLoop(VPlan &EpiPlan, Loop *L,
7662 DominatorTree *DT,
7663 GeneratedRTChecks &Checks,
7664 ArrayRef<Instruction *> InstsToMove,
7665 ArrayRef<VPInstruction *> ResumeValues) {
7666 BasicBlock *VecEpilogueIterationCountCheck =
7667 cast<VPIRBasicBlock>(EpiPlan.getEntry())->getIRBasicBlock();
7668
7669 BasicBlock *VecEpiloguePreHeader =
7670 cast<CondBrInst>(VecEpilogueIterationCountCheck->getTerminator())
7671 ->getSuccessor(1);
7672 // Adjust the control flow taking the state info from the main loop
7673 // vectorization into account.
7675 "expected this to be saved from the previous pass.");
7676 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
7677
7678 // Helper to redirect an edge from \p BB to \p VecEpilogueIterationCountCheck
7679 // to \p NewSucc instead, updating the DomTree.
7680 auto RedirectEdge = [&](BasicBlock *BB, BasicBlock *NewSucc) {
7681 BB->getTerminator()->replaceUsesOfWith(VecEpilogueIterationCountCheck,
7682 NewSucc);
7683 DTU.applyUpdates(
7684 {{DominatorTree::Delete, BB, VecEpilogueIterationCountCheck},
7685 {DominatorTree::Insert, BB, NewSucc}});
7686 };
7687
7688 RedirectEdge(EPI.MainLoopIterationCountCheck, VecEpiloguePreHeader);
7689
7690 BasicBlock *ScalarPH =
7691 cast<VPIRBasicBlock>(EpiPlan.getScalarPreheader())->getIRBasicBlock();
7692 RedirectEdge(EPI.EpilogueIterationCountCheck, ScalarPH);
7693
7694 // Adjust the terminators of runtime check blocks and phis using them.
7695 BasicBlock *SCEVCheckBlock = Checks.getSCEVChecks().second;
7696 BasicBlock *MemCheckBlock = Checks.getMemRuntimeChecks().second;
7697 if (SCEVCheckBlock)
7698 RedirectEdge(SCEVCheckBlock, ScalarPH);
7699 if (MemCheckBlock)
7700 RedirectEdge(MemCheckBlock, ScalarPH);
7701
7702 // The vec.epilog.iter.check block may contain Phi nodes from inductions
7703 // or reductions which merge control-flow from the latch block and the
7704 // middle block. Update the incoming values here and move the Phi into the
7705 // preheader.
7706 SmallVector<PHINode *, 4> PhisInBlock(
7707 llvm::make_pointer_range(VecEpilogueIterationCountCheck->phis()));
7708
7709 for (PHINode *Phi : PhisInBlock) {
7710 Phi->moveBefore(VecEpiloguePreHeader->getFirstNonPHIIt());
7711 Phi->replaceIncomingBlockWith(
7712 VecEpilogueIterationCountCheck->getSinglePredecessor(),
7713 VecEpilogueIterationCountCheck);
7714
7715 // If the phi doesn't have an incoming value from the
7716 // EpilogueIterationCountCheck, we are done. Otherwise remove the
7717 // incoming value and also those from other check blocks. This is needed
7718 // for reduction phis only.
7719 if (none_of(Phi->blocks(), [&](BasicBlock *IncB) {
7720 return EPI.EpilogueIterationCountCheck == IncB;
7721 }))
7722 continue;
7723 for (BasicBlock *BB :
7724 {EPI.EpilogueIterationCountCheck, SCEVCheckBlock, MemCheckBlock}) {
7725 if (BB)
7726 Phi->removeIncomingValue(BB);
7727 }
7728 }
7729
7730 auto IP = VecEpiloguePreHeader->getFirstNonPHIIt();
7731 for (auto *I : InstsToMove)
7732 I->moveBefore(IP);
7733
7734 // VecEpilogueIterationCountCheck conditionally skips over the epilogue loop
7735 // after executing the main loop. We need to update the resume values of
7736 // inductions and reductions during epilogue vectorization.
7737 fixScalarResumeValuesFromBypass(VecEpilogueIterationCountCheck, L, EpiPlan,
7738 ResumeValues);
7739
7740 // Remove dead phis that were moved to the epilogue preheader but are unused
7741 // (e.g., resume phis for inductions not widened in the epilogue vector loop).
7742 for (PHINode &Phi : make_early_inc_range(VecEpiloguePreHeader->phis()))
7743 if (Phi.use_empty())
7744 Phi.eraseFromParent();
7745}
7746
7748 assert((EnableVPlanNativePath || L->isInnermost()) &&
7749 "VPlan-native path is not enabled. Only process inner loops.");
7750
7751 LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
7752 << L->getHeader()->getParent()->getName() << "' from "
7753 << L->getLocStr() << "\n");
7754
7755 LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
7756
7757 LLVM_DEBUG(
7758 dbgs() << "LV: Loop hints:"
7759 << " force="
7761 ? "disabled"
7763 ? "enabled"
7764 : "?"))
7765 << " width=" << Hints.getWidth()
7766 << " interleave=" << Hints.getInterleave() << "\n");
7767
7768 // Function containing loop
7769 Function *F = L->getHeader()->getParent();
7770
7771 // Looking at the diagnostic output is the only way to determine if a loop
7772 // was vectorized (other than looking at the IR or machine code), so it
7773 // is important to generate an optimization remark for each loop. Most of
7774 // these messages are generated as OptimizationRemarkAnalysis. Remarks
7775 // generated as OptimizationRemark and OptimizationRemarkMissed are
7776 // less verbose reporting vectorized loops and unvectorized loops that may
7777 // benefit from vectorization, respectively.
7778
7779 if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
7780 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
7781 return false;
7782 }
7783
7784 PredicatedScalarEvolution PSE(*SE, *L);
7785
7786 // Query this against the original loop and save it here because the profile
7787 // of the original loop header may change as the transformation happens.
7788 bool OptForSize = llvm::shouldOptimizeForSize(
7789 L->getHeader(), PSI,
7790 PSI && PSI->hasProfileSummary() ? &GetBFI() : nullptr,
7792
7793 // Check if it is legal to vectorize the loop.
7794 LoopVectorizationRequirements Requirements;
7795 LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, F, *LAIs, LI, ORE,
7796 &Requirements, &Hints, DB, AC,
7797 /*AllowRuntimeSCEVChecks=*/!OptForSize, AA);
7799 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
7800 Hints.emitRemarkWithHints();
7801 return false;
7802 }
7803
7804 bool IsInnerLoop = L->isInnermost();
7805
7806 // Outer loops require a computable trip count.
7807 if (!IsInnerLoop && isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
7808 LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
7809 return false;
7810 }
7811
7812 if (LVL.hasUncountableEarlyExit()) {
7814 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
7815 "early exit is not enabled",
7816 "UncountableEarlyExitLoopsDisabled", ORE, L);
7817 return false;
7818 }
7821 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
7822 "early exit and side effects is not enabled",
7823 "UncountableEarlyExitSideEffectLoopsDisabled",
7824 ORE, L);
7825 return false;
7826 }
7827 }
7828
7829 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI(), OptForSize);
7830 bool UseInterleaved =
7831 IsInnerLoop && TTI->enableInterleavedAccessVectorization();
7832
7833 // If an override option has been passed in for interleaved accesses, use it.
7834 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
7835 UseInterleaved = IsInnerLoop && EnableInterleavedMemAccesses;
7836
7837 // Analyze interleaved memory accesses.
7838 if (UseInterleaved)
7840
7841 if (LVL.hasUncountableEarlyExit()) {
7842 BasicBlock *LoopLatch = L->getLoopLatch();
7843 if (IAI.requiresScalarEpilogue() ||
7844 any_of(LVL.getCountableExitingBlocks(), not_equal_to(LoopLatch))) {
7845 reportVectorizationFailure("Auto-vectorization of early exit loops "
7846 "requiring a scalar epilogue is unsupported",
7847 "UncountableEarlyExitUnsupported", ORE, L);
7848 return false;
7849 }
7850 }
7851
7852 // Check the function attributes and profiles to find out if this function
7853 // should be optimized for size.
7854 EpilogueLowering SEL =
7855 getEpilogueLowering(F, L, Hints, OptForSize, TTI, TLI, LVL, &IAI);
7856
7857 // Check the loop for a trip count threshold: vectorize loops with a tiny trip
7858 // count by optimizing for size, to minimize overheads.
7859 auto ExpectedTC = getSmallBestKnownTC(PSE, L);
7860 if (ExpectedTC && ExpectedTC->isFixed() &&
7861 ExpectedTC->getFixedValue() < TinyTripCountVectorThreshold) {
7862 LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
7863 << "This loop is worth vectorizing only if no scalar "
7864 << "iteration overheads are incurred.");
7866 LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
7867 else {
7868 LLVM_DEBUG(dbgs() << "\n");
7869 // Tail-folded loops are efficient even when the loop
7870 // iteration count is low. However, setting the epilogue policy to
7871 // `CM_EpilogueNotAllowedLowTripLoop` prevents vectorizing loops
7872 // with runtime checks. It's more effective to let
7873 // `isOutsideLoopWorkProfitable` determine if vectorization is
7874 // beneficial for the loop.
7877 }
7878 }
7879
7880 // Check the function attributes to see if implicit floats or vectors are
7881 // allowed.
7882 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7884 "Can't vectorize when the NoImplicitFloat attribute is used",
7885 "loop not vectorized due to NoImplicitFloat attribute",
7886 "NoImplicitFloat", ORE, L);
7887 Hints.emitRemarkWithHints();
7888 return false;
7889 }
7890
7891 // Check if the target supports potentially unsafe FP vectorization.
7892 // FIXME: Add a check for the type of safety issue (denormal, signaling)
7893 // for the target we're vectorizing for, to make sure none of the
7894 // additional fp-math flags can help.
7895 if (Hints.isPotentiallyUnsafe() &&
7896 TTI->isFPVectorizationPotentiallyUnsafe()) {
7898 "Potentially unsafe FP op prevents vectorization",
7899 "loop not vectorized due to unsafe FP support.", "UnsafeFP", ORE, L);
7900 Hints.emitRemarkWithHints();
7901 return false;
7902 }
7903
7904 bool AllowOrderedReductions;
7905 // If the flag is set, use that instead and override the TTI behaviour.
7906 if (ForceOrderedReductions.getNumOccurrences() > 0)
7907 AllowOrderedReductions = ForceOrderedReductions;
7908 else
7909 AllowOrderedReductions = TTI->enableOrderedReductions();
7910 if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
7911 ORE->emit([&]() {
7912 auto *ExactFPMathInst = Requirements.getExactFPInst();
7913 return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
7914 ExactFPMathInst->getDebugLoc(),
7915 ExactFPMathInst->getParent())
7916 << "loop not vectorized: cannot prove it is safe to reorder "
7917 "floating-point operations";
7918 });
7919 LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
7920 "reorder floating-point operations\n");
7921 Hints.emitRemarkWithHints();
7922 return false;
7923 }
7924
7925 // Use the cost model.
7926 VFSelectionContext Config(*TTI, &LVL, L, *F, PSE, DB, ORE, &Hints,
7927 OptForSize);
7928 // Use the planner for vectorization.
7930 L, LI, DT, TLI, *TTI, &LVL,
7931 std::make_unique<LoopVectorizationCostModel>(
7932 SEL, L, PSE, LI, &LVL, *TTI, TLI, AC, ORE, GetBFI, F, IAI, Config),
7933 Config, IAI, PSE, ORE);
7934
7935 EpilogueLowering EpilogueTailLoweringStatus =
7936 getEpilogueTailLowering(LVP.getCostModel(), L, ORE, LVL, Hints);
7937 if (EpilogueTailLoweringStatus ==
7939 // TODO: Apply tail-folding on the vectorized epilogue loop.
7940 LLVM_DEBUG(dbgs() << "LV: epilogue tail-folding is not supported yet\n");
7942 "The epilogue-tail-folding policy prefer-fold-tail is not supported "
7943 "yet, fall back to a normal epilogue",
7944 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
7945 }
7946
7947 // Get user vectorization factor and interleave count.
7948 ElementCount UserVF = Hints.getWidth();
7949 unsigned UserIC = Hints.getInterleave();
7950 // Outer loops don't have LoopAccessInfo, so skip the safety check and reset
7951 // UserIC (interleaving is not supported for outer loops).
7952 if (!IsInnerLoop)
7953 UserIC = 0;
7954 else if (UserIC > 1 && !LVL.isSafeForAnyVectorWidth())
7955 UserIC = 1;
7956
7957 // Plan how to best vectorize.
7958 LVP.plan(UserVF, UserIC);
7959 auto [VF, BestPlanPtr] = LVP.computeBestVF();
7960 unsigned IC = 1;
7961
7962 // For VPlan build stress testing of outer loops, bail after plan
7963 // construction.
7964 if (!IsInnerLoop && VPlanBuildOuterloopStressTest)
7965 return false;
7966
7967 if (IsInnerLoop && ORE->allowExtraAnalysis(LV_NAME))
7969
7970 assert((IsInnerLoop || !LVP.getCostModel().maskPartialAliasing()) &&
7971 "Did not expect to alias-mask outer loop");
7972
7973 GeneratedRTChecks Checks(PSE, DT, LI, TTI, Config.CostKind,
7975 if (IsInnerLoop && LVP.hasPlanWithVF(VF.Width)) {
7976 // Select the interleave count.
7977 IC = LVP.selectInterleaveCount(*BestPlanPtr, VF.Width, VF.Cost);
7978
7979 unsigned SelectedIC = std::max(IC, UserIC);
7980 // Optimistically generate runtime checks if they are needed. Drop them if
7981 // they turn out to not be profitable.
7982 if (VF.Width.isVector() || SelectedIC > 1) {
7983 Checks.create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC,
7984 *ORE);
7985
7986 // Bail out early if either the SCEV or memory runtime checks are known to
7987 // fail. In that case, the vector loop would never execute.
7988 using namespace llvm::PatternMatch;
7989 if (Checks.getSCEVChecks().first &&
7990 match(Checks.getSCEVChecks().first, m_One()))
7991 return false;
7992 if (Checks.getMemRuntimeChecks().first &&
7993 match(Checks.getMemRuntimeChecks().first, m_One()))
7994 return false;
7995 }
7996
7997 // Check if it is profitable to vectorize with runtime checks.
7998 bool ForceVectorization =
8000 VPCostContext CostCtx(*TLI, *BestPlanPtr, LVP.getCostModel(), Config,
8001 /*ReusePrintingSlotTracker=*/true);
8002 if (!ForceVectorization &&
8003 !isOutsideLoopWorkProfitable(Checks, VF, L, PSE, CostCtx, *BestPlanPtr,
8004 SEL, Config.getVScaleForTuning())) {
8005 ORE->emit([&]() {
8007 DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
8008 L->getHeader())
8009 << "loop not vectorized: cannot prove it is safe to reorder "
8010 "memory operations";
8011 });
8012 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
8013 Hints.emitRemarkWithHints();
8014 return false;
8015 }
8016 }
8017
8018 // Identify the diagnostic messages that should be produced.
8019 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
8020 bool VectorizeLoop = true, InterleaveLoop = true;
8021 if (VF.Width.isScalar()) {
8022 LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
8023 VecDiagMsg = {
8024 "VectorizationNotBeneficial",
8025 "the cost-model indicates that vectorization is not beneficial"};
8026 VectorizeLoop = false;
8027 }
8028
8029 if (UserIC == 1 && Hints.getInterleave() > 1) {
8031 "UserIC should only be ignored due to unsafe dependencies");
8032 LLVM_DEBUG(dbgs() << "LV: Ignoring user-specified interleave count.\n");
8033 IntDiagMsg = {"InterleavingUnsafe",
8034 "Ignoring user-specified interleave count due to possibly "
8035 "unsafe dependencies in the loop."};
8036 InterleaveLoop = false;
8037 } else if (!LVP.hasPlanWithVF(VF.Width) && UserIC > 1) {
8038 // Tell the user interleaving was avoided up-front, despite being explicitly
8039 // requested.
8040 LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
8041 "interleaving should be avoided up front\n");
8042 IntDiagMsg = {"InterleavingAvoided",
8043 "Ignoring UserIC, because interleaving was avoided up front"};
8044 InterleaveLoop = false;
8045 } else if (IC == 1 && UserIC <= 1) {
8046 // Tell the user interleaving is not beneficial.
8047 LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
8048 IntDiagMsg = {
8049 "InterleavingNotBeneficial",
8050 "the cost-model indicates that interleaving is not beneficial"};
8051 InterleaveLoop = false;
8052 if (UserIC == 1) {
8053 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
8054 IntDiagMsg.second +=
8055 " and is explicitly disabled or interleave count is set to 1";
8056 }
8057 } else if (IC > 1 && UserIC == 1) {
8058 // Tell the user interleaving is beneficial, but it explicitly disabled.
8059 LLVM_DEBUG(dbgs() << "LV: Interleaving is beneficial but is explicitly "
8060 "disabled.\n");
8061 IntDiagMsg = {"InterleavingBeneficialButDisabled",
8062 "the cost-model indicates that interleaving is beneficial "
8063 "but is explicitly disabled or interleave count is set to 1"};
8064 InterleaveLoop = false;
8065 }
8066
8067 // If there is a histogram in the loop, do not just interleave without
8068 // vectorizing. The order of operations will be incorrect without the
8069 // histogram intrinsics, which are only used for recipes with VF > 1.
8070 if (!VectorizeLoop && InterleaveLoop && LVL.hasHistograms()) {
8071 LLVM_DEBUG(dbgs() << "LV: Not interleaving without vectorization due "
8072 << "to histogram operations.\n");
8073 IntDiagMsg = {
8074 "HistogramPreventsScalarInterleaving",
8075 "Unable to interleave without vectorization due to constraints on "
8076 "the order of histogram operations"};
8077 InterleaveLoop = false;
8078 }
8079
8080 // Override IC if user provided an interleave count.
8081 IC = UserIC > 0 ? UserIC : IC;
8082
8083 if (LVP.getCostModel().maskPartialAliasing()) {
8084 LLVM_DEBUG(
8085 dbgs()
8086 << "LV: Not interleaving due to partial aliasing vectorization.\n");
8087 IntDiagMsg = {
8088 "PartialAliasingVectorization",
8089 "Unable to interleave due to partial aliasing vectorization."};
8090 InterleaveLoop = false;
8091 IC = 1;
8092 }
8093
8094 // FIXME: Enable interleaving for EE-with-side-effects.
8095 if (InterleaveLoop && LVL.hasUncountableExitWithSideEffects()) {
8096 LLVM_DEBUG(dbgs() << "LV: Not interleaving due to EE with side effects.\n");
8097 IntDiagMsg = {"EEWithSideEffectsPreventsInterleaving",
8098 "Unable to interleave due to early exit with side effects."};
8099 InterleaveLoop = false;
8100 IC = 1;
8101 }
8102
8103 // Emit diagnostic messages, if any.
8104 if (!VectorizeLoop && !InterleaveLoop) {
8105 // Do not vectorize or interleaving the loop.
8106 ORE->emit([&]() {
8107 return OptimizationRemarkMissed(LV_NAME, VecDiagMsg.first,
8108 L->getStartLoc(), L->getHeader())
8109 << VecDiagMsg.second;
8110 });
8111 ORE->emit([&]() {
8112 return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
8113 L->getStartLoc(), L->getHeader())
8114 << IntDiagMsg.second;
8115 });
8116 return false;
8117 }
8118
8119 if (!VectorizeLoop && InterleaveLoop) {
8120 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
8121 ORE->emit([&]() {
8122 return OptimizationRemarkAnalysis(LV_NAME, VecDiagMsg.first,
8123 L->getStartLoc(), L->getHeader())
8124 << VecDiagMsg.second;
8125 });
8126 } else if (VectorizeLoop && !InterleaveLoop) {
8127 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
8128 << ") in " << L->getLocStr() << '\n');
8129 ORE->emit([&]() {
8130 return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
8131 L->getStartLoc(), L->getHeader())
8132 << IntDiagMsg.second;
8133 });
8134 } else if (VectorizeLoop && InterleaveLoop) {
8135 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
8136 << ") in " << L->getLocStr() << '\n');
8137 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
8138 }
8139
8140 // Report the vectorization decision.
8141 if (VF.Width.isScalar()) {
8142 using namespace ore;
8143 assert(IC > 1);
8144 ORE->emit([&]() {
8145 return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
8146 L->getHeader())
8147 << "interleaved loop (interleaved count: "
8148 << NV("InterleaveCount", IC) << ")";
8149 });
8150 } else {
8151 // Report the vectorization decision.
8152 reportVectorization(ORE, L, VF.Width, IC);
8153 }
8154 if (ORE->allowExtraAnalysis(LV_NAME))
8156
8157 // If we decided that it is *legal* to interleave or vectorize the loop, then
8158 // do it.
8159
8160 // Whether a scalar epilogue may be created is decided by the epilogue
8161 // lowering policy.
8162 // TODO: Also move check to be based on VPlan.
8163 bool ScalarEpilogueAllowed = LVP.getCostModel().isEpilogueAllowed();
8164
8165 // Destroy the cost model before executing any plan, so that code generation
8166 // cannot rely on cost-modeling decisions.
8167 LVP.clearCostModel();
8168
8169 VPlan &BestPlan = *BestPlanPtr;
8170 // Consider vectorizing the epilogue too if it's profitable.
8171 std::unique_ptr<VPlan> EpiPlan =
8172 LVP.selectBestEpiloguePlan(BestPlan, VF.Width, IC, ScalarEpilogueAllowed);
8173 bool HasBranchWeights =
8174 hasBranchWeightMD(*L->getLoopLatch()->getTerminator());
8175 if (EpiPlan) {
8176 VPlan &BestEpiPlan = *EpiPlan;
8177 VPlan &BestMainPlan = BestPlan;
8178 ElementCount EpilogueVF = BestEpiPlan.getSingleVF();
8179
8180 // The first pass vectorizes the main loop and creates a scalar epilogue
8181 // to be vectorized by executing the plan (potentially with a different
8182 // factor) again shortly afterwards.
8183 BestEpiPlan.getMiddleBlock()->setName("vec.epilog.middle.block");
8184 BestEpiPlan.getVectorPreheader()->setName("vec.epilog.ph");
8185 SmallVector<VPInstruction *> ResumeValues =
8186 preparePlanForMainVectorLoop(BestMainPlan, BestEpiPlan);
8187 EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF, 1);
8188
8189 // Add minimum iteration check for the epilogue plan, followed by runtime
8190 // checks for the main plan.
8191 LVP.addMinimumIterationCheck(BestMainPlan, EPI.EpilogueVF, EPI.EpilogueUF,
8193 LVP.attachRuntimeChecks(BestMainPlan, Checks, HasBranchWeights);
8196 EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan.requiresScalarEpilogue(),
8197 L, HasBranchWeights ? MinItersBypassWeights : nullptr,
8198 L->getLoopPredecessor()->getTerminator()->getDebugLoc(), PSE);
8199
8200 EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TTI, AC, EPI, Checks,
8201 BestMainPlan);
8202 auto ExpandedSCEVs = LVP.executePlan(
8203 EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV, DT,
8205 ++LoopsVectorized;
8206
8207 // Derive EPI fields from VPlan-generated IR.
8208 BasicBlock *EntryBB =
8209 cast<VPIRBasicBlock>(BestMainPlan.getEntry())->getIRBasicBlock();
8210 EntryBB->setName("iter.check");
8211 EPI.EpilogueIterationCountCheck = EntryBB;
8212 // The check chain is: Entry -> [SCEV] -> [Mem] -> MainCheck -> VecPH.
8213 // MainCheck is the non-bypass successor of the last runtime check block
8214 // (or Entry if there are no runtime checks).
8215 BasicBlock *LastCheck = EntryBB;
8216 if (BasicBlock *MemBB = Checks.getMemRuntimeChecks().second)
8217 LastCheck = MemBB;
8218 else if (BasicBlock *SCEVBB = Checks.getSCEVChecks().second)
8219 LastCheck = SCEVBB;
8220 BasicBlock *ScalarPH = L->getLoopPreheader();
8221 auto *BI = cast<CondBrInst>(LastCheck->getTerminator());
8223 BI->getSuccessor(BI->getSuccessor(0) == ScalarPH);
8224
8225 // Second pass vectorizes the epilogue and adjusts the control flow
8226 // edges from the first pass.
8227 EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TTI, AC, EPI,
8228 Checks, BestEpiPlan);
8230 BestMainPlan, BestEpiPlan, L, ExpandedSCEVs, EPI, LVP, Config,
8231 *PSE.getSE(), ResumeValues);
8233 LVP.executePlan(
8234 EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV, DT,
8236 connectEpilogueVectorLoop(BestEpiPlan, L, EPI, DT, Checks, InstsToMove,
8237 ResumeValues);
8238 ++LoopsEpilogueVectorized;
8239 } else {
8240 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, IC, Checks,
8241 BestPlan);
8242 LVP.addMinimumIterationCheck(BestPlan, VF.Width, IC,
8243 VF.MinProfitableTripCount);
8244 LVP.attachRuntimeChecks(BestPlan, Checks, HasBranchWeights);
8245
8246 if (!IsInnerLoop)
8247 LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \"" << F->getName()
8248 << "\"\n");
8249 LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
8250 ++LoopsVectorized;
8251 }
8252
8253 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
8254 "DT not preserved correctly");
8255
8256 return true;
8257}
8258
8260 CFGChanged = false;
8261
8262 // Don't attempt if
8263 // 1. the target claims to have no vector registers, and
8264 // 2. interleaving won't help ILP.
8265 //
8266 // The second condition is necessary because, even if the target has no
8267 // vector registers, loop vectorization may still enable scalar
8268 // interleaving.
8269 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
8270 (TTI->getMaxInterleaveFactor(ElementCount::getFixed(1), false) < 2 ||
8271 TTI->getMaxInterleaveFactor(ElementCount::getFixed(1), true) < 2))
8272 return LoopVectorizeResult(false, false);
8273
8274 bool Changed = false;
8275
8276 // The vectorizer requires loops to be in simplified form.
8277 // Since simplification may add new inner loops, it has to run before the
8278 // legality and profitability checks. This means running the loop vectorizer
8279 // will simplify all loops, regardless of whether anything end up being
8280 // vectorized.
8281 for (const auto &L : *LI)
8282 Changed |= CFGChanged |=
8283 simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
8284
8285 // Build up a worklist of inner-loops to vectorize. This is necessary as
8286 // the act of vectorizing or partially unrolling a loop creates new loops
8287 // and can invalidate iterators across the loops.
8288 SmallVector<Loop *, 8> Worklist;
8289
8290 for (Loop *L : *LI)
8291 collectSupportedLoops(*L, LI, ORE, Worklist);
8292
8293 LoopsAnalyzed += Worklist.size();
8294
8295 // Now walk the identified inner loops.
8296 while (!Worklist.empty()) {
8297 Loop *L = Worklist.pop_back_val();
8298
8299 // For the inner loops we actually process, form LCSSA to simplify the
8300 // transform.
8301 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
8302
8304
8305 if (Changed) {
8306 LAIs->clear();
8307
8308#ifndef NDEBUG
8309 if (VerifySCEV)
8310 SE->verify();
8311#endif
8312 }
8313 }
8314
8315 // Verify once per function rather than once per processed loop, which would
8316 // make the pass quadratic in the number of loops.
8317 assert((!Changed || !verifyFunction(F, &dbgs())) &&
8318 "Invalid IR produced by LoopVectorize");
8319
8320 // Process each loop nest in the function.
8322}
8323
8326 LI = &AM.getResult<LoopAnalysis>(F);
8327 // There are no loops in the function. Return before computing other
8328 // expensive analyses.
8329 if (LI->empty())
8330 return PreservedAnalyses::all();
8339 AA = &AM.getResult<AAManager>(F);
8340
8341 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
8342 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
8343 GetBFI = [this, &AM, &F]() -> BlockFrequencyInfo & {
8344 // CycleInfo cached by an earlier pass is invalidated when the CFG changes.
8348 };
8349 LoopVectorizeResult Result = runImpl(F);
8350 if (!Result.MadeAnyChange)
8351 return PreservedAnalyses::all();
8353
8354 if (isAssignmentTrackingEnabled(*F.getParent())) {
8355 for (auto &BB : F)
8357 }
8358
8359 PA.preserve<LoopAnalysis>();
8363
8364 if (Result.MadeCFGChange) {
8365 // Making CFG changes likely means a loop got vectorized. Indicate that
8366 // extra simplification passes should be run.
8367 // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
8368 // be run if runtime checks have been added.
8371 } else {
8373 }
8374 return PA;
8375}
8376
8378 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
8379 static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
8380 OS, MapClassName2PassName);
8381
8382 OS << '<';
8383 OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
8384 OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
8385 OS << '>';
8386}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Lower Kernel Arguments
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(const Function &Caller, const Function &Callee)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
This is the interface for LLVM's primary stateless and local alias analysis.
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static InstructionCost getCost(Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:73
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
This file defines the DenseMap class.
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static cl::opt< ElementCount, true > VectorizationFactor("force-vector-width", cl::Hidden, cl::desc("Sets the SIMD width. Zero is autoselect."), cl::location(VectorizerParams::VectorizationFactor))
This header provides classes for managing per-loop analyses.
static const char * VerboseDebug
#define LV_NAME
This file defines the LoopVectorizationLegality class.
cl::opt< bool > VPlanBuildOuterloopStressTest
static cl::opt< bool > ConsiderRegPressure("vectorizer-consider-reg-pressure", cl::init(false), cl::Hidden, cl::desc("Discard VFs if their register pressure is too high."))
This file provides a LoopVectorizationPlanner class.
static void collectSupportedLoops(Loop &L, LoopInfo *LI, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Loop * > &V)
static cl::opt< unsigned > EpilogueVectorizationMinVF("epilogue-vectorization-minimum-VF", cl::Hidden, cl::desc("Only loops with vectorization factor equal to or larger than " "the specified value are considered for epilogue vectorization."))
static unsigned getMaxTCFromNonZeroRange(PredicatedScalarEvolution &PSE, Loop *L)
Get the maximum trip count for L from the SCEV unsigned range, excluding zero from the range.
static SmallVector< Instruction * > preparePlanForEpilogueVectorLoop(VPlan &MainPlan, VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationPlanner &LVP, VFSelectionContext &Config, ScalarEvolution &SE, ArrayRef< VPInstruction * > ResumeValues)
Prepare Plan for vectorizing the epilogue loop.
static Type * maybeVectorizeType(Type *Ty, ElementCount VF)
static ElementCount getSmallConstantTripCount(ScalarEvolution *SE, const Loop *L)
A version of ScalarEvolution::getSmallConstantTripCount that returns an ElementCount to include loops...
static cl::opt< unsigned > VectorizeMemoryCheckThreshold("vectorize-memory-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum allowed number of runtime memory checks"))
static void connectEpilogueVectorLoop(VPlan &EpiPlan, Loop *L, EpilogueLoopVectorizationInfo &EPI, DominatorTree *DT, GeneratedRTChecks &Checks, ArrayRef< Instruction * > InstsToMove, ArrayRef< VPInstruction * > ResumeValues)
Connect the epilogue vector loop generated for EpiPlan to the main vector loop, after both plans have...
static cl::opt< unsigned > TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), cl::Hidden, cl::desc("Loops with a constant trip count that is smaller than this " "value are vectorized only if no scalar iteration overheads " "are incurred."))
Loops with a known constant trip count below this number are vectorized only if no scalar iteration o...
static cl::opt< unsigned > PragmaVectorizeSCEVCheckThreshold("pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed with a " "vectorize(enable) pragma"))
static cl::opt< cl::boolOrDefault > ForceMaskedDivRem("force-widen-divrem-via-masked-intrinsic", cl::Hidden, cl::desc("Override cost based masked intrinsic widening " "for div/rem instructions"))
static void legacyCSE(BasicBlock *BB)
FIXME: This legacy common-subexpression-elimination routine is scheduled for removal,...
static VPIRBasicBlock * replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB, VPlan *Plan=nullptr)
Replace VPBB with a VPIRBasicBlock wrapping IRBB.
static Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
static DebugLoc getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or its operands.
TailFoldingPolicyTy
Option tail-folding-policy controls the tail-folding strategy and lists all available options.
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
static cl::opt< TailFoldingPolicyTy > EpilogueTailFoldingPolicy("epilogue-tail-folding-policy", cl::Hidden, cl::desc("Epilogue-tail-folding preferences over creating an epilogue loop."), cl::values(clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail", "Don't tail-fold loops."), clEnumValN(TailFoldingPolicyTy::PreferFoldTail, "prefer-fold-tail", "prefer tail-folding, otherwise create an epilogue when " "appropriate.")))
static cl::opt< bool > EnableEarlyExitVectorization("enable-early-exit-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of early exit loops with uncountable exits."))
static unsigned estimateElementCount(ElementCount VF, std::optional< unsigned > VScale)
This function attempts to return a value that represents the ElementCount at runtime.
static bool hasVectorLibraryVariantFor(const CallInst &CI, ElementCount VF, bool MaskRequired, const TargetLibraryInfo *TLI)
Returns true iff CI has a library vector variant usable at VF.
static constexpr uint32_t MinItersBypassWeights[]
static cl::opt< unsigned > ForceTargetNumScalarRegs("force-target-num-scalar-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of scalar registers."))
static SmallVector< VPInstruction * > preparePlanForMainVectorLoop(VPlan &MainPlan, VPlan &EpiPlan)
Prepare MainPlan for vectorizing the main vector loop during epilogue vectorization.
static cl::opt< unsigned > SmallLoopCost("small-loop-cost", cl::init(20), cl::Hidden, cl::desc("The cost of a loop that is considered 'small' by the interleaver."))
static cl::opt< bool > ForcePartialAliasingVectorization("force-partial-aliasing-vectorization", cl::init(false), cl::Hidden, cl::desc("Replace pointer diff checks with alias masks."))
static Function * getVectorLibraryVariantFor(const CallInst &CI, ElementCount VF, bool MaskRequired, const TargetLibraryInfo *TLI)
Returns the vector library variant function of CI usable at VF, respecting MaskRequired,...
static cl::opt< unsigned > ForceTargetNumVectorRegs("force-target-num-vector-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of vector registers."))
static bool isExplicitVecOuterLoop(Loop *OuterLp, OptimizationRemarkEmitter *ORE)
static cl::opt< bool > EnableIndVarRegisterHeur("enable-ind-var-reg-heur", cl::init(true), cl::Hidden, cl::desc("Count the induction variable only once when interleaving"))
static bool hasForcedEpilogueVF()
static EpilogueLowering getEpilogueTailLowering(const LoopVectorizationCostModel &MainCM, const Loop *L, OptimizationRemarkEmitter *ORE, LoopVectorizationLegality &LVL, LoopVectorizeHints &Hints)
Determine how to lower the epilogue for the vector epilogue loop.
static cl::opt< TailFoldingStyle > ForceTailFoldingStyle("force-tail-folding-style", cl::desc("Force the tail folding style"), cl::init(TailFoldingStyle::None), cl::values(clEnumValN(TailFoldingStyle::None, "none", "Disable tail folding"), clEnumValN(TailFoldingStyle::Data, "data", "Create lane mask for data only, using active.lane.mask intrinsic"), clEnumValN(TailFoldingStyle::DataWithoutLaneMask, "data-without-lane-mask", "Create lane mask with compare/stepvector"), clEnumValN(TailFoldingStyle::DataAndControlFlow, "data-and-control", "Create lane mask using active.lane.mask intrinsic, and use " "it for both data and control flow"), clEnumValN(TailFoldingStyle::DataWithEVL, "data-with-evl", "Use predicated EVL instructions for tail folding. If EVL " "is unsupported, fallback to data-without-lane-mask.")))
static void printOptimizedVPlan(VPlan &)
static cl::opt< bool > EnableEpilogueVectorization("enable-epilogue-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of epilogue loops."))
static cl::opt< bool > PreferPredicatedReductionSelect("prefer-predicated-reduction-select", cl::init(false), cl::Hidden, cl::desc("Prefer predicating a reduction operation over an after loop select."))
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
static cl::opt< bool > EnableLoadStoreRuntimeInterleave("enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, cl::desc("Enable runtime interleaving until load/store ports are saturated"))
static cl::opt< bool > LoopVectorizeWithBlockFrequency("loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden, cl::desc("Enable the use of the block frequency analysis to access PGO " "heuristics minimizing code growth in cold regions and being more " "aggressive in hot regions."))
static bool useActiveLaneMask(TailFoldingStyle Style)
static bool hasReplicatorRegion(VPlan &Plan)
static std::optional< ElementCount > getSmallBestKnownTC(PredicatedScalarEvolution &PSE, Loop *L, bool CanUseConstantMax=true, bool CanExcludeZeroTrips=false, bool ComputeUpperBoundOnly=false)
Returns "best known" trip count, which is either a valid positive trip count or std::nullopt when an ...
static bool isIndvarOverflowCheckKnownFalse(const LoopVectorizationCostModel *Cost, ElementCount VF, std::optional< unsigned > UF=std::nullopt)
For the given VF and UF and maximum trip count computed for the loop, return whether the induction va...
static void addFullyUnrolledInstructionsToIgnore(Loop *L, const LoopVectorizationLegality::InductionList &IL, SmallPtrSetImpl< Instruction * > &InstsToIgnore)
Knowing that loop L executes a single vector iteration, add instructions that will get simplified and...
static bool hasFindLastReductionPhi(VPlan &Plan)
Returns true if the VPlan contains a VPReductionPHIRecipe with FindLast recurrence kind.
static cl::opt< bool > EnableInterleavedMemAccesses("enable-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on interleaved memory accesses in a loop"))
static cl::opt< unsigned > VectorizeSCEVCheckThreshold("vectorize-scev-check-threshold", cl::init(16), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed."))
static cl::opt< bool > EnableMaskedInterleavedMemAccesses("enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"))
An interleave-group may need masking if it resides in a block that needs predication,...
static cl::opt< bool > ForceOrderedReductions("force-ordered-reductions", cl::init(false), cl::Hidden, cl::desc("Enable the vectorisation of loops with in-order (strict) " "FP reductions"))
static cl::opt< bool > EnableEarlyExitVectorizationWithSideEffects("enable-early-exit-vectorization-with-side-effects", cl::init(false), cl::Hidden, cl::desc("Enable vectorization of early exit loops with uncountable exits " "and side effects"))
static bool verifyExecutionFrequenciesMatchBFI(VPlan &Plan, Loop *OrigLoop, LoopInfo *LI, LoopVectorizationCostModel &CM)
Cross-check vputils::computeExecutionFrequencies for the loop region of Plan against BlockFrequencyIn...
static cl::opt< TailFoldingPolicyTy > TailFoldingPolicy("tail-folding-policy", cl::init(TailFoldingPolicyTy::None), cl::Hidden, cl::desc("Tail-folding preferences over creating an epilogue loop."), cl::values(clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail", "Don't tail-fold loops."), clEnumValN(TailFoldingPolicyTy::PreferFoldTail, "prefer-fold-tail", "prefer tail-folding, otherwise create an epilogue when " "appropriate."), clEnumValN(TailFoldingPolicyTy::MustFoldTail, "must-fold-tail", "always tail-fold, don't attempt vectorization if " "tail-folding fails.")))
static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks, VectorizationFactor &VF, Loop *L, PredicatedScalarEvolution &PSE, VPCostContext &CostCtx, VPlan &Plan, EpilogueLowering SEL, std::optional< unsigned > VScale)
This function determines whether or not it's still profitable to vectorize the loop given the extra w...
static InstructionCost calculateEarlyExitCost(VPCostContext &CostCtx, VPlan &Plan, ElementCount VF)
For loops with uncountable early exits, find the cost of doing work when exiting the loop early,...
cl::opt< bool > VPlanBuildOuterloopStressTest("vplan-build-outerloop-stress-test", cl::init(false), cl::Hidden, cl::desc("Build VPlan for every supported loop nest in the function and bail " "out right after the build (stress test the VPlan H-CFG construction " "in the VPlan-native vectorization path)."))
static cl::opt< unsigned > ForceTargetMaxVectorInterleaveFactor("force-target-max-vector-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "vectorized loops."))
static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI)
cl::opt< unsigned > NumberOfStoresToPredicate("vectorize-num-stores-pred", cl::init(1), cl::Hidden, cl::desc("Max number of stores to be predicated behind an if."))
The number of stores in a loop that are allowed to need predication.
static EpilogueLowering getEpilogueLowering(Function *F, Loop *L, LoopVectorizeHints &Hints, bool OptForSize, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, LoopVectorizationLegality &LVL, InterleavedAccessInfo *IAI)
static void fixScalarResumeValuesFromBypass(BasicBlock *BypassBlock, Loop *L, VPlan &BestEpiPlan, ArrayRef< VPInstruction * > ResumeValues)
static cl::opt< unsigned > MaxNestedScalarReductionIC("max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden, cl::desc("The maximum interleave count to use when interleaving a scalar " "reduction in a nested loop."))
static cl::opt< unsigned > ForceTargetMaxScalarInterleaveFactor("force-target-max-scalar-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "scalar loops."))
static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE)
static cl::opt< ElementCount > EpilogueVectorizationForceVF("epilogue-vectorization-force-VF", cl::init(ElementCount::getFixed(1)), cl::Hidden, cl::desc("When epilogue vectorization is enabled, and a value greater than " "1 is specified, forces the given VF for all applicable epilogue " "loops. Note: This allows all scalable VFs >= vscale x 1."))
static bool willGenerateVectors(VPlan &Plan, ElementCount VF, const TargetTransformInfo &TTI)
Check if any recipe of Plan will generate a vector value, which will be assigned a vector register.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
SI Fold Operands
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
#define OP(OPC)
Definition Instruction.h:46
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
This pass exposes codegen information to IR-level passes.
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
#define RUN_VPLAN_PASS(PASS,...)
#define RUN_VPLAN_PASS_NO_VERIFY(PASS,...)
This file declares the class VPlanVerifier, which contains utility functions to check the consistency...
This file contains the declarations of the Vectorization Plan base classes:
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
A manager for alias analyses.
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
void clearAnalysis(IRUnitT &IR)
Directly clear a cached analysis for an IR unit.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static uint32_t getDenominator()
uint32_t getNumerator() const
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
Conditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This class represents a range of values.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
Analysis pass which computes a CycleInfo.
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getTemporary()
Definition DebugLoc.h:152
static DebugLoc getUnknown()
Definition DebugLoc.h:153
An analysis that produces DemandedBits for a function.
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:268
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
void insert_range(Range &&R)
Inserts range of 'std::pair<KeyT, ValueT>' values into the map.
Definition DenseMap.h:337
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Definition DenseMap.h:260
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:320
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:308
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:311
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
EpilogueVectorizerEpilogueLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, GeneratedRTChecks &Checks, VPlan &Plan)
BasicBlock * createVectorizedLoopSkeleton() final
Implements the interface for creating a vectorized skeleton using the epilogue loop strategy (i....
void printDebugTracesAtStart() override
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
A specialized derived class of inner loop vectorizer that performs vectorization of main loops in the...
EpilogueVectorizerMainLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, GeneratedRTChecks &Check, VPlan &Plan)
void printDebugTracesAtStart() override
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
Tagged union holding either a T or a Error.
Definition Error.h:485
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Class to represent function types.
param_iterator param_begin() const
param_iterator param_end() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2910
A struct for saving information about induction variables.
const SCEV * getStep() const
ArrayRef< Instruction * > getCastInsts() const
Returns an ArrayRef to the type cast instructions in the induction update chain, that are redundant w...
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
InnerLoopAndEpilogueVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, GeneratedRTChecks &Checks, VPlan &Plan, ElementCount VecWidth, unsigned UnrollFactor)
EpilogueLoopVectorizationInfo & EPI
Holds and updates state information required to vectorize the main loop and its epilogue in two separ...
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
virtual void printDebugTracesAtStart()
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
const TargetTransformInfo * TTI
Target Transform Info.
friend class LoopVectorizationPlanner
PredicatedScalarEvolution & PSE
A wrapper around ScalarEvolution used to add runtime SCEV checks.
LoopInfo * LI
Loop Info.
DominatorTree * DT
Dominator Tree.
InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, ElementCount VecWidth, unsigned UnrollFactor, GeneratedRTChecks &RTChecks, VPlan &Plan)
void fixVectorizedLoop(VPTransformState &State)
Fix the vectorized code, taking care of header phi's, and more.
virtual BasicBlock * createVectorizedLoopSkeleton()
Creates a basic block for the scalar preheader.
virtual void printDebugTracesAtEnd()
AssumptionCache * AC
Assumption Cache.
IRBuilder Builder
The builder that we use.
VPBasicBlock * VectorPHVPBB
The vector preheader block of Plan, used as target for check blocks introduced during skeleton creati...
unsigned UF
The vectorization unroll factor to use.
GeneratedRTChecks & RTChecks
Structure to hold information about generated runtime checks, responsible for cleaning the checks,...
virtual ~InnerLoopVectorizer()=default
ElementCount VF
The vectorization SIMD factor to use.
Loop * OrigLoop
The original loop.
BasicBlock * createScalarPreheader(StringRef Prefix)
Create and return a new IR basic block for the scalar preheader whose name is prefixed with Prefix.
static InstructionCost getInvalid(CostType Val=0)
static InstructionCost getMax()
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
bool isCast() const
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
LLVM_ABI APInt getMask() const
For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
Definition Type.cpp:372
The group of interleaved loads/stores sharing the same stride and close to each other.
auto members() const
Return an iterator range over the non-null members of this group, in index order.
InstTy * getInsertPos() const
uint32_t getNumMembers() const
Drive the analysis of interleaved memory accesses in the loop.
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
LLVM_ABI void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
An instruction for reading from memory.
Type * getPointerOperandType() const
This analysis provides dependence information for the memory accesses of a loop.
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
const SymbolicStrideMap & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
BlockT * getHeader() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Store the result of a depth first search within basic blocks contained by a single loop.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
LLVM_ABI void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
bool isPredicatedInst(Instruction *I) const
Returns true if I is an instruction that needs to be predicated at runtime.
void collectValuesToIgnore()
Collect values we want to ignore in the cost model.
BlockFrequencyInfo * BFI
The BlockFrequencyInfo returned from GetBFI.
BlockFrequencyInfo & getBFI()
Returns the BlockFrequencyInfo for the function if cached, otherwise fetches it via GetBFI.
bool isForcedScalar(Instruction *I, ElementCount VF) const
Returns true if I has been forced to be scalarized at VF.
bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be uniform after vectorization.
bool preferTailFoldedLoop() const
Returns true if tail-folding is preferred over an epilogue.
void collectNonVectorizedAndSetWideningDecisions(ElementCount VF)
Collect values that will not be widened, including Uniforms, Scalars, and Instructions to Scalarize f...
bool isMaskRequired(Instruction *I) const
Wrapper function for LoopVectorizationLegality::isMaskRequired, that passes the Instruction I and if ...
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
const TargetTransformInfo & TTI
Vector target information.
LoopVectorizationLegality * Legal
Vectorization legality.
uint64_t getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind, const BasicBlock *BB)
A helper function that returns how much we should divide the cost of a predicated block by.
std::optional< InstWidening > memoryInstructionCanBeWidened(Instruction *I, ElementCount VF)
If I is a memory instruction with a consecutive pointer that can be widened, returns the widening kin...
InstructionCost getInstructionCost(Instruction *I, ElementCount VF)
Returns the execution time cost of an instruction for a given vector width.
bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const
Returns true if I is a memory instruction in an interleaved-group of memory accesses that can be vect...
const TargetLibraryInfo * TLI
Target Library Info.
const InterleaveGroup< Instruction > * getInterleavedAccessGroup(Instruction *Instr) const
Get the interleaved access group that Instr belongs to.
InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const
Estimate cost of an intrinsic call instruction CI if it were vectorized with factor VF.
bool maskPartialAliasing() const
Returns true if all loop blocks should have partial aliases masked.
bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalar after vectorization.
bool isOptimizableIVTruncate(Instruction *I, ElementCount VF)
Return True if instruction I is an optimizable truncate whose operand is an induction variable.
bool isLegalGatherOrScatter(Instruction *I, ElementCount VF) const
Returns true if the target machine supports gather or scatter for I's data type and alignment.
FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC)
Loop * TheLoop
The loop that we evaluate.
InterleavedAccessInfo & InterleaveInfo
The interleave access information contains groups of interleaved accesses with the same stride and cl...
SmallPtrSet< const Value *, 16 > ValuesToIgnore
Values to ignore in the cost model.
LoopVectorizationCostModel(EpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, std::function< BlockFrequencyInfo &()> GetBFI, const Function *F, InterleavedAccessInfo &IAI, VFSelectionContext &Config)
void invalidateCostModelingDecisions()
Invalidates decisions already taken by the cost model.
bool isAccessInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleaved access group.
void setTailFoldingStyle(bool IsScalableVF, unsigned UserIC)
Selects and saves TailFoldingStyle.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
LoopInfo * LI
Loop Info analysis.
bool requiresScalarEpilogue(bool IsVectorizing) const
Returns true if we're required to use a scalar epilogue for at least the final iteration of the origi...
SmallPtrSet< const Value *, 16 > VecValuesToIgnore
Values to ignore in the cost model when VF > 1.
bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF) const
Returns true if an artificially high cost for emulated masked memrefs should be used.
bool isLegalMaskedLoadOrStore(Instruction *I, ElementCount VF) const
Returns true if the target machine supports masked loads or stores for I's data type and alignment.
bool isProfitableToScalarize(Instruction *I, ElementCount VF) const
void setWideningDecision(const InterleaveGroup< Instruction > *Grp, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for interleaving group Grp and vector ...
bool isEpilogueAllowed() const
Returns true if an epilogue is allowed (e.g., not prevented by optsize or a loop hint annotation).
bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const
bool shouldConsiderInvariant(Value *Op)
Returns true if Op should be considered invariant and if it is trivially hoistable.
bool foldTailByMasking() const
Returns true if all loop blocks should be masked to fold tail loop.
bool foldTailWithEVL() const
Returns true if VP intrinsics with explicit vector length support should be generated in the tail fol...
bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const
Returns true if the instructions in this block requires predication for any reason,...
AssumptionCache * AC
Assumption cache.
void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for instruction I and vector width VF.
InstWidening
Decision that was taken during cost calculation for memory instruction.
@ CM_InvalidatedDecision
A widening decision that has been invalidated after replacing the corresponding recipe during VPlan t...
bool usePredicatedReductionSelect(RecurKind RecurrenceKind) const
Returns true if the predicated reduction select should be used to set the incoming value for the redu...
std::pair< InstructionCost, InstructionCost > getDivRemSpeculationCost(Instruction *I, ElementCount VF)
Return the costs for our two available strategies for lowering a div/rem operation which requires spe...
InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const
Estimate cost of a call instruction CI if it were vectorized with factor VF.
bool isScalarWithPredication(Instruction *I, ElementCount VF)
Returns true if I is an instruction which requires predication and for which our chosen predication s...
std::function< BlockFrequencyInfo &()> GetBFI
A function to lazily fetch BlockFrequencyInfo.
InstructionCost expectedCost(ElementCount VF)
Returns the expected execution cost.
void setCostBasedWideningDecision(ElementCount VF)
Memory access instruction may be vectorized in more than one way.
bool isDivRemScalarWithPredication(InstructionCost ScalarCost, InstructionCost MaskedCost) const
Given costs for both strategies, return true if the scalar predication lowering should be used for di...
InstWidening getWideningDecision(Instruction *I, ElementCount VF) const
Return the cost model decision for the given instruction I and vector width VF.
InstructionCost getWideningCost(Instruction *I, ElementCount VF)
Return the vectorization cost for the given instruction I and vector width VF.
TailFoldingStyle getTailFoldingStyle() const
Returns the TailFoldingStyle that is best for the current loop.
void collectInstsToScalarize(ElementCount VF)
Collects the instructions to scalarize for each predicated instruction in the loop.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
MapVector< PHINode *, InductionDescriptor > InductionList
InductionList saves induction variables and maps them to the induction descriptor.
LLVM_ABI bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
bool hasUncountableExitWithSideEffects() const
Returns true if this is an early exit loop with state-changing or potentially-faulting operations and...
LLVM_ABI bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
const SmallVector< BasicBlock *, 4 > & getCountableExitingBlocks() const
Returns all exiting blocks with a countable exit, i.e.
bool hasUncountableEarlyExit() const
Returns true if the loop has uncountable early exits, i.e.
bool hasHistograms() const
Returns a list of all known histogram operations in the loop.
const LoopAccessInfo * getLAI() const
Planner drives the vectorization process after having passed Legality checks.
DenseMap< const SCEV *, Value * > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, InnerLoopVectorizer &LB, DominatorTree *DT, EpilogueVectorizationKind EpilogueVecKind=EpilogueVectorizationKind::None)
EpilogueVectorizationKind
Generate the IR code for the vectorized loop captured in VPlan BestPlan according to the best selecte...
@ MainLoop
Vectorizing the main loop of epilogue vectorization.
void clearCostModel()
Destroy the cost model.
VPlan & getPlanFor(ElementCount VF) const
Return the VPlan for VF.
Definition VPlan.cpp:1722
void updateLoopMetadataAndProfileInfo(Loop *VectorLoop, VPBasicBlock *HeaderVPBB, const VPlan &Plan, bool VectorizingEpilogue, MDNode *OrigLoopID, std::optional< unsigned > OrigAverageTripCount, unsigned OrigLoopInvocationWeight, unsigned EstimatedVFxUF, bool DisableRuntimeUnroll, bool UnrollVectorizedLoop)
Update loop metadata and profile info for both the scalar remainder loop and VectorLoop,...
Definition VPlan.cpp:1773
LoopVectorizationCostModel & getCostModel()
Return the cost model. Must not be called after clearCostModel().
void attachRuntimeChecks(VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const
Attach the runtime checks of RTChecks to Plan.
unsigned selectInterleaveCount(VPlan &Plan, ElementCount VF, InstructionCost LoopCost)
void emitInvalidCostRemarks(OptimizationRemarkEmitter *ORE)
Emit remarks for recipes with invalid costs in the available VPlans.
LoopVectorizationPlanner(Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal, std::unique_ptr< LoopVectorizationCostModel > CM, VFSelectionContext &Config, InterleavedAccessInfo &IAI, PredicatedScalarEvolution &PSE, OptimizationRemarkEmitter *ORE)
static bool getDecisionAndClampRange(const std::function< bool(ElementCount)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
Definition VPlan.cpp:1687
void printPlans(raw_ostream &O)
Definition VPlan.cpp:1877
std::unique_ptr< VPlan > selectBestEpiloguePlan(VPlan &MainPlan, ElementCount MainLoopVF, unsigned IC, bool ScalarEpilogueAllowed)
void plan(ElementCount UserVF, unsigned UserIC)
Build VPlans for the specified UserVF and UserIC if they are non-zero or all applicable candidate VFs...
void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount) const
Create a check to Plan to see if the vector loop should be executed based on its trip count.
bool hasPlanWithVF(ElementCount VF) const
Look through the existing plans and return true if we have one with vectorization factor VF.
std::pair< VectorizationFactor, VPlan * > computeBestVF()
Compute and return the most profitable vectorization factor and the corresponding best VPlan.
This holds vectorization requirements that must be verified late in the process.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
LLVM_ABI bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:235
Diagnostic information for optimization analysis remarks related to pointer aliasing.
Diagnostic information for optimization analysis remarks related to floating-point non-commutativity.
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Type * getRecurrenceType() const
Returns the type of the recurrence.
const SmallPtrSet< Instruction *, 8 > & getCastInsts() const
Returns a reference to the instructions used for type-promoting the recurrence.
static bool isFindLastRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
bool isSigned() const
Returns true if all source operands of the recurrence are SExtInsts.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
std::optional< ArrayRef< PointerDiffInfo > > getDiffChecks() const
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
This class uses information about analyze scalars to rewrite expressions in canonical form.
ScalarEvolution * getSE()
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
LLVM_ABI Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
LLVM_ABI void eraseDeadInstructions(Value *Root)
Remove inserted instructions that are dead, e.g.
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool supportsEfficientVectorElementLoadStore() const
If target has efficient vector element load/store instructions, it can return true here so that inser...
LLVM_ABI bool prefersVectorizedAddressing() const
Return true if target doesn't mind addresses in vectors.
LLVM_ABI InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const
LLVM_ABI InstructionCost getOperandsScalarizationOverhead(ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Estimate the overhead of scalarizing operands with the given types.
LLVM_ABI InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
LLVM_ABI InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
LLVM_ABI InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const
llvm::VectorInstrContext VectorInstrContext
LLVM_ABI InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask={}, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) const
@ TCC_Free
Expected to fold away in lowering.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const
LLVM_ABI InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Estimate the overhead of scalarizing an instruction.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_Reverse
Reverse the order of the vector.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ None
The cast is not used with a load/store of any kind.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class implements a switch-like dispatch statement for a value of 'T' using dyn_cast functionalit...
Definition TypeSwitch.h:89
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
Definition TypeSwitch.h:98
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
Definition VectorUtils.h:76
Holds state needed to make cost decisions before computing costs per-VF, including the maximum VFs.
const TTI::TargetCostKind CostKind
The kind of cost that we are calculating.
bool isEpilogueVectorizationProfitable(ElementCount VF, unsigned IC) const
Returns true if epilogue vectorization is considered profitable for a main loop with vectorization fa...
std::optional< unsigned > getVScaleForTuning() const
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4453
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4480
iterator end()
Definition VPlan.h:4490
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4488
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4541
InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override
Return the cost of this VPBasicBlock.
Definition VPlan.cpp:793
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:266
const VPRecipeBase & front() const
Definition VPlan.h:4500
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:663
bool empty() const
Definition VPlan.h:4499
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:236
void setName(const Twine &newName)
Definition VPlan.h:186
VPlan * getPlan()
Definition VPlan.cpp:211
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:234
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:422
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition VPlanUtils.h:376
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:404
VPlan-based builder utility analogous to IRBuilder.
VPInstruction * createAdd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false})
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt, Type *ResultTy=nullptr)
Create a phi with IncomingValues, using the default flags for the result type, unless Flags is set.
T * insert(T *R)
Insert R at the current insertion point. Returns R unchanged.
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr)
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
static VPSingleDefRecipe * createSingleScalarOp(unsigned Opcode, ArrayRef< VPValue * > Operands, VPValue *Mask, const VPIRFlags &Flags, const VPIRMetadata &Metadata, DebugLoc DL, Instruction *UV)
Create a single-scalar recipe with Opcode and Operands without inserting it.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:578
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:551
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2482
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2529
void setBackedgeValue(VPValue *V)
Update the incoming value from the loop backedge.
Definition VPlan.h:2532
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2518
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:2209
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4606
Class to record and manage LLVM IR flags.
Definition VPlan.h:705
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1266
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1538
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1370
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1363
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1320
unsigned getOpcode() const
Definition VPlan.h:1460
void setName(StringRef NewName)
Set the symbolic name for the VPInstruction.
Definition VPlan.h:1565
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1532
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3176
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:412
VPBasicBlock * getParent()
Definition VPlan.h:484
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:562
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Helper class to create VPRecipies from IR instructions.
VPRecipeBase * tryToCreateWidenNonPhiRecipe(VPSingleDefRecipe *R, VFRange &Range)
Create and return a widened recipe for a non-phi recipe R if one can be created within the given VF R...
VPHistogramRecipe * widenIfHistogram(VPInstruction *VPI)
If VPI represents a histogram operation (as determined by LoopVectorizationLegality) make that safe f...
bool prefersVectorizedAddressing() const
Returns true if the target prefers vectorized addressing.
VPRecipeBase * tryToWidenMemory(VPInstruction *VPI, VFRange &Range)
Check if the load or store instruction VPI should widened for Range.Start and potentially masked.
bool replaceWithFinalIfReductionStore(VPInstruction *VPI, VPBuilder &FinalRedStoresBuilder)
If VPI is a store of a reduction into an invariant address, delete it.
VPSingleDefRecipe * handleReplication(VPInstruction *VPI, VFRange &Range)
Build a replicating or single-scalar recipe for VPI.
bool isPredicatedInst(Instruction *I) const
Returns true if I needs to be predicated (i.e.
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:354
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2959
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2943
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2962
VPReductionPHIRecipe * cloneWithOperands(VPValue *Start, VPValue *BackedgeValue)
Definition VPlan.h:2925
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2956
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3269
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4678
const VPBlockBase * getEntry() const
Definition VPlan.h:4722
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4845
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4798
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3436
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:620
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:690
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:401
operand_range operands()
Definition VPlanValue.h:474
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:447
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:442
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:149
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:143
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:130
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1501
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1507
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1925
A recipe for handling GEP instructions.
Definition VPlan.h:2252
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2654
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1859
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4865
bool hasVF(ElementCount VF) const
Definition VPlan.h:5097
ElementCount getSingleVF() const
Returns the single VF of the plan, asserting that the plan has exactly one VF.
Definition VPlan.h:5110
VPBasicBlock * getEntry()
Definition VPlan.h:4961
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5033
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5073
bool hasUF(unsigned UF) const
Definition VPlan.h:5122
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5027
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5147
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5173
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1086
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:5277
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1068
LLVM_ABI_FOR_TEST bool isOuterLoop() const
Returns true if this VPlan is for an outer loop, i.e., its vector loop region contains a nested loop ...
Definition VPlan.cpp:1105
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:5047
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5003
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4966
bool requiresScalarEpilogue() const
Returns true if the plan requires a scalar epilogue after the vector loop.
Definition VPlan.h:4989
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:5070
bool hasScalarVFOnly() const
Definition VPlan.h:5115
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5017
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:961
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:4982
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5023
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5066
LLVM_ABI_FOR_TEST VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition VPlan.cpp:1246
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isNonZero() const
Definition TypeSize.h:155
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:216
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr bool isZero() const
Definition TypeSize.h:153
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:223
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
IteratorT end() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
CallInst * Call
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ Legal
The operation is expected to be selectable directly by the target, and no transformation is necessary...
void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr, DebugLoc DL={})
Reports an informative message: print Msg for debugging purposes as well as an optimization remark.
void reportVectorization(OptimizationRemarkEmitter *ORE, Loop *TheLoop, ElementCount VFWidth, unsigned IC)
Report successful vectorization of the loop.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
bool matchFindIVResult(VPInstruction *VPI, Op0_t ReducedIV, Op1_t Start)
Match FindIV result pattern: select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),...
VPInstruction_match< VPInstruction::ExtractLastLane, Op0_t > m_ExtractLastLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
bool match(Val *V, const Pattern &P)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::ExtractLane, Op0_t, Op1_t > m_ExtractLane(const Op0_t &Op0, const Op1_t &Op1)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
InstructionCost getScalarizationOverhead(const TargetTransformInfo &TTI, bool ReVec, Type *ScalarTy, VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, const TTI::TargetCostKind CostKind, bool ForPoisonSrc, ArrayRef< Value * > VL, TTI::VectorInstrContext VIC)
This is similar to TargetTransformInfo::getScalarizationOverhead, but if ScalarTy is a FixedVectorTyp...
BranchProbability getExecutionProbability(BlockFrequency Freq)
Returns Freq as a BranchProbability, relative to AlwaysExecutesFreq.
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
VPBasicBlock * getFirstLoopHeader(VPlan &Plan, VPDominatorTree &VPDT)
Returns the header block of the first, top-level loop, or null if none exist.
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
VPInstruction * findCanonicalIVIncrement(VPlan &Plan)
Find the canonical IV increment of Plan's vector loop region.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
VPValue * findIncomingAliasMask(const VPlan &Plan)
Finds the incoming alias-mask within the vector preheader.
DenseMap< const VPBasicBlock *, std::optional< BlockFrequency > > computeExecutionFrequencies(ArrayRef< VPBasicBlock * > Blocks)
Computes for each block in Blocks, which must be in reverse post-order, the frequency with which it e...
bool doesGeneratePerAllLanes(const VPRecipeBase *R)
Returns true if R produces scalar values for all VF lanes.
VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
Definition VPlanUtils.h:151
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:830
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2180
LLVM_ABI Value * addRuntimeChecks(Instruction *Loc, Loop *TheLoop, const SmallVectorImpl< RuntimePointerCheck > &PointerChecks, SCEVExpander &Expander, bool HoistRuntimeChecks=false)
Add code that checks at runtime if the accessed arrays in PointerChecks overlap.
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI_FOR_TEST cl::opt< bool > VerifyEachVPlan
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition VPlanCFG.h:250
LLVM_ABI bool VerifySCEV
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintAfterAll
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition VPlanCFG.h:285
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:365
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr auto bind_front(FnT &&Fn, BindArgsT &&...BindArgs)
C++20 bind_front.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
Definition CFG.h:154
std::optional< uint64_t > getMaxRuntimeElementCount(ElementCount EC, const Function &F)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
bool hasIrregularType(Type *Ty, const DataLayout &DL)
A helper function that returns true if the given type is irregular.
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:81
@ ReadOnly
No side effects to worry about, so we can process any uncountable exits in the loop and branch either...
Definition VPlan.h:85
@ MaskedHandleExitInScalarLoop
All memory operations other than the load(s) required to determine whether an uncountable exit occurr...
Definition VPlan.h:90
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI cl::opt< bool > EnableLoopVectorization
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
LLVM_ABI_FOR_TEST cl::list< std::string > VPlanPrintAfterPasses
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:409
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1837
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
cl::opt< unsigned > ForceTargetInstructionCost
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
TargetTransformInfo TTI
@ CM_EpilogueNotAllowedLowTripLoop
@ CM_EpilogueNotNeededFoldTail
@ CM_EpilogueNotAllowedFoldTail
@ CM_EpilogueNotAllowedOptSize
@ CM_EpilogueAllowed
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
LLVM_ABI_FOR_TEST cl::list< std::string > VPlanPrintBeforePasses
RecurKind
These are the kinds of recurrences that we support.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
constexpr T AbsoluteDifference(U X, V Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition MathExtras.h:595
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintBeforeAll
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
cl::opt< bool > EnableVPlanNativePath
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
@ None
Don't use tail folding.
@ DataWithEVL
Use predicated EVL instructions for tail-folding.
@ DataAndControlFlow
Use predicate to control both data and control flow.
@ DataWithoutLaneMask
Same as Data, but avoids using the get.active.lane.mask intrinsic to calculate the mask and instead i...
@ Data
Use predicate only to mask operations on data in the loop.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
@ Disabled
Don't do any conversion of .debug_str_offsets tables.
Definition DWP.h:30
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:76
LLVM_ABI Value * addDiffRuntimeChecks(Instruction *Loc, ArrayRef< PointerDiffInfo > Checks, SCEVExpander &Expander, ElementCount VF, unsigned IC)
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI_FOR_TEST bool verifyVPlanIsValid(const VPlan &Plan)
Verify invariants for general VPlans.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintVectorRegionScope
LLVM_ABI cl::opt< bool > EnableLoopInterleaving
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
Encapsulate information regarding vectorization of a loop and its epilogue.
EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF, ElementCount EVF, unsigned EUF)
A class that represents two vectorization factors (initialized with 0 by default).
static FixedScalableVFPair getNone()
This holds details about a histogram operation – a load -> update -> store sequence where each lane i...
TargetLibraryInfo * TLI
LLVM_ABI LoopVectorizeResult runImpl(Function &F)
LLVM_ABI bool processLoop(Loop *L)
ProfileSummaryInfo * PSI
LoopAccessInfoManager * LAIs
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI LoopVectorizePass(LoopVectorizeOptions Opts={})
ScalarEvolution * SE
AssumptionCache * AC
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
OptimizationRemarkEmitter * ORE
std::function< BlockFrequencyInfo &()> GetBFI
TargetTransformInfo * TTI
Storage for information about made changes.
A marker analysis to determine if extra passes should be run after loop vectorization.
static LLVM_ABI AnalysisKey Key
Parameters that control the generic loop unrolling transformation.
bool UnrollVectorizedLoop
Disable runtime unrolling by default for vectorized loops.
Holds the VFShape for a specific scalar to vector function mapping.
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
ElementCount End
Struct to hold various analysis needed for cost computations.
LLVMContext & LLVMCtx
const VFSelectionContext & Config
LoopVectorizationCostModel & CM
VPCostContext(const TargetLibraryInfo &TLI, const VPlan &Plan, LoopVectorizationCostModel &CM, VFSelectionContext &Config, bool ReusePrintingSlotTracker=false)
bool skipCostComputation(Instruction *UI, bool IsVector) const
Return true if the cost for UI shouldn't be computed, e.g.
InstructionCost getLegacyCost(Instruction *UI, ElementCount VF) const
Return the cost for UI with VF using the legacy cost model as fallback until computing the cost of al...
bool isMaskRequired(Instruction *I) const
Forwards to LoopVectorizationCostModel::isMaskRequired.
void invalidateWideningDecision(Instruction *I, ElementCount VF)
Mark the widening decision for I at VF as invalidated since a VPlan transform replaced the original r...
PredicatedScalarEvolution & PSE
bool willBeScalarized(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalarized at VF.
static bool executesAtMostOnce(const VPlan &Plan, ElementCount VF)
Returns true if the vector loop body of Plan is known to execute at most once at VF,...
uint64_t getPredBlockCostDivisor(BasicBlock *BB) const
TargetTransformInfo::TargetCostKind CostKind
const TargetLibraryInfo & TLI
const TargetTransformInfo & TTI
SmallPtrSet< Instruction *, 8 > SkipCostComputation
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:1127
A struct that represents some properties of the register usage of a loop.
InstructionCost spillCost(const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, unsigned OverrideMaxNumRegs=0) const
Calculate the estimated cost of any spills due to using more registers than the number available for ...
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3853
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:3958
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-ins and replace them with constants, if they can be simplified via SCEV.
static void expandSCEVsToVPInstructions(VPlan &Plan, ScalarEvolution &SE)
Expand VPExpandSCEVRecipes in Plan's entry block to VPInstructions.
static void materializeBroadcasts(VPlan &Plan)
Add explicit broadcasts for live-ins and VPValues defined in Plan's entry block if they are used as v...
static void materializePacksAndUnpacks(VPlan &Plan)
Add explicit Build[Struct]Vector recipes to Pack multiple scalar values into vectors and Unpack recip...
static void createInterleaveGroups(VPlan &Plan, const SmallPtrSetImpl< const InterleaveGroup< Instruction > * > &InterleaveGroups, const bool &EpilogueAllowed)
static bool simplifyKnownEVL(VPlan &Plan, ElementCount VF, PredicatedScalarEvolution &PSE)
Try to simplify VPInstruction::ExplicitVectorLength recipes when the AVL is known to be <= VF,...
static void introduceMasksAndLinearize(VPlan &Plan)
Predicate and linearize the control-flow in the only loop region of Plan.
static void materializeFactors(VPlan &Plan, VPBasicBlock *VectorPH, ElementCount VF)
Materialize UF, VF and VFxUF to be computed explicitly using VPInstructions.
static void foldTailByMasking(VPlan &Plan)
Adapts the vector loop region for tail folding by introducing a header mask and conditionally executi...
static void materializeBackedgeTakenCount(VPlan &Plan, VPBasicBlock *VectorPH)
Materialize the backedge-taken count to be computed explicitly using VPInstructions.
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, Value *VectorTripCount, bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned EpilogueUF, unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE)
Add a check to Plan to see if the epilogue vector loop should be executed.
static LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlan &Plan, const TargetLibraryInfo &TLI, PredicatedScalarEvolution &PSE, Loop *OuterLoop)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static bool handleMultiUseReductions(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Try to legalize reductions with multiple in-loop uses.
static void convertToVariableLengthStep(VPlan &Plan)
Transform loops with variable-length stepping after region dissolution.
static void materializeHeaderMask(VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow)
Materialize the abstract header mask of the loop region into concrete recipes: an active-lane-mask if...
static void addBranchWeightToMiddleTerminator(VPlan &Plan, ElementCount VF, std::optional< unsigned > VScaleForTuning)
Add branch weight metadata, if the Plan's middle block is terminated by a BranchOnCond recipe.
static std::unique_ptr< VPlan > narrowInterleaveGroups(VPlan &Plan, const TargetTransformInfo &TTI)
Try to find a single VF among Plan's VFs for which all interleave groups (with known minimum VF eleme...
static bool handleFindLastReductions(VPlan &Plan)
Check if Plan contains any FindLast reductions.
static void createInLoopReductionRecipes(VPlan &Plan, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
static void materializeAliasMaskCheckBlock(VPlan &Plan, ArrayRef< PointerDiffInfo > DiffChecks, bool HasBranchWeights)
Materializes the alias mask within a check block before the loop.
static void unrollByUF(VPlan &Plan, unsigned UF)
Explicitly unroll Plan by UF.
static DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand remaining VPExpandSCEVRecipes in Plan's entry block using SCEVExpander.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan, DebugLoc DL)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static void makeMemOpWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert load/store VPInstructions in Plan into widened or replicate recipes.
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...
static bool createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, const VPDominatorTree &VPDT, const MapVector< PHINode *, InductionDescriptor > &Inductions, const MapVector< PHINode *, RecurrenceDescriptor > &Reductions, const SmallPtrSetImpl< const PHINode * > &FixedOrderRecurrences, const SmallPtrSetImpl< PHINode * > &InLoopReductions, bool AllowReordering)
Replace VPPhi recipes in Plan's header with corresponding VPHeaderPHIRecipe subclasses for inductions...
static void expandBranchOnTwoConds(VPlan &Plan)
Expand BranchOnTwoConds instructions into explicit CFG with BranchOnCond instructions.
static void materializeVectorTripCount(VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking, bool RequiresScalarEpilogue, VPValue *Step, std::optional< uint64_t > MaxRuntimeStep=std::nullopt)
Materialize vector trip count computations to a set of VPInstructions.
static LLVM_ABI_FOR_TEST bool handleUncountableEarlyExits(VPlan &Plan, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC, UncountableExitStyle Style)
Update Plan to account for uncountable early exits by introducing appropriate branching logic in the ...
static void hoistPredicatedLoads(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
Hoist predicated loads from the same address to the loop entry block, if they are guaranteed to execu...
static void attachAliasMaskToHeaderMask(VPlan &Plan)
Attaches the alias-mask to the existing header-mask.
static void optimizeFindIVReductions(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L)
Optimize FindLast reductions selecting IVs (or expressions of IVs) by converting them to FindIV reduc...
static void convertToAbstractRecipes(VPlan &Plan, VPCostContext &Ctx, VFRange &Range)
This function converts initial recipes to the abstract recipes and clamps Range based on cost model f...
static void materializeConstantVectorTripCount(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
static void makeScalarizationDecisions(VPlan &Plan, VFRange &Range)
Make VPlan-based scalarization decision prior to delegating to the ones made by the legacy CM.
static void replaceWideCanonicalIVWithWideIV(VPlan &Plan, ScalarEvolution &SE, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, ElementCount VF, unsigned UF)
Replace a VPWidenCanonicalIVRecipe if it is present in Plan, with a VPWidenIntOrFpInductionRecipe,...
static void optimizeInductionLiveOutUsers(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
If there's a single exit block, optimize its phi recipes that use exiting IV values by feeding them p...
static void addExplicitVectorLength(VPlan &Plan, const std::optional< unsigned > &MaxEVLSafeElements)
Add a VPCurrentIterationPHIRecipe and related recipes to Plan and replaces all uses of the canonical ...
static void makeCallWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert call VPInstructions in Plan into widened call, vector intrinsic or replicate recipes based on...
static void adjustFirstOrderRecurrenceMiddleUsers(VPlan &Plan, VFRange &Range)
Adjust first-order recurrence users in the middle block: create penultimate element extracts for LCSS...
static void optimizeEVLMasks(VPlan &Plan)
Optimize recipes which use an EVL-based header mask to VP intrinsics, for example:
static bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum or FMinNum reductions.
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
static LLVM_ABI_FOR_TEST void handleCountableEarlyExits(VPlan &Plan)
Disconnect countable early exits from the loop.
static void simplifyRecipes(VPlan &Plan)
Perform instcombine-like simplifications on recipes in Plan.
static void sinkPredicatedStores(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
Sink predicated stores to the same address with complementary predicates (P and NOT P) to an uncondit...
static bool finalizeSCEVPredicates(VPlan &Plan, PredicatedScalarEvolution &PSE, bool OptForSize, unsigned SCEVCheckThreshold, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Finalize SCEV predicates by adding induction predicates from Plan to PSE and checking constraints.
static void replicateByVF(VPlan &Plan, ElementCount VF)
Replace replicating VPReplicateRecipe, VPScalarIVStepsRecipe and VPInstruction in Plan with VF single...
static bool removeBranchOnConst(VPlan &Plan, bool OnlyLatches=false)
Remove BranchOnCond recipes with true or false conditions together with removing dead edges to their ...
static void convertToStridedAccesses(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L, VPCostContext &Ctx, VFRange &Range)
Transform widen memory recipes into strided access recipes when legal and profitable.
static void addIterationCountCheckBlock(VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE)
Add a new check block before the vector preheader to Plan to check if the main vector loop should be ...
static void clearReductionWrapFlags(VPlan &Plan)
Clear NSW/NUW flags from reduction instructions if necessary.
static void createPartialReductions(VPlan &Plan, VPCostContext &CostCtx, VFRange &Range)
Detect and create partial reduction recipes for scaled or unordered reductions in Plan.
static void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE, VPBasicBlock *CheckBlock)
static void cse(VPlan &Plan)
Perform common-subexpression-elimination on Plan.
static void replaceSymbolicStrides(VPlan &Plan, PredicatedScalarEvolution &PSE, const SymbolicStrideMap &StridesMap, const VPDominatorTree &VPDT)
Replace symbolic strides from StridesMap in Plan with constants when possible.
static LLVM_ABI_FOR_TEST void optimize(VPlan &Plan)
Apply VPlan-to-VPlan optimizations to Plan, including induction recipe optimizations,...
static void dissolveLoopRegions(VPlan &Plan)
Replace loop regions with explicit CFG.
static void truncateToMinimalBitwidths(VPlan &Plan, const MapVector< Instruction *, uint64_t > &MinBWs)
Insert truncates and extends for any truncated recipe.
static void dropPoisonGeneratingRecipes(VPlan &Plan)
Drop poison flags from recipes that may generate a poison value that is used after vectorization,...
static void optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Optimize Plan based on BestVF and BestUF.
static void convertEVLExitCond(VPlan &Plan)
Replaces the exit condition from (branch-on-cond eq CanonicalIVInc, VectorTripCount) to (branch-on-co...
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class.
InstructionCost Cost
Cost of the loop with that width.
ElementCount MinProfitableTripCount
The minimum trip count required to make vectorization profitable, e.g.
ElementCount Width
Vector width with best cost.
InstructionCost ScalarCost
Cost of the scalar loop.
static VectorizationFactor Disabled()
Width 1 means no vectorization, cost 0 means uncomputed cost.
static LLVM_ABI bool HoistRuntimeChecks