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