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