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