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;
161
162#define LV_NAME "loop-vectorize"
163#define DEBUG_TYPE LV_NAME
164
165#ifndef NDEBUG
166const char VerboseDebug[] = DEBUG_TYPE "-verbose";
167#endif
168
169STATISTIC(LoopsVectorized, "Number of loops vectorized");
170STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
171STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
172STATISTIC(LoopsEarlyExitVectorized, "Number of early exit loops vectorized");
173
175 "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
176 cl::desc("Enable vectorization of epilogue loops."));
177
179 "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
180 cl::desc("When epilogue vectorization is enabled, and a value greater than "
181 "1 is specified, forces the given VF for all applicable epilogue "
182 "loops."));
183
185 "epilogue-vectorization-minimum-VF", cl::Hidden,
186 cl::desc("Only loops with vectorization factor equal to or larger than "
187 "the specified value are considered for epilogue vectorization."));
188
189/// Loops with a known constant trip count below this number are vectorized only
190/// if no scalar iteration overheads are incurred.
192 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
193 cl::desc("Loops with a constant trip count that is smaller than this "
194 "value are vectorized only if no scalar iteration overheads "
195 "are incurred."));
196
198 "vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
199 cl::desc("The maximum allowed number of runtime memory checks"));
200
201// Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
202// that predication is preferred, and this lists all options. I.e., the
203// vectorizer will try to fold the tail-loop (epilogue) into the vector body
204// and predicate the instructions accordingly. If tail-folding fails, there are
205// different fallback strategies depending on these values:
212} // namespace PreferPredicateTy
213
215 "prefer-predicate-over-epilogue",
218 cl::desc("Tail-folding and predication preferences over creating a scalar "
219 "epilogue loop."),
221 "scalar-epilogue",
222 "Don't tail-predicate loops, create scalar epilogue"),
224 "predicate-else-scalar-epilogue",
225 "prefer tail-folding, create scalar epilogue if tail "
226 "folding fails."),
228 "predicate-dont-vectorize",
229 "prefers tail-folding, don't attempt vectorization if "
230 "tail-folding fails.")));
231
233 "force-tail-folding-style", cl::desc("Force the tail folding style"),
236 clEnumValN(TailFoldingStyle::None, "none", "Disable tail folding"),
239 "Create lane mask for data only, using active.lane.mask intrinsic"),
241 "data-without-lane-mask",
242 "Create lane mask with compare/stepvector"),
244 "Create lane mask using active.lane.mask intrinsic, and use "
245 "it for both data and control flow"),
247 "data-and-control-without-rt-check",
248 "Similar to data-and-control, but remove the runtime check"),
250 "Use predicated EVL instructions for tail folding. If EVL "
251 "is unsupported, fallback to data-without-lane-mask.")));
252
254 "enable-wide-lane-mask", cl::init(false), cl::Hidden,
255 cl::desc("Enable use of wide lane masks when used for control flow in "
256 "tail-folded loops"));
257
259 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
260 cl::desc("Maximize bandwidth when selecting vectorization factor which "
261 "will be determined by the smallest type in loop."));
262
264 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
265 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
266
267/// An interleave-group may need masking if it resides in a block that needs
268/// predication, or in order to mask away gaps.
270 "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
271 cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
272
274 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
275 cl::desc("A flag that overrides the target's number of scalar registers."));
276
278 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
279 cl::desc("A flag that overrides the target's number of vector registers."));
280
282 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
283 cl::desc("A flag that overrides the target's max interleave factor for "
284 "scalar loops."));
285
287 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
288 cl::desc("A flag that overrides the target's max interleave factor for "
289 "vectorized loops."));
290
292 "force-target-instruction-cost", cl::init(0), cl::Hidden,
293 cl::desc("A flag that overrides the target's expected cost for "
294 "an instruction to a single constant value. Mostly "
295 "useful for getting consistent testing."));
296
298 "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
299 cl::desc(
300 "Pretend that scalable vectors are supported, even if the target does "
301 "not support them. This flag should only be used for testing."));
302
304 "small-loop-cost", cl::init(20), cl::Hidden,
305 cl::desc(
306 "The cost of a loop that is considered 'small' by the interleaver."));
307
309 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
310 cl::desc("Enable the use of the block frequency analysis to access PGO "
311 "heuristics minimizing code growth in cold regions and being more "
312 "aggressive in hot regions."));
313
314// Runtime interleave loops for load/store throughput.
316 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
317 cl::desc(
318 "Enable runtime interleaving until load/store ports are saturated"));
319
320/// The number of stores in a loop that are allowed to need predication.
322 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
323 cl::desc("Max number of stores to be predicated behind an if."));
324
326 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
327 cl::desc("Count the induction variable only once when interleaving"));
328
330 "enable-cond-stores-vec", cl::init(true), cl::Hidden,
331 cl::desc("Enable if predication of stores during vectorization."));
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
338static cl::opt<bool>
339 PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
341 cl::desc("Prefer in-loop vector reductions, "
342 "overriding the targets preference."));
343
345 "force-ordered-reductions", cl::init(false), cl::Hidden,
346 cl::desc("Enable the vectorisation of loops with in-order (strict) "
347 "FP reductions"));
348
350 "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
351 cl::desc(
352 "Prefer predicating a reduction operation over an after loop select."));
353
355 "enable-vplan-native-path", cl::Hidden,
356 cl::desc("Enable VPlan-native vectorization path with "
357 "support for outer loop vectorization."));
358
360 llvm::VerifyEachVPlan("vplan-verify-each",
361#ifdef EXPENSIVE_CHECKS
362 cl::init(true),
363#else
364 cl::init(false),
365#endif
367 cl::desc("Verfiy VPlans after VPlan transforms."));
368
369// This flag enables the stress testing of the VPlan H-CFG construction in the
370// VPlan-native vectorization path. It must be used in conjuction with
371// -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
372// verification of the H-CFGs built.
374 "vplan-build-stress-test", cl::init(false), cl::Hidden,
375 cl::desc(
376 "Build VPlan for every supported loop nest in the function and bail "
377 "out right after the build (stress test the VPlan H-CFG construction "
378 "in the VPlan-native vectorization path)."));
379
381 "interleave-loops", cl::init(true), cl::Hidden,
382 cl::desc("Enable loop interleaving in Loop vectorization passes"));
384 "vectorize-loops", cl::init(true), cl::Hidden,
385 cl::desc("Run the Loop vectorization passes"));
386
388 "force-widen-divrem-via-safe-divisor", cl::Hidden,
389 cl::desc(
390 "Override cost based safe divisor widening for div/rem instructions"));
391
393 "vectorizer-maximize-bandwidth-for-vector-calls", cl::init(true),
395 cl::desc("Try wider VFs if they enable the use of vector variants"));
396
398 "enable-early-exit-vectorization", cl::init(true), cl::Hidden,
399 cl::desc(
400 "Enable vectorization of early exit loops with uncountable exits."));
401
403 "vectorizer-consider-reg-pressure", cl::init(false), cl::Hidden,
404 cl::desc("Discard VFs if their register pressure is too high."));
405
406// Likelyhood of bypassing the vectorized loop because there are zero trips left
407// after prolog. See `emitIterationCountCheck`.
408static constexpr uint32_t MinItersBypassWeights[] = {1, 127};
409
410/// A helper function that returns true if the given type is irregular. The
411/// type is irregular if its allocated size doesn't equal the store size of an
412/// element of the corresponding vector type.
413static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
414 // Determine if an array of N elements of type Ty is "bitcast compatible"
415 // with a <N x Ty> vector.
416 // This is only true if there is no padding between the array elements.
417 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
418}
419
420/// A version of ScalarEvolution::getSmallConstantTripCount that returns an
421/// ElementCount to include loops whose trip count is a function of vscale.
423 const Loop *L) {
424 if (unsigned ExpectedTC = SE->getSmallConstantTripCount(L))
425 return ElementCount::getFixed(ExpectedTC);
426
427 const SCEV *BTC = SE->getBackedgeTakenCount(L);
429 return ElementCount::getFixed(0);
430
431 const SCEV *ExitCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
432 if (isa<SCEVVScale>(ExitCount))
434
435 const APInt *Scale;
436 if (match(ExitCount, m_scev_Mul(m_scev_APInt(Scale), m_SCEVVScale())))
437 if (cast<SCEVMulExpr>(ExitCount)->hasNoUnsignedWrap())
438 if (Scale->getActiveBits() <= 32)
440
441 return ElementCount::getFixed(0);
442}
443
444/// Returns "best known" trip count, which is either a valid positive trip count
445/// or std::nullopt when an estimate cannot be made (including when the trip
446/// count would overflow), for the specified loop \p L as defined by the
447/// following procedure:
448/// 1) Returns exact trip count if it is known.
449/// 2) Returns expected trip count according to profile data if any.
450/// 3) Returns upper bound estimate if known, and if \p CanUseConstantMax.
451/// 4) Returns std::nullopt if all of the above failed.
452static std::optional<ElementCount>
454 bool CanUseConstantMax = true) {
455 // Check if exact trip count is known.
456 if (auto ExpectedTC = getSmallConstantTripCount(PSE.getSE(), L))
457 return ExpectedTC;
458
459 // Check if there is an expected trip count available from profile data.
461 if (auto EstimatedTC = getLoopEstimatedTripCount(L))
462 return ElementCount::getFixed(*EstimatedTC);
463
464 if (!CanUseConstantMax)
465 return std::nullopt;
466
467 // Check if upper bound estimate is known.
468 if (unsigned ExpectedTC = PSE.getSmallConstantMaxTripCount())
469 return ElementCount::getFixed(ExpectedTC);
470
471 return std::nullopt;
472}
473
474namespace {
475// Forward declare GeneratedRTChecks.
476class GeneratedRTChecks;
477
478using SCEV2ValueTy = DenseMap<const SCEV *, Value *>;
479} // namespace
480
481namespace llvm {
482
484
485/// InnerLoopVectorizer vectorizes loops which contain only one basic
486/// block to a specified vectorization factor (VF).
487/// This class performs the widening of scalars into vectors, or multiple
488/// scalars. This class also implements the following features:
489/// * It inserts an epilogue loop for handling loops that don't have iteration
490/// counts that are known to be a multiple of the vectorization factor.
491/// * It handles the code generation for reduction variables.
492/// * Scalarization (implementation using scalars) of un-vectorizable
493/// instructions.
494/// InnerLoopVectorizer does not perform any vectorization-legality
495/// checks, and relies on the caller to check for the different legality
496/// aspects. The InnerLoopVectorizer relies on the
497/// LoopVectorizationLegality class to provide information about the induction
498/// and reduction variables that were found to a given vectorization factor.
500public:
504 ElementCount VecWidth, unsigned UnrollFactor,
506 GeneratedRTChecks &RTChecks, VPlan &Plan)
507 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TTI(TTI), AC(AC),
508 VF(VecWidth), UF(UnrollFactor), Builder(PSE.getSE()->getContext()),
511 Plan.getVectorLoopRegion()->getSinglePredecessor())) {}
512
513 virtual ~InnerLoopVectorizer() = default;
514
515 /// Creates a basic block for the scalar preheader. Both
516 /// EpilogueVectorizerMainLoop and EpilogueVectorizerEpilogueLoop overwrite
517 /// the method to create additional blocks and checks needed for epilogue
518 /// vectorization.
520
521 /// Fix the vectorized code, taking care of header phi's, and more.
523
524 /// Fix the non-induction PHIs in \p Plan.
526
527 /// Returns the original loop trip count.
528 Value *getTripCount() const { return TripCount; }
529
530 /// Used to set the trip count after ILV's construction and after the
531 /// preheader block has been executed. Note that this always holds the trip
532 /// count of the original loop for both main loop and epilogue vectorization.
533 void setTripCount(Value *TC) { TripCount = TC; }
534
535protected:
537
538 /// Create and return a new IR basic block for the scalar preheader whose name
539 /// is prefixed with \p Prefix.
541
542 /// Allow subclasses to override and print debug traces before/after vplan
543 /// execution, when trace information is requested.
544 virtual void printDebugTracesAtStart() {}
545 virtual void printDebugTracesAtEnd() {}
546
547 /// The original loop.
549
550 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
551 /// dynamic knowledge to simplify SCEV expressions and converts them to a
552 /// more usable form.
554
555 /// Loop Info.
557
558 /// Dominator Tree.
560
561 /// Target Transform Info.
563
564 /// Assumption Cache.
566
567 /// The vectorization SIMD factor to use. Each vector will have this many
568 /// vector elements.
570
571 /// The vectorization unroll factor to use. Each scalar is vectorized to this
572 /// many different vector instructions.
573 unsigned UF;
574
575 /// The builder that we use
577
578 // --- Vectorization state ---
579
580 /// Trip count of the original loop.
581 Value *TripCount = nullptr;
582
583 /// The profitablity analysis.
585
586 /// Structure to hold information about generated runtime checks, responsible
587 /// for cleaning the checks, if vectorization turns out unprofitable.
588 GeneratedRTChecks &RTChecks;
589
591
592 /// The vector preheader block of \p Plan, used as target for check blocks
593 /// introduced during skeleton creation.
595};
596
597/// Encapsulate information regarding vectorization of a loop and its epilogue.
598/// This information is meant to be updated and used across two stages of
599/// epilogue vectorization.
602 unsigned MainLoopUF = 0;
604 unsigned EpilogueUF = 0;
607 Value *TripCount = nullptr;
610
612 ElementCount EVF, unsigned EUF,
614 : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF),
616 assert(EUF == 1 &&
617 "A high UF for the epilogue loop is likely not beneficial.");
618 }
619};
620
621/// An extension of the inner loop vectorizer that creates a skeleton for a
622/// vectorized loop that has its epilogue (residual) also vectorized.
623/// The idea is to run the vplan on a given loop twice, firstly to setup the
624/// skeleton and vectorize the main loop, and secondly to complete the skeleton
625/// from the first step and vectorize the epilogue. This is achieved by
626/// deriving two concrete strategy classes from this base class and invoking
627/// them in succession from the loop vectorizer planner.
629public:
639
640 /// Holds and updates state information required to vectorize the main loop
641 /// and its epilogue in two separate passes. This setup helps us avoid
642 /// regenerating and recomputing runtime safety checks. It also helps us to
643 /// shorten the iteration-count-check path length for the cases where the
644 /// iteration count of the loop is so small that the main vector loop is
645 /// completely skipped.
647
648protected:
650};
651
652/// A specialized derived class of inner loop vectorizer that performs
653/// vectorization of *main* loops in the process of vectorizing loops and their
654/// epilogues.
656public:
667 /// Implements the interface for creating a vectorized skeleton using the
668 /// *main loop* strategy (i.e., the first pass of VPlan execution).
670
671protected:
672 /// Introduces a new VPIRBasicBlock for \p CheckIRBB to Plan between the
673 /// vector preheader and its predecessor, also connecting the new block to the
674 /// scalar preheader.
675 void introduceCheckBlockInVPlan(BasicBlock *CheckIRBB);
676
677 // Create a check to see if the main vector loop should be executed
679 unsigned UF) const;
680
681 /// Emits an iteration count bypass check once for the main loop (when \p
682 /// ForEpilogue is false) and once for the epilogue loop (when \p
683 /// ForEpilogue is true).
685 bool ForEpilogue);
686 void printDebugTracesAtStart() override;
687 void printDebugTracesAtEnd() override;
688};
689
690// A specialized derived class of inner loop vectorizer that performs
691// vectorization of *epilogue* loops in the process of vectorizing loops and
692// their epilogues.
694public:
701 GeneratedRTChecks &Checks, VPlan &Plan)
703 Checks, Plan, EPI.EpilogueVF,
704 EPI.EpilogueVF, EPI.EpilogueUF) {}
705 /// Implements the interface for creating a vectorized skeleton using the
706 /// *epilogue loop* strategy (i.e., the second pass of VPlan execution).
708
709protected:
710 void printDebugTracesAtStart() override;
711 void printDebugTracesAtEnd() override;
712};
713} // end namespace llvm
714
715/// Look for a meaningful debug location on the instruction or its operands.
717 if (!I)
718 return DebugLoc::getUnknown();
719
721 if (I->getDebugLoc() != Empty)
722 return I->getDebugLoc();
723
724 for (Use &Op : I->operands()) {
725 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
726 if (OpInst->getDebugLoc() != Empty)
727 return OpInst->getDebugLoc();
728 }
729
730 return I->getDebugLoc();
731}
732
733/// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
734/// is passed, the message relates to that particular instruction.
735#ifndef NDEBUG
736static void debugVectorizationMessage(const StringRef Prefix,
737 const StringRef DebugMsg,
738 Instruction *I) {
739 dbgs() << "LV: " << Prefix << DebugMsg;
740 if (I != nullptr)
741 dbgs() << " " << *I;
742 else
743 dbgs() << '.';
744 dbgs() << '\n';
745}
746#endif
747
748/// Create an analysis remark that explains why vectorization failed
749///
750/// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
751/// RemarkName is the identifier for the remark. If \p I is passed it is an
752/// instruction that prevents vectorization. Otherwise \p TheLoop is used for
753/// the location of the remark. If \p DL is passed, use it as debug location for
754/// the remark. \return the remark object that can be streamed to.
755static OptimizationRemarkAnalysis
756createLVAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop,
757 Instruction *I, DebugLoc DL = {}) {
758 BasicBlock *CodeRegion = I ? I->getParent() : TheLoop->getHeader();
759 // If debug location is attached to the instruction, use it. Otherwise if DL
760 // was not provided, use the loop's.
761 if (I && I->getDebugLoc())
762 DL = I->getDebugLoc();
763 else if (!DL)
764 DL = TheLoop->getStartLoc();
765
766 return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
767}
768
769namespace llvm {
770
771/// Return a value for Step multiplied by VF.
773 int64_t Step) {
774 assert(Ty->isIntegerTy() && "Expected an integer step");
775 ElementCount VFxStep = VF.multiplyCoefficientBy(Step);
776 assert(isPowerOf2_64(VF.getKnownMinValue()) && "must pass power-of-2 VF");
777 if (VF.isScalable() && isPowerOf2_64(Step)) {
778 return B.CreateShl(
779 B.CreateVScale(Ty),
780 ConstantInt::get(Ty, Log2_64(VFxStep.getKnownMinValue())), "", true);
781 }
782 return B.CreateElementCount(Ty, VFxStep);
783}
784
785/// Return the runtime value for VF.
787 return B.CreateElementCount(Ty, VF);
788}
789
791 const StringRef OREMsg, const StringRef ORETag,
792 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
793 Instruction *I) {
794 LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
795 LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
796 ORE->emit(
797 createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
798 << "loop not vectorized: " << OREMsg);
799}
800
801/// Reports an informative message: print \p Msg for debugging purposes as well
802/// as an optimization remark. Uses either \p I as location of the remark, or
803/// otherwise \p TheLoop. If \p DL is passed, use it as debug location for the
804/// remark. If \p DL is passed, use it as debug location for the remark.
805static void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
807 Loop *TheLoop, Instruction *I = nullptr,
808 DebugLoc DL = {}) {
810 LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
811 ORE->emit(createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop,
812 I, DL)
813 << Msg);
814}
815
816/// Report successful vectorization of the loop. In case an outer loop is
817/// vectorized, prepend "outer" to the vectorization remark.
819 VectorizationFactor VF, unsigned IC) {
821 "Vectorizing: ", TheLoop->isInnermost() ? "innermost loop" : "outer loop",
822 nullptr));
823 StringRef LoopType = TheLoop->isInnermost() ? "" : "outer ";
824 ORE->emit([&]() {
825 return OptimizationRemark(LV_NAME, "Vectorized", TheLoop->getStartLoc(),
826 TheLoop->getHeader())
827 << "vectorized " << LoopType << "loop (vectorization width: "
828 << ore::NV("VectorizationFactor", VF.Width)
829 << ", interleaved count: " << ore::NV("InterleaveCount", IC) << ")";
830 });
831}
832
833} // end namespace llvm
834
835namespace llvm {
836
837// Loop vectorization cost-model hints how the scalar epilogue loop should be
838// lowered.
840
841 // The default: allowing scalar epilogues.
843
844 // Vectorization with OptForSize: don't allow epilogues.
846
847 // A special case of vectorisation with OptForSize: loops with a very small
848 // trip count are considered for vectorization under OptForSize, thereby
849 // making sure the cost of their loop body is dominant, free of runtime
850 // guards and scalar iteration overheads.
852
853 // Loop hint predicate indicating an epilogue is undesired.
855
856 // Directive indicating we must either tail fold or not vectorize
858};
859
860/// LoopVectorizationCostModel - estimates the expected speedups due to
861/// vectorization.
862/// In many cases vectorization is not profitable. This can happen because of
863/// a number of reasons. In this class we mainly attempt to predict the
864/// expected speedup/slowdowns due to the supported instruction set. We use the
865/// TargetTransformInfo to query the different backends for the cost of
866/// different operations.
869
870public:
878 std::function<BlockFrequencyInfo &()> GetBFI,
879 const Function *F, const LoopVectorizeHints *Hints,
881 : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
882 TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), GetBFI(GetBFI),
885 if (TTI.supportsScalableVectors() || ForceTargetSupportsScalableVectors)
886 initializeVScaleForTuning();
888 }
889
890 /// \return An upper bound for the vectorization factors (both fixed and
891 /// scalable). If the factors are 0, vectorization and interleaving should be
892 /// avoided up front.
893 FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
894
895 /// \return True if runtime checks are required for vectorization, and false
896 /// otherwise.
897 bool runtimeChecksRequired();
898
899 /// Setup cost-based decisions for user vectorization factor.
900 /// \return true if the UserVF is a feasible VF to be chosen.
903 return expectedCost(UserVF).isValid();
904 }
905
906 /// \return True if maximizing vector bandwidth is enabled by the target or
907 /// user options, for the given register kind.
908 bool useMaxBandwidth(TargetTransformInfo::RegisterKind RegKind);
909
910 /// \return True if register pressure should be considered for the given VF.
911 bool shouldConsiderRegPressureForVF(ElementCount VF);
912
913 /// \return The size (in bits) of the smallest and widest types in the code
914 /// that needs to be vectorized. We ignore values that remain scalar such as
915 /// 64 bit loop indices.
916 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
917
918 /// Memory access instruction may be vectorized in more than one way.
919 /// Form of instruction after vectorization depends on cost.
920 /// This function takes cost-based decisions for Load/Store instructions
921 /// and collects them in a map. This decisions map is used for building
922 /// the lists of loop-uniform and loop-scalar instructions.
923 /// The calculated cost is saved with widening decision in order to
924 /// avoid redundant calculations.
925 void setCostBasedWideningDecision(ElementCount VF);
926
927 /// A call may be vectorized in different ways depending on whether we have
928 /// vectorized variants available and whether the target supports masking.
929 /// This function analyzes all calls in the function at the supplied VF,
930 /// makes a decision based on the costs of available options, and stores that
931 /// decision in a map for use in planning and plan execution.
932 void setVectorizedCallDecision(ElementCount VF);
933
934 /// Collect values we want to ignore in the cost model.
935 void collectValuesToIgnore();
936
937 /// Collect all element types in the loop for which widening is needed.
938 void collectElementTypesForWidening();
939
940 /// Split reductions into those that happen in the loop, and those that happen
941 /// outside. In loop reductions are collected into InLoopReductions.
942 void collectInLoopReductions();
943
944 /// Returns true if we should use strict in-order reductions for the given
945 /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
946 /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
947 /// of FP operations.
948 bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const {
949 return !Hints->allowReordering() && RdxDesc.isOrdered();
950 }
951
952 /// \returns The smallest bitwidth each instruction can be represented with.
953 /// The vector equivalents of these instructions should be truncated to this
954 /// type.
956 return MinBWs;
957 }
958
959 /// \returns True if it is more profitable to scalarize instruction \p I for
960 /// vectorization factor \p VF.
962 assert(VF.isVector() &&
963 "Profitable to scalarize relevant only for VF > 1.");
964 assert(
965 TheLoop->isInnermost() &&
966 "cost-model should not be used for outer loops (in VPlan-native path)");
967
968 auto Scalars = InstsToScalarize.find(VF);
969 assert(Scalars != InstsToScalarize.end() &&
970 "VF not yet analyzed for scalarization profitability");
971 return Scalars->second.contains(I);
972 }
973
974 /// Returns true if \p I is known to be uniform after vectorization.
976 assert(
977 TheLoop->isInnermost() &&
978 "cost-model should not be used for outer loops (in VPlan-native path)");
979 // Pseudo probe needs to be duplicated for each unrolled iteration and
980 // vector lane so that profiled loop trip count can be accurately
981 // accumulated instead of being under counted.
983 return false;
984
985 if (VF.isScalar())
986 return true;
987
988 auto UniformsPerVF = Uniforms.find(VF);
989 assert(UniformsPerVF != Uniforms.end() &&
990 "VF not yet analyzed for uniformity");
991 return UniformsPerVF->second.count(I);
992 }
993
994 /// Returns true if \p I is known to be scalar after vectorization.
996 assert(
997 TheLoop->isInnermost() &&
998 "cost-model should not be used for outer loops (in VPlan-native path)");
999 if (VF.isScalar())
1000 return true;
1001
1002 auto ScalarsPerVF = Scalars.find(VF);
1003 assert(ScalarsPerVF != Scalars.end() &&
1004 "Scalar values are not calculated for VF");
1005 return ScalarsPerVF->second.count(I);
1006 }
1007
1008 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1009 /// for vectorization factor \p VF.
1011 // Truncs must truncate at most to their destination type.
1012 if (isa_and_nonnull<TruncInst>(I) && MinBWs.contains(I) &&
1013 I->getType()->getScalarSizeInBits() < MinBWs.lookup(I))
1014 return false;
1015 return VF.isVector() && MinBWs.contains(I) &&
1016 !isProfitableToScalarize(I, VF) &&
1018 }
1019
1020 /// Decision that was taken during cost calculation for memory instruction.
1023 CM_Widen, // For consecutive accesses with stride +1.
1024 CM_Widen_Reverse, // For consecutive accesses with stride -1.
1030 };
1031
1032 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1033 /// instruction \p I and vector width \p VF.
1036 assert(VF.isVector() && "Expected VF >=2");
1037 WideningDecisions[{I, VF}] = {W, Cost};
1038 }
1039
1040 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1041 /// interleaving group \p Grp and vector width \p VF.
1045 assert(VF.isVector() && "Expected VF >=2");
1046 /// Broadcast this decicion to all instructions inside the group.
1047 /// When interleaving, the cost will only be assigned one instruction, the
1048 /// insert position. For other cases, add the appropriate fraction of the
1049 /// total cost to each instruction. This ensures accurate costs are used,
1050 /// even if the insert position instruction is not used.
1051 InstructionCost InsertPosCost = Cost;
1052 InstructionCost OtherMemberCost = 0;
1053 if (W != CM_Interleave)
1054 OtherMemberCost = InsertPosCost = Cost / Grp->getNumMembers();
1055 ;
1056 for (unsigned Idx = 0; Idx < Grp->getFactor(); ++Idx) {
1057 if (auto *I = Grp->getMember(Idx)) {
1058 if (Grp->getInsertPos() == I)
1059 WideningDecisions[{I, VF}] = {W, InsertPosCost};
1060 else
1061 WideningDecisions[{I, VF}] = {W, OtherMemberCost};
1062 }
1063 }
1064 }
1065
1066 /// Return the cost model decision for the given instruction \p I and vector
1067 /// width \p VF. Return CM_Unknown if this instruction did not pass
1068 /// through the cost modeling.
1070 assert(VF.isVector() && "Expected VF to be a vector VF");
1071 assert(
1072 TheLoop->isInnermost() &&
1073 "cost-model should not be used for outer loops (in VPlan-native path)");
1074
1075 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
1076 auto Itr = WideningDecisions.find(InstOnVF);
1077 if (Itr == WideningDecisions.end())
1078 return CM_Unknown;
1079 return Itr->second.first;
1080 }
1081
1082 /// Return the vectorization cost for the given instruction \p I and vector
1083 /// width \p VF.
1085 assert(VF.isVector() && "Expected VF >=2");
1086 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
1087 assert(WideningDecisions.contains(InstOnVF) &&
1088 "The cost is not calculated");
1089 return WideningDecisions[InstOnVF].second;
1090 }
1091
1099
1101 Function *Variant, Intrinsic::ID IID,
1102 std::optional<unsigned> MaskPos,
1104 assert(!VF.isScalar() && "Expected vector VF");
1105 CallWideningDecisions[{CI, VF}] = {Kind, Variant, IID, MaskPos, Cost};
1106 }
1107
1109 ElementCount VF) const {
1110 assert(!VF.isScalar() && "Expected vector VF");
1111 auto I = CallWideningDecisions.find({CI, VF});
1112 if (I == CallWideningDecisions.end())
1113 return {CM_Unknown, nullptr, Intrinsic::not_intrinsic, std::nullopt, 0};
1114 return I->second;
1115 }
1116
1117 /// Return True if instruction \p I is an optimizable truncate whose operand
1118 /// is an induction variable. Such a truncate will be removed by adding a new
1119 /// induction variable with the destination type.
1121 // If the instruction is not a truncate, return false.
1122 auto *Trunc = dyn_cast<TruncInst>(I);
1123 if (!Trunc)
1124 return false;
1125
1126 // Get the source and destination types of the truncate.
1127 Type *SrcTy = toVectorTy(Trunc->getSrcTy(), VF);
1128 Type *DestTy = toVectorTy(Trunc->getDestTy(), VF);
1129
1130 // If the truncate is free for the given types, return false. Replacing a
1131 // free truncate with an induction variable would add an induction variable
1132 // update instruction to each iteration of the loop. We exclude from this
1133 // check the primary induction variable since it will need an update
1134 // instruction regardless.
1135 Value *Op = Trunc->getOperand(0);
1136 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1137 return false;
1138
1139 // If the truncated value is not an induction variable, return false.
1140 return Legal->isInductionPhi(Op);
1141 }
1142
1143 /// Collects the instructions to scalarize for each predicated instruction in
1144 /// the loop.
1145 void collectInstsToScalarize(ElementCount VF);
1146
1147 /// Collect values that will not be widened, including Uniforms, Scalars, and
1148 /// Instructions to Scalarize for the given \p VF.
1149 /// The sets depend on CM decision for Load/Store instructions
1150 /// that may be vectorized as interleave, gather-scatter or scalarized.
1151 /// Also make a decision on what to do about call instructions in the loop
1152 /// at that VF -- scalarize, call a known vector routine, or call a
1153 /// vector intrinsic.
1155 // Do the analysis once.
1156 if (VF.isScalar() || Uniforms.contains(VF))
1157 return;
1159 collectLoopUniforms(VF);
1161 collectLoopScalars(VF);
1163 }
1164
1165 /// Returns true if the target machine supports masked store operation
1166 /// for the given \p DataType and kind of access to \p Ptr.
1167 bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment,
1168 unsigned AddressSpace) const {
1169 return Legal->isConsecutivePtr(DataType, Ptr) &&
1170 TTI.isLegalMaskedStore(DataType, Alignment, AddressSpace);
1171 }
1172
1173 /// Returns true if the target machine supports masked load operation
1174 /// for the given \p DataType and kind of access to \p Ptr.
1175 bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment,
1176 unsigned AddressSpace) const {
1177 return Legal->isConsecutivePtr(DataType, Ptr) &&
1178 TTI.isLegalMaskedLoad(DataType, Alignment, AddressSpace);
1179 }
1180
1181 /// Returns true if the target machine can represent \p V as a masked gather
1182 /// or scatter operation.
1184 bool LI = isa<LoadInst>(V);
1185 bool SI = isa<StoreInst>(V);
1186 if (!LI && !SI)
1187 return false;
1188 auto *Ty = getLoadStoreType(V);
1190 if (VF.isVector())
1191 Ty = VectorType::get(Ty, VF);
1192 return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1193 (SI && TTI.isLegalMaskedScatter(Ty, Align));
1194 }
1195
1196 /// Returns true if the target machine supports all of the reduction
1197 /// variables found for the given VF.
1199 return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1200 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1201 return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1202 }));
1203 }
1204
1205 /// Given costs for both strategies, return true if the scalar predication
1206 /// lowering should be used for div/rem. This incorporates an override
1207 /// option so it is not simply a cost comparison.
1209 InstructionCost SafeDivisorCost) const {
1210 switch (ForceSafeDivisor) {
1211 case cl::BOU_UNSET:
1212 return ScalarCost < SafeDivisorCost;
1213 case cl::BOU_TRUE:
1214 return false;
1215 case cl::BOU_FALSE:
1216 return true;
1217 }
1218 llvm_unreachable("impossible case value");
1219 }
1220
1221 /// Returns true if \p I is an instruction which requires predication and
1222 /// for which our chosen predication strategy is scalarization (i.e. we
1223 /// don't have an alternate strategy such as masking available).
1224 /// \p VF is the vectorization factor that will be used to vectorize \p I.
1225 bool isScalarWithPredication(Instruction *I, ElementCount VF);
1226
1227 /// Returns true if \p I is an instruction that needs to be predicated
1228 /// at runtime. The result is independent of the predication mechanism.
1229 /// Superset of instructions that return true for isScalarWithPredication.
1230 bool isPredicatedInst(Instruction *I) const;
1231
1232 /// A helper function that returns how much we should divide the cost of a
1233 /// predicated block by. Typically this is the reciprocal of the block
1234 /// probability, i.e. if we return X we are assuming the predicated block will
1235 /// execute once for every X iterations of the loop header so the block should
1236 /// only contribute 1/X of its cost to the total cost calculation, but when
1237 /// optimizing for code size it will just be 1 as code size costs don't depend
1238 /// on execution probabilities.
1239 ///
1240 /// Note that if a block wasn't originally predicated but was predicated due
1241 /// to tail folding, the divisor will still be 1 because it will execute for
1242 /// every iteration of the loop header.
1243 inline uint64_t
1244 getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind,
1245 const BasicBlock *BB);
1246
1247 /// Return the costs for our two available strategies for lowering a
1248 /// div/rem operation which requires speculating at least one lane.
1249 /// First result is for scalarization (will be invalid for scalable
1250 /// vectors); second is for the safe-divisor strategy.
1251 std::pair<InstructionCost, InstructionCost>
1252 getDivRemSpeculationCost(Instruction *I, ElementCount VF);
1253
1254 /// Returns true if \p I is a memory instruction with consecutive memory
1255 /// access that can be widened.
1256 bool memoryInstructionCanBeWidened(Instruction *I, ElementCount VF);
1257
1258 /// Returns true if \p I is a memory instruction in an interleaved-group
1259 /// of memory accesses that can be vectorized with wide vector loads/stores
1260 /// and shuffles.
1261 bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const;
1262
1263 /// Check if \p Instr belongs to any interleaved access group.
1265 return InterleaveInfo.isInterleaved(Instr);
1266 }
1267
1268 /// Get the interleaved access group that \p Instr belongs to.
1271 return InterleaveInfo.getInterleaveGroup(Instr);
1272 }
1273
1274 /// Returns true if we're required to use a scalar epilogue for at least
1275 /// the final iteration of the original loop.
1276 bool requiresScalarEpilogue(bool IsVectorizing) const {
1277 if (!isScalarEpilogueAllowed()) {
1278 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1279 return false;
1280 }
1281 // If we might exit from anywhere but the latch and early exit vectorization
1282 // is disabled, we must run the exiting iteration in scalar form.
1283 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
1284 !(EnableEarlyExitVectorization && Legal->hasUncountableEarlyExit())) {
1285 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: not exiting "
1286 "from latch block\n");
1287 return true;
1288 }
1289 if (IsVectorizing && InterleaveInfo.requiresScalarEpilogue()) {
1290 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: "
1291 "interleaved group requires scalar epilogue\n");
1292 return true;
1293 }
1294 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1295 return false;
1296 }
1297
1298 /// Returns true if a scalar epilogue is not allowed due to optsize or a
1299 /// loop hint annotation.
1301 return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1302 }
1303
1304 /// Returns true if tail-folding is preferred over a scalar epilogue.
1306 return ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate ||
1307 ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate;
1308 }
1309
1310 /// Returns the TailFoldingStyle that is best for the current loop.
1311 TailFoldingStyle getTailFoldingStyle(bool IVUpdateMayOverflow = true) const {
1312 if (!ChosenTailFoldingStyle)
1314 return IVUpdateMayOverflow ? ChosenTailFoldingStyle->first
1315 : ChosenTailFoldingStyle->second;
1316 }
1317
1318 /// Selects and saves TailFoldingStyle for 2 options - if IV update may
1319 /// overflow or not.
1320 /// \param IsScalableVF true if scalable vector factors enabled.
1321 /// \param UserIC User specific interleave count.
1322 void setTailFoldingStyles(bool IsScalableVF, unsigned UserIC) {
1323 assert(!ChosenTailFoldingStyle && "Tail folding must not be selected yet.");
1324 if (!Legal->canFoldTailByMasking()) {
1325 ChosenTailFoldingStyle = {TailFoldingStyle::None, TailFoldingStyle::None};
1326 return;
1327 }
1328
1329 // Default to TTI preference, but allow command line override.
1330 ChosenTailFoldingStyle = {
1331 TTI.getPreferredTailFoldingStyle(/*IVUpdateMayOverflow=*/true),
1332 TTI.getPreferredTailFoldingStyle(/*IVUpdateMayOverflow=*/false)};
1333 if (ForceTailFoldingStyle.getNumOccurrences())
1334 ChosenTailFoldingStyle = {ForceTailFoldingStyle.getValue(),
1335 ForceTailFoldingStyle.getValue()};
1336
1337 if (ChosenTailFoldingStyle->first != TailFoldingStyle::DataWithEVL &&
1338 ChosenTailFoldingStyle->second != TailFoldingStyle::DataWithEVL)
1339 return;
1340 // Override EVL styles if needed.
1341 // FIXME: Investigate opportunity for fixed vector factor.
1342 bool EVLIsLegal = UserIC <= 1 && IsScalableVF &&
1343 TTI.hasActiveVectorLength() && !EnableVPlanNativePath;
1344 if (EVLIsLegal)
1345 return;
1346 // If for some reason EVL mode is unsupported, fallback to a scalar epilogue
1347 // if it's allowed, or DataWithoutLaneMask otherwise.
1348 if (ScalarEpilogueStatus == CM_ScalarEpilogueAllowed ||
1349 ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate)
1350 ChosenTailFoldingStyle = {TailFoldingStyle::None, TailFoldingStyle::None};
1351 else
1352 ChosenTailFoldingStyle = {TailFoldingStyle::DataWithoutLaneMask,
1354
1355 LLVM_DEBUG(
1356 dbgs() << "LV: Preference for VP intrinsics indicated. Will "
1357 "not try to generate VP Intrinsics "
1358 << (UserIC > 1
1359 ? "since interleave count specified is greater than 1.\n"
1360 : "due to non-interleaving reasons.\n"));
1361 }
1362
1363 /// Returns true if all loop blocks should be masked to fold tail loop.
1364 bool foldTailByMasking() const {
1365 // TODO: check if it is possible to check for None style independent of
1366 // IVUpdateMayOverflow flag in getTailFoldingStyle.
1368 }
1369
1370 /// Returns true if the use of wide lane masks is requested and the loop is
1371 /// using tail-folding with a lane mask for control flow.
1380
1381 /// Return maximum safe number of elements to be processed per vector
1382 /// iteration, which do not prevent store-load forwarding and are safe with
1383 /// regard to the memory dependencies. Required for EVL-based VPlans to
1384 /// correctly calculate AVL (application vector length) as min(remaining AVL,
1385 /// MaxSafeElements).
1386 /// TODO: need to consider adjusting cost model to use this value as a
1387 /// vectorization factor for EVL-based vectorization.
1388 std::optional<unsigned> getMaxSafeElements() const { return MaxSafeElements; }
1389
1390 /// Returns true if the instructions in this block requires predication
1391 /// for any reason, e.g. because tail folding now requires a predicate
1392 /// or because the block in the original loop was predicated.
1394 return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1395 }
1396
1397 /// Returns true if VP intrinsics with explicit vector length support should
1398 /// be generated in the tail folded loop.
1402
1403 /// Returns true if the Phi is part of an inloop reduction.
1404 bool isInLoopReduction(PHINode *Phi) const {
1405 return InLoopReductions.contains(Phi);
1406 }
1407
1408 /// Returns the set of in-loop reduction PHIs.
1410 return InLoopReductions;
1411 }
1412
1413 /// Returns true if the predicated reduction select should be used to set the
1414 /// incoming value for the reduction phi.
1416 // Force to use predicated reduction select since the EVL of the
1417 // second-to-last iteration might not be VF*UF.
1418 if (foldTailWithEVL())
1419 return true;
1421 TTI.preferPredicatedReductionSelect();
1422 }
1423
1424 /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1425 /// with factor VF. Return the cost of the instruction, including
1426 /// scalarization overhead if it's needed.
1427 InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1428
1429 /// Estimate cost of a call instruction CI if it were vectorized with factor
1430 /// VF. Return the cost of the instruction, including scalarization overhead
1431 /// if it's needed.
1432 InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const;
1433
1434 /// Invalidates decisions already taken by the cost model.
1436 WideningDecisions.clear();
1437 CallWideningDecisions.clear();
1438 Uniforms.clear();
1439 Scalars.clear();
1440 }
1441
1442 /// Returns the expected execution cost. The unit of the cost does
1443 /// not matter because we use the 'cost' units to compare different
1444 /// vector widths. The cost that is returned is *not* normalized by
1445 /// the factor width.
1446 InstructionCost expectedCost(ElementCount VF);
1447
1448 bool hasPredStores() const { return NumPredStores > 0; }
1449
1450 /// Returns true if epilogue vectorization is considered profitable, and
1451 /// false otherwise.
1452 /// \p VF is the vectorization factor chosen for the original loop.
1453 /// \p Multiplier is an aditional scaling factor applied to VF before
1454 /// comparing to EpilogueVectorizationMinVF.
1455 bool isEpilogueVectorizationProfitable(const ElementCount VF,
1456 const unsigned IC) const;
1457
1458 /// Returns the execution time cost of an instruction for a given vector
1459 /// width. Vector width of one means scalar.
1460 InstructionCost getInstructionCost(Instruction *I, ElementCount VF);
1461
1462 /// Return the cost of instructions in an inloop reduction pattern, if I is
1463 /// part of that pattern.
1464 std::optional<InstructionCost> getReductionPatternCost(Instruction *I,
1465 ElementCount VF,
1466 Type *VectorTy) const;
1467
1468 /// Returns true if \p Op should be considered invariant and if it is
1469 /// trivially hoistable.
1470 bool shouldConsiderInvariant(Value *Op);
1471
1472 /// Return the value of vscale used for tuning the cost model.
1473 std::optional<unsigned> getVScaleForTuning() const { return VScaleForTuning; }
1474
1475private:
1476 unsigned NumPredStores = 0;
1477
1478 /// Used to store the value of vscale used for tuning the cost model. It is
1479 /// initialized during object construction.
1480 std::optional<unsigned> VScaleForTuning;
1481
1482 /// Initializes the value of vscale used for tuning the cost model. If
1483 /// vscale_range.min == vscale_range.max then return vscale_range.max, else
1484 /// return the value returned by the corresponding TTI method.
1485 void initializeVScaleForTuning() {
1486 const Function *Fn = TheLoop->getHeader()->getParent();
1487 if (Fn->hasFnAttribute(Attribute::VScaleRange)) {
1488 auto Attr = Fn->getFnAttribute(Attribute::VScaleRange);
1489 auto Min = Attr.getVScaleRangeMin();
1490 auto Max = Attr.getVScaleRangeMax();
1491 if (Max && Min == Max) {
1492 VScaleForTuning = Max;
1493 return;
1494 }
1495 }
1496
1497 VScaleForTuning = TTI.getVScaleForTuning();
1498 }
1499
1500 /// \return An upper bound for the vectorization factors for both
1501 /// fixed and scalable vectorization, where the minimum-known number of
1502 /// elements is a power-of-2 larger than zero. If scalable vectorization is
1503 /// disabled or unsupported, then the scalable part will be equal to
1504 /// ElementCount::getScalable(0).
1505 FixedScalableVFPair computeFeasibleMaxVF(unsigned MaxTripCount,
1506 ElementCount UserVF,
1507 bool FoldTailByMasking);
1508
1509 /// If \p VF > MaxTripcount, clamps it to the next lower VF that is <=
1510 /// MaxTripCount.
1511 ElementCount clampVFByMaxTripCount(ElementCount VF, unsigned MaxTripCount,
1512 bool FoldTailByMasking) const;
1513
1514 /// \return the maximized element count based on the targets vector
1515 /// registers and the loop trip-count, but limited to a maximum safe VF.
1516 /// This is a helper function of computeFeasibleMaxVF.
1517 ElementCount getMaximizedVFForTarget(unsigned MaxTripCount,
1518 unsigned SmallestType,
1519 unsigned WidestType,
1520 ElementCount MaxSafeVF,
1521 bool FoldTailByMasking);
1522
1523 /// Checks if scalable vectorization is supported and enabled. Caches the
1524 /// result to avoid repeated debug dumps for repeated queries.
1525 bool isScalableVectorizationAllowed();
1526
1527 /// \return the maximum legal scalable VF, based on the safe max number
1528 /// of elements.
1529 ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1530
1531 /// Calculate vectorization cost of memory instruction \p I.
1532 InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1533
1534 /// The cost computation for scalarized memory instruction.
1535 InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1536
1537 /// The cost computation for interleaving group of memory instructions.
1538 InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1539
1540 /// The cost computation for Gather/Scatter instruction.
1541 InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1542
1543 /// The cost computation for widening instruction \p I with consecutive
1544 /// memory access.
1545 InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1546
1547 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1548 /// Load: scalar load + broadcast.
1549 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1550 /// element)
1551 InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1552
1553 /// Estimate the overhead of scalarizing an instruction. This is a
1554 /// convenience wrapper for the type-based getScalarizationOverhead API.
1556 ElementCount VF) const;
1557
1558 /// Returns true if an artificially high cost for emulated masked memrefs
1559 /// should be used.
1560 bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1561
1562 /// Map of scalar integer values to the smallest bitwidth they can be legally
1563 /// represented as. The vector equivalents of these values should be truncated
1564 /// to this type.
1565 MapVector<Instruction *, uint64_t> MinBWs;
1566
1567 /// A type representing the costs for instructions if they were to be
1568 /// scalarized rather than vectorized. The entries are Instruction-Cost
1569 /// pairs.
1570 using ScalarCostsTy = MapVector<Instruction *, InstructionCost>;
1571
1572 /// A set containing all BasicBlocks that are known to present after
1573 /// vectorization as a predicated block.
1574 DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
1575 PredicatedBBsAfterVectorization;
1576
1577 /// Records whether it is allowed to have the original scalar loop execute at
1578 /// least once. This may be needed as a fallback loop in case runtime
1579 /// aliasing/dependence checks fail, or to handle the tail/remainder
1580 /// iterations when the trip count is unknown or doesn't divide by the VF,
1581 /// or as a peel-loop to handle gaps in interleave-groups.
1582 /// Under optsize and when the trip count is very small we don't allow any
1583 /// iterations to execute in the scalar loop.
1584 ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1585
1586 /// Control finally chosen tail folding style. The first element is used if
1587 /// the IV update may overflow, the second element - if it does not.
1588 std::optional<std::pair<TailFoldingStyle, TailFoldingStyle>>
1589 ChosenTailFoldingStyle;
1590
1591 /// true if scalable vectorization is supported and enabled.
1592 std::optional<bool> IsScalableVectorizationAllowed;
1593
1594 /// Maximum safe number of elements to be processed per vector iteration,
1595 /// which do not prevent store-load forwarding and are safe with regard to the
1596 /// memory dependencies. Required for EVL-based veectorization, where this
1597 /// value is used as the upper bound of the safe AVL.
1598 std::optional<unsigned> MaxSafeElements;
1599
1600 /// A map holding scalar costs for different vectorization factors. The
1601 /// presence of a cost for an instruction in the mapping indicates that the
1602 /// instruction will be scalarized when vectorizing with the associated
1603 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1604 MapVector<ElementCount, ScalarCostsTy> InstsToScalarize;
1605
1606 /// Holds the instructions known to be uniform after vectorization.
1607 /// The data is collected per VF.
1608 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1609
1610 /// Holds the instructions known to be scalar after vectorization.
1611 /// The data is collected per VF.
1612 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1613
1614 /// Holds the instructions (address computations) that are forced to be
1615 /// scalarized.
1616 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1617
1618 /// PHINodes of the reductions that should be expanded in-loop.
1619 SmallPtrSet<PHINode *, 4> InLoopReductions;
1620
1621 /// A Map of inloop reduction operations and their immediate chain operand.
1622 /// FIXME: This can be removed once reductions can be costed correctly in
1623 /// VPlan. This was added to allow quick lookup of the inloop operations.
1624 DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1625
1626 /// Returns the expected difference in cost from scalarizing the expression
1627 /// feeding a predicated instruction \p PredInst. The instructions to
1628 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1629 /// non-negative return value implies the expression will be scalarized.
1630 /// Currently, only single-use chains are considered for scalarization.
1631 InstructionCost computePredInstDiscount(Instruction *PredInst,
1632 ScalarCostsTy &ScalarCosts,
1633 ElementCount VF);
1634
1635 /// Collect the instructions that are uniform after vectorization. An
1636 /// instruction is uniform if we represent it with a single scalar value in
1637 /// the vectorized loop corresponding to each vector iteration. Examples of
1638 /// uniform instructions include pointer operands of consecutive or
1639 /// interleaved memory accesses. Note that although uniformity implies an
1640 /// instruction will be scalar, the reverse is not true. In general, a
1641 /// scalarized instruction will be represented by VF scalar values in the
1642 /// vectorized loop, each corresponding to an iteration of the original
1643 /// scalar loop.
1644 void collectLoopUniforms(ElementCount VF);
1645
1646 /// Collect the instructions that are scalar after vectorization. An
1647 /// instruction is scalar if it is known to be uniform or will be scalarized
1648 /// during vectorization. collectLoopScalars should only add non-uniform nodes
1649 /// to the list if they are used by a load/store instruction that is marked as
1650 /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1651 /// VF values in the vectorized loop, each corresponding to an iteration of
1652 /// the original scalar loop.
1653 void collectLoopScalars(ElementCount VF);
1654
1655 /// Keeps cost model vectorization decision and cost for instructions.
1656 /// Right now it is used for memory instructions only.
1657 using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1658 std::pair<InstWidening, InstructionCost>>;
1659
1660 DecisionList WideningDecisions;
1661
1662 using CallDecisionList =
1663 DenseMap<std::pair<CallInst *, ElementCount>, CallWideningDecision>;
1664
1665 CallDecisionList CallWideningDecisions;
1666
1667 /// Returns true if \p V is expected to be vectorized and it needs to be
1668 /// extracted.
1669 bool needsExtract(Value *V, ElementCount VF) const {
1671 if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1672 TheLoop->isLoopInvariant(I) ||
1673 getWideningDecision(I, VF) == CM_Scalarize ||
1674 (isa<CallInst>(I) &&
1675 getCallWideningDecision(cast<CallInst>(I), VF).Kind == CM_Scalarize))
1676 return false;
1677
1678 // Assume we can vectorize V (and hence we need extraction) if the
1679 // scalars are not computed yet. This can happen, because it is called
1680 // via getScalarizationOverhead from setCostBasedWideningDecision, before
1681 // the scalars are collected. That should be a safe assumption in most
1682 // cases, because we check if the operands have vectorizable types
1683 // beforehand in LoopVectorizationLegality.
1684 return !Scalars.contains(VF) || !isScalarAfterVectorization(I, VF);
1685 };
1686
1687 /// Returns a range containing only operands needing to be extracted.
1688 SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1689 ElementCount VF) const {
1690
1691 SmallPtrSet<const Value *, 4> UniqueOperands;
1692 SmallVector<Value *, 4> Res;
1693 for (Value *Op : Ops) {
1694 if (isa<Constant>(Op) || !UniqueOperands.insert(Op).second ||
1695 !needsExtract(Op, VF))
1696 continue;
1697 Res.push_back(Op);
1698 }
1699 return Res;
1700 }
1701
1702public:
1703 /// The loop that we evaluate.
1705
1706 /// Predicated scalar evolution analysis.
1708
1709 /// Loop Info analysis.
1711
1712 /// Vectorization legality.
1714
1715 /// Vector target information.
1717
1718 /// Target Library Info.
1720
1721 /// Demanded bits analysis.
1723
1724 /// Assumption cache.
1726
1727 /// Interface to emit optimization remarks.
1729
1730 /// A function to lazily fetch BlockFrequencyInfo. This avoids computing it
1731 /// unless necessary, e.g. when the loop isn't legal to vectorize or when
1732 /// there is no predication.
1733 std::function<BlockFrequencyInfo &()> GetBFI;
1734 /// The BlockFrequencyInfo returned from GetBFI.
1736 /// Returns the BlockFrequencyInfo for the function if cached, otherwise
1737 /// fetches it via GetBFI. Avoids an indirect call to the std::function.
1739 if (!BFI)
1740 BFI = &GetBFI();
1741 return *BFI;
1742 }
1743
1745
1746 /// Loop Vectorize Hint.
1748
1749 /// The interleave access information contains groups of interleaved accesses
1750 /// with the same stride and close to each other.
1752
1753 /// Values to ignore in the cost model.
1755
1756 /// Values to ignore in the cost model when VF > 1.
1758
1759 /// All element types found in the loop.
1761
1762 /// The kind of cost that we are calculating
1764
1765 /// Whether this loop should be optimized for size based on function attribute
1766 /// or profile information.
1768
1769 /// The highest VF possible for this loop, without using MaxBandwidth.
1771};
1772} // end namespace llvm
1773
1774namespace {
1775/// Helper struct to manage generating runtime checks for vectorization.
1776///
1777/// The runtime checks are created up-front in temporary blocks to allow better
1778/// estimating the cost and un-linked from the existing IR. After deciding to
1779/// vectorize, the checks are moved back. If deciding not to vectorize, the
1780/// temporary blocks are completely removed.
1781class GeneratedRTChecks {
1782 /// Basic block which contains the generated SCEV checks, if any.
1783 BasicBlock *SCEVCheckBlock = nullptr;
1784
1785 /// The value representing the result of the generated SCEV checks. If it is
1786 /// nullptr no SCEV checks have been generated.
1787 Value *SCEVCheckCond = nullptr;
1788
1789 /// Basic block which contains the generated memory runtime checks, if any.
1790 BasicBlock *MemCheckBlock = nullptr;
1791
1792 /// The value representing the result of the generated memory runtime checks.
1793 /// If it is nullptr no memory runtime checks have been generated.
1794 Value *MemRuntimeCheckCond = nullptr;
1795
1796 DominatorTree *DT;
1797 LoopInfo *LI;
1799
1800 SCEVExpander SCEVExp;
1801 SCEVExpander MemCheckExp;
1802
1803 bool CostTooHigh = false;
1804
1805 Loop *OuterLoop = nullptr;
1806
1808
1809 /// The kind of cost that we are calculating
1811
1812public:
1813 GeneratedRTChecks(PredicatedScalarEvolution &PSE, DominatorTree *DT,
1816 : DT(DT), LI(LI), TTI(TTI),
1817 SCEVExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1818 MemCheckExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1819 PSE(PSE), CostKind(CostKind) {}
1820
1821 /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1822 /// accurately estimate the cost of the runtime checks. The blocks are
1823 /// un-linked from the IR and are added back during vector code generation. If
1824 /// there is no vector code generation, the check blocks are removed
1825 /// completely.
1826 void create(Loop *L, const LoopAccessInfo &LAI,
1827 const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC,
1828 OptimizationRemarkEmitter &ORE) {
1829
1830 // Hard cutoff to limit compile-time increase in case a very large number of
1831 // runtime checks needs to be generated.
1832 // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1833 // profile info.
1834 CostTooHigh =
1836 if (CostTooHigh) {
1837 // Mark runtime checks as never succeeding when they exceed the threshold.
1838 MemRuntimeCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1839 SCEVCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1840 ORE.emit([&]() {
1841 return OptimizationRemarkAnalysisAliasing(
1842 DEBUG_TYPE, "TooManyMemoryRuntimeChecks", L->getStartLoc(),
1843 L->getHeader())
1844 << "loop not vectorized: too many memory checks needed";
1845 });
1846 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1847 return;
1848 }
1849
1850 BasicBlock *LoopHeader = L->getHeader();
1851 BasicBlock *Preheader = L->getLoopPreheader();
1852
1853 // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1854 // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1855 // may be used by SCEVExpander. The blocks will be un-linked from their
1856 // predecessors and removed from LI & DT at the end of the function.
1857 if (!UnionPred.isAlwaysTrue()) {
1858 SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1859 nullptr, "vector.scevcheck");
1860
1861 SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1862 &UnionPred, SCEVCheckBlock->getTerminator());
1863 if (isa<Constant>(SCEVCheckCond)) {
1864 // Clean up directly after expanding the predicate to a constant, to
1865 // avoid further expansions re-using anything left over from SCEVExp.
1866 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1867 SCEVCleaner.cleanup();
1868 }
1869 }
1870
1871 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1872 if (RtPtrChecking.Need) {
1873 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1874 MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1875 "vector.memcheck");
1876
1877 auto DiffChecks = RtPtrChecking.getDiffChecks();
1878 if (DiffChecks) {
1879 Value *RuntimeVF = nullptr;
1880 MemRuntimeCheckCond = addDiffRuntimeChecks(
1881 MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp,
1882 [VF, &RuntimeVF](IRBuilderBase &B, unsigned Bits) {
1883 if (!RuntimeVF)
1884 RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1885 return RuntimeVF;
1886 },
1887 IC);
1888 } else {
1889 MemRuntimeCheckCond = addRuntimeChecks(
1890 MemCheckBlock->getTerminator(), L, RtPtrChecking.getChecks(),
1892 }
1893 assert(MemRuntimeCheckCond &&
1894 "no RT checks generated although RtPtrChecking "
1895 "claimed checks are required");
1896 }
1897
1898 SCEVExp.eraseDeadInstructions(SCEVCheckCond);
1899
1900 if (!MemCheckBlock && !SCEVCheckBlock)
1901 return;
1902
1903 // Unhook the temporary block with the checks, update various places
1904 // accordingly.
1905 if (SCEVCheckBlock)
1906 SCEVCheckBlock->replaceAllUsesWith(Preheader);
1907 if (MemCheckBlock)
1908 MemCheckBlock->replaceAllUsesWith(Preheader);
1909
1910 if (SCEVCheckBlock) {
1911 SCEVCheckBlock->getTerminator()->moveBefore(
1912 Preheader->getTerminator()->getIterator());
1913 auto *UI = new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1914 UI->setDebugLoc(DebugLoc::getTemporary());
1915 Preheader->getTerminator()->eraseFromParent();
1916 }
1917 if (MemCheckBlock) {
1918 MemCheckBlock->getTerminator()->moveBefore(
1919 Preheader->getTerminator()->getIterator());
1920 auto *UI = new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1921 UI->setDebugLoc(DebugLoc::getTemporary());
1922 Preheader->getTerminator()->eraseFromParent();
1923 }
1924
1925 DT->changeImmediateDominator(LoopHeader, Preheader);
1926 if (MemCheckBlock) {
1927 DT->eraseNode(MemCheckBlock);
1928 LI->removeBlock(MemCheckBlock);
1929 }
1930 if (SCEVCheckBlock) {
1931 DT->eraseNode(SCEVCheckBlock);
1932 LI->removeBlock(SCEVCheckBlock);
1933 }
1934
1935 // Outer loop is used as part of the later cost calculations.
1936 OuterLoop = L->getParentLoop();
1937 }
1938
1940 if (SCEVCheckBlock || MemCheckBlock)
1941 LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1942
1943 if (CostTooHigh) {
1945 Cost.setInvalid();
1946 LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
1947 return Cost;
1948 }
1949
1950 InstructionCost RTCheckCost = 0;
1951 if (SCEVCheckBlock)
1952 for (Instruction &I : *SCEVCheckBlock) {
1953 if (SCEVCheckBlock->getTerminator() == &I)
1954 continue;
1956 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1957 RTCheckCost += C;
1958 }
1959 if (MemCheckBlock) {
1960 InstructionCost MemCheckCost = 0;
1961 for (Instruction &I : *MemCheckBlock) {
1962 if (MemCheckBlock->getTerminator() == &I)
1963 continue;
1965 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1966 MemCheckCost += C;
1967 }
1968
1969 // If the runtime memory checks are being created inside an outer loop
1970 // we should find out if these checks are outer loop invariant. If so,
1971 // the checks will likely be hoisted out and so the effective cost will
1972 // reduce according to the outer loop trip count.
1973 if (OuterLoop) {
1974 ScalarEvolution *SE = MemCheckExp.getSE();
1975 // TODO: If profitable, we could refine this further by analysing every
1976 // individual memory check, since there could be a mixture of loop
1977 // variant and invariant checks that mean the final condition is
1978 // variant.
1979 const SCEV *Cond = SE->getSCEV(MemRuntimeCheckCond);
1980 if (SE->isLoopInvariant(Cond, OuterLoop)) {
1981 // It seems reasonable to assume that we can reduce the effective
1982 // cost of the checks even when we know nothing about the trip
1983 // count. Assume that the outer loop executes at least twice.
1984 unsigned BestTripCount = 2;
1985
1986 // Get the best known TC estimate.
1987 if (auto EstimatedTC = getSmallBestKnownTC(
1988 PSE, OuterLoop, /* CanUseConstantMax = */ false))
1989 if (EstimatedTC->isFixed())
1990 BestTripCount = EstimatedTC->getFixedValue();
1991
1992 InstructionCost NewMemCheckCost = MemCheckCost / BestTripCount;
1993
1994 // Let's ensure the cost is always at least 1.
1995 NewMemCheckCost = std::max(NewMemCheckCost.getValue(),
1996 (InstructionCost::CostType)1);
1997
1998 if (BestTripCount > 1)
2000 << "We expect runtime memory checks to be hoisted "
2001 << "out of the outer loop. Cost reduced from "
2002 << MemCheckCost << " to " << NewMemCheckCost << '\n');
2003
2004 MemCheckCost = NewMemCheckCost;
2005 }
2006 }
2007
2008 RTCheckCost += MemCheckCost;
2009 }
2010
2011 if (SCEVCheckBlock || MemCheckBlock)
2012 LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
2013 << "\n");
2014
2015 return RTCheckCost;
2016 }
2017
2018 /// Remove the created SCEV & memory runtime check blocks & instructions, if
2019 /// unused.
2020 ~GeneratedRTChecks() {
2021 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2022 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2023 bool SCEVChecksUsed = !SCEVCheckBlock || !pred_empty(SCEVCheckBlock);
2024 bool MemChecksUsed = !MemCheckBlock || !pred_empty(MemCheckBlock);
2025 if (SCEVChecksUsed)
2026 SCEVCleaner.markResultUsed();
2027
2028 if (MemChecksUsed) {
2029 MemCheckCleaner.markResultUsed();
2030 } else {
2031 auto &SE = *MemCheckExp.getSE();
2032 // Memory runtime check generation creates compares that use expanded
2033 // values. Remove them before running the SCEVExpanderCleaners.
2034 for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2035 if (MemCheckExp.isInsertedInstruction(&I))
2036 continue;
2037 SE.forgetValue(&I);
2038 I.eraseFromParent();
2039 }
2040 }
2041 MemCheckCleaner.cleanup();
2042 SCEVCleaner.cleanup();
2043
2044 if (!SCEVChecksUsed)
2045 SCEVCheckBlock->eraseFromParent();
2046 if (!MemChecksUsed)
2047 MemCheckBlock->eraseFromParent();
2048 }
2049
2050 /// Retrieves the SCEVCheckCond and SCEVCheckBlock that were generated as IR
2051 /// outside VPlan.
2052 std::pair<Value *, BasicBlock *> getSCEVChecks() const {
2053 using namespace llvm::PatternMatch;
2054 if (!SCEVCheckCond || match(SCEVCheckCond, m_ZeroInt()))
2055 return {nullptr, nullptr};
2056
2057 return {SCEVCheckCond, SCEVCheckBlock};
2058 }
2059
2060 /// Retrieves the MemCheckCond and MemCheckBlock that were generated as IR
2061 /// outside VPlan.
2062 std::pair<Value *, BasicBlock *> getMemRuntimeChecks() const {
2063 using namespace llvm::PatternMatch;
2064 if (MemRuntimeCheckCond && match(MemRuntimeCheckCond, m_ZeroInt()))
2065 return {nullptr, nullptr};
2066 return {MemRuntimeCheckCond, MemCheckBlock};
2067 }
2068
2069 /// Return true if any runtime checks have been added
2070 bool hasChecks() const {
2071 return getSCEVChecks().first || getMemRuntimeChecks().first;
2072 }
2073};
2074} // namespace
2075
2081
2086
2087// Return true if \p OuterLp is an outer loop annotated with hints for explicit
2088// vectorization. The loop needs to be annotated with #pragma omp simd
2089// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2090// vector length information is not provided, vectorization is not considered
2091// explicit. Interleave hints are not allowed either. These limitations will be
2092// relaxed in the future.
2093// Please, note that we are currently forced to abuse the pragma 'clang
2094// vectorize' semantics. This pragma provides *auto-vectorization hints*
2095// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2096// provides *explicit vectorization hints* (LV can bypass legal checks and
2097// assume that vectorization is legal). However, both hints are implemented
2098// using the same metadata (llvm.loop.vectorize, processed by
2099// LoopVectorizeHints). This will be fixed in the future when the native IR
2100// representation for pragma 'omp simd' is introduced.
2101static bool isExplicitVecOuterLoop(Loop *OuterLp,
2103 assert(!OuterLp->isInnermost() && "This is not an outer loop");
2104 LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2105
2106 // Only outer loops with an explicit vectorization hint are supported.
2107 // Unannotated outer loops are ignored.
2109 return false;
2110
2111 Function *Fn = OuterLp->getHeader()->getParent();
2112 if (!Hints.allowVectorization(Fn, OuterLp,
2113 true /*VectorizeOnlyWhenForced*/)) {
2114 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2115 return false;
2116 }
2117
2118 if (Hints.getInterleave() > 1) {
2119 // TODO: Interleave support is future work.
2120 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2121 "outer loops.\n");
2122 Hints.emitRemarkWithHints();
2123 return false;
2124 }
2125
2126 return true;
2127}
2128
2132 // Collect inner loops and outer loops without irreducible control flow. For
2133 // now, only collect outer loops that have explicit vectorization hints. If we
2134 // are stress testing the VPlan H-CFG construction, we collect the outermost
2135 // loop of every loop nest.
2136 if (L.isInnermost() || VPlanBuildStressTest ||
2138 LoopBlocksRPO RPOT(&L);
2139 RPOT.perform(LI);
2141 V.push_back(&L);
2142 // TODO: Collect inner loops inside marked outer loops in case
2143 // vectorization fails for the outer loop. Do not invoke
2144 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2145 // already known to be reducible. We can use an inherited attribute for
2146 // that.
2147 return;
2148 }
2149 }
2150 for (Loop *InnerL : L)
2151 collectSupportedLoops(*InnerL, LI, ORE, V);
2152}
2153
2154//===----------------------------------------------------------------------===//
2155// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2156// LoopVectorizationCostModel and LoopVectorizationPlanner.
2157//===----------------------------------------------------------------------===//
2158
2159/// Compute the transformed value of Index at offset StartValue using step
2160/// StepValue.
2161/// For integer induction, returns StartValue + Index * StepValue.
2162/// For pointer induction, returns StartValue[Index * StepValue].
2163/// FIXME: The newly created binary instructions should contain nsw/nuw
2164/// flags, which can be found from the original scalar operations.
2165static Value *
2167 Value *Step,
2169 const BinaryOperator *InductionBinOp) {
2170 using namespace llvm::PatternMatch;
2171 Type *StepTy = Step->getType();
2172 Value *CastedIndex = StepTy->isIntegerTy()
2173 ? B.CreateSExtOrTrunc(Index, StepTy)
2174 : B.CreateCast(Instruction::SIToFP, Index, StepTy);
2175 if (CastedIndex != Index) {
2176 CastedIndex->setName(CastedIndex->getName() + ".cast");
2177 Index = CastedIndex;
2178 }
2179
2180 // Note: the IR at this point is broken. We cannot use SE to create any new
2181 // SCEV and then expand it, hoping that SCEV's simplification will give us
2182 // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2183 // lead to various SCEV crashes. So all we can do is to use builder and rely
2184 // on InstCombine for future simplifications. Here we handle some trivial
2185 // cases only.
2186 auto CreateAdd = [&B](Value *X, Value *Y) {
2187 assert(X->getType() == Y->getType() && "Types don't match!");
2188 if (match(X, m_ZeroInt()))
2189 return Y;
2190 if (match(Y, m_ZeroInt()))
2191 return X;
2192 return B.CreateAdd(X, Y);
2193 };
2194
2195 // We allow X to be a vector type, in which case Y will potentially be
2196 // splatted into a vector with the same element count.
2197 auto CreateMul = [&B](Value *X, Value *Y) {
2198 assert(X->getType()->getScalarType() == Y->getType() &&
2199 "Types don't match!");
2200 if (match(X, m_One()))
2201 return Y;
2202 if (match(Y, m_One()))
2203 return X;
2204 VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2205 if (XVTy && !isa<VectorType>(Y->getType()))
2206 Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2207 return B.CreateMul(X, Y);
2208 };
2209
2210 switch (InductionKind) {
2212 assert(!isa<VectorType>(Index->getType()) &&
2213 "Vector indices not supported for integer inductions yet");
2214 assert(Index->getType() == StartValue->getType() &&
2215 "Index type does not match StartValue type");
2216 if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2217 return B.CreateSub(StartValue, Index);
2218 auto *Offset = CreateMul(Index, Step);
2219 return CreateAdd(StartValue, Offset);
2220 }
2222 return B.CreatePtrAdd(StartValue, CreateMul(Index, Step));
2224 assert(!isa<VectorType>(Index->getType()) &&
2225 "Vector indices not supported for FP inductions yet");
2226 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2227 assert(InductionBinOp &&
2228 (InductionBinOp->getOpcode() == Instruction::FAdd ||
2229 InductionBinOp->getOpcode() == Instruction::FSub) &&
2230 "Original bin op should be defined for FP induction");
2231
2232 Value *MulExp = B.CreateFMul(Step, Index);
2233 return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2234 "induction");
2235 }
2237 return nullptr;
2238 }
2239 llvm_unreachable("invalid enum");
2240}
2241
2242static std::optional<unsigned> getMaxVScale(const Function &F,
2243 const TargetTransformInfo &TTI) {
2244 if (std::optional<unsigned> MaxVScale = TTI.getMaxVScale())
2245 return MaxVScale;
2246
2247 if (F.hasFnAttribute(Attribute::VScaleRange))
2248 return F.getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
2249
2250 return std::nullopt;
2251}
2252
2253/// For the given VF and UF and maximum trip count computed for the loop, return
2254/// whether the induction variable might overflow in the vectorized loop. If not,
2255/// then we know a runtime overflow check always evaluates to false and can be
2256/// removed.
2258 const LoopVectorizationCostModel *Cost,
2259 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
2260 // Always be conservative if we don't know the exact unroll factor.
2261 unsigned MaxUF = UF ? *UF : Cost->TTI.getMaxInterleaveFactor(VF);
2262
2263 IntegerType *IdxTy = Cost->Legal->getWidestInductionType();
2264 APInt MaxUIntTripCount = IdxTy->getMask();
2265
2266 // We know the runtime overflow check is known false iff the (max) trip-count
2267 // is known and (max) trip-count + (VF * UF) does not overflow in the type of
2268 // the vector loop induction variable.
2269 if (unsigned TC = Cost->PSE.getSmallConstantMaxTripCount()) {
2270 uint64_t MaxVF = VF.getKnownMinValue();
2271 if (VF.isScalable()) {
2272 std::optional<unsigned> MaxVScale =
2273 getMaxVScale(*Cost->TheFunction, Cost->TTI);
2274 if (!MaxVScale)
2275 return false;
2276 MaxVF *= *MaxVScale;
2277 }
2278
2279 return (MaxUIntTripCount - TC).ugt(MaxVF * MaxUF);
2280 }
2281
2282 return false;
2283}
2284
2285// Return whether we allow using masked interleave-groups (for dealing with
2286// strided loads/stores that reside in predicated blocks, or for dealing
2287// with gaps).
2289 // If an override option has been passed in for interleaved accesses, use it.
2290 if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2292
2293 return TTI.enableMaskedInterleavedAccessVectorization();
2294}
2295
2297 BasicBlock *CheckIRBB) {
2298 // Note: The block with the minimum trip-count check is already connected
2299 // during earlier VPlan construction.
2300 VPBlockBase *ScalarPH = Plan.getScalarPreheader();
2301 VPBlockBase *PreVectorPH = VectorPHVPBB->getSinglePredecessor();
2302 assert(PreVectorPH->getNumSuccessors() == 2 && "Expected 2 successors");
2303 assert(PreVectorPH->getSuccessors()[0] == ScalarPH && "Unexpected successor");
2304 VPIRBasicBlock *CheckVPIRBB = Plan.createVPIRBasicBlock(CheckIRBB);
2305 VPBlockUtils::insertOnEdge(PreVectorPH, VectorPHVPBB, CheckVPIRBB);
2306 PreVectorPH = CheckVPIRBB;
2307 VPBlockUtils::connectBlocks(PreVectorPH, ScalarPH);
2308 PreVectorPH->swapSuccessors();
2309
2310 // We just connected a new block to the scalar preheader. Update all
2311 // VPPhis by adding an incoming value for it, replicating the last value.
2312 unsigned NumPredecessors = ScalarPH->getNumPredecessors();
2313 for (VPRecipeBase &R : cast<VPBasicBlock>(ScalarPH)->phis()) {
2314 assert(isa<VPPhi>(&R) && "Phi expected to be VPPhi");
2315 assert(cast<VPPhi>(&R)->getNumIncoming() == NumPredecessors - 1 &&
2316 "must have incoming values for all operands");
2317 R.addOperand(R.getOperand(NumPredecessors - 2));
2318 }
2319}
2320
2322 BasicBlock *VectorPH, ElementCount VF, unsigned UF) const {
2323 // Generate code to check if the loop's trip count is less than VF * UF, or
2324 // equal to it in case a scalar epilogue is required; this implies that the
2325 // vector trip count is zero. This check also covers the case where adding one
2326 // to the backedge-taken count overflowed leading to an incorrect trip count
2327 // of zero. In this case we will also jump to the scalar loop.
2328 auto P = Cost->requiresScalarEpilogue(VF.isVector()) ? ICmpInst::ICMP_ULE
2330
2331 // Reuse existing vector loop preheader for TC checks.
2332 // Note that new preheader block is generated for vector loop.
2333 BasicBlock *const TCCheckBlock = VectorPH;
2335 TCCheckBlock->getContext(),
2336 InstSimplifyFolder(TCCheckBlock->getDataLayout()));
2337 Builder.SetInsertPoint(TCCheckBlock->getTerminator());
2338
2339 // If tail is to be folded, vector loop takes care of all iterations.
2341 Type *CountTy = Count->getType();
2342 Value *CheckMinIters = Builder.getFalse();
2343 auto CreateStep = [&]() -> Value * {
2344 // Create step with max(MinProTripCount, UF * VF).
2345 if (UF * VF.getKnownMinValue() >= MinProfitableTripCount.getKnownMinValue())
2346 return createStepForVF(Builder, CountTy, VF, UF);
2347
2348 Value *MinProfTC =
2349 Builder.CreateElementCount(CountTy, MinProfitableTripCount);
2350 if (!VF.isScalable())
2351 return MinProfTC;
2352 return Builder.CreateBinaryIntrinsic(
2353 Intrinsic::umax, MinProfTC, createStepForVF(Builder, CountTy, VF, UF));
2354 };
2355
2356 TailFoldingStyle Style = Cost->getTailFoldingStyle();
2357 if (Style == TailFoldingStyle::None) {
2358 Value *Step = CreateStep();
2359 ScalarEvolution &SE = *PSE.getSE();
2360 // TODO: Emit unconditional branch to vector preheader instead of
2361 // conditional branch with known condition.
2362 const SCEV *TripCountSCEV = SE.applyLoopGuards(SE.getSCEV(Count), OrigLoop);
2363 // Check if the trip count is < the step.
2364 if (SE.isKnownPredicate(P, TripCountSCEV, SE.getSCEV(Step))) {
2365 // TODO: Ensure step is at most the trip count when determining max VF and
2366 // UF, w/o tail folding.
2367 CheckMinIters = Builder.getTrue();
2369 TripCountSCEV, SE.getSCEV(Step))) {
2370 // Generate the minimum iteration check only if we cannot prove the
2371 // check is known to be true, or known to be false.
2372 CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
2373 } // else step known to be < trip count, use CheckMinIters preset to false.
2374 } else if (VF.isScalable() && !TTI->isVScaleKnownToBeAPowerOfTwo() &&
2377 // vscale is not necessarily a power-of-2, which means we cannot guarantee
2378 // an overflow to zero when updating induction variables and so an
2379 // additional overflow check is required before entering the vector loop.
2380
2381 // Get the maximum unsigned value for the type.
2382 Value *MaxUIntTripCount =
2383 ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2384 Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2385
2386 // Don't execute the vector loop if (UMax - n) < (VF * UF).
2387 CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, CreateStep());
2388 }
2389 return CheckMinIters;
2390}
2391
2392/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
2393/// VPBB are moved to the end of the newly created VPIRBasicBlock. All
2394/// predecessors and successors of VPBB, if any, are rewired to the new
2395/// VPIRBasicBlock. If \p VPBB may be unreachable, \p Plan must be passed.
2397 BasicBlock *IRBB,
2398 VPlan *Plan = nullptr) {
2399 if (!Plan)
2400 Plan = VPBB->getPlan();
2401 VPIRBasicBlock *IRVPBB = Plan->createVPIRBasicBlock(IRBB);
2402 auto IP = IRVPBB->begin();
2403 for (auto &R : make_early_inc_range(VPBB->phis()))
2404 R.moveBefore(*IRVPBB, IP);
2405
2406 for (auto &R :
2408 R.moveBefore(*IRVPBB, IRVPBB->end());
2409
2410 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB);
2411 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
2412 return IRVPBB;
2413}
2414
2416 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2417 assert(VectorPH && "Invalid loop structure");
2418 assert((OrigLoop->getUniqueLatchExitBlock() ||
2419 Cost->requiresScalarEpilogue(VF.isVector())) &&
2420 "loops not exiting via the latch without required epilogue?");
2421
2422 // NOTE: The Plan's scalar preheader VPBB isn't replaced with a VPIRBasicBlock
2423 // wrapping the newly created scalar preheader here at the moment, because the
2424 // Plan's scalar preheader may be unreachable at this point. Instead it is
2425 // replaced in executePlan.
2426 return SplitBlock(VectorPH, VectorPH->getTerminator(), DT, LI, nullptr,
2427 Twine(Prefix) + "scalar.ph");
2428}
2429
2430/// Return the expanded step for \p ID using \p ExpandedSCEVs to look up SCEV
2431/// expansion results.
2433 const SCEV2ValueTy &ExpandedSCEVs) {
2434 const SCEV *Step = ID.getStep();
2435 if (auto *C = dyn_cast<SCEVConstant>(Step))
2436 return C->getValue();
2437 if (auto *U = dyn_cast<SCEVUnknown>(Step))
2438 return U->getValue();
2439 Value *V = ExpandedSCEVs.lookup(Step);
2440 assert(V && "SCEV must be expanded at this point");
2441 return V;
2442}
2443
2444/// Knowing that loop \p L executes a single vector iteration, add instructions
2445/// that will get simplified and thus should not have any cost to \p
2446/// InstsToIgnore.
2449 SmallPtrSetImpl<Instruction *> &InstsToIgnore) {
2450 auto *Cmp = L->getLatchCmpInst();
2451 if (Cmp)
2452 InstsToIgnore.insert(Cmp);
2453 for (const auto &KV : IL) {
2454 // Extract the key by hand so that it can be used in the lambda below. Note
2455 // that captured structured bindings are a C++20 extension.
2456 const PHINode *IV = KV.first;
2457
2458 // Get next iteration value of the induction variable.
2459 Instruction *IVInst =
2460 cast<Instruction>(IV->getIncomingValueForBlock(L->getLoopLatch()));
2461 if (all_of(IVInst->users(),
2462 [&](const User *U) { return U == IV || U == Cmp; }))
2463 InstsToIgnore.insert(IVInst);
2464 }
2465}
2466
2468 // Create a new IR basic block for the scalar preheader.
2469 BasicBlock *ScalarPH = createScalarPreheader("");
2470 return ScalarPH->getSinglePredecessor();
2471}
2472
2473namespace {
2474
2475struct CSEDenseMapInfo {
2476 static bool canHandle(const Instruction *I) {
2479 }
2480
2481 static inline Instruction *getEmptyKey() {
2483 }
2484
2485 static inline Instruction *getTombstoneKey() {
2486 return DenseMapInfo<Instruction *>::getTombstoneKey();
2487 }
2488
2489 static unsigned getHashValue(const Instruction *I) {
2490 assert(canHandle(I) && "Unknown instruction!");
2491 return hash_combine(I->getOpcode(),
2492 hash_combine_range(I->operand_values()));
2493 }
2494
2495 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
2496 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2497 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2498 return LHS == RHS;
2499 return LHS->isIdenticalTo(RHS);
2500 }
2501};
2502
2503} // end anonymous namespace
2504
2505/// FIXME: This legacy common-subexpression-elimination routine is scheduled for
2506/// removal, in favor of the VPlan-based one.
2507static void legacyCSE(BasicBlock *BB) {
2508 // Perform simple cse.
2510 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
2511 if (!CSEDenseMapInfo::canHandle(&In))
2512 continue;
2513
2514 // Check if we can replace this instruction with any of the
2515 // visited instructions.
2516 if (Instruction *V = CSEMap.lookup(&In)) {
2517 In.replaceAllUsesWith(V);
2518 In.eraseFromParent();
2519 continue;
2520 }
2521
2522 CSEMap[&In] = &In;
2523 }
2524}
2525
2526/// This function attempts to return a value that represents the ElementCount
2527/// at runtime. For fixed-width VFs we know this precisely at compile
2528/// time, but for scalable VFs we calculate it based on an estimate of the
2529/// vscale value.
2531 std::optional<unsigned> VScale) {
2532 unsigned EstimatedVF = VF.getKnownMinValue();
2533 if (VF.isScalable())
2534 if (VScale)
2535 EstimatedVF *= *VScale;
2536 assert(EstimatedVF >= 1 && "Estimated VF shouldn't be less than 1");
2537 return EstimatedVF;
2538}
2539
2542 ElementCount VF) const {
2543 // We only need to calculate a cost if the VF is scalar; for actual vectors
2544 // we should already have a pre-calculated cost at each VF.
2545 if (!VF.isScalar())
2546 return getCallWideningDecision(CI, VF).Cost;
2547
2548 Type *RetTy = CI->getType();
2550 if (auto RedCost = getReductionPatternCost(CI, VF, RetTy))
2551 return *RedCost;
2552
2554 for (auto &ArgOp : CI->args())
2555 Tys.push_back(ArgOp->getType());
2556
2557 InstructionCost ScalarCallCost =
2558 TTI.getCallInstrCost(CI->getCalledFunction(), RetTy, Tys, CostKind);
2559
2560 // If this is an intrinsic we may have a lower cost for it.
2563 return std::min(ScalarCallCost, IntrinsicCost);
2564 }
2565 return ScalarCallCost;
2566}
2567
2569 if (VF.isScalar() || !canVectorizeTy(Ty))
2570 return Ty;
2571 return toVectorizedTy(Ty, VF);
2572}
2573
2576 ElementCount VF) const {
2578 assert(ID && "Expected intrinsic call!");
2579 Type *RetTy = maybeVectorizeType(CI->getType(), VF);
2580 FastMathFlags FMF;
2581 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2582 FMF = FPMO->getFastMathFlags();
2583
2586 SmallVector<Type *> ParamTys;
2587 std::transform(FTy->param_begin(), FTy->param_end(),
2588 std::back_inserter(ParamTys),
2589 [&](Type *Ty) { return maybeVectorizeType(Ty, VF); });
2590
2591 IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
2594 return TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
2595}
2596
2598 // Fix widened non-induction PHIs by setting up the PHI operands.
2599 fixNonInductionPHIs(State);
2600
2601 // Don't apply optimizations below when no (vector) loop remains, as they all
2602 // require one at the moment.
2603 VPBasicBlock *HeaderVPBB =
2604 vputils::getFirstLoopHeader(*State.Plan, State.VPDT);
2605 if (!HeaderVPBB)
2606 return;
2607
2608 BasicBlock *HeaderBB = State.CFG.VPBB2IRBB[HeaderVPBB];
2609
2610 // Remove redundant induction instructions.
2611 legacyCSE(HeaderBB);
2612}
2613
2615 auto Iter = vp_depth_first_shallow(Plan.getEntry());
2617 for (VPRecipeBase &P : VPBB->phis()) {
2619 if (!VPPhi)
2620 continue;
2621 PHINode *NewPhi = cast<PHINode>(State.get(VPPhi));
2622 // Make sure the builder has a valid insert point.
2623 Builder.SetInsertPoint(NewPhi);
2624 for (const auto &[Inc, VPBB] : VPPhi->incoming_values_and_blocks())
2625 NewPhi->addIncoming(State.get(Inc), State.CFG.VPBB2IRBB[VPBB]);
2626 }
2627 }
2628}
2629
2630void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
2631 // We should not collect Scalars more than once per VF. Right now, this
2632 // function is called from collectUniformsAndScalars(), which already does
2633 // this check. Collecting Scalars for VF=1 does not make any sense.
2634 assert(VF.isVector() && !Scalars.contains(VF) &&
2635 "This function should not be visited twice for the same VF");
2636
2637 // This avoids any chances of creating a REPLICATE recipe during planning
2638 // since that would result in generation of scalarized code during execution,
2639 // which is not supported for scalable vectors.
2640 if (VF.isScalable()) {
2641 Scalars[VF].insert_range(Uniforms[VF]);
2642 return;
2643 }
2644
2646
2647 // These sets are used to seed the analysis with pointers used by memory
2648 // accesses that will remain scalar.
2650 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
2651 auto *Latch = TheLoop->getLoopLatch();
2652
2653 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
2654 // The pointer operands of loads and stores will be scalar as long as the
2655 // memory access is not a gather or scatter operation. The value operand of a
2656 // store will remain scalar if the store is scalarized.
2657 auto IsScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
2658 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
2659 assert(WideningDecision != CM_Unknown &&
2660 "Widening decision should be ready at this moment");
2661 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
2662 if (Ptr == Store->getValueOperand())
2663 return WideningDecision == CM_Scalarize;
2664 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
2665 "Ptr is neither a value or pointer operand");
2666 return WideningDecision != CM_GatherScatter;
2667 };
2668
2669 // A helper that returns true if the given value is a getelementptr
2670 // instruction contained in the loop.
2671 auto IsLoopVaryingGEP = [&](Value *V) {
2672 return isa<GetElementPtrInst>(V) && !TheLoop->isLoopInvariant(V);
2673 };
2674
2675 // A helper that evaluates a memory access's use of a pointer. If the use will
2676 // be a scalar use and the pointer is only used by memory accesses, we place
2677 // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
2678 // PossibleNonScalarPtrs.
2679 auto EvaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
2680 // We only care about bitcast and getelementptr instructions contained in
2681 // the loop.
2682 if (!IsLoopVaryingGEP(Ptr))
2683 return;
2684
2685 // If the pointer has already been identified as scalar (e.g., if it was
2686 // also identified as uniform), there's nothing to do.
2687 auto *I = cast<Instruction>(Ptr);
2688 if (Worklist.count(I))
2689 return;
2690
2691 // If the use of the pointer will be a scalar use, and all users of the
2692 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
2693 // place the pointer in PossibleNonScalarPtrs.
2694 if (IsScalarUse(MemAccess, Ptr) &&
2696 ScalarPtrs.insert(I);
2697 else
2698 PossibleNonScalarPtrs.insert(I);
2699 };
2700
2701 // We seed the scalars analysis with three classes of instructions: (1)
2702 // instructions marked uniform-after-vectorization and (2) bitcast,
2703 // getelementptr and (pointer) phi instructions used by memory accesses
2704 // requiring a scalar use.
2705 //
2706 // (1) Add to the worklist all instructions that have been identified as
2707 // uniform-after-vectorization.
2708 Worklist.insert_range(Uniforms[VF]);
2709
2710 // (2) Add to the worklist all bitcast and getelementptr instructions used by
2711 // memory accesses requiring a scalar use. The pointer operands of loads and
2712 // stores will be scalar unless the operation is a gather or scatter.
2713 // The value operand of a store will remain scalar if the store is scalarized.
2714 for (auto *BB : TheLoop->blocks())
2715 for (auto &I : *BB) {
2716 if (auto *Load = dyn_cast<LoadInst>(&I)) {
2717 EvaluatePtrUse(Load, Load->getPointerOperand());
2718 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
2719 EvaluatePtrUse(Store, Store->getPointerOperand());
2720 EvaluatePtrUse(Store, Store->getValueOperand());
2721 }
2722 }
2723 for (auto *I : ScalarPtrs)
2724 if (!PossibleNonScalarPtrs.count(I)) {
2725 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
2726 Worklist.insert(I);
2727 }
2728
2729 // Insert the forced scalars.
2730 // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
2731 // induction variable when the PHI user is scalarized.
2732 auto ForcedScalar = ForcedScalars.find(VF);
2733 if (ForcedScalar != ForcedScalars.end())
2734 for (auto *I : ForcedScalar->second) {
2735 LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
2736 Worklist.insert(I);
2737 }
2738
2739 // Expand the worklist by looking through any bitcasts and getelementptr
2740 // instructions we've already identified as scalar. This is similar to the
2741 // expansion step in collectLoopUniforms(); however, here we're only
2742 // expanding to include additional bitcasts and getelementptr instructions.
2743 unsigned Idx = 0;
2744 while (Idx != Worklist.size()) {
2745 Instruction *Dst = Worklist[Idx++];
2746 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
2747 continue;
2748 auto *Src = cast<Instruction>(Dst->getOperand(0));
2749 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
2750 auto *J = cast<Instruction>(U);
2751 return !TheLoop->contains(J) || Worklist.count(J) ||
2752 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
2753 IsScalarUse(J, Src));
2754 })) {
2755 Worklist.insert(Src);
2756 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
2757 }
2758 }
2759
2760 // An induction variable will remain scalar if all users of the induction
2761 // variable and induction variable update remain scalar.
2762 for (const auto &Induction : Legal->getInductionVars()) {
2763 auto *Ind = Induction.first;
2764 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2765
2766 // If tail-folding is applied, the primary induction variable will be used
2767 // to feed a vector compare.
2768 if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
2769 continue;
2770
2771 // Returns true if \p Indvar is a pointer induction that is used directly by
2772 // load/store instruction \p I.
2773 auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
2774 Instruction *I) {
2775 return Induction.second.getKind() ==
2778 Indvar == getLoadStorePointerOperand(I) && IsScalarUse(I, Indvar);
2779 };
2780
2781 // Determine if all users of the induction variable are scalar after
2782 // vectorization.
2783 bool ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
2784 auto *I = cast<Instruction>(U);
2785 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2786 IsDirectLoadStoreFromPtrIndvar(Ind, I);
2787 });
2788 if (!ScalarInd)
2789 continue;
2790
2791 // If the induction variable update is a fixed-order recurrence, neither the
2792 // induction variable or its update should be marked scalar after
2793 // vectorization.
2794 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
2795 if (IndUpdatePhi && Legal->isFixedOrderRecurrence(IndUpdatePhi))
2796 continue;
2797
2798 // Determine if all users of the induction variable update instruction are
2799 // scalar after vectorization.
2800 bool ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2801 auto *I = cast<Instruction>(U);
2802 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
2803 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
2804 });
2805 if (!ScalarIndUpdate)
2806 continue;
2807
2808 // The induction variable and its update instruction will remain scalar.
2809 Worklist.insert(Ind);
2810 Worklist.insert(IndUpdate);
2811 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
2812 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
2813 << "\n");
2814 }
2815
2816 Scalars[VF].insert_range(Worklist);
2817}
2818
2820 ElementCount VF) {
2821 if (!isPredicatedInst(I))
2822 return false;
2823
2824 // Do we have a non-scalar lowering for this predicated
2825 // instruction? No - it is scalar with predication.
2826 switch(I->getOpcode()) {
2827 default:
2828 return true;
2829 case Instruction::Call:
2830 if (VF.isScalar())
2831 return true;
2833 case Instruction::Load:
2834 case Instruction::Store: {
2835 auto *Ptr = getLoadStorePointerOperand(I);
2836 auto *Ty = getLoadStoreType(I);
2837 unsigned AS = getLoadStoreAddressSpace(I);
2838 Type *VTy = Ty;
2839 if (VF.isVector())
2840 VTy = VectorType::get(Ty, VF);
2841 const Align Alignment = getLoadStoreAlignment(I);
2842 return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment, AS) ||
2843 TTI.isLegalMaskedGather(VTy, Alignment))
2844 : !(isLegalMaskedStore(Ty, Ptr, Alignment, AS) ||
2845 TTI.isLegalMaskedScatter(VTy, Alignment));
2846 }
2847 case Instruction::UDiv:
2848 case Instruction::SDiv:
2849 case Instruction::SRem:
2850 case Instruction::URem: {
2851 // We have the option to use the safe-divisor idiom to avoid predication.
2852 // The cost based decision here will always select safe-divisor for
2853 // scalable vectors as scalarization isn't legal.
2854 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
2855 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost);
2856 }
2857 }
2858}
2859
2860// TODO: Fold into LoopVectorizationLegality::isMaskRequired.
2862 // TODO: We can use the loop-preheader as context point here and get
2863 // context sensitive reasoning for isSafeToSpeculativelyExecute.
2865 (isa<LoadInst, StoreInst, CallInst>(I) && !Legal->isMaskRequired(I)) ||
2867 return false;
2868
2869 // If the instruction was executed conditionally in the original scalar loop,
2870 // predication is needed with a mask whose lanes are all possibly inactive.
2871 if (Legal->blockNeedsPredication(I->getParent()))
2872 return true;
2873
2874 // If we're not folding the tail by masking, predication is unnecessary.
2875 if (!foldTailByMasking())
2876 return false;
2877
2878 // All that remain are instructions with side-effects originally executed in
2879 // the loop unconditionally, but now execute under a tail-fold mask (only)
2880 // having at least one active lane (the first). If the side-effects of the
2881 // instruction are invariant, executing it w/o (the tail-folding) mask is safe
2882 // - it will cause the same side-effects as when masked.
2883 switch(I->getOpcode()) {
2884 default:
2886 "instruction should have been considered by earlier checks");
2887 case Instruction::Call:
2888 // Side-effects of a Call are assumed to be non-invariant, needing a
2889 // (fold-tail) mask.
2890 assert(Legal->isMaskRequired(I) &&
2891 "should have returned earlier for calls not needing a mask");
2892 return true;
2893 case Instruction::Load:
2894 // If the address is loop invariant no predication is needed.
2895 return !Legal->isInvariant(getLoadStorePointerOperand(I));
2896 case Instruction::Store: {
2897 // For stores, we need to prove both speculation safety (which follows from
2898 // the same argument as loads), but also must prove the value being stored
2899 // is correct. The easiest form of the later is to require that all values
2900 // stored are the same.
2901 return !(Legal->isInvariant(getLoadStorePointerOperand(I)) &&
2902 TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()));
2903 }
2904 case Instruction::UDiv:
2905 case Instruction::URem:
2906 // If the divisor is loop-invariant no predication is needed.
2907 return !Legal->isInvariant(I->getOperand(1));
2908 case Instruction::SDiv:
2909 case Instruction::SRem:
2910 // Conservative for now, since masked-off lanes may be poison and could
2911 // trigger signed overflow.
2912 return true;
2913 }
2914}
2915
2919 return 1;
2920 // If the block wasn't originally predicated then return early to avoid
2921 // computing BlockFrequencyInfo unnecessarily.
2922 if (!Legal->blockNeedsPredication(BB))
2923 return 1;
2924
2925 uint64_t HeaderFreq =
2926 getBFI().getBlockFreq(TheLoop->getHeader()).getFrequency();
2927 uint64_t BBFreq = getBFI().getBlockFreq(BB).getFrequency();
2928 assert(HeaderFreq >= BBFreq &&
2929 "Header has smaller block freq than dominated BB?");
2930 return std::round((double)HeaderFreq / BBFreq);
2931}
2932
2933std::pair<InstructionCost, InstructionCost>
2935 ElementCount VF) {
2936 assert(I->getOpcode() == Instruction::UDiv ||
2937 I->getOpcode() == Instruction::SDiv ||
2938 I->getOpcode() == Instruction::SRem ||
2939 I->getOpcode() == Instruction::URem);
2941
2942 // Scalarization isn't legal for scalable vector types
2943 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
2944 if (!VF.isScalable()) {
2945 // Get the scalarization cost and scale this amount by the probability of
2946 // executing the predicated block. If the instruction is not predicated,
2947 // we fall through to the next case.
2948 ScalarizationCost = 0;
2949
2950 // These instructions have a non-void type, so account for the phi nodes
2951 // that we will create. This cost is likely to be zero. The phi node
2952 // cost, if any, should be scaled by the block probability because it
2953 // models a copy at the end of each predicated block.
2954 ScalarizationCost +=
2955 VF.getFixedValue() * TTI.getCFInstrCost(Instruction::PHI, CostKind);
2956
2957 // The cost of the non-predicated instruction.
2958 ScalarizationCost +=
2959 VF.getFixedValue() *
2960 TTI.getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind);
2961
2962 // The cost of insertelement and extractelement instructions needed for
2963 // scalarization.
2964 ScalarizationCost += getScalarizationOverhead(I, VF);
2965
2966 // Scale the cost by the probability of executing the predicated blocks.
2967 // This assumes the predicated block for each vector lane is equally
2968 // likely.
2969 ScalarizationCost =
2970 ScalarizationCost / getPredBlockCostDivisor(CostKind, I->getParent());
2971 }
2972
2973 InstructionCost SafeDivisorCost = 0;
2974 auto *VecTy = toVectorTy(I->getType(), VF);
2975 // The cost of the select guard to ensure all lanes are well defined
2976 // after we speculate above any internal control flow.
2977 SafeDivisorCost +=
2978 TTI.getCmpSelInstrCost(Instruction::Select, VecTy,
2979 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
2981
2982 SmallVector<const Value *, 4> Operands(I->operand_values());
2983 SafeDivisorCost += TTI.getArithmeticInstrCost(
2984 I->getOpcode(), VecTy, CostKind,
2985 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
2986 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
2987 Operands, I);
2988 return {ScalarizationCost, SafeDivisorCost};
2989}
2990
2992 Instruction *I, ElementCount VF) const {
2993 assert(isAccessInterleaved(I) && "Expecting interleaved access.");
2995 "Decision should not be set yet.");
2996 auto *Group = getInterleavedAccessGroup(I);
2997 assert(Group && "Must have a group.");
2998 unsigned InterleaveFactor = Group->getFactor();
2999
3000 // If the instruction's allocated size doesn't equal its type size, it
3001 // requires padding and will be scalarized.
3002 auto &DL = I->getDataLayout();
3003 auto *ScalarTy = getLoadStoreType(I);
3004 if (hasIrregularType(ScalarTy, DL))
3005 return false;
3006
3007 // For scalable vectors, the interleave factors must be <= 8 since we require
3008 // the (de)interleaveN intrinsics instead of shufflevectors.
3009 if (VF.isScalable() && InterleaveFactor > 8)
3010 return false;
3011
3012 // If the group involves a non-integral pointer, we may not be able to
3013 // losslessly cast all values to a common type.
3014 bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
3015 for (unsigned Idx = 0; Idx < InterleaveFactor; Idx++) {
3016 Instruction *Member = Group->getMember(Idx);
3017 if (!Member)
3018 continue;
3019 auto *MemberTy = getLoadStoreType(Member);
3020 bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
3021 // Don't coerce non-integral pointers to integers or vice versa.
3022 if (MemberNI != ScalarNI)
3023 // TODO: Consider adding special nullptr value case here
3024 return false;
3025 if (MemberNI && ScalarNI &&
3026 ScalarTy->getPointerAddressSpace() !=
3027 MemberTy->getPointerAddressSpace())
3028 return false;
3029 }
3030
3031 // Check if masking is required.
3032 // A Group may need masking for one of two reasons: it resides in a block that
3033 // needs predication, or it was decided to use masking to deal with gaps
3034 // (either a gap at the end of a load-access that may result in a speculative
3035 // load, or any gaps in a store-access).
3036 bool PredicatedAccessRequiresMasking =
3037 blockNeedsPredicationForAnyReason(I->getParent()) &&
3038 Legal->isMaskRequired(I);
3039 bool LoadAccessWithGapsRequiresEpilogMasking =
3040 isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
3042 bool StoreAccessWithGapsRequiresMasking =
3043 isa<StoreInst>(I) && !Group->isFull();
3044 if (!PredicatedAccessRequiresMasking &&
3045 !LoadAccessWithGapsRequiresEpilogMasking &&
3046 !StoreAccessWithGapsRequiresMasking)
3047 return true;
3048
3049 // If masked interleaving is required, we expect that the user/target had
3050 // enabled it, because otherwise it either wouldn't have been created or
3051 // it should have been invalidated by the CostModel.
3053 "Masked interleave-groups for predicated accesses are not enabled.");
3054
3055 if (Group->isReverse())
3056 return false;
3057
3058 // TODO: Support interleaved access that requires a gap mask for scalable VFs.
3059 bool NeedsMaskForGaps = LoadAccessWithGapsRequiresEpilogMasking ||
3060 StoreAccessWithGapsRequiresMasking;
3061 if (VF.isScalable() && NeedsMaskForGaps)
3062 return false;
3063
3064 auto *Ty = getLoadStoreType(I);
3065 const Align Alignment = getLoadStoreAlignment(I);
3066 unsigned AS = getLoadStoreAddressSpace(I);
3067 return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment, AS)
3068 : TTI.isLegalMaskedStore(Ty, Alignment, AS);
3069}
3070
3072 Instruction *I, ElementCount VF) {
3073 // Get and ensure we have a valid memory instruction.
3074 assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
3075
3076 auto *Ptr = getLoadStorePointerOperand(I);
3077 auto *ScalarTy = getLoadStoreType(I);
3078
3079 // In order to be widened, the pointer should be consecutive, first of all.
3080 if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
3081 return false;
3082
3083 // If the instruction is a store located in a predicated block, it will be
3084 // scalarized.
3085 if (isScalarWithPredication(I, VF))
3086 return false;
3087
3088 // If the instruction's allocated size doesn't equal it's type size, it
3089 // requires padding and will be scalarized.
3090 auto &DL = I->getDataLayout();
3091 if (hasIrregularType(ScalarTy, DL))
3092 return false;
3093
3094 return true;
3095}
3096
3097void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
3098 // We should not collect Uniforms more than once per VF. Right now,
3099 // this function is called from collectUniformsAndScalars(), which
3100 // already does this check. Collecting Uniforms for VF=1 does not make any
3101 // sense.
3102
3103 assert(VF.isVector() && !Uniforms.contains(VF) &&
3104 "This function should not be visited twice for the same VF");
3105
3106 // Visit the list of Uniforms. If we find no uniform value, we won't
3107 // analyze again. Uniforms.count(VF) will return 1.
3108 Uniforms[VF].clear();
3109
3110 // Now we know that the loop is vectorizable!
3111 // Collect instructions inside the loop that will remain uniform after
3112 // vectorization.
3113
3114 // Global values, params and instructions outside of current loop are out of
3115 // scope.
3116 auto IsOutOfScope = [&](Value *V) -> bool {
3118 return (!I || !TheLoop->contains(I));
3119 };
3120
3121 // Worklist containing uniform instructions demanding lane 0.
3122 SetVector<Instruction *> Worklist;
3123
3124 // Add uniform instructions demanding lane 0 to the worklist. Instructions
3125 // that require predication must not be considered uniform after
3126 // vectorization, because that would create an erroneous replicating region
3127 // where only a single instance out of VF should be formed.
3128 auto AddToWorklistIfAllowed = [&](Instruction *I) -> void {
3129 if (IsOutOfScope(I)) {
3130 LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
3131 << *I << "\n");
3132 return;
3133 }
3134 if (isPredicatedInst(I)) {
3135 LLVM_DEBUG(
3136 dbgs() << "LV: Found not uniform due to requiring predication: " << *I
3137 << "\n");
3138 return;
3139 }
3140 LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
3141 Worklist.insert(I);
3142 };
3143
3144 // Start with the conditional branches exiting the loop. If the branch
3145 // condition is an instruction contained in the loop that is only used by the
3146 // branch, it is uniform. Note conditions from uncountable early exits are not
3147 // uniform.
3149 TheLoop->getExitingBlocks(Exiting);
3150 for (BasicBlock *E : Exiting) {
3151 if (Legal->hasUncountableEarlyExit() && TheLoop->getLoopLatch() != E)
3152 continue;
3153 auto *Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
3154 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
3155 AddToWorklistIfAllowed(Cmp);
3156 }
3157
3158 auto PrevVF = VF.divideCoefficientBy(2);
3159 // Return true if all lanes perform the same memory operation, and we can
3160 // thus choose to execute only one.
3161 auto IsUniformMemOpUse = [&](Instruction *I) {
3162 // If the value was already known to not be uniform for the previous
3163 // (smaller VF), it cannot be uniform for the larger VF.
3164 if (PrevVF.isVector()) {
3165 auto Iter = Uniforms.find(PrevVF);
3166 if (Iter != Uniforms.end() && !Iter->second.contains(I))
3167 return false;
3168 }
3169 if (!Legal->isUniformMemOp(*I, VF))
3170 return false;
3171 if (isa<LoadInst>(I))
3172 // Loading the same address always produces the same result - at least
3173 // assuming aliasing and ordering which have already been checked.
3174 return true;
3175 // Storing the same value on every iteration.
3176 return TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand());
3177 };
3178
3179 auto IsUniformDecision = [&](Instruction *I, ElementCount VF) {
3180 InstWidening WideningDecision = getWideningDecision(I, VF);
3181 assert(WideningDecision != CM_Unknown &&
3182 "Widening decision should be ready at this moment");
3183
3184 if (IsUniformMemOpUse(I))
3185 return true;
3186
3187 return (WideningDecision == CM_Widen ||
3188 WideningDecision == CM_Widen_Reverse ||
3189 WideningDecision == CM_Interleave);
3190 };
3191
3192 // Returns true if Ptr is the pointer operand of a memory access instruction
3193 // I, I is known to not require scalarization, and the pointer is not also
3194 // stored.
3195 auto IsVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
3196 if (isa<StoreInst>(I) && I->getOperand(0) == Ptr)
3197 return false;
3198 return getLoadStorePointerOperand(I) == Ptr &&
3199 (IsUniformDecision(I, VF) || Legal->isInvariant(Ptr));
3200 };
3201
3202 // Holds a list of values which are known to have at least one uniform use.
3203 // Note that there may be other uses which aren't uniform. A "uniform use"
3204 // here is something which only demands lane 0 of the unrolled iterations;
3205 // it does not imply that all lanes produce the same value (e.g. this is not
3206 // the usual meaning of uniform)
3207 SetVector<Value *> HasUniformUse;
3208
3209 // Scan the loop for instructions which are either a) known to have only
3210 // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
3211 for (auto *BB : TheLoop->blocks())
3212 for (auto &I : *BB) {
3213 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
3214 switch (II->getIntrinsicID()) {
3215 case Intrinsic::sideeffect:
3216 case Intrinsic::experimental_noalias_scope_decl:
3217 case Intrinsic::assume:
3218 case Intrinsic::lifetime_start:
3219 case Intrinsic::lifetime_end:
3220 if (TheLoop->hasLoopInvariantOperands(&I))
3221 AddToWorklistIfAllowed(&I);
3222 break;
3223 default:
3224 break;
3225 }
3226 }
3227
3228 if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
3229 if (IsOutOfScope(EVI->getAggregateOperand())) {
3230 AddToWorklistIfAllowed(EVI);
3231 continue;
3232 }
3233 // Only ExtractValue instructions where the aggregate value comes from a
3234 // call are allowed to be non-uniform.
3235 assert(isa<CallInst>(EVI->getAggregateOperand()) &&
3236 "Expected aggregate value to be call return value");
3237 }
3238
3239 // If there's no pointer operand, there's nothing to do.
3240 auto *Ptr = getLoadStorePointerOperand(&I);
3241 if (!Ptr)
3242 continue;
3243
3244 // If the pointer can be proven to be uniform, always add it to the
3245 // worklist.
3246 if (isa<Instruction>(Ptr) && Legal->isUniform(Ptr, VF))
3247 AddToWorklistIfAllowed(cast<Instruction>(Ptr));
3248
3249 if (IsUniformMemOpUse(&I))
3250 AddToWorklistIfAllowed(&I);
3251
3252 if (IsVectorizedMemAccessUse(&I, Ptr))
3253 HasUniformUse.insert(Ptr);
3254 }
3255
3256 // Add to the worklist any operands which have *only* uniform (e.g. lane 0
3257 // demanding) users. Since loops are assumed to be in LCSSA form, this
3258 // disallows uses outside the loop as well.
3259 for (auto *V : HasUniformUse) {
3260 if (IsOutOfScope(V))
3261 continue;
3262 auto *I = cast<Instruction>(V);
3263 bool UsersAreMemAccesses = all_of(I->users(), [&](User *U) -> bool {
3264 auto *UI = cast<Instruction>(U);
3265 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
3266 });
3267 if (UsersAreMemAccesses)
3268 AddToWorklistIfAllowed(I);
3269 }
3270
3271 // Expand Worklist in topological order: whenever a new instruction
3272 // is added , its users should be already inside Worklist. It ensures
3273 // a uniform instruction will only be used by uniform instructions.
3274 unsigned Idx = 0;
3275 while (Idx != Worklist.size()) {
3276 Instruction *I = Worklist[Idx++];
3277
3278 for (auto *OV : I->operand_values()) {
3279 // isOutOfScope operands cannot be uniform instructions.
3280 if (IsOutOfScope(OV))
3281 continue;
3282 // First order recurrence Phi's should typically be considered
3283 // non-uniform.
3284 auto *OP = dyn_cast<PHINode>(OV);
3285 if (OP && Legal->isFixedOrderRecurrence(OP))
3286 continue;
3287 // If all the users of the operand are uniform, then add the
3288 // operand into the uniform worklist.
3289 auto *OI = cast<Instruction>(OV);
3290 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
3291 auto *J = cast<Instruction>(U);
3292 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
3293 }))
3294 AddToWorklistIfAllowed(OI);
3295 }
3296 }
3297
3298 // For an instruction to be added into Worklist above, all its users inside
3299 // the loop should also be in Worklist. However, this condition cannot be
3300 // true for phi nodes that form a cyclic dependence. We must process phi
3301 // nodes separately. An induction variable will remain uniform if all users
3302 // of the induction variable and induction variable update remain uniform.
3303 // The code below handles both pointer and non-pointer induction variables.
3304 BasicBlock *Latch = TheLoop->getLoopLatch();
3305 for (const auto &Induction : Legal->getInductionVars()) {
3306 auto *Ind = Induction.first;
3307 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
3308
3309 // Determine if all users of the induction variable are uniform after
3310 // vectorization.
3311 bool UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
3312 auto *I = cast<Instruction>(U);
3313 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
3314 IsVectorizedMemAccessUse(I, Ind);
3315 });
3316 if (!UniformInd)
3317 continue;
3318
3319 // Determine if all users of the induction variable update instruction are
3320 // uniform after vectorization.
3321 bool UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
3322 auto *I = cast<Instruction>(U);
3323 return I == Ind || Worklist.count(I) ||
3324 IsVectorizedMemAccessUse(I, IndUpdate);
3325 });
3326 if (!UniformIndUpdate)
3327 continue;
3328
3329 // The induction variable and its update instruction will remain uniform.
3330 AddToWorklistIfAllowed(Ind);
3331 AddToWorklistIfAllowed(IndUpdate);
3332 }
3333
3334 Uniforms[VF].insert_range(Worklist);
3335}
3336
3338 LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
3339
3340 if (Legal->getRuntimePointerChecking()->Need) {
3341 reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
3342 "runtime pointer checks needed. Enable vectorization of this "
3343 "loop with '#pragma clang loop vectorize(enable)' when "
3344 "compiling with -Os/-Oz",
3345 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3346 return true;
3347 }
3348
3349 if (!PSE.getPredicate().isAlwaysTrue()) {
3350 reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
3351 "runtime SCEV checks needed. Enable vectorization of this "
3352 "loop with '#pragma clang loop vectorize(enable)' when "
3353 "compiling with -Os/-Oz",
3354 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3355 return true;
3356 }
3357
3358 // FIXME: Avoid specializing for stride==1 instead of bailing out.
3359 if (!Legal->getLAI()->getSymbolicStrides().empty()) {
3360 reportVectorizationFailure("Runtime stride check for small trip count",
3361 "runtime stride == 1 checks needed. Enable vectorization of "
3362 "this loop without such check by compiling with -Os/-Oz",
3363 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3364 return true;
3365 }
3366
3367 return false;
3368}
3369
3370bool LoopVectorizationCostModel::isScalableVectorizationAllowed() {
3371 if (IsScalableVectorizationAllowed)
3372 return *IsScalableVectorizationAllowed;
3373
3374 IsScalableVectorizationAllowed = false;
3375 if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
3376 return false;
3377
3378 if (Hints->isScalableVectorizationDisabled()) {
3379 reportVectorizationInfo("Scalable vectorization is explicitly disabled",
3380 "ScalableVectorizationDisabled", ORE, TheLoop);
3381 return false;
3382 }
3383
3384 LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
3385
3386 auto MaxScalableVF = ElementCount::getScalable(
3387 std::numeric_limits<ElementCount::ScalarTy>::max());
3388
3389 // Test that the loop-vectorizer can legalize all operations for this MaxVF.
3390 // FIXME: While for scalable vectors this is currently sufficient, this should
3391 // be replaced by a more detailed mechanism that filters out specific VFs,
3392 // instead of invalidating vectorization for a whole set of VFs based on the
3393 // MaxVF.
3394
3395 // Disable scalable vectorization if the loop contains unsupported reductions.
3396 if (!canVectorizeReductions(MaxScalableVF)) {
3398 "Scalable vectorization not supported for the reduction "
3399 "operations found in this loop.",
3400 "ScalableVFUnfeasible", ORE, TheLoop);
3401 return false;
3402 }
3403
3404 // Disable scalable vectorization if the loop contains any instructions
3405 // with element types not supported for scalable vectors.
3406 if (any_of(ElementTypesInLoop, [&](Type *Ty) {
3407 return !Ty->isVoidTy() &&
3409 })) {
3410 reportVectorizationInfo("Scalable vectorization is not supported "
3411 "for all element types found in this loop.",
3412 "ScalableVFUnfeasible", ORE, TheLoop);
3413 return false;
3414 }
3415
3416 if (!Legal->isSafeForAnyVectorWidth() && !getMaxVScale(*TheFunction, TTI)) {
3417 reportVectorizationInfo("The target does not provide maximum vscale value "
3418 "for safe distance analysis.",
3419 "ScalableVFUnfeasible", ORE, TheLoop);
3420 return false;
3421 }
3422
3423 IsScalableVectorizationAllowed = true;
3424 return true;
3425}
3426
3427ElementCount
3428LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
3429 if (!isScalableVectorizationAllowed())
3430 return ElementCount::getScalable(0);
3431
3432 auto MaxScalableVF = ElementCount::getScalable(
3433 std::numeric_limits<ElementCount::ScalarTy>::max());
3434 if (Legal->isSafeForAnyVectorWidth())
3435 return MaxScalableVF;
3436
3437 std::optional<unsigned> MaxVScale = getMaxVScale(*TheFunction, TTI);
3438 // Limit MaxScalableVF by the maximum safe dependence distance.
3439 MaxScalableVF = ElementCount::getScalable(MaxSafeElements / *MaxVScale);
3440
3441 if (!MaxScalableVF)
3443 "Max legal vector width too small, scalable vectorization "
3444 "unfeasible.",
3445 "ScalableVFUnfeasible", ORE, TheLoop);
3446
3447 return MaxScalableVF;
3448}
3449
3450FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
3451 unsigned MaxTripCount, ElementCount UserVF, bool FoldTailByMasking) {
3452 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
3453 unsigned SmallestType, WidestType;
3454 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
3455
3456 // Get the maximum safe dependence distance in bits computed by LAA.
3457 // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
3458 // the memory accesses that is most restrictive (involved in the smallest
3459 // dependence distance).
3460 unsigned MaxSafeElementsPowerOf2 =
3461 bit_floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
3462 if (!Legal->isSafeForAnyStoreLoadForwardDistances()) {
3463 unsigned SLDist = Legal->getMaxStoreLoadForwardSafeDistanceInBits();
3464 MaxSafeElementsPowerOf2 =
3465 std::min(MaxSafeElementsPowerOf2, SLDist / WidestType);
3466 }
3467 auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElementsPowerOf2);
3468 auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElementsPowerOf2);
3469
3470 if (!Legal->isSafeForAnyVectorWidth())
3471 this->MaxSafeElements = MaxSafeElementsPowerOf2;
3472
3473 LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
3474 << ".\n");
3475 LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
3476 << ".\n");
3477
3478 // First analyze the UserVF, fall back if the UserVF should be ignored.
3479 if (UserVF) {
3480 auto MaxSafeUserVF =
3481 UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
3482
3483 if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
3484 // If `VF=vscale x N` is safe, then so is `VF=N`
3485 if (UserVF.isScalable())
3486 return FixedScalableVFPair(
3487 ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
3488
3489 return UserVF;
3490 }
3491
3492 assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
3493
3494 // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
3495 // is better to ignore the hint and let the compiler choose a suitable VF.
3496 if (!UserVF.isScalable()) {
3497 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3498 << " is unsafe, clamping to max safe VF="
3499 << MaxSafeFixedVF << ".\n");
3500 ORE->emit([&]() {
3501 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3502 TheLoop->getStartLoc(),
3503 TheLoop->getHeader())
3504 << "User-specified vectorization factor "
3505 << ore::NV("UserVectorizationFactor", UserVF)
3506 << " is unsafe, clamping to maximum safe vectorization factor "
3507 << ore::NV("VectorizationFactor", MaxSafeFixedVF);
3508 });
3509 return MaxSafeFixedVF;
3510 }
3511
3513 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3514 << " is ignored because scalable vectors are not "
3515 "available.\n");
3516 ORE->emit([&]() {
3517 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3518 TheLoop->getStartLoc(),
3519 TheLoop->getHeader())
3520 << "User-specified vectorization factor "
3521 << ore::NV("UserVectorizationFactor", UserVF)
3522 << " is ignored because the target does not support scalable "
3523 "vectors. The compiler will pick a more suitable value.";
3524 });
3525 } else {
3526 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3527 << " is unsafe. Ignoring scalable UserVF.\n");
3528 ORE->emit([&]() {
3529 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3530 TheLoop->getStartLoc(),
3531 TheLoop->getHeader())
3532 << "User-specified vectorization factor "
3533 << ore::NV("UserVectorizationFactor", UserVF)
3534 << " is unsafe. Ignoring the hint to let the compiler pick a "
3535 "more suitable value.";
3536 });
3537 }
3538 }
3539
3540 LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
3541 << " / " << WidestType << " bits.\n");
3542
3543 FixedScalableVFPair Result(ElementCount::getFixed(1),
3545 if (auto MaxVF =
3546 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3547 MaxSafeFixedVF, FoldTailByMasking))
3548 Result.FixedVF = MaxVF;
3549
3550 if (auto MaxVF =
3551 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3552 MaxSafeScalableVF, FoldTailByMasking))
3553 if (MaxVF.isScalable()) {
3554 Result.ScalableVF = MaxVF;
3555 LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
3556 << "\n");
3557 }
3558
3559 return Result;
3560}
3561
3562FixedScalableVFPair
3564 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
3565 // TODO: It may be useful to do since it's still likely to be dynamically
3566 // uniform if the target can skip.
3568 "Not inserting runtime ptr check for divergent target",
3569 "runtime pointer checks needed. Not enabled for divergent target",
3570 "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
3572 }
3573
3574 ScalarEvolution *SE = PSE.getSE();
3576 unsigned MaxTC = PSE.getSmallConstantMaxTripCount();
3577 LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
3578 if (TC != ElementCount::getFixed(MaxTC))
3579 LLVM_DEBUG(dbgs() << "LV: Found maximum trip count: " << MaxTC << '\n');
3580 if (TC.isScalar()) {
3581 reportVectorizationFailure("Single iteration (non) loop",
3582 "loop trip count is one, irrelevant for vectorization",
3583 "SingleIterationLoop", ORE, TheLoop);
3585 }
3586
3587 // If BTC matches the widest induction type and is -1 then the trip count
3588 // computation will wrap to 0 and the vector trip count will be 0. Do not try
3589 // to vectorize.
3590 const SCEV *BTC = SE->getBackedgeTakenCount(TheLoop);
3591 if (!isa<SCEVCouldNotCompute>(BTC) &&
3592 BTC->getType()->getScalarSizeInBits() >=
3593 Legal->getWidestInductionType()->getScalarSizeInBits() &&
3595 SE->getMinusOne(BTC->getType()))) {
3597 "Trip count computation wrapped",
3598 "backedge-taken count is -1, loop trip count wrapped to 0",
3599 "TripCountWrapped", ORE, TheLoop);
3601 }
3602
3603 switch (ScalarEpilogueStatus) {
3605 return computeFeasibleMaxVF(MaxTC, UserVF, false);
3607 [[fallthrough]];
3609 LLVM_DEBUG(
3610 dbgs() << "LV: vector predicate hint/switch found.\n"
3611 << "LV: Not allowing scalar epilogue, creating predicated "
3612 << "vector loop.\n");
3613 break;
3615 // fallthrough as a special case of OptForSize
3617 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
3618 LLVM_DEBUG(
3619 dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
3620 else
3621 LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
3622 << "count.\n");
3623
3624 // Bail if runtime checks are required, which are not good when optimising
3625 // for size.
3628
3629 break;
3630 }
3631
3632 // Now try the tail folding
3633
3634 // Invalidate interleave groups that require an epilogue if we can't mask
3635 // the interleave-group.
3637 assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
3638 "No decisions should have been taken at this point");
3639 // Note: There is no need to invalidate any cost modeling decisions here, as
3640 // none were taken so far.
3641 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
3642 }
3643
3644 FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(MaxTC, UserVF, true);
3645
3646 // Avoid tail folding if the trip count is known to be a multiple of any VF
3647 // we choose.
3648 std::optional<unsigned> MaxPowerOf2RuntimeVF =
3649 MaxFactors.FixedVF.getFixedValue();
3650 if (MaxFactors.ScalableVF) {
3651 std::optional<unsigned> MaxVScale = getMaxVScale(*TheFunction, TTI);
3652 if (MaxVScale && TTI.isVScaleKnownToBeAPowerOfTwo()) {
3653 MaxPowerOf2RuntimeVF = std::max<unsigned>(
3654 *MaxPowerOf2RuntimeVF,
3655 *MaxVScale * MaxFactors.ScalableVF.getKnownMinValue());
3656 } else
3657 MaxPowerOf2RuntimeVF = std::nullopt; // Stick with tail-folding for now.
3658 }
3659
3660 auto NoScalarEpilogueNeeded = [this, &UserIC](unsigned MaxVF) {
3661 // Return false if the loop is neither a single-latch-exit loop nor an
3662 // early-exit loop as tail-folding is not supported in that case.
3663 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
3664 !Legal->hasUncountableEarlyExit())
3665 return false;
3666 unsigned MaxVFtimesIC = UserIC ? MaxVF * UserIC : MaxVF;
3667 ScalarEvolution *SE = PSE.getSE();
3668 // Calling getSymbolicMaxBackedgeTakenCount enables support for loops
3669 // with uncountable exits. For countable loops, the symbolic maximum must
3670 // remain identical to the known back-edge taken count.
3671 const SCEV *BackedgeTakenCount = PSE.getSymbolicMaxBackedgeTakenCount();
3672 assert((Legal->hasUncountableEarlyExit() ||
3673 BackedgeTakenCount == PSE.getBackedgeTakenCount()) &&
3674 "Invalid loop count");
3675 const SCEV *ExitCount = SE->getAddExpr(
3676 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3677 const SCEV *Rem = SE->getURemExpr(
3678 SE->applyLoopGuards(ExitCount, TheLoop),
3679 SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
3680 return Rem->isZero();
3681 };
3682
3683 if (MaxPowerOf2RuntimeVF > 0u) {
3684 assert((UserVF.isNonZero() || isPowerOf2_32(*MaxPowerOf2RuntimeVF)) &&
3685 "MaxFixedVF must be a power of 2");
3686 if (NoScalarEpilogueNeeded(*MaxPowerOf2RuntimeVF)) {
3687 // Accept MaxFixedVF if we do not have a tail.
3688 LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
3689 return MaxFactors;
3690 }
3691 }
3692
3693 auto ExpectedTC = getSmallBestKnownTC(PSE, TheLoop);
3694 if (ExpectedTC && ExpectedTC->isFixed() &&
3695 ExpectedTC->getFixedValue() <=
3696 TTI.getMinTripCountTailFoldingThreshold()) {
3697 if (MaxPowerOf2RuntimeVF > 0u) {
3698 // If we have a low-trip-count, and the fixed-width VF is known to divide
3699 // the trip count but the scalable factor does not, use the fixed-width
3700 // factor in preference to allow the generation of a non-predicated loop.
3701 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedLowTripLoop &&
3702 NoScalarEpilogueNeeded(MaxFactors.FixedVF.getFixedValue())) {
3703 LLVM_DEBUG(dbgs() << "LV: Picking a fixed-width so that no tail will "
3704 "remain for any chosen VF.\n");
3705 MaxFactors.ScalableVF = ElementCount::getScalable(0);
3706 return MaxFactors;
3707 }
3708 }
3709
3711 "The trip count is below the minial threshold value.",
3712 "loop trip count is too low, avoiding vectorization", "LowTripCount",
3713 ORE, TheLoop);
3715 }
3716
3717 // If we don't know the precise trip count, or if the trip count that we
3718 // found modulo the vectorization factor is not zero, try to fold the tail
3719 // by masking.
3720 // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
3721 bool ContainsScalableVF = MaxFactors.ScalableVF.isNonZero();
3722 setTailFoldingStyles(ContainsScalableVF, UserIC);
3723 if (foldTailByMasking()) {
3724 if (foldTailWithEVL()) {
3725 LLVM_DEBUG(
3726 dbgs()
3727 << "LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
3728 "try to generate VP Intrinsics with scalable vector "
3729 "factors only.\n");
3730 // Tail folded loop using VP intrinsics restricts the VF to be scalable
3731 // for now.
3732 // TODO: extend it for fixed vectors, if required.
3733 assert(ContainsScalableVF && "Expected scalable vector factor.");
3734
3735 MaxFactors.FixedVF = ElementCount::getFixed(1);
3736 }
3737 return MaxFactors;
3738 }
3739
3740 // If there was a tail-folding hint/switch, but we can't fold the tail by
3741 // masking, fallback to a vectorization with a scalar epilogue.
3742 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
3743 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
3744 "scalar epilogue instead.\n");
3745 ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
3746 return MaxFactors;
3747 }
3748
3749 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
3750 LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
3752 }
3753
3754 if (TC.isZero()) {
3756 "unable to calculate the loop count due to complex control flow",
3757 "UnknownLoopCountComplexCFG", ORE, TheLoop);
3759 }
3760
3762 "Cannot optimize for size and vectorize at the same time.",
3763 "cannot optimize for size and vectorize at the same time. "
3764 "Enable vectorization of this loop with '#pragma clang loop "
3765 "vectorize(enable)' when compiling with -Os/-Oz",
3766 "NoTailLoopWithOptForSize", ORE, TheLoop);
3768}
3769
3771 ElementCount VF) {
3772 if (ConsiderRegPressure.getNumOccurrences())
3773 return ConsiderRegPressure;
3774
3775 // TODO: We should eventually consider register pressure for all targets. The
3776 // TTI hook is temporary whilst target-specific issues are being fixed.
3777 if (TTI.shouldConsiderVectorizationRegPressure())
3778 return true;
3779
3780 if (!useMaxBandwidth(VF.isScalable()
3783 return false;
3784 // Only calculate register pressure for VFs enabled by MaxBandwidth.
3786 VF, VF.isScalable() ? MaxPermissibleVFWithoutMaxBW.ScalableVF
3788}
3789
3792 return MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
3793 (TTI.shouldMaximizeVectorBandwidth(RegKind) ||
3795 Legal->hasVectorCallVariants())));
3796}
3797
3798ElementCount LoopVectorizationCostModel::clampVFByMaxTripCount(
3799 ElementCount VF, unsigned MaxTripCount, bool FoldTailByMasking) const {
3800 unsigned EstimatedVF = VF.getKnownMinValue();
3801 if (VF.isScalable() && TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
3802 auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
3803 auto Min = Attr.getVScaleRangeMin();
3804 EstimatedVF *= Min;
3805 }
3806
3807 // When a scalar epilogue is required, at least one iteration of the scalar
3808 // loop has to execute. Adjust MaxTripCount accordingly to avoid picking a
3809 // max VF that results in a dead vector loop.
3810 if (MaxTripCount > 0 && requiresScalarEpilogue(true))
3811 MaxTripCount -= 1;
3812
3813 if (MaxTripCount && MaxTripCount <= EstimatedVF &&
3814 (!FoldTailByMasking || isPowerOf2_32(MaxTripCount))) {
3815 // If upper bound loop trip count (TC) is known at compile time there is no
3816 // point in choosing VF greater than TC (as done in the loop below). Select
3817 // maximum power of two which doesn't exceed TC. If VF is
3818 // scalable, we only fall back on a fixed VF when the TC is less than or
3819 // equal to the known number of lanes.
3820 auto ClampedUpperTripCount = llvm::bit_floor(MaxTripCount);
3821 LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
3822 "exceeding the constant trip count: "
3823 << ClampedUpperTripCount << "\n");
3824 return ElementCount::get(ClampedUpperTripCount,
3825 FoldTailByMasking ? VF.isScalable() : false);
3826 }
3827 return VF;
3828}
3829
3830ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
3831 unsigned MaxTripCount, unsigned SmallestType, unsigned WidestType,
3832 ElementCount MaxSafeVF, bool FoldTailByMasking) {
3833 bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
3834 const TypeSize WidestRegister = TTI.getRegisterBitWidth(
3835 ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
3837
3838 // Convenience function to return the minimum of two ElementCounts.
3839 auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
3840 assert((LHS.isScalable() == RHS.isScalable()) &&
3841 "Scalable flags must match");
3842 return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
3843 };
3844
3845 // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
3846 // Note that both WidestRegister and WidestType may not be a powers of 2.
3847 auto MaxVectorElementCount = ElementCount::get(
3848 llvm::bit_floor(WidestRegister.getKnownMinValue() / WidestType),
3849 ComputeScalableMaxVF);
3850 MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
3851 LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
3852 << (MaxVectorElementCount * WidestType) << " bits.\n");
3853
3854 if (!MaxVectorElementCount) {
3855 LLVM_DEBUG(dbgs() << "LV: The target has no "
3856 << (ComputeScalableMaxVF ? "scalable" : "fixed")
3857 << " vector registers.\n");
3858 return ElementCount::getFixed(1);
3859 }
3860
3861 ElementCount MaxVF = clampVFByMaxTripCount(MaxVectorElementCount,
3862 MaxTripCount, FoldTailByMasking);
3863 // If the MaxVF was already clamped, there's no point in trying to pick a
3864 // larger one.
3865 if (MaxVF != MaxVectorElementCount)
3866 return MaxVF;
3867
3869 ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
3871
3872 if (MaxVF.isScalable())
3873 MaxPermissibleVFWithoutMaxBW.ScalableVF = MaxVF;
3874 else
3875 MaxPermissibleVFWithoutMaxBW.FixedVF = MaxVF;
3876
3877 if (useMaxBandwidth(RegKind)) {
3878 auto MaxVectorElementCountMaxBW = ElementCount::get(
3879 llvm::bit_floor(WidestRegister.getKnownMinValue() / SmallestType),
3880 ComputeScalableMaxVF);
3881 MaxVF = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
3882
3883 if (ElementCount MinVF =
3884 TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
3885 if (ElementCount::isKnownLT(MaxVF, MinVF)) {
3886 LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
3887 << ") with target's minimum: " << MinVF << '\n');
3888 MaxVF = MinVF;
3889 }
3890 }
3891
3892 MaxVF = clampVFByMaxTripCount(MaxVF, MaxTripCount, FoldTailByMasking);
3893
3894 if (MaxVectorElementCount != MaxVF) {
3895 // Invalidate any widening decisions we might have made, in case the loop
3896 // requires prediction (decided later), but we have already made some
3897 // load/store widening decisions.
3898 invalidateCostModelingDecisions();
3899 }
3900 }
3901 return MaxVF;
3902}
3903
3904bool LoopVectorizationPlanner::isMoreProfitable(const VectorizationFactor &A,
3905 const VectorizationFactor &B,
3906 const unsigned MaxTripCount,
3907 bool HasTail,
3908 bool IsEpilogue) const {
3909 InstructionCost CostA = A.Cost;
3910 InstructionCost CostB = B.Cost;
3911
3912 // Improve estimate for the vector width if it is scalable.
3913 unsigned EstimatedWidthA = A.Width.getKnownMinValue();
3914 unsigned EstimatedWidthB = B.Width.getKnownMinValue();
3915 if (std::optional<unsigned> VScale = CM.getVScaleForTuning()) {
3916 if (A.Width.isScalable())
3917 EstimatedWidthA *= *VScale;
3918 if (B.Width.isScalable())
3919 EstimatedWidthB *= *VScale;
3920 }
3921
3922 // When optimizing for size choose whichever is smallest, which will be the
3923 // one with the smallest cost for the whole loop. On a tie pick the larger
3924 // vector width, on the assumption that throughput will be greater.
3925 if (CM.CostKind == TTI::TCK_CodeSize)
3926 return CostA < CostB ||
3927 (CostA == CostB && EstimatedWidthA > EstimatedWidthB);
3928
3929 // Assume vscale may be larger than 1 (or the value being tuned for),
3930 // so that scalable vectorization is slightly favorable over fixed-width
3931 // vectorization.
3932 bool PreferScalable = !TTI.preferFixedOverScalableIfEqualCost(IsEpilogue) &&
3933 A.Width.isScalable() && !B.Width.isScalable();
3934
3935 auto CmpFn = [PreferScalable](const InstructionCost &LHS,
3936 const InstructionCost &RHS) {
3937 return PreferScalable ? LHS <= RHS : LHS < RHS;
3938 };
3939
3940 // To avoid the need for FP division:
3941 // (CostA / EstimatedWidthA) < (CostB / EstimatedWidthB)
3942 // <=> (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA)
3943 if (!MaxTripCount)
3944 return CmpFn(CostA * EstimatedWidthB, CostB * EstimatedWidthA);
3945
3946 auto GetCostForTC = [MaxTripCount, HasTail](unsigned VF,
3947 InstructionCost VectorCost,
3948 InstructionCost ScalarCost) {
3949 // If the trip count is a known (possibly small) constant, the trip count
3950 // will be rounded up to an integer number of iterations under
3951 // FoldTailByMasking. The total cost in that case will be
3952 // VecCost*ceil(TripCount/VF). When not folding the tail, the total
3953 // cost will be VecCost*floor(TC/VF) + ScalarCost*(TC%VF). There will be
3954 // some extra overheads, but for the purpose of comparing the costs of
3955 // different VFs we can use this to compare the total loop-body cost
3956 // expected after vectorization.
3957 if (HasTail)
3958 return VectorCost * (MaxTripCount / VF) +
3959 ScalarCost * (MaxTripCount % VF);
3960 return VectorCost * divideCeil(MaxTripCount, VF);
3961 };
3962
3963 auto RTCostA = GetCostForTC(EstimatedWidthA, CostA, A.ScalarCost);
3964 auto RTCostB = GetCostForTC(EstimatedWidthB, CostB, B.ScalarCost);
3965 return CmpFn(RTCostA, RTCostB);
3966}
3967
3968bool LoopVectorizationPlanner::isMoreProfitable(const VectorizationFactor &A,
3969 const VectorizationFactor &B,
3970 bool HasTail,
3971 bool IsEpilogue) const {
3972 const unsigned MaxTripCount = PSE.getSmallConstantMaxTripCount();
3973 return LoopVectorizationPlanner::isMoreProfitable(A, B, MaxTripCount, HasTail,
3974 IsEpilogue);
3975}
3976
3979 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
3980 SmallVector<RecipeVFPair> InvalidCosts;
3981 for (const auto &Plan : VPlans) {
3982 for (ElementCount VF : Plan->vectorFactors()) {
3983 // The VPlan-based cost model is designed for computing vector cost.
3984 // Querying VPlan-based cost model with a scarlar VF will cause some
3985 // errors because we expect the VF is vector for most of the widen
3986 // recipes.
3987 if (VF.isScalar())
3988 continue;
3989
3990 VPCostContext CostCtx(CM.TTI, *CM.TLI, *Plan, CM, CM.CostKind, CM.PSE,
3991 OrigLoop);
3992 precomputeCosts(*Plan, VF, CostCtx);
3993 auto Iter = vp_depth_first_deep(Plan->getVectorLoopRegion()->getEntry());
3995 for (auto &R : *VPBB) {
3996 if (!R.cost(VF, CostCtx).isValid())
3997 InvalidCosts.emplace_back(&R, VF);
3998 }
3999 }
4000 }
4001 }
4002 if (InvalidCosts.empty())
4003 return;
4004
4005 // Emit a report of VFs with invalid costs in the loop.
4006
4007 // Group the remarks per recipe, keeping the recipe order from InvalidCosts.
4009 unsigned I = 0;
4010 for (auto &Pair : InvalidCosts)
4011 if (Numbering.try_emplace(Pair.first, I).second)
4012 ++I;
4013
4014 // Sort the list, first on recipe(number) then on VF.
4015 sort(InvalidCosts, [&Numbering](RecipeVFPair &A, RecipeVFPair &B) {
4016 unsigned NA = Numbering[A.first];
4017 unsigned NB = Numbering[B.first];
4018 if (NA != NB)
4019 return NA < NB;
4020 return ElementCount::isKnownLT(A.second, B.second);
4021 });
4022
4023 // For a list of ordered recipe-VF pairs:
4024 // [(load, VF1), (load, VF2), (store, VF1)]
4025 // group the recipes together to emit separate remarks for:
4026 // load (VF1, VF2)
4027 // store (VF1)
4028 auto Tail = ArrayRef<RecipeVFPair>(InvalidCosts);
4029 auto Subset = ArrayRef<RecipeVFPair>();
4030 do {
4031 if (Subset.empty())
4032 Subset = Tail.take_front(1);
4033
4034 VPRecipeBase *R = Subset.front().first;
4035
4036 unsigned Opcode =
4039 [](const auto *R) { return Instruction::PHI; })
4040 .Case<VPWidenStoreRecipe>(
4041 [](const auto *R) { return Instruction::Store; })
4042 .Case<VPWidenLoadRecipe>(
4043 [](const auto *R) { return Instruction::Load; })
4044 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
4045 [](const auto *R) { return Instruction::Call; })
4048 [](const auto *R) { return R->getOpcode(); })
4049 .Case<VPInterleaveRecipe>([](const VPInterleaveRecipe *R) {
4050 return R->getStoredValues().empty() ? Instruction::Load
4051 : Instruction::Store;
4052 })
4053 .Case<VPReductionRecipe>([](const auto *R) {
4054 return RecurrenceDescriptor::getOpcode(R->getRecurrenceKind());
4055 });
4056
4057 // If the next recipe is different, or if there are no other pairs,
4058 // emit a remark for the collated subset. e.g.
4059 // [(load, VF1), (load, VF2))]
4060 // to emit:
4061 // remark: invalid costs for 'load' at VF=(VF1, VF2)
4062 if (Subset == Tail || Tail[Subset.size()].first != R) {
4063 std::string OutString;
4064 raw_string_ostream OS(OutString);
4065 assert(!Subset.empty() && "Unexpected empty range");
4066 OS << "Recipe with invalid costs prevented vectorization at VF=(";
4067 for (const auto &Pair : Subset)
4068 OS << (Pair.second == Subset.front().second ? "" : ", ") << Pair.second;
4069 OS << "):";
4070 if (Opcode == Instruction::Call) {
4071 StringRef Name = "";
4072 if (auto *Int = dyn_cast<VPWidenIntrinsicRecipe>(R)) {
4073 Name = Int->getIntrinsicName();
4074 } else {
4075 auto *WidenCall = dyn_cast<VPWidenCallRecipe>(R);
4076 Function *CalledFn =
4077 WidenCall ? WidenCall->getCalledScalarFunction()
4078 : cast<Function>(R->getOperand(R->getNumOperands() - 1)
4079 ->getLiveInIRValue());
4080 Name = CalledFn->getName();
4081 }
4082 OS << " call to " << Name;
4083 } else
4084 OS << " " << Instruction::getOpcodeName(Opcode);
4085 reportVectorizationInfo(OutString, "InvalidCost", ORE, OrigLoop, nullptr,
4086 R->getDebugLoc());
4087 Tail = Tail.drop_front(Subset.size());
4088 Subset = {};
4089 } else
4090 // Grow the subset by one element
4091 Subset = Tail.take_front(Subset.size() + 1);
4092 } while (!Tail.empty());
4093}
4094
4095/// Check if any recipe of \p Plan will generate a vector value, which will be
4096/// assigned a vector register.
4098 const TargetTransformInfo &TTI) {
4099 assert(VF.isVector() && "Checking a scalar VF?");
4100 VPTypeAnalysis TypeInfo(Plan);
4101 DenseSet<VPRecipeBase *> EphemeralRecipes;
4102 collectEphemeralRecipesForVPlan(Plan, EphemeralRecipes);
4103 // Set of already visited types.
4104 DenseSet<Type *> Visited;
4107 for (VPRecipeBase &R : *VPBB) {
4108 if (EphemeralRecipes.contains(&R))
4109 continue;
4110 // Continue early if the recipe is considered to not produce a vector
4111 // result. Note that this includes VPInstruction where some opcodes may
4112 // produce a vector, to preserve existing behavior as VPInstructions model
4113 // aspects not directly mapped to existing IR instructions.
4114 switch (R.getVPDefID()) {
4115 case VPDef::VPDerivedIVSC:
4116 case VPDef::VPScalarIVStepsSC:
4117 case VPDef::VPReplicateSC:
4118 case VPDef::VPInstructionSC:
4119 case VPDef::VPCanonicalIVPHISC:
4120 case VPDef::VPVectorPointerSC:
4121 case VPDef::VPVectorEndPointerSC:
4122 case VPDef::VPExpandSCEVSC:
4123 case VPDef::VPEVLBasedIVPHISC:
4124 case VPDef::VPPredInstPHISC:
4125 case VPDef::VPBranchOnMaskSC:
4126 continue;
4127 case VPDef::VPReductionSC:
4128 case VPDef::VPActiveLaneMaskPHISC:
4129 case VPDef::VPWidenCallSC:
4130 case VPDef::VPWidenCanonicalIVSC:
4131 case VPDef::VPWidenCastSC:
4132 case VPDef::VPWidenGEPSC:
4133 case VPDef::VPWidenIntrinsicSC:
4134 case VPDef::VPWidenSC:
4135 case VPDef::VPBlendSC:
4136 case VPDef::VPFirstOrderRecurrencePHISC:
4137 case VPDef::VPHistogramSC:
4138 case VPDef::VPWidenPHISC:
4139 case VPDef::VPWidenIntOrFpInductionSC:
4140 case VPDef::VPWidenPointerInductionSC:
4141 case VPDef::VPReductionPHISC:
4142 case VPDef::VPInterleaveEVLSC:
4143 case VPDef::VPInterleaveSC:
4144 case VPDef::VPWidenLoadEVLSC:
4145 case VPDef::VPWidenLoadSC:
4146 case VPDef::VPWidenStoreEVLSC:
4147 case VPDef::VPWidenStoreSC:
4148 break;
4149 default:
4150 llvm_unreachable("unhandled recipe");
4151 }
4152
4153 auto WillGenerateTargetVectors = [&TTI, VF](Type *VectorTy) {
4154 unsigned NumLegalParts = TTI.getNumberOfParts(VectorTy);
4155 if (!NumLegalParts)
4156 return false;
4157 if (VF.isScalable()) {
4158 // <vscale x 1 x iN> is assumed to be profitable over iN because
4159 // scalable registers are a distinct register class from scalar
4160 // ones. If we ever find a target which wants to lower scalable
4161 // vectors back to scalars, we'll need to update this code to
4162 // explicitly ask TTI about the register class uses for each part.
4163 return NumLegalParts <= VF.getKnownMinValue();
4164 }
4165 // Two or more elements that share a register - are vectorized.
4166 return NumLegalParts < VF.getFixedValue();
4167 };
4168
4169 // If no def nor is a store, e.g., branches, continue - no value to check.
4170 if (R.getNumDefinedValues() == 0 &&
4172 continue;
4173 // For multi-def recipes, currently only interleaved loads, suffice to
4174 // check first def only.
4175 // For stores check their stored value; for interleaved stores suffice
4176 // the check first stored value only. In all cases this is the second
4177 // operand.
4178 VPValue *ToCheck =
4179 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
4180 Type *ScalarTy = TypeInfo.inferScalarType(ToCheck);
4181 if (!Visited.insert({ScalarTy}).second)
4182 continue;
4183 Type *WideTy = toVectorizedTy(ScalarTy, VF);
4184 if (any_of(getContainedTypes(WideTy), WillGenerateTargetVectors))
4185 return true;
4186 }
4187 }
4188
4189 return false;
4190}
4191
4192static bool hasReplicatorRegion(VPlan &Plan) {
4194 Plan.getVectorLoopRegion()->getEntry())),
4195 [](auto *VPRB) { return VPRB->isReplicator(); });
4196}
4197
4198#ifndef NDEBUG
4199VectorizationFactor LoopVectorizationPlanner::selectVectorizationFactor() {
4200 InstructionCost ExpectedCost = CM.expectedCost(ElementCount::getFixed(1));
4201 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
4202 assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
4203 assert(
4204 any_of(VPlans,
4205 [](std::unique_ptr<VPlan> &P) { return P->hasScalarVFOnly(); }) &&
4206 "Expected Scalar VF to be a candidate");
4207
4208 const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost,
4209 ExpectedCost);
4210 VectorizationFactor ChosenFactor = ScalarCost;
4211
4212 bool ForceVectorization = Hints.getForce() == LoopVectorizeHints::FK_Enabled;
4213 if (ForceVectorization &&
4214 (VPlans.size() > 1 || !VPlans[0]->hasScalarVFOnly())) {
4215 // Ignore scalar width, because the user explicitly wants vectorization.
4216 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
4217 // evaluation.
4218 ChosenFactor.Cost = InstructionCost::getMax();
4219 }
4220
4221 for (auto &P : VPlans) {
4222 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
4223 P->vectorFactors().end());
4224
4226 if (any_of(VFs, [this](ElementCount VF) {
4227 return CM.shouldConsiderRegPressureForVF(VF);
4228 }))
4229 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI, CM.ValuesToIgnore);
4230
4231 for (unsigned I = 0; I < VFs.size(); I++) {
4232 ElementCount VF = VFs[I];
4233 // The cost for scalar VF=1 is already calculated, so ignore it.
4234 if (VF.isScalar())
4235 continue;
4236
4237 /// If the register pressure needs to be considered for VF,
4238 /// don't consider the VF as valid if it exceeds the number
4239 /// of registers for the target.
4240 if (CM.shouldConsiderRegPressureForVF(VF) &&
4241 RUs[I].exceedsMaxNumRegs(TTI, ForceTargetNumVectorRegs))
4242 continue;
4243
4244 InstructionCost C = CM.expectedCost(VF);
4245
4246 // Add on other costs that are modelled in VPlan, but not in the legacy
4247 // cost model.
4248 VPCostContext CostCtx(CM.TTI, *CM.TLI, *P, CM, CM.CostKind, CM.PSE,
4249 OrigLoop);
4250 VPRegionBlock *VectorRegion = P->getVectorLoopRegion();
4251 assert(VectorRegion && "Expected to have a vector region!");
4252 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
4253 vp_depth_first_shallow(VectorRegion->getEntry()))) {
4254 for (VPRecipeBase &R : *VPBB) {
4255 auto *VPI = dyn_cast<VPInstruction>(&R);
4256 if (!VPI)
4257 continue;
4258 switch (VPI->getOpcode()) {
4259 // Selects are only modelled in the legacy cost model for safe
4260 // divisors.
4261 case Instruction::Select: {
4262 if (auto *WR =
4263 dyn_cast_or_null<VPWidenRecipe>(VPI->getSingleUser())) {
4264 switch (WR->getOpcode()) {
4265 case Instruction::UDiv:
4266 case Instruction::SDiv:
4267 case Instruction::URem:
4268 case Instruction::SRem:
4269 continue;
4270 default:
4271 break;
4272 }
4273 }
4274 C += VPI->cost(VF, CostCtx);
4275 break;
4276 }
4278 unsigned Multiplier =
4279 cast<VPConstantInt>(VPI->getOperand(2))->getZExtValue();
4280 C += VPI->cost(VF * Multiplier, CostCtx);
4281 break;
4282 }
4284 C += VPI->cost(VF, CostCtx);
4285 break;
4286 default:
4287 break;
4288 }
4289 }
4290 }
4291
4292 VectorizationFactor Candidate(VF, C, ScalarCost.ScalarCost);
4293 unsigned Width =
4294 estimateElementCount(Candidate.Width, CM.getVScaleForTuning());
4295 LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << VF
4296 << " costs: " << (Candidate.Cost / Width));
4297 if (VF.isScalable())
4298 LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
4299 << CM.getVScaleForTuning().value_or(1) << ")");
4300 LLVM_DEBUG(dbgs() << ".\n");
4301
4302 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
4303 LLVM_DEBUG(
4304 dbgs()
4305 << "LV: Not considering vector loop of width " << VF
4306 << " because it will not generate any vector instructions.\n");
4307 continue;
4308 }
4309
4310 if (CM.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
4311 LLVM_DEBUG(
4312 dbgs()
4313 << "LV: Not considering vector loop of width " << VF
4314 << " because it would cause replicated blocks to be generated,"
4315 << " which isn't allowed when optimizing for size.\n");
4316 continue;
4317 }
4318
4319 if (isMoreProfitable(Candidate, ChosenFactor, P->hasScalarTail()))
4320 ChosenFactor = Candidate;
4321 }
4322 }
4323
4324 if (!EnableCondStoresVectorization && CM.hasPredStores()) {
4326 "There are conditional stores.",
4327 "store that is conditionally executed prevents vectorization",
4328 "ConditionalStore", ORE, OrigLoop);
4329 ChosenFactor = ScalarCost;
4330 }
4331
4332 LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
4333 !isMoreProfitable(ChosenFactor, ScalarCost,
4334 !CM.foldTailByMasking())) dbgs()
4335 << "LV: Vectorization seems to be not beneficial, "
4336 << "but was forced by a user.\n");
4337 return ChosenFactor;
4338}
4339#endif
4340
4341bool LoopVectorizationPlanner::isCandidateForEpilogueVectorization(
4342 ElementCount VF) const {
4343 // Cross iteration phis such as fixed-order recurrences and FMaxNum/FMinNum
4344 // reductions need special handling and are currently unsupported.
4345 // FindLast reductions also require special handling for the synthesized
4346 // mask PHI.
4347 if (any_of(OrigLoop->getHeader()->phis(), [&](PHINode &Phi) {
4348 if (!Legal->isReductionVariable(&Phi))
4349 return Legal->isFixedOrderRecurrence(&Phi);
4350 RecurKind Kind =
4351 Legal->getRecurrenceDescriptor(&Phi).getRecurrenceKind();
4352 return RecurrenceDescriptor::isFindLastRecurrenceKind(Kind) ||
4353 RecurrenceDescriptor::isFPMinMaxNumRecurrenceKind(Kind);
4354 }))
4355 return false;
4356
4357 // Phis with uses outside of the loop require special handling and are
4358 // currently unsupported.
4359 for (const auto &Entry : Legal->getInductionVars()) {
4360 // Look for uses of the value of the induction at the last iteration.
4361 Value *PostInc =
4362 Entry.first->getIncomingValueForBlock(OrigLoop->getLoopLatch());
4363 for (User *U : PostInc->users())
4364 if (!OrigLoop->contains(cast<Instruction>(U)))
4365 return false;
4366 // Look for uses of penultimate value of the induction.
4367 for (User *U : Entry.first->users())
4368 if (!OrigLoop->contains(cast<Instruction>(U)))
4369 return false;
4370 }
4371
4372 // Epilogue vectorization code has not been auditted to ensure it handles
4373 // non-latch exits properly. It may be fine, but it needs auditted and
4374 // tested.
4375 // TODO: Add support for loops with an early exit.
4376 if (OrigLoop->getExitingBlock() != OrigLoop->getLoopLatch())
4377 return false;
4378
4379 return true;
4380}
4381
4383 const ElementCount VF, const unsigned IC) const {
4384 // FIXME: We need a much better cost-model to take different parameters such
4385 // as register pressure, code size increase and cost of extra branches into
4386 // account. For now we apply a very crude heuristic and only consider loops
4387 // with vectorization factors larger than a certain value.
4388
4389 // Allow the target to opt out entirely.
4390 if (!TTI.preferEpilogueVectorization())
4391 return false;
4392
4393 // We also consider epilogue vectorization unprofitable for targets that don't
4394 // consider interleaving beneficial (eg. MVE).
4395 if (TTI.getMaxInterleaveFactor(VF) <= 1)
4396 return false;
4397
4398 unsigned MinVFThreshold = EpilogueVectorizationMinVF.getNumOccurrences() > 0
4400 : TTI.getEpilogueVectorizationMinVF();
4401 return estimateElementCount(VF * IC, VScaleForTuning) >= MinVFThreshold;
4402}
4403
4405 const ElementCount MainLoopVF, unsigned IC) {
4408 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n");
4409 return Result;
4410 }
4411
4412 if (!CM.isScalarEpilogueAllowed()) {
4413 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because no "
4414 "epilogue is allowed.\n");
4415 return Result;
4416 }
4417
4418 // Not really a cost consideration, but check for unsupported cases here to
4419 // simplify the logic.
4420 if (!isCandidateForEpilogueVectorization(MainLoopVF)) {
4421 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because the loop "
4422 "is not a supported candidate.\n");
4423 return Result;
4424 }
4425
4427 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n");
4429 if (hasPlanWithVF(ForcedEC))
4430 return {ForcedEC, 0, 0};
4431
4432 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization forced factor is not "
4433 "viable.\n");
4434 return Result;
4435 }
4436
4437 if (OrigLoop->getHeader()->getParent()->hasOptSize()) {
4438 LLVM_DEBUG(
4439 dbgs() << "LEV: Epilogue vectorization skipped due to opt for size.\n");
4440 return Result;
4441 }
4442
4443 if (!CM.isEpilogueVectorizationProfitable(MainLoopVF, IC)) {
4444 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
4445 "this loop\n");
4446 return Result;
4447 }
4448
4449 // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
4450 // the main loop handles 8 lanes per iteration. We could still benefit from
4451 // vectorizing the epilogue loop with VF=4.
4452 ElementCount EstimatedRuntimeVF = ElementCount::getFixed(
4453 estimateElementCount(MainLoopVF, CM.getVScaleForTuning()));
4454
4455 Type *TCType = Legal->getWidestInductionType();
4456 const SCEV *RemainingIterations = nullptr;
4457 unsigned MaxTripCount = 0;
4459 getPlanFor(MainLoopVF).getTripCount(), PSE);
4460 assert(!isa<SCEVCouldNotCompute>(TC) && "Trip count SCEV must be computable");
4461 const SCEV *KnownMinTC;
4462 bool ScalableTC = match(TC, m_scev_c_Mul(m_SCEV(KnownMinTC), m_SCEVVScale()));
4463 bool ScalableRemIter = false;
4464 ScalarEvolution &SE = *PSE.getSE();
4465 // Use versions of TC and VF in which both are either scalable or fixed.
4466 if (ScalableTC == MainLoopVF.isScalable()) {
4467 ScalableRemIter = ScalableTC;
4468 RemainingIterations =
4469 SE.getURemExpr(TC, SE.getElementCount(TCType, MainLoopVF * IC));
4470 } else if (ScalableTC) {
4471 const SCEV *EstimatedTC = SE.getMulExpr(
4472 KnownMinTC,
4473 SE.getConstant(TCType, CM.getVScaleForTuning().value_or(1)));
4474 RemainingIterations = SE.getURemExpr(
4475 EstimatedTC, SE.getElementCount(TCType, MainLoopVF * IC));
4476 } else
4477 RemainingIterations =
4478 SE.getURemExpr(TC, SE.getElementCount(TCType, EstimatedRuntimeVF * IC));
4479
4480 // No iterations left to process in the epilogue.
4481 if (RemainingIterations->isZero())
4482 return Result;
4483
4484 if (MainLoopVF.isFixed()) {
4485 MaxTripCount = MainLoopVF.getFixedValue() * IC - 1;
4486 if (SE.isKnownPredicate(CmpInst::ICMP_ULT, RemainingIterations,
4487 SE.getConstant(TCType, MaxTripCount))) {
4488 MaxTripCount = SE.getUnsignedRangeMax(RemainingIterations).getZExtValue();
4489 }
4490 LLVM_DEBUG(dbgs() << "LEV: Maximum Trip Count for Epilogue: "
4491 << MaxTripCount << "\n");
4492 }
4493
4494 auto SkipVF = [&](const SCEV *VF, const SCEV *RemIter) -> bool {
4495 return SE.isKnownPredicate(CmpInst::ICMP_UGT, VF, RemIter);
4496 };
4497 for (auto &NextVF : ProfitableVFs) {
4498 // Skip candidate VFs without a corresponding VPlan.
4499 if (!hasPlanWithVF(NextVF.Width))
4500 continue;
4501
4502 // Skip candidate VFs with widths >= the (estimated) runtime VF (scalable
4503 // vectors) or > the VF of the main loop (fixed vectors).
4504 if ((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
4505 ElementCount::isKnownGE(NextVF.Width, EstimatedRuntimeVF)) ||
4506 (NextVF.Width.isScalable() &&
4507 ElementCount::isKnownGE(NextVF.Width, MainLoopVF)) ||
4508 (!NextVF.Width.isScalable() && !MainLoopVF.isScalable() &&
4509 ElementCount::isKnownGT(NextVF.Width, MainLoopVF)))
4510 continue;
4511
4512 // If NextVF is greater than the number of remaining iterations, the
4513 // epilogue loop would be dead. Skip such factors.
4514 // TODO: We should also consider comparing against a scalable
4515 // RemainingIterations when SCEV be able to evaluate non-canonical
4516 // vscale-based expressions.
4517 if (!ScalableRemIter) {
4518 // Handle the case where NextVF and RemainingIterations are in different
4519 // numerical spaces.
4520 ElementCount EC = NextVF.Width;
4521 if (NextVF.Width.isScalable())
4523 estimateElementCount(NextVF.Width, CM.getVScaleForTuning()));
4524 if (SkipVF(SE.getElementCount(TCType, EC), RemainingIterations))
4525 continue;
4526 }
4527
4528 if (Result.Width.isScalar() ||
4529 isMoreProfitable(NextVF, Result, MaxTripCount, !CM.foldTailByMasking(),
4530 /*IsEpilogue*/ true))
4531 Result = NextVF;
4532 }
4533
4534 if (Result != VectorizationFactor::Disabled())
4535 LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
4536 << Result.Width << "\n");
4537 return Result;
4538}
4539
4540std::pair<unsigned, unsigned>
4542 unsigned MinWidth = -1U;
4543 unsigned MaxWidth = 8;
4544 const DataLayout &DL = TheFunction->getDataLayout();
4545 // For in-loop reductions, no element types are added to ElementTypesInLoop
4546 // if there are no loads/stores in the loop. In this case, check through the
4547 // reduction variables to determine the maximum width.
4548 if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
4549 for (const auto &PhiDescriptorPair : Legal->getReductionVars()) {
4550 const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
4551 // When finding the min width used by the recurrence we need to account
4552 // for casts on the input operands of the recurrence.
4553 MinWidth = std::min(
4554 MinWidth,
4555 std::min(RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
4557 MaxWidth = std::max(MaxWidth,
4559 }
4560 } else {
4561 for (Type *T : ElementTypesInLoop) {
4562 MinWidth = std::min<unsigned>(
4563 MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedValue());
4564 MaxWidth = std::max<unsigned>(
4565 MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedValue());
4566 }
4567 }
4568 return {MinWidth, MaxWidth};
4569}
4570
4572 ElementTypesInLoop.clear();
4573 // For each block.
4574 for (BasicBlock *BB : TheLoop->blocks()) {
4575 // For each instruction in the loop.
4576 for (Instruction &I : BB->instructionsWithoutDebug()) {
4577 Type *T = I.getType();
4578
4579 // Skip ignored values.
4580 if (ValuesToIgnore.count(&I))
4581 continue;
4582
4583 // Only examine Loads, Stores and PHINodes.
4584 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
4585 continue;
4586
4587 // Examine PHI nodes that are reduction variables. Update the type to
4588 // account for the recurrence type.
4589 if (auto *PN = dyn_cast<PHINode>(&I)) {
4590 if (!Legal->isReductionVariable(PN))
4591 continue;
4592 const RecurrenceDescriptor &RdxDesc =
4593 Legal->getRecurrenceDescriptor(PN);
4595 TTI.preferInLoopReduction(RdxDesc.getRecurrenceKind(),
4596 RdxDesc.getRecurrenceType()))
4597 continue;
4598 T = RdxDesc.getRecurrenceType();
4599 }
4600
4601 // Examine the stored values.
4602 if (auto *ST = dyn_cast<StoreInst>(&I))
4603 T = ST->getValueOperand()->getType();
4604
4605 assert(T->isSized() &&
4606 "Expected the load/store/recurrence type to be sized");
4607
4608 ElementTypesInLoop.insert(T);
4609 }
4610 }
4611}
4612
4613unsigned
4615 InstructionCost LoopCost) {
4616 // -- The interleave heuristics --
4617 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4618 // There are many micro-architectural considerations that we can't predict
4619 // at this level. For example, frontend pressure (on decode or fetch) due to
4620 // code size, or the number and capabilities of the execution ports.
4621 //
4622 // We use the following heuristics to select the interleave count:
4623 // 1. If the code has reductions, then we interleave to break the cross
4624 // iteration dependency.
4625 // 2. If the loop is really small, then we interleave to reduce the loop
4626 // overhead.
4627 // 3. We don't interleave if we think that we will spill registers to memory
4628 // due to the increased register pressure.
4629
4630 // Only interleave tail-folded loops if wide lane masks are requested, as the
4631 // overhead of multiple instructions to calculate the predicate is likely
4632 // not beneficial. If a scalar epilogue is not allowed for any other reason,
4633 // do not interleave.
4634 if (!CM.isScalarEpilogueAllowed() &&
4635 !(CM.preferPredicatedLoop() && CM.useWideActiveLaneMask()))
4636 return 1;
4637
4640 LLVM_DEBUG(dbgs() << "LV: Preference for VP intrinsics indicated. "
4641 "Unroll factor forced to be 1.\n");
4642 return 1;
4643 }
4644
4645 // We used the distance for the interleave count.
4646 if (!Legal->isSafeForAnyVectorWidth())
4647 return 1;
4648
4649 // We don't attempt to perform interleaving for loops with uncountable early
4650 // exits because the VPInstruction::AnyOf code cannot currently handle
4651 // multiple parts.
4652 if (Plan.hasEarlyExit())
4653 return 1;
4654
4655 const bool HasReductions =
4658
4659 // FIXME: implement interleaving for FindLast transform correctly.
4660 if (any_of(make_second_range(Legal->getReductionVars()),
4661 [](const RecurrenceDescriptor &RdxDesc) {
4662 return RecurrenceDescriptor::isFindLastRecurrenceKind(
4663 RdxDesc.getRecurrenceKind());
4664 }))
4665 return 1;
4666
4667 // If we did not calculate the cost for VF (because the user selected the VF)
4668 // then we calculate the cost of VF here.
4669 if (LoopCost == 0) {
4670 if (VF.isScalar())
4671 LoopCost = CM.expectedCost(VF);
4672 else
4673 LoopCost = cost(Plan, VF);
4674 assert(LoopCost.isValid() && "Expected to have chosen a VF with valid cost");
4675
4676 // Loop body is free and there is no need for interleaving.
4677 if (LoopCost == 0)
4678 return 1;
4679 }
4680
4681 VPRegisterUsage R =
4682 calculateRegisterUsageForPlan(Plan, {VF}, TTI, CM.ValuesToIgnore)[0];
4683 // We divide by these constants so assume that we have at least one
4684 // instruction that uses at least one register.
4685 for (auto &Pair : R.MaxLocalUsers) {
4686 Pair.second = std::max(Pair.second, 1U);
4687 }
4688
4689 // We calculate the interleave count using the following formula.
4690 // Subtract the number of loop invariants from the number of available
4691 // registers. These registers are used by all of the interleaved instances.
4692 // Next, divide the remaining registers by the number of registers that is
4693 // required by the loop, in order to estimate how many parallel instances
4694 // fit without causing spills. All of this is rounded down if necessary to be
4695 // a power of two. We want power of two interleave count to simplify any
4696 // addressing operations or alignment considerations.
4697 // We also want power of two interleave counts to ensure that the induction
4698 // variable of the vector loop wraps to zero, when tail is folded by masking;
4699 // this currently happens when OptForSize, in which case IC is set to 1 above.
4700 unsigned IC = UINT_MAX;
4701
4702 for (const auto &Pair : R.MaxLocalUsers) {
4703 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(Pair.first);
4704 LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
4705 << " registers of "
4706 << TTI.getRegisterClassName(Pair.first)
4707 << " register class\n");
4708 if (VF.isScalar()) {
4709 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4710 TargetNumRegisters = ForceTargetNumScalarRegs;
4711 } else {
4712 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4713 TargetNumRegisters = ForceTargetNumVectorRegs;
4714 }
4715 unsigned MaxLocalUsers = Pair.second;
4716 unsigned LoopInvariantRegs = 0;
4717 if (R.LoopInvariantRegs.contains(Pair.first))
4718 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
4719
4720 unsigned TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
4721 MaxLocalUsers);
4722 // Don't count the induction variable as interleaved.
4724 TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
4725 std::max(1U, (MaxLocalUsers - 1)));
4726 }
4727
4728 IC = std::min(IC, TmpIC);
4729 }
4730
4731 // Clamp the interleave ranges to reasonable counts.
4732 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4733
4734 // Check if the user has overridden the max.
4735 if (VF.isScalar()) {
4736 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4737 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4738 } else {
4739 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4740 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4741 }
4742
4743 // Try to get the exact trip count, or an estimate based on profiling data or
4744 // ConstantMax from PSE, failing that.
4745 auto BestKnownTC = getSmallBestKnownTC(PSE, OrigLoop);
4746
4747 // For fixed length VFs treat a scalable trip count as unknown.
4748 if (BestKnownTC && (BestKnownTC->isFixed() || VF.isScalable())) {
4749 // Re-evaluate trip counts and VFs to be in the same numerical space.
4750 unsigned AvailableTC =
4751 estimateElementCount(*BestKnownTC, CM.getVScaleForTuning());
4752 unsigned EstimatedVF = estimateElementCount(VF, CM.getVScaleForTuning());
4753
4754 // At least one iteration must be scalar when this constraint holds. So the
4755 // maximum available iterations for interleaving is one less.
4756 if (CM.requiresScalarEpilogue(VF.isVector()))
4757 --AvailableTC;
4758
4759 unsigned InterleaveCountLB = bit_floor(std::max(
4760 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
4761
4762 if (getSmallConstantTripCount(PSE.getSE(), OrigLoop).isNonZero()) {
4763 // If the best known trip count is exact, we select between two
4764 // prospective ICs, where
4765 //
4766 // 1) the aggressive IC is capped by the trip count divided by VF
4767 // 2) the conservative IC is capped by the trip count divided by (VF * 2)
4768 //
4769 // The final IC is selected in a way that the epilogue loop trip count is
4770 // minimized while maximizing the IC itself, so that we either run the
4771 // vector loop at least once if it generates a small epilogue loop, or
4772 // else we run the vector loop at least twice.
4773
4774 unsigned InterleaveCountUB = bit_floor(std::max(
4775 1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
4776 MaxInterleaveCount = InterleaveCountLB;
4777
4778 if (InterleaveCountUB != InterleaveCountLB) {
4779 unsigned TailTripCountUB =
4780 (AvailableTC % (EstimatedVF * InterleaveCountUB));
4781 unsigned TailTripCountLB =
4782 (AvailableTC % (EstimatedVF * InterleaveCountLB));
4783 // If both produce same scalar tail, maximize the IC to do the same work
4784 // in fewer vector loop iterations
4785 if (TailTripCountUB == TailTripCountLB)
4786 MaxInterleaveCount = InterleaveCountUB;
4787 }
4788 } else {
4789 // If trip count is an estimated compile time constant, limit the
4790 // IC to be capped by the trip count divided by VF * 2, such that the
4791 // vector loop runs at least twice to make interleaving seem profitable
4792 // when there is an epilogue loop present. Since exact Trip count is not
4793 // known we choose to be conservative in our IC estimate.
4794 MaxInterleaveCount = InterleaveCountLB;
4795 }
4796 }
4797
4798 assert(MaxInterleaveCount > 0 &&
4799 "Maximum interleave count must be greater than 0");
4800
4801 // Clamp the calculated IC to be between the 1 and the max interleave count
4802 // that the target and trip count allows.
4803 if (IC > MaxInterleaveCount)
4804 IC = MaxInterleaveCount;
4805 else
4806 // Make sure IC is greater than 0.
4807 IC = std::max(1u, IC);
4808
4809 assert(IC > 0 && "Interleave count must be greater than 0.");
4810
4811 // Interleave if we vectorized this loop and there is a reduction that could
4812 // benefit from interleaving.
4813 if (VF.isVector() && HasReductions) {
4814 LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4815 return IC;
4816 }
4817
4818 // For any scalar loop that either requires runtime checks or predication we
4819 // are better off leaving this to the unroller. Note that if we've already
4820 // vectorized the loop we will have done the runtime check and so interleaving
4821 // won't require further checks.
4822 bool ScalarInterleavingRequiresPredication =
4823 (VF.isScalar() && any_of(OrigLoop->blocks(), [this](BasicBlock *BB) {
4824 return Legal->blockNeedsPredication(BB);
4825 }));
4826 bool ScalarInterleavingRequiresRuntimePointerCheck =
4827 (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
4828
4829 // We want to interleave small loops in order to reduce the loop overhead and
4830 // potentially expose ILP opportunities.
4831 LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
4832 << "LV: IC is " << IC << '\n'
4833 << "LV: VF is " << VF << '\n');
4834 const bool AggressivelyInterleaveReductions =
4835 TTI.enableAggressiveInterleaving(HasReductions);
4836 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
4837 !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
4838 // We assume that the cost overhead is 1 and we use the cost model
4839 // to estimate the cost of the loop and interleave until the cost of the
4840 // loop overhead is about 5% of the cost of the loop.
4841 unsigned SmallIC = std::min(IC, (unsigned)llvm::bit_floor<uint64_t>(
4842 SmallLoopCost / LoopCost.getValue()));
4843
4844 // Interleave until store/load ports (estimated by max interleave count) are
4845 // saturated.
4846 unsigned NumStores = 0;
4847 unsigned NumLoads = 0;
4850 for (VPRecipeBase &R : *VPBB) {
4852 NumLoads++;
4853 continue;
4854 }
4856 NumStores++;
4857 continue;
4858 }
4859
4860 if (auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R)) {
4861 if (unsigned StoreOps = InterleaveR->getNumStoreOperands())
4862 NumStores += StoreOps;
4863 else
4864 NumLoads += InterleaveR->getNumDefinedValues();
4865 continue;
4866 }
4867 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
4868 NumLoads += isa<LoadInst>(RepR->getUnderlyingInstr());
4869 NumStores += isa<StoreInst>(RepR->getUnderlyingInstr());
4870 continue;
4871 }
4872 if (isa<VPHistogramRecipe>(&R)) {
4873 NumLoads++;
4874 NumStores++;
4875 continue;
4876 }
4877 }
4878 }
4879 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4880 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4881
4882 // There is little point in interleaving for reductions containing selects
4883 // and compares when VF=1 since it may just create more overhead than it's
4884 // worth for loops with small trip counts. This is because we still have to
4885 // do the final reduction after the loop.
4886 bool HasSelectCmpReductions =
4887 HasReductions &&
4889 [](VPRecipeBase &R) {
4890 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
4891 return RedR && (RecurrenceDescriptor::isAnyOfRecurrenceKind(
4892 RedR->getRecurrenceKind()) ||
4893 RecurrenceDescriptor::isFindIVRecurrenceKind(
4894 RedR->getRecurrenceKind()));
4895 });
4896 if (HasSelectCmpReductions) {
4897 LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
4898 return 1;
4899 }
4900
4901 // If we have a scalar reduction (vector reductions are already dealt with
4902 // by this point), we can increase the critical path length if the loop
4903 // we're interleaving is inside another loop. For tree-wise reductions
4904 // set the limit to 2, and for ordered reductions it's best to disable
4905 // interleaving entirely.
4906 if (HasReductions && OrigLoop->getLoopDepth() > 1) {
4907 bool HasOrderedReductions =
4909 [](VPRecipeBase &R) {
4910 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
4911
4912 return RedR && RedR->isOrdered();
4913 });
4914 if (HasOrderedReductions) {
4915 LLVM_DEBUG(
4916 dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
4917 return 1;
4918 }
4919
4920 unsigned F = MaxNestedScalarReductionIC;
4921 SmallIC = std::min(SmallIC, F);
4922 StoresIC = std::min(StoresIC, F);
4923 LoadsIC = std::min(LoadsIC, F);
4924 }
4925
4927 std::max(StoresIC, LoadsIC) > SmallIC) {
4928 LLVM_DEBUG(
4929 dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4930 return std::max(StoresIC, LoadsIC);
4931 }
4932
4933 // If there are scalar reductions and TTI has enabled aggressive
4934 // interleaving for reductions, we will interleave to expose ILP.
4935 if (VF.isScalar() && AggressivelyInterleaveReductions) {
4936 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4937 // Interleave no less than SmallIC but not as aggressive as the normal IC
4938 // to satisfy the rare situation when resources are too limited.
4939 return std::max(IC / 2, SmallIC);
4940 }
4941
4942 LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4943 return SmallIC;
4944 }
4945
4946 // Interleave if this is a large loop (small loops are already dealt with by
4947 // this point) that could benefit from interleaving.
4948 if (AggressivelyInterleaveReductions) {
4949 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4950 return IC;
4951 }
4952
4953 LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
4954 return 1;
4955}
4956
4957bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
4958 ElementCount VF) {
4959 // TODO: Cost model for emulated masked load/store is completely
4960 // broken. This hack guides the cost model to use an artificially
4961 // high enough value to practically disable vectorization with such
4962 // operations, except where previously deployed legality hack allowed
4963 // using very low cost values. This is to avoid regressions coming simply
4964 // from moving "masked load/store" check from legality to cost model.
4965 // Masked Load/Gather emulation was previously never allowed.
4966 // Limited number of Masked Store/Scatter emulation was allowed.
4967 assert((isPredicatedInst(I)) &&
4968 "Expecting a scalar emulated instruction");
4969 return isa<LoadInst>(I) ||
4970 (isa<StoreInst>(I) &&
4971 NumPredStores > NumberOfStoresToPredicate);
4972}
4973
4975 assert(VF.isVector() && "Expected VF >= 2");
4976
4977 // If we've already collected the instructions to scalarize or the predicated
4978 // BBs after vectorization, there's nothing to do. Collection may already have
4979 // occurred if we have a user-selected VF and are now computing the expected
4980 // cost for interleaving.
4981 if (InstsToScalarize.contains(VF) ||
4982 PredicatedBBsAfterVectorization.contains(VF))
4983 return;
4984
4985 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
4986 // not profitable to scalarize any instructions, the presence of VF in the
4987 // map will indicate that we've analyzed it already.
4988 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
4989
4990 // Find all the instructions that are scalar with predication in the loop and
4991 // determine if it would be better to not if-convert the blocks they are in.
4992 // If so, we also record the instructions to scalarize.
4993 for (BasicBlock *BB : TheLoop->blocks()) {
4995 continue;
4996 for (Instruction &I : *BB)
4997 if (isScalarWithPredication(&I, VF)) {
4998 ScalarCostsTy ScalarCosts;
4999 // Do not apply discount logic for:
5000 // 1. Scalars after vectorization, as there will only be a single copy
5001 // of the instruction.
5002 // 2. Scalable VF, as that would lead to invalid scalarization costs.
5003 // 3. Emulated masked memrefs, if a hacked cost is needed.
5004 if (!isScalarAfterVectorization(&I, VF) && !VF.isScalable() &&
5005 !useEmulatedMaskMemRefHack(&I, VF) &&
5006 computePredInstDiscount(&I, ScalarCosts, VF) >= 0) {
5007 for (const auto &[I, IC] : ScalarCosts)
5008 ScalarCostsVF.insert({I, IC});
5009 // Check if we decided to scalarize a call. If so, update the widening
5010 // decision of the call to CM_Scalarize with the computed scalar cost.
5011 for (const auto &[I, Cost] : ScalarCosts) {
5012 auto *CI = dyn_cast<CallInst>(I);
5013 if (!CI || !CallWideningDecisions.contains({CI, VF}))
5014 continue;
5015 CallWideningDecisions[{CI, VF}].Kind = CM_Scalarize;
5016 CallWideningDecisions[{CI, VF}].Cost = Cost;
5017 }
5018 }
5019 // Remember that BB will remain after vectorization.
5020 PredicatedBBsAfterVectorization[VF].insert(BB);
5021 for (auto *Pred : predecessors(BB)) {
5022 if (Pred->getSingleSuccessor() == BB)
5023 PredicatedBBsAfterVectorization[VF].insert(Pred);
5024 }
5025 }
5026 }
5027}
5028
5029InstructionCost LoopVectorizationCostModel::computePredInstDiscount(
5030 Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
5031 assert(!isUniformAfterVectorization(PredInst, VF) &&
5032 "Instruction marked uniform-after-vectorization will be predicated");
5033
5034 // Initialize the discount to zero, meaning that the scalar version and the
5035 // vector version cost the same.
5036 InstructionCost Discount = 0;
5037
5038 // Holds instructions to analyze. The instructions we visit are mapped in
5039 // ScalarCosts. Those instructions are the ones that would be scalarized if
5040 // we find that the scalar version costs less.
5042
5043 // Returns true if the given instruction can be scalarized.
5044 auto CanBeScalarized = [&](Instruction *I) -> bool {
5045 // We only attempt to scalarize instructions forming a single-use chain
5046 // from the original predicated block that would otherwise be vectorized.
5047 // Although not strictly necessary, we give up on instructions we know will
5048 // already be scalar to avoid traversing chains that are unlikely to be
5049 // beneficial.
5050 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
5051 isScalarAfterVectorization(I, VF))
5052 return false;
5053
5054 // If the instruction is scalar with predication, it will be analyzed
5055 // separately. We ignore it within the context of PredInst.
5056 if (isScalarWithPredication(I, VF))
5057 return false;
5058
5059 // If any of the instruction's operands are uniform after vectorization,
5060 // the instruction cannot be scalarized. This prevents, for example, a
5061 // masked load from being scalarized.
5062 //
5063 // We assume we will only emit a value for lane zero of an instruction
5064 // marked uniform after vectorization, rather than VF identical values.
5065 // Thus, if we scalarize an instruction that uses a uniform, we would
5066 // create uses of values corresponding to the lanes we aren't emitting code
5067 // for. This behavior can be changed by allowing getScalarValue to clone
5068 // the lane zero values for uniforms rather than asserting.
5069 for (Use &U : I->operands())
5070 if (auto *J = dyn_cast<Instruction>(U.get()))
5071 if (isUniformAfterVectorization(J, VF))
5072 return false;
5073
5074 // Otherwise, we can scalarize the instruction.
5075 return true;
5076 };
5077
5078 // Compute the expected cost discount from scalarizing the entire expression
5079 // feeding the predicated instruction. We currently only consider expressions
5080 // that are single-use instruction chains.
5081 Worklist.push_back(PredInst);
5082 while (!Worklist.empty()) {
5083 Instruction *I = Worklist.pop_back_val();
5084
5085 // If we've already analyzed the instruction, there's nothing to do.
5086 if (ScalarCosts.contains(I))
5087 continue;
5088
5089 // Cannot scalarize fixed-order recurrence phis at the moment.
5090 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
5091 continue;
5092
5093 // Compute the cost of the vector instruction. Note that this cost already
5094 // includes the scalarization overhead of the predicated instruction.
5095 InstructionCost VectorCost = getInstructionCost(I, VF);
5096
5097 // Compute the cost of the scalarized instruction. This cost is the cost of
5098 // the instruction as if it wasn't if-converted and instead remained in the
5099 // predicated block. We will scale this cost by block probability after
5100 // computing the scalarization overhead.
5101 InstructionCost ScalarCost =
5102 VF.getFixedValue() * getInstructionCost(I, ElementCount::getFixed(1));
5103
5104 // Compute the scalarization overhead of needed insertelement instructions
5105 // and phi nodes.
5106 if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
5107 Type *WideTy = toVectorizedTy(I->getType(), VF);
5108 for (Type *VectorTy : getContainedTypes(WideTy)) {
5109 ScalarCost += TTI.getScalarizationOverhead(
5111 /*Insert=*/true,
5112 /*Extract=*/false, CostKind);
5113 }
5114 ScalarCost +=
5115 VF.getFixedValue() * TTI.getCFInstrCost(Instruction::PHI, CostKind);
5116 }
5117
5118 // Compute the scalarization overhead of needed extractelement
5119 // instructions. For each of the instruction's operands, if the operand can
5120 // be scalarized, add it to the worklist; otherwise, account for the
5121 // overhead.
5122 for (Use &U : I->operands())
5123 if (auto *J = dyn_cast<Instruction>(U.get())) {
5124 assert(canVectorizeTy(J->getType()) &&
5125 "Instruction has non-scalar type");
5126 if (CanBeScalarized(J))
5127 Worklist.push_back(J);
5128 else if (needsExtract(J, VF)) {
5129 Type *WideTy = toVectorizedTy(J->getType(), VF);
5130 for (Type *VectorTy : getContainedTypes(WideTy)) {
5131 ScalarCost += TTI.getScalarizationOverhead(
5132 cast<VectorType>(VectorTy),
5133 APInt::getAllOnes(VF.getFixedValue()), /*Insert*/ false,
5134 /*Extract*/ true, CostKind);
5135 }
5136 }
5137 }
5138
5139 // Scale the total scalar cost by block probability.
5140 ScalarCost /= getPredBlockCostDivisor(CostKind, I->getParent());
5141
5142 // Compute the discount. A non-negative discount means the vector version
5143 // of the instruction costs more, and scalarizing would be beneficial.
5144 Discount += VectorCost - ScalarCost;
5145 ScalarCosts[I] = ScalarCost;
5146 }
5147
5148 return Discount;
5149}
5150
5153
5154 // If the vector loop gets executed exactly once with the given VF, ignore the
5155 // costs of comparison and induction instructions, as they'll get simplified
5156 // away.
5157 SmallPtrSet<Instruction *, 2> ValuesToIgnoreForVF;
5158 auto TC = getSmallConstantTripCount(PSE.getSE(), TheLoop);
5159 if (TC == VF && !foldTailByMasking())
5161 ValuesToIgnoreForVF);
5162
5163 // For each block.
5164 for (BasicBlock *BB : TheLoop->blocks()) {
5165 InstructionCost BlockCost;
5166
5167 // For each instruction in the old loop.
5168 for (Instruction &I : BB->instructionsWithoutDebug()) {
5169 // Skip ignored values.
5170 if (ValuesToIgnore.count(&I) || ValuesToIgnoreForVF.count(&I) ||
5171 (VF.isVector() && VecValuesToIgnore.count(&I)))
5172 continue;
5173
5175
5176 // Check if we should override the cost.
5177 if (C.isValid() && ForceTargetInstructionCost.getNumOccurrences() > 0) {
5178 // For interleave groups, use ForceTargetInstructionCost once for the
5179 // whole group.
5180 if (VF.isVector() && getWideningDecision(&I, VF) == CM_Interleave) {
5181 if (getInterleavedAccessGroup(&I)->getInsertPos() == &I)
5183 else
5184 C = InstructionCost(0);
5185 } else {
5187 }
5188 }
5189
5190 BlockCost += C;
5191 LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF "
5192 << VF << " For instruction: " << I << '\n');
5193 }
5194
5195 // If we are vectorizing a predicated block, it will have been
5196 // if-converted. This means that the block's instructions (aside from
5197 // stores and instructions that may divide by zero) will now be
5198 // unconditionally executed. For the scalar case, we may not always execute
5199 // the predicated block, if it is an if-else block. Thus, scale the block's
5200 // cost by the probability of executing it.
5201 // getPredBlockCostDivisor will return 1 for blocks that are only predicated
5202 // by the header mask when folding the tail.
5203 if (VF.isScalar())
5204 BlockCost /= getPredBlockCostDivisor(CostKind, BB);
5205
5206 Cost += BlockCost;
5207 }
5208
5209 return Cost;
5210}
5211
5212/// Gets the address access SCEV for Ptr, if it should be used for cost modeling
5213/// according to isAddressSCEVForCost.
5214///
5215/// This SCEV can be sent to the Target in order to estimate the address
5216/// calculation cost.
5218 Value *Ptr,
5220 const Loop *TheLoop) {
5221 const SCEV *Addr = PSE.getSCEV(Ptr);
5222 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), TheLoop) ? Addr
5223 : nullptr;
5224}
5225
5227LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
5228 ElementCount VF) {
5229 assert(VF.isVector() &&
5230 "Scalarization cost of instruction implies vectorization.");
5231 if (VF.isScalable())
5232 return InstructionCost::getInvalid();
5233
5234 Type *ValTy = getLoadStoreType(I);
5235 auto *SE = PSE.getSE();
5236
5237 unsigned AS = getLoadStoreAddressSpace(I);
5239 Type *PtrTy = toVectorTy(Ptr->getType(), VF);
5240 // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
5241 // that it is being called from this specific place.
5242
5243 // Figure out whether the access is strided and get the stride value
5244 // if it's known in compile time
5245 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, PSE, TheLoop);
5246
5247 // Get the cost of the scalar memory instruction and address computation.
5249 PtrTy, SE, PtrSCEV, CostKind);
5250
5251 // Don't pass *I here, since it is scalar but will actually be part of a
5252 // vectorized loop where the user of it is a vectorized instruction.
5253 const Align Alignment = getLoadStoreAlignment(I);
5254 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5255 Cost += VF.getFixedValue() *
5256 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
5257 AS, CostKind, OpInfo);
5258
5259 // Get the overhead of the extractelement and insertelement instructions
5260 // we might create due to scalarization.
5262
5263 // If we have a predicated load/store, it will need extra i1 extracts and
5264 // conditional branches, but may not be executed for each vector lane. Scale
5265 // the cost by the probability of executing the predicated block.
5266 if (isPredicatedInst(I)) {
5267 Cost /= getPredBlockCostDivisor(CostKind, I->getParent());
5268
5269 // Add the cost of an i1 extract and a branch
5270 auto *VecI1Ty =
5271 VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
5273 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
5274 /*Insert=*/false, /*Extract=*/true, CostKind);
5275 Cost += TTI.getCFInstrCost(Instruction::Br, CostKind);
5276
5277 if (useEmulatedMaskMemRefHack(I, VF))
5278 // Artificially setting to a high enough value to practically disable
5279 // vectorization with such operations.
5280 Cost = 3000000;
5281 }
5282
5283 return Cost;
5284}
5285
5287LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
5288 ElementCount VF) {
5289 Type *ValTy = getLoadStoreType(I);
5290 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5292 unsigned AS = getLoadStoreAddressSpace(I);
5293 int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
5294
5295 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5296 "Stride should be 1 or -1 for consecutive memory access");
5297 const Align Alignment = getLoadStoreAlignment(I);
5299 if (Legal->isMaskRequired(I)) {
5300 unsigned IID = I->getOpcode() == Instruction::Load
5301 ? Intrinsic::masked_load
5302 : Intrinsic::masked_store;
5304 MemIntrinsicCostAttributes(IID, VectorTy, Alignment, AS), CostKind);
5305 } else {
5306 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5307 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
5308 CostKind, OpInfo, I);
5309 }
5310
5311 bool Reverse = ConsecutiveStride < 0;
5312 if (Reverse)
5314 VectorTy, {}, CostKind, 0);
5315 return Cost;
5316}
5317
5319LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
5320 ElementCount VF) {
5321 assert(Legal->isUniformMemOp(*I, VF));
5322
5323 Type *ValTy = getLoadStoreType(I);
5325 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5326 const Align Alignment = getLoadStoreAlignment(I);
5327 unsigned AS = getLoadStoreAddressSpace(I);
5328 if (isa<LoadInst>(I)) {
5329 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5330 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
5331 CostKind) +
5333 VectorTy, {}, CostKind);
5334 }
5335 StoreInst *SI = cast<StoreInst>(I);
5336
5337 bool IsLoopInvariantStoreValue = Legal->isInvariant(SI->getValueOperand());
5338 // TODO: We have existing tests that request the cost of extracting element
5339 // VF.getKnownMinValue() - 1 from a scalable vector. This does not represent
5340 // the actual generated code, which involves extracting the last element of
5341 // a scalable vector where the lane to extract is unknown at compile time.
5343 TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5344 TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS, CostKind);
5345 if (!IsLoopInvariantStoreValue)
5346 Cost += TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
5347 VectorTy, CostKind, 0);
5348 return Cost;
5349}
5350
5352LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
5353 ElementCount VF) {
5354 Type *ValTy = getLoadStoreType(I);
5355 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5356 const Align Alignment = getLoadStoreAlignment(I);
5358 Type *PtrTy = Ptr->getType();
5359
5360 if (!Legal->isUniform(Ptr, VF))
5361 PtrTy = toVectorTy(PtrTy, VF);
5362
5363 unsigned IID = I->getOpcode() == Instruction::Load
5364 ? Intrinsic::masked_gather
5365 : Intrinsic::masked_scatter;
5366 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5368 MemIntrinsicCostAttributes(IID, VectorTy, Ptr,
5369 Legal->isMaskRequired(I), Alignment, I),
5370 CostKind);
5371}
5372
5374LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
5375 ElementCount VF) {
5376 const auto *Group = getInterleavedAccessGroup(I);
5377 assert(Group && "Fail to get an interleaved access group.");
5378
5379 Instruction *InsertPos = Group->getInsertPos();
5380 Type *ValTy = getLoadStoreType(InsertPos);
5381 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5382 unsigned AS = getLoadStoreAddressSpace(InsertPos);
5383
5384 unsigned InterleaveFactor = Group->getFactor();
5385 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5386
5387 // Holds the indices of existing members in the interleaved group.
5388 SmallVector<unsigned, 4> Indices;
5389 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5390 if (Group->getMember(IF))
5391 Indices.push_back(IF);
5392
5393 // Calculate the cost of the whole interleaved group.
5394 bool UseMaskForGaps =
5395 (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
5396 (isa<StoreInst>(I) && !Group->isFull());
5398 InsertPos->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5399 Group->getAlign(), AS, CostKind, Legal->isMaskRequired(I),
5400 UseMaskForGaps);
5401
5402 if (Group->isReverse()) {
5403 // TODO: Add support for reversed masked interleaved access.
5404 assert(!Legal->isMaskRequired(I) &&
5405 "Reverse masked interleaved access not supported.");
5406 Cost += Group->getNumMembers() *
5408 VectorTy, {}, CostKind, 0);
5409 }
5410 return Cost;
5411}
5412
5413std::optional<InstructionCost>
5415 ElementCount VF,
5416 Type *Ty) const {
5417 using namespace llvm::PatternMatch;
5418 // Early exit for no inloop reductions
5419 if (InLoopReductions.empty() || VF.isScalar() || !isa<VectorType>(Ty))
5420 return std::nullopt;
5421 auto *VectorTy = cast<VectorType>(Ty);
5422
5423 // We are looking for a pattern of, and finding the minimal acceptable cost:
5424 // reduce(mul(ext(A), ext(B))) or
5425 // reduce(mul(A, B)) or
5426 // reduce(ext(A)) or
5427 // reduce(A).
5428 // The basic idea is that we walk down the tree to do that, finding the root
5429 // reduction instruction in InLoopReductionImmediateChains. From there we find
5430 // the pattern of mul/ext and test the cost of the entire pattern vs the cost
5431 // of the components. If the reduction cost is lower then we return it for the
5432 // reduction instruction and 0 for the other instructions in the pattern. If
5433 // it is not we return an invalid cost specifying the orignal cost method
5434 // should be used.
5435 Instruction *RetI = I;
5436 if (match(RetI, m_ZExtOrSExt(m_Value()))) {
5437 if (!RetI->hasOneUser())
5438 return std::nullopt;
5439 RetI = RetI->user_back();
5440 }
5441
5442 if (match(RetI, m_OneUse(m_Mul(m_Value(), m_Value()))) &&
5443 RetI->user_back()->getOpcode() == Instruction::Add) {
5444 RetI = RetI->user_back();
5445 }
5446
5447 // Test if the found instruction is a reduction, and if not return an invalid
5448 // cost specifying the parent to use the original cost modelling.
5449 Instruction *LastChain = InLoopReductionImmediateChains.lookup(RetI);
5450 if (!LastChain)
5451 return std::nullopt;
5452
5453 // Find the reduction this chain is a part of and calculate the basic cost of
5454 // the reduction on its own.
5455 Instruction *ReductionPhi = LastChain;
5456 while (!isa<PHINode>(ReductionPhi))
5457 ReductionPhi = InLoopReductionImmediateChains.at(ReductionPhi);
5458
5459 const RecurrenceDescriptor &RdxDesc =
5460 Legal->getRecurrenceDescriptor(cast<PHINode>(ReductionPhi));
5461
5462 InstructionCost BaseCost;
5463 RecurKind RK = RdxDesc.getRecurrenceKind();
5466 BaseCost = TTI.getMinMaxReductionCost(MinMaxID, VectorTy,
5467 RdxDesc.getFastMathFlags(), CostKind);
5468 } else {
5469 BaseCost = TTI.getArithmeticReductionCost(
5470 RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
5471 }
5472
5473 // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
5474 // normal fmul instruction to the cost of the fadd reduction.
5475 if (RK == RecurKind::FMulAdd)
5476 BaseCost +=
5477 TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
5478
5479 // If we're using ordered reductions then we can just return the base cost
5480 // here, since getArithmeticReductionCost calculates the full ordered
5481 // reduction cost when FP reassociation is not allowed.
5482 if (useOrderedReductions(RdxDesc))
5483 return BaseCost;
5484
5485 // Get the operand that was not the reduction chain and match it to one of the
5486 // patterns, returning the better cost if it is found.
5487 Instruction *RedOp = RetI->getOperand(1) == LastChain
5490
5491 VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
5492
5493 Instruction *Op0, *Op1;
5494 if (RedOp && RdxDesc.getOpcode() == Instruction::Add &&
5495 match(RedOp,
5497 match(Op0, m_ZExtOrSExt(m_Value())) &&
5498 Op0->getOpcode() == Op1->getOpcode() &&
5499 Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
5500 !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
5501 (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
5502
5503 // Matched reduce.add(ext(mul(ext(A), ext(B)))
5504 // Note that the extend opcodes need to all match, or if A==B they will have
5505 // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
5506 // which is equally fine.
5507 bool IsUnsigned = isa<ZExtInst>(Op0);
5508 auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
5509 auto *MulType = VectorType::get(Op0->getType(), VectorTy);
5510
5511 InstructionCost ExtCost =
5512 TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
5514 InstructionCost MulCost =
5515 TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
5516 InstructionCost Ext2Cost =
5517 TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
5519
5520 InstructionCost RedCost = TTI.getMulAccReductionCost(
5521 IsUnsigned, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), ExtType,
5522 CostKind);
5523
5524 if (RedCost.isValid() &&
5525 RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
5526 return I == RetI ? RedCost : 0;
5527 } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
5528 !TheLoop->isLoopInvariant(RedOp)) {
5529 // Matched reduce(ext(A))
5530 bool IsUnsigned = isa<ZExtInst>(RedOp);
5531 auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
5532 InstructionCost RedCost = TTI.getExtendedReductionCost(
5533 RdxDesc.getOpcode(), IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
5534 RdxDesc.getFastMathFlags(), CostKind);
5535
5536 InstructionCost ExtCost =
5537 TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
5539 if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
5540 return I == RetI ? RedCost : 0;
5541 } else if (RedOp && RdxDesc.getOpcode() == Instruction::Add &&
5542 match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
5543 if (match(Op0, m_ZExtOrSExt(m_Value())) &&
5544 Op0->getOpcode() == Op1->getOpcode() &&
5545 !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
5546 bool IsUnsigned = isa<ZExtInst>(Op0);
5547 Type *Op0Ty = Op0->getOperand(0)->getType();
5548 Type *Op1Ty = Op1->getOperand(0)->getType();
5549 Type *LargestOpTy =
5550 Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
5551 : Op0Ty;
5552 auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
5553
5554 // Matched reduce.add(mul(ext(A), ext(B))), where the two ext may be of
5555 // different sizes. We take the largest type as the ext to reduce, and add
5556 // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
5557 InstructionCost ExtCost0 = TTI.getCastInstrCost(
5558 Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
5560 InstructionCost ExtCost1 = TTI.getCastInstrCost(
5561 Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
5563 InstructionCost MulCost =
5564 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
5565
5566 InstructionCost RedCost = TTI.getMulAccReductionCost(
5567 IsUnsigned, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), ExtType,
5568 CostKind);
5569 InstructionCost ExtraExtCost = 0;
5570 if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
5571 Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
5572 ExtraExtCost = TTI.getCastInstrCost(
5573 ExtraExtOp->getOpcode(), ExtType,
5574 VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
5576 }
5577
5578 if (RedCost.isValid() &&
5579 (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
5580 return I == RetI ? RedCost : 0;
5581 } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
5582 // Matched reduce.add(mul())
5583 InstructionCost MulCost =
5584 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
5585
5586 InstructionCost RedCost = TTI.getMulAccReductionCost(
5587 true, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), VectorTy,
5588 CostKind);
5589
5590 if (RedCost.isValid() && RedCost < MulCost + BaseCost)
5591 return I == RetI ? RedCost : 0;
5592 }
5593 }
5594
5595 return I == RetI ? std::optional<InstructionCost>(BaseCost) : std::nullopt;
5596}
5597
5599LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
5600 ElementCount VF) {
5601 // Calculate scalar cost only. Vectorization cost should be ready at this
5602 // moment.
5603 if (VF.isScalar()) {
5604 Type *ValTy = getLoadStoreType(I);
5606 const Align Alignment = getLoadStoreAlignment(I);
5607 unsigned AS = getLoadStoreAddressSpace(I);
5608
5609 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5610 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5611 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, CostKind,
5612 OpInfo, I);
5613 }
5614 return getWideningCost(I, VF);
5615}
5616
5618LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
5619 ElementCount VF) const {
5620
5621 // There is no mechanism yet to create a scalable scalarization loop,
5622 // so this is currently Invalid.
5623 if (VF.isScalable())
5624 return InstructionCost::getInvalid();
5625
5626 if (VF.isScalar())
5627 return 0;
5628
5630 Type *RetTy = toVectorizedTy(I->getType(), VF);
5631 if (!RetTy->isVoidTy() &&
5633
5634 for (Type *VectorTy : getContainedTypes(RetTy)) {
5637 /*Insert=*/true,
5638 /*Extract=*/false, CostKind);
5639 }
5640 }
5641
5642 // Some targets keep addresses scalar.
5644 return Cost;
5645
5646 // Some targets support efficient element stores.
5648 return Cost;
5649
5650 // Collect operands to consider.
5651 CallInst *CI = dyn_cast<CallInst>(I);
5652 Instruction::op_range Ops = CI ? CI->args() : I->operands();
5653
5654 // Skip operands that do not require extraction/scalarization and do not incur
5655 // any overhead.
5657 for (auto *V : filterExtractingOperands(Ops, VF))
5658 Tys.push_back(maybeVectorizeType(V->getType(), VF));
5660}
5661
5663 if (VF.isScalar())
5664 return;
5665 NumPredStores = 0;
5666 for (BasicBlock *BB : TheLoop->blocks()) {
5667 // For each instruction in the old loop.
5668 for (Instruction &I : *BB) {
5670 if (!Ptr)
5671 continue;
5672
5673 // TODO: We should generate better code and update the cost model for
5674 // predicated uniform stores. Today they are treated as any other
5675 // predicated store (see added test cases in
5676 // invariant-store-vectorization.ll).
5678 NumPredStores++;
5679
5680 if (Legal->isUniformMemOp(I, VF)) {
5681 auto IsLegalToScalarize = [&]() {
5682 if (!VF.isScalable())
5683 // Scalarization of fixed length vectors "just works".
5684 return true;
5685
5686 // We have dedicated lowering for unpredicated uniform loads and
5687 // stores. Note that even with tail folding we know that at least
5688 // one lane is active (i.e. generalized predication is not possible
5689 // here), and the logic below depends on this fact.
5690 if (!foldTailByMasking())
5691 return true;
5692
5693 // For scalable vectors, a uniform memop load is always
5694 // uniform-by-parts and we know how to scalarize that.
5695 if (isa<LoadInst>(I))
5696 return true;
5697
5698 // A uniform store isn't neccessarily uniform-by-part
5699 // and we can't assume scalarization.
5700 auto &SI = cast<StoreInst>(I);
5701 return TheLoop->isLoopInvariant(SI.getValueOperand());
5702 };
5703
5704 const InstructionCost GatherScatterCost =
5706 getGatherScatterCost(&I, VF) : InstructionCost::getInvalid();
5707
5708 // Load: Scalar load + broadcast
5709 // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
5710 // FIXME: This cost is a significant under-estimate for tail folded
5711 // memory ops.
5712 const InstructionCost ScalarizationCost =
5713 IsLegalToScalarize() ? getUniformMemOpCost(&I, VF)
5715
5716 // Choose better solution for the current VF, Note that Invalid
5717 // costs compare as maximumal large. If both are invalid, we get
5718 // scalable invalid which signals a failure and a vectorization abort.
5719 if (GatherScatterCost < ScalarizationCost)
5720 setWideningDecision(&I, VF, CM_GatherScatter, GatherScatterCost);
5721 else
5722 setWideningDecision(&I, VF, CM_Scalarize, ScalarizationCost);
5723 continue;
5724 }
5725
5726 // We assume that widening is the best solution when possible.
5727 if (memoryInstructionCanBeWidened(&I, VF)) {
5728 InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
5729 int ConsecutiveStride = Legal->isConsecutivePtr(
5731 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5732 "Expected consecutive stride.");
5733 InstWidening Decision =
5734 ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
5735 setWideningDecision(&I, VF, Decision, Cost);
5736 continue;
5737 }
5738
5739 // Choose between Interleaving, Gather/Scatter or Scalarization.
5741 unsigned NumAccesses = 1;
5742 if (isAccessInterleaved(&I)) {
5743 const auto *Group = getInterleavedAccessGroup(&I);
5744 assert(Group && "Fail to get an interleaved access group.");
5745
5746 // Make one decision for the whole group.
5747 if (getWideningDecision(&I, VF) != CM_Unknown)
5748 continue;
5749
5750 NumAccesses = Group->getNumMembers();
5752 InterleaveCost = getInterleaveGroupCost(&I, VF);
5753 }
5754
5755 InstructionCost GatherScatterCost =
5757 ? getGatherScatterCost(&I, VF) * NumAccesses
5759
5760 InstructionCost ScalarizationCost =
5761 getMemInstScalarizationCost(&I, VF) * NumAccesses;
5762
5763 // Choose better solution for the current VF,
5764 // write down this decision and use it during vectorization.
5766 InstWidening Decision;
5767 if (InterleaveCost <= GatherScatterCost &&
5768 InterleaveCost < ScalarizationCost) {
5769 Decision = CM_Interleave;
5770 Cost = InterleaveCost;
5771 } else if (GatherScatterCost < ScalarizationCost) {
5772 Decision = CM_GatherScatter;
5773 Cost = GatherScatterCost;
5774 } else {
5775 Decision = CM_Scalarize;
5776 Cost = ScalarizationCost;
5777 }
5778 // If the instructions belongs to an interleave group, the whole group
5779 // receives the same decision. The whole group receives the cost, but
5780 // the cost will actually be assigned to one instruction.
5781 if (const auto *Group = getInterleavedAccessGroup(&I)) {
5782 if (Decision == CM_Scalarize) {
5783 for (unsigned Idx = 0; Idx < Group->getFactor(); ++Idx) {
5784 if (auto *I = Group->getMember(Idx)) {
5785 setWideningDecision(I, VF, Decision,
5786 getMemInstScalarizationCost(I, VF));
5787 }
5788 }
5789 } else {
5790 setWideningDecision(Group, VF, Decision, Cost);
5791 }
5792 } else
5793 setWideningDecision(&I, VF, Decision, Cost);
5794 }
5795 }
5796
5797 // Make sure that any load of address and any other address computation
5798 // remains scalar unless there is gather/scatter support. This avoids
5799 // inevitable extracts into address registers, and also has the benefit of
5800 // activating LSR more, since that pass can't optimize vectorized
5801 // addresses.
5802 if (TTI.prefersVectorizedAddressing())
5803 return;
5804
5805 // Start with all scalar pointer uses.
5807 for (BasicBlock *BB : TheLoop->blocks())
5808 for (Instruction &I : *BB) {
5809 Instruction *PtrDef =
5811 if (PtrDef && TheLoop->contains(PtrDef) &&
5813 AddrDefs.insert(PtrDef);
5814 }
5815
5816 // Add all instructions used to generate the addresses.
5818 append_range(Worklist, AddrDefs);
5819 while (!Worklist.empty()) {
5820 Instruction *I = Worklist.pop_back_val();
5821 for (auto &Op : I->operands())
5822 if (auto *InstOp = dyn_cast<Instruction>(Op))
5823 if (TheLoop->contains(InstOp) && !isa<PHINode>(InstOp) &&
5824 AddrDefs.insert(InstOp).second)
5825 Worklist.push_back(InstOp);
5826 }
5827
5828 auto UpdateMemOpUserCost = [this, VF](LoadInst *LI) {
5829 // If there are direct memory op users of the newly scalarized load,
5830 // their cost may have changed because there's no scalarization
5831 // overhead for the operand. Update it.
5832 for (User *U : LI->users()) {
5834 continue;
5836 continue;
5839 getMemInstScalarizationCost(cast<Instruction>(U), VF));
5840 }
5841 };
5842 for (auto *I : AddrDefs) {
5843 if (isa<LoadInst>(I)) {
5844 // Setting the desired widening decision should ideally be handled in
5845 // by cost functions, but since this involves the task of finding out
5846 // if the loaded register is involved in an address computation, it is
5847 // instead changed here when we know this is the case.
5848 InstWidening Decision = getWideningDecision(I, VF);
5849 if (Decision == CM_Widen || Decision == CM_Widen_Reverse ||
5850 (!isPredicatedInst(I) && !Legal->isUniformMemOp(*I, VF) &&
5851 Decision == CM_Scalarize)) {
5852 // Scalarize a widened load of address or update the cost of a scalar
5853 // load of an address.
5855 I, VF, CM_Scalarize,
5856 (VF.getKnownMinValue() *
5857 getMemoryInstructionCost(I, ElementCount::getFixed(1))));
5858 UpdateMemOpUserCost(cast<LoadInst>(I));
5859 } else if (const auto *Group = getInterleavedAccessGroup(I)) {
5860 // Scalarize all members of this interleaved group when any member
5861 // is used as an address. The address-used load skips scalarization
5862 // overhead, other members include it.
5863 for (unsigned Idx = 0; Idx < Group->getFactor(); ++Idx) {
5864 if (Instruction *Member = Group->getMember(Idx)) {
5866 AddrDefs.contains(Member)
5867 ? (VF.getKnownMinValue() *
5868 getMemoryInstructionCost(Member,
5870 : getMemInstScalarizationCost(Member, VF);
5872 UpdateMemOpUserCost(cast<LoadInst>(Member));
5873 }
5874 }
5875 }
5876 } else {
5877 // Cannot scalarize fixed-order recurrence phis at the moment.
5878 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
5879 continue;
5880
5881 // Make sure I gets scalarized and a cost estimate without
5882 // scalarization overhead.
5883 ForcedScalars[VF].insert(I);
5884 }
5885 }
5886}
5887
5889 assert(!VF.isScalar() &&
5890 "Trying to set a vectorization decision for a scalar VF");
5891
5892 auto ForcedScalar = ForcedScalars.find(VF);
5893 for (BasicBlock *BB : TheLoop->blocks()) {
5894 // For each instruction in the old loop.
5895 for (Instruction &I : *BB) {
5897
5898 if (!CI)
5899 continue;
5900
5904 Function *ScalarFunc = CI->getCalledFunction();
5905 Type *ScalarRetTy = CI->getType();
5906 SmallVector<Type *, 4> Tys, ScalarTys;
5907 for (auto &ArgOp : CI->args())
5908 ScalarTys.push_back(ArgOp->getType());
5909
5910 // Estimate cost of scalarized vector call. The source operands are
5911 // assumed to be vectors, so we need to extract individual elements from
5912 // there, execute VF scalar calls, and then gather the result into the
5913 // vector return value.
5914 if (VF.isFixed()) {
5915 InstructionCost ScalarCallCost =
5916 TTI.getCallInstrCost(ScalarFunc, ScalarRetTy, ScalarTys, CostKind);
5917
5918 // Compute costs of unpacking argument values for the scalar calls and
5919 // packing the return values to a vector.
5920 InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
5921 ScalarCost = ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
5922 } else {
5923 // There is no point attempting to calculate the scalar cost for a
5924 // scalable VF as we know it will be Invalid.
5926 "Unexpected valid cost for scalarizing scalable vectors");
5927 ScalarCost = InstructionCost::getInvalid();
5928 }
5929
5930 // Honor ForcedScalars and UniformAfterVectorization decisions.
5931 // TODO: For calls, it might still be more profitable to widen. Use
5932 // VPlan-based cost model to compare different options.
5933 if (VF.isVector() && ((ForcedScalar != ForcedScalars.end() &&
5934 ForcedScalar->second.contains(CI)) ||
5935 isUniformAfterVectorization(CI, VF))) {
5936 setCallWideningDecision(CI, VF, CM_Scalarize, nullptr,
5937 Intrinsic::not_intrinsic, std::nullopt,
5938 ScalarCost);
5939 continue;
5940 }
5941
5942 bool MaskRequired = Legal->isMaskRequired(CI);
5943 // Compute corresponding vector type for return value and arguments.
5944 Type *RetTy = toVectorizedTy(ScalarRetTy, VF);
5945 for (Type *ScalarTy : ScalarTys)
5946 Tys.push_back(toVectorizedTy(ScalarTy, VF));
5947
5948 // An in-loop reduction using an fmuladd intrinsic is a special case;
5949 // we don't want the normal cost for that intrinsic.
5951 if (auto RedCost = getReductionPatternCost(CI, VF, RetTy)) {
5954 std::nullopt, *RedCost);
5955 continue;
5956 }
5957
5958 // Find the cost of vectorizing the call, if we can find a suitable
5959 // vector variant of the function.
5960 VFInfo FuncInfo;
5961 Function *VecFunc = nullptr;
5962 // Search through any available variants for one we can use at this VF.
5963 for (VFInfo &Info : VFDatabase::getMappings(*CI)) {
5964 // Must match requested VF.
5965 if (Info.Shape.VF != VF)
5966 continue;
5967
5968 // Must take a mask argument if one is required
5969 if (MaskRequired && !Info.isMasked())
5970 continue;
5971
5972 // Check that all parameter kinds are supported
5973 bool ParamsOk = true;
5974 for (VFParameter Param : Info.Shape.Parameters) {
5975 switch (Param.ParamKind) {
5977 break;
5979 Value *ScalarParam = CI->getArgOperand(Param.ParamPos);
5980 // Make sure the scalar parameter in the loop is invariant.
5981 if (!PSE.getSE()->isLoopInvariant(PSE.getSCEV(ScalarParam),
5982 TheLoop))
5983 ParamsOk = false;
5984 break;
5985 }
5987 Value *ScalarParam = CI->getArgOperand(Param.ParamPos);
5988 // Find the stride for the scalar parameter in this loop and see if
5989 // it matches the stride for the variant.
5990 // TODO: do we need to figure out the cost of an extract to get the
5991 // first lane? Or do we hope that it will be folded away?
5992 ScalarEvolution *SE = PSE.getSE();
5993 if (!match(SE->getSCEV(ScalarParam),
5995 m_SCEV(), m_scev_SpecificSInt(Param.LinearStepOrPos),
5997 ParamsOk = false;
5998 break;
5999 }
6001 break;
6002 default:
6003 ParamsOk = false;
6004 break;
6005 }
6006 }
6007
6008 if (!ParamsOk)
6009 continue;
6010
6011 // Found a suitable candidate, stop here.
6012 VecFunc = CI->getModule()->getFunction(Info.VectorName);
6013 FuncInfo = Info;
6014 break;
6015 }
6016
6017 if (TLI && VecFunc && !CI->isNoBuiltin())
6018 VectorCost = TTI.getCallInstrCost(nullptr, RetTy, Tys, CostKind);
6019
6020 // Find the cost of an intrinsic; some targets may have instructions that
6021 // perform the operation without needing an actual call.
6023 if (IID != Intrinsic::not_intrinsic)
6025
6026 InstructionCost Cost = ScalarCost;
6027 InstWidening Decision = CM_Scalarize;
6028
6029 if (VectorCost.isValid() && VectorCost <= Cost) {
6030 Cost = VectorCost;
6031 Decision = CM_VectorCall;
6032 }
6033
6034 if (IntrinsicCost.isValid() && IntrinsicCost <= Cost) {
6036 Decision = CM_IntrinsicCall;
6037 }
6038
6039 setCallWideningDecision(CI, VF, Decision, VecFunc, IID,
6041 }
6042 }
6043}
6044
6046 if (!Legal->isInvariant(Op))
6047 return false;
6048 // Consider Op invariant, if it or its operands aren't predicated
6049 // instruction in the loop. In that case, it is not trivially hoistable.
6050 auto *OpI = dyn_cast<Instruction>(Op);
6051 return !OpI || !TheLoop->contains(OpI) ||
6052 (!isPredicatedInst(OpI) &&
6053 (!isa<PHINode>(OpI) || OpI->getParent() != TheLoop->getHeader()) &&
6054 all_of(OpI->operands(),
6055 [this](Value *Op) { return shouldConsiderInvariant(Op); }));
6056}
6057
6060 ElementCount VF) {
6061 // If we know that this instruction will remain uniform, check the cost of
6062 // the scalar version.
6064 VF = ElementCount::getFixed(1);
6065
6066 if (VF.isVector() && isProfitableToScalarize(I, VF))
6067 return InstsToScalarize[VF][I];
6068
6069 // Forced scalars do not have any scalarization overhead.
6070 auto ForcedScalar = ForcedScalars.find(VF);
6071 if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6072 auto InstSet = ForcedScalar->second;
6073 if (InstSet.count(I))
6075 VF.getKnownMinValue();
6076 }
6077
6078 Type *RetTy = I->getType();
6080 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6081 auto *SE = PSE.getSE();
6082
6083 Type *VectorTy;
6084 if (isScalarAfterVectorization(I, VF)) {
6085 [[maybe_unused]] auto HasSingleCopyAfterVectorization =
6086 [this](Instruction *I, ElementCount VF) -> bool {
6087 if (VF.isScalar())
6088 return true;
6089
6090 auto Scalarized = InstsToScalarize.find(VF);
6091 assert(Scalarized != InstsToScalarize.end() &&
6092 "VF not yet analyzed for scalarization profitability");
6093 return !Scalarized->second.count(I) &&
6094 llvm::all_of(I->users(), [&](User *U) {
6095 auto *UI = cast<Instruction>(U);
6096 return !Scalarized->second.count(UI);
6097 });
6098 };
6099
6100 // With the exception of GEPs and PHIs, after scalarization there should
6101 // only be one copy of the instruction generated in the loop. This is
6102 // because the VF is either 1, or any instructions that need scalarizing
6103 // have already been dealt with by the time we get here. As a result,
6104 // it means we don't have to multiply the instruction cost by VF.
6105 assert(I->getOpcode() == Instruction::GetElementPtr ||
6106 I->getOpcode() == Instruction::PHI ||
6107 (I->getOpcode() == Instruction::BitCast &&
6108 I->getType()->isPointerTy()) ||
6109 HasSingleCopyAfterVectorization(I, VF));
6110 VectorTy = RetTy;
6111 } else
6112 VectorTy = toVectorizedTy(RetTy, VF);
6113
6114 if (VF.isVector() && VectorTy->isVectorTy() &&
6115 !TTI.getNumberOfParts(VectorTy))
6117
6118 // TODO: We need to estimate the cost of intrinsic calls.
6119 switch (I->getOpcode()) {
6120 case Instruction::GetElementPtr:
6121 // We mark this instruction as zero-cost because the cost of GEPs in
6122 // vectorized code depends on whether the corresponding memory instruction
6123 // is scalarized or not. Therefore, we handle GEPs with the memory
6124 // instruction cost.
6125 return 0;
6126 case Instruction::Br: {
6127 // In cases of scalarized and predicated instructions, there will be VF
6128 // predicated blocks in the vectorized loop. Each branch around these
6129 // blocks requires also an extract of its vector compare i1 element.
6130 // Note that the conditional branch from the loop latch will be replaced by
6131 // a single branch controlling the loop, so there is no extra overhead from
6132 // scalarization.
6133 bool ScalarPredicatedBB = false;
6135 if (VF.isVector() && BI->isConditional() &&
6136 (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
6137 PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))) &&
6138 BI->getParent() != TheLoop->getLoopLatch())
6139 ScalarPredicatedBB = true;
6140
6141 if (ScalarPredicatedBB) {
6142 // Not possible to scalarize scalable vector with predicated instructions.
6143 if (VF.isScalable())
6145 // Return cost for branches around scalarized and predicated blocks.
6146 auto *VecI1Ty =
6148 return (
6149 TTI.getScalarizationOverhead(
6150 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
6151 /*Insert*/ false, /*Extract*/ true, CostKind) +
6152 (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
6153 }
6154
6155 if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
6156 // The back-edge branch will remain, as will all scalar branches.
6157 return TTI.getCFInstrCost(Instruction::Br, CostKind);
6158
6159 // This branch will be eliminated by if-conversion.
6160 return 0;
6161 // Note: We currently assume zero cost for an unconditional branch inside
6162 // a predicated block since it will become a fall-through, although we
6163 // may decide in the future to call TTI for all branches.
6164 }
6165 case Instruction::Switch: {
6166 if (VF.isScalar())
6167 return TTI.getCFInstrCost(Instruction::Switch, CostKind);
6168 auto *Switch = cast<SwitchInst>(I);
6169 return Switch->getNumCases() *
6170 TTI.getCmpSelInstrCost(
6171 Instruction::ICmp,
6172 toVectorTy(Switch->getCondition()->getType(), VF),
6173 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
6175 }
6176 case Instruction::PHI: {
6177 auto *Phi = cast<PHINode>(I);
6178
6179 // First-order recurrences are replaced by vector shuffles inside the loop.
6180 if (VF.isVector() && Legal->isFixedOrderRecurrence(Phi)) {
6182 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
6183 return TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
6184 cast<VectorType>(VectorTy),
6185 cast<VectorType>(VectorTy), Mask, CostKind,
6186 VF.getKnownMinValue() - 1);
6187 }
6188
6189 // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
6190 // converted into select instructions. We require N - 1 selects per phi
6191 // node, where N is the number of incoming values.
6192 if (VF.isVector() && Phi->getParent() != TheLoop->getHeader()) {
6193 Type *ResultTy = Phi->getType();
6194
6195 // All instructions in an Any-of reduction chain are narrowed to bool.
6196 // Check if that is the case for this phi node.
6197 auto *HeaderUser = cast_if_present<PHINode>(
6198 find_singleton<User>(Phi->users(), [this](User *U, bool) -> User * {
6199 auto *Phi = dyn_cast<PHINode>(U);
6200 if (Phi && Phi->getParent() == TheLoop->getHeader())
6201 return Phi;
6202 return nullptr;
6203 }));
6204 if (HeaderUser) {
6205 auto &ReductionVars = Legal->getReductionVars();
6206 auto Iter = ReductionVars.find(HeaderUser);
6207 if (Iter != ReductionVars.end() &&
6209 Iter->second.getRecurrenceKind()))
6210 ResultTy = Type::getInt1Ty(Phi->getContext());
6211 }
6212 return (Phi->getNumIncomingValues() - 1) *
6213 TTI.getCmpSelInstrCost(
6214 Instruction::Select, toVectorTy(ResultTy, VF),
6215 toVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
6217 }
6218
6219 // When tail folding with EVL, if the phi is part of an out of loop
6220 // reduction then it will be transformed into a wide vp_merge.
6221 if (VF.isVector() && foldTailWithEVL() &&
6222 Legal->getReductionVars().contains(Phi) && !isInLoopReduction(Phi)) {
6224 Intrinsic::vp_merge, toVectorTy(Phi->getType(), VF),
6225 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
6226 return TTI.getIntrinsicInstrCost(ICA, CostKind);
6227 }
6228
6229 return TTI.getCFInstrCost(Instruction::PHI, CostKind);
6230 }
6231 case Instruction::UDiv:
6232 case Instruction::SDiv:
6233 case Instruction::URem:
6234 case Instruction::SRem:
6235 if (VF.isVector() && isPredicatedInst(I)) {
6236 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
6237 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost) ?
6238 ScalarCost : SafeDivisorCost;
6239 }
6240 // We've proven all lanes safe to speculate, fall through.
6241 [[fallthrough]];
6242 case Instruction::Add:
6243 case Instruction::Sub: {
6244 auto Info = Legal->getHistogramInfo(I);
6245 if (Info && VF.isVector()) {
6246 const HistogramInfo *HGram = Info.value();
6247 // Assume that a non-constant update value (or a constant != 1) requires
6248 // a multiply, and add that into the cost.
6250 ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1));
6251 if (!RHS || RHS->getZExtValue() != 1)
6252 MulCost =
6253 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6254
6255 // Find the cost of the histogram operation itself.
6256 Type *PtrTy = VectorType::get(HGram->Load->getPointerOperandType(), VF);
6257 Type *ScalarTy = I->getType();
6258 Type *MaskTy = VectorType::get(Type::getInt1Ty(I->getContext()), VF);
6259 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
6260 Type::getVoidTy(I->getContext()),
6261 {PtrTy, ScalarTy, MaskTy});
6262
6263 // Add the costs together with the add/sub operation.
6264 return TTI.getIntrinsicInstrCost(ICA, CostKind) + MulCost +
6265 TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, CostKind);
6266 }
6267 [[fallthrough]];
6268 }
6269 case Instruction::FAdd:
6270 case Instruction::FSub:
6271 case Instruction::Mul:
6272 case Instruction::FMul:
6273 case Instruction::FDiv:
6274 case Instruction::FRem:
6275 case Instruction::Shl:
6276 case Instruction::LShr:
6277 case Instruction::AShr:
6278 case Instruction::And:
6279 case Instruction::Or:
6280 case Instruction::Xor: {
6281 // If we're speculating on the stride being 1, the multiplication may
6282 // fold away. We can generalize this for all operations using the notion
6283 // of neutral elements. (TODO)
6284 if (I->getOpcode() == Instruction::Mul &&
6285 ((TheLoop->isLoopInvariant(I->getOperand(0)) &&
6286 PSE.getSCEV(I->getOperand(0))->isOne()) ||
6287 (TheLoop->isLoopInvariant(I->getOperand(1)) &&
6288 PSE.getSCEV(I->getOperand(1))->isOne())))
6289 return 0;
6290
6291 // Detect reduction patterns
6292 if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
6293 return *RedCost;
6294
6295 // Certain instructions can be cheaper to vectorize if they have a constant
6296 // second vector operand. One example of this are shifts on x86.
6297 Value *Op2 = I->getOperand(1);
6298 if (!isa<Constant>(Op2) && TheLoop->isLoopInvariant(Op2) &&
6299 PSE.getSE()->isSCEVable(Op2->getType()) &&
6300 isa<SCEVConstant>(PSE.getSCEV(Op2))) {
6301 Op2 = cast<SCEVConstant>(PSE.getSCEV(Op2))->getValue();
6302 }
6303 auto Op2Info = TTI.getOperandInfo(Op2);
6304 if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue &&
6307
6308 SmallVector<const Value *, 4> Operands(I->operand_values());
6309 return TTI.getArithmeticInstrCost(
6310 I->getOpcode(), VectorTy, CostKind,
6311 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6312 Op2Info, Operands, I, TLI);
6313 }
6314 case Instruction::FNeg: {
6315 return TTI.getArithmeticInstrCost(
6316 I->getOpcode(), VectorTy, CostKind,
6317 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6318 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6319 I->getOperand(0), I);
6320 }
6321 case Instruction::Select: {
6323 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
6324 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6325
6326 const Value *Op0, *Op1;
6327 using namespace llvm::PatternMatch;
6328 if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
6329 match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
6330 // select x, y, false --> x & y
6331 // select x, true, y --> x | y
6332 const auto [Op1VK, Op1VP] = TTI::getOperandInfo(Op0);
6333 const auto [Op2VK, Op2VP] = TTI::getOperandInfo(Op1);
6334 assert(Op0->getType()->getScalarSizeInBits() == 1 &&
6335 Op1->getType()->getScalarSizeInBits() == 1);
6336
6337 return TTI.getArithmeticInstrCost(
6338 match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And,
6339 VectorTy, CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, {Op0, Op1}, I);
6340 }
6341
6342 Type *CondTy = SI->getCondition()->getType();
6343 if (!ScalarCond)
6344 CondTy = VectorType::get(CondTy, VF);
6345
6347 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
6348 Pred = Cmp->getPredicate();
6349 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
6350 CostKind, {TTI::OK_AnyValue, TTI::OP_None},
6351 {TTI::OK_AnyValue, TTI::OP_None}, I);
6352 }
6353 case Instruction::ICmp:
6354 case Instruction::FCmp: {
6355 Type *ValTy = I->getOperand(0)->getType();
6356
6358 [[maybe_unused]] Instruction *Op0AsInstruction =
6359 dyn_cast<Instruction>(I->getOperand(0));
6360 assert((!canTruncateToMinimalBitwidth(Op0AsInstruction, VF) ||
6361 MinBWs[I] == MinBWs[Op0AsInstruction]) &&
6362 "if both the operand and the compare are marked for "
6363 "truncation, they must have the same bitwidth");
6364 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[I]);
6365 }
6366
6367 VectorTy = toVectorTy(ValTy, VF);
6368 return TTI.getCmpSelInstrCost(
6369 I->getOpcode(), VectorTy, CmpInst::makeCmpResultType(VectorTy),
6370 cast<CmpInst>(I)->getPredicate(), CostKind,
6371 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
6372 }
6373 case Instruction::Store:
6374 case Instruction::Load: {
6375 ElementCount Width = VF;
6376 if (Width.isVector()) {
6377 InstWidening Decision = getWideningDecision(I, Width);
6378 assert(Decision != CM_Unknown &&
6379 "CM decision should be taken at this point");
6382 if (Decision == CM_Scalarize)
6383 Width = ElementCount::getFixed(1);
6384 }
6385 VectorTy = toVectorTy(getLoadStoreType(I), Width);
6386 return getMemoryInstructionCost(I, VF);
6387 }
6388 case Instruction::BitCast:
6389 if (I->getType()->isPointerTy())
6390 return 0;
6391 [[fallthrough]];
6392 case Instruction::ZExt:
6393 case Instruction::SExt:
6394 case Instruction::FPToUI:
6395 case Instruction::FPToSI:
6396 case Instruction::FPExt:
6397 case Instruction::PtrToInt:
6398 case Instruction::IntToPtr:
6399 case Instruction::SIToFP:
6400 case Instruction::UIToFP:
6401 case Instruction::Trunc:
6402 case Instruction::FPTrunc: {
6403 // Computes the CastContextHint from a Load/Store instruction.
6404 auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
6406 "Expected a load or a store!");
6407
6408 if (VF.isScalar() || !TheLoop->contains(I))
6410
6411 switch (getWideningDecision(I, VF)) {
6423 llvm_unreachable("Instr did not go through cost modelling?");
6426 llvm_unreachable_internal("Instr has invalid widening decision");
6427 }
6428
6429 llvm_unreachable("Unhandled case!");
6430 };
6431
6432 unsigned Opcode = I->getOpcode();
6434 // For Trunc, the context is the only user, which must be a StoreInst.
6435 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
6436 if (I->hasOneUse())
6437 if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
6438 CCH = ComputeCCH(Store);
6439 }
6440 // For Z/Sext, the context is the operand, which must be a LoadInst.
6441 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
6442 Opcode == Instruction::FPExt) {
6443 if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
6444 CCH = ComputeCCH(Load);
6445 }
6446
6447 // We optimize the truncation of induction variables having constant
6448 // integer steps. The cost of these truncations is the same as the scalar
6449 // operation.
6450 if (isOptimizableIVTruncate(I, VF)) {
6451 auto *Trunc = cast<TruncInst>(I);
6452 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
6453 Trunc->getSrcTy(), CCH, CostKind, Trunc);
6454 }
6455
6456 // Detect reduction patterns
6457 if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
6458 return *RedCost;
6459
6460 Type *SrcScalarTy = I->getOperand(0)->getType();
6461 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
6462 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
6463 SrcScalarTy =
6464 IntegerType::get(SrcScalarTy->getContext(), MinBWs[Op0AsInstruction]);
6465 Type *SrcVecTy =
6466 VectorTy->isVectorTy() ? toVectorTy(SrcScalarTy, VF) : SrcScalarTy;
6467
6469 // If the result type is <= the source type, there will be no extend
6470 // after truncating the users to the minimal required bitwidth.
6471 if (VectorTy->getScalarSizeInBits() <= SrcVecTy->getScalarSizeInBits() &&
6472 (I->getOpcode() == Instruction::ZExt ||
6473 I->getOpcode() == Instruction::SExt))
6474 return 0;
6475 }
6476
6477 return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
6478 }
6479 case Instruction::Call:
6480 return getVectorCallCost(cast<CallInst>(I), VF);
6481 case Instruction::ExtractValue:
6482 return TTI.getInstructionCost(I, CostKind);
6483 case Instruction::Alloca:
6484 // We cannot easily widen alloca to a scalable alloca, as
6485 // the result would need to be a vector of pointers.
6486 if (VF.isScalable())
6488 return TTI.getArithmeticInstrCost(Instruction::Mul, RetTy, CostKind);
6489 default:
6490 // This opcode is unknown. Assume that it is the same as 'mul'.
6491 return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6492 } // end of switch.
6493}
6494
6496 // Ignore ephemeral values.
6498
6499 SmallVector<Value *, 4> DeadInterleavePointerOps;
6501
6502 // If a scalar epilogue is required, users outside the loop won't use
6503 // live-outs from the vector loop but from the scalar epilogue. Ignore them if
6504 // that is the case.
6505 bool RequiresScalarEpilogue = requiresScalarEpilogue(true);
6506 auto IsLiveOutDead = [this, RequiresScalarEpilogue](User *U) {
6507 return RequiresScalarEpilogue &&
6508 !TheLoop->contains(cast<Instruction>(U)->getParent());
6509 };
6510
6512 DFS.perform(LI);
6513 for (BasicBlock *BB : reverse(make_range(DFS.beginRPO(), DFS.endRPO())))
6514 for (Instruction &I : reverse(*BB)) {
6515 if (VecValuesToIgnore.contains(&I) || ValuesToIgnore.contains(&I))
6516 continue;
6517
6518 // Add instructions that would be trivially dead and are only used by
6519 // values already ignored to DeadOps to seed worklist.
6521 all_of(I.users(), [this, IsLiveOutDead](User *U) {
6522 return VecValuesToIgnore.contains(U) ||
6523 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
6524 }))
6525 DeadOps.push_back(&I);
6526
6527 // For interleave groups, we only create a pointer for the start of the
6528 // interleave group. Queue up addresses of group members except the insert
6529 // position for further processing.
6530 if (isAccessInterleaved(&I)) {
6531 auto *Group = getInterleavedAccessGroup(&I);
6532 if (Group->getInsertPos() == &I)
6533 continue;
6534 Value *PointerOp = getLoadStorePointerOperand(&I);
6535 DeadInterleavePointerOps.push_back(PointerOp);
6536 }
6537
6538 // Queue branches for analysis. They are dead, if their successors only
6539 // contain dead instructions.
6540 if (auto *Br = dyn_cast<BranchInst>(&I)) {
6541 if (Br->isConditional())
6542 DeadOps.push_back(&I);
6543 }
6544 }
6545
6546 // Mark ops feeding interleave group members as free, if they are only used
6547 // by other dead computations.
6548 for (unsigned I = 0; I != DeadInterleavePointerOps.size(); ++I) {
6549 auto *Op = dyn_cast<Instruction>(DeadInterleavePointerOps[I]);
6550 if (!Op || !TheLoop->contains(Op) || any_of(Op->users(), [this](User *U) {
6551 Instruction *UI = cast<Instruction>(U);
6552 return !VecValuesToIgnore.contains(U) &&
6553 (!isAccessInterleaved(UI) ||
6554 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
6555 }))
6556 continue;
6557 VecValuesToIgnore.insert(Op);
6558 append_range(DeadInterleavePointerOps, Op->operands());
6559 }
6560
6561 // Mark ops that would be trivially dead and are only used by ignored
6562 // instructions as free.
6563 BasicBlock *Header = TheLoop->getHeader();
6564
6565 // Returns true if the block contains only dead instructions. Such blocks will
6566 // be removed by VPlan-to-VPlan transforms and won't be considered by the
6567 // VPlan-based cost model, so skip them in the legacy cost-model as well.
6568 auto IsEmptyBlock = [this](BasicBlock *BB) {
6569 return all_of(*BB, [this](Instruction &I) {
6570 return ValuesToIgnore.contains(&I) || VecValuesToIgnore.contains(&I) ||
6571 (isa<BranchInst>(&I) && !cast<BranchInst>(&I)->isConditional());
6572 });
6573 };
6574 for (unsigned I = 0; I != DeadOps.size(); ++I) {
6575 auto *Op = dyn_cast<Instruction>(DeadOps[I]);
6576
6577 // Check if the branch should be considered dead.
6578 if (auto *Br = dyn_cast_or_null<BranchInst>(Op)) {
6579 BasicBlock *ThenBB = Br->getSuccessor(0);
6580 BasicBlock *ElseBB = Br->getSuccessor(1);
6581 // Don't considers branches leaving the loop for simplification.
6582 if (!TheLoop->contains(ThenBB) || !TheLoop->contains(ElseBB))
6583 continue;
6584 bool ThenEmpty = IsEmptyBlock(ThenBB);
6585 bool ElseEmpty = IsEmptyBlock(ElseBB);
6586 if ((ThenEmpty && ElseEmpty) ||
6587 (ThenEmpty && ThenBB->getSingleSuccessor() == ElseBB &&
6588 ElseBB->phis().empty()) ||
6589 (ElseEmpty && ElseBB->getSingleSuccessor() == ThenBB &&
6590 ThenBB->phis().empty())) {
6591 VecValuesToIgnore.insert(Br);
6592 DeadOps.push_back(Br->getCondition());
6593 }
6594 continue;
6595 }
6596
6597 // Skip any op that shouldn't be considered dead.
6598 if (!Op || !TheLoop->contains(Op) ||
6599 (isa<PHINode>(Op) && Op->getParent() == Header) ||
6601 any_of(Op->users(), [this, IsLiveOutDead](User *U) {
6602 return !VecValuesToIgnore.contains(U) &&
6603 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
6604 }))
6605 continue;
6606
6607 // If all of Op's users are in ValuesToIgnore, add it to ValuesToIgnore
6608 // which applies for both scalar and vector versions. Otherwise it is only
6609 // dead in vector versions, so only add it to VecValuesToIgnore.
6610 if (all_of(Op->users(),
6611 [this](User *U) { return ValuesToIgnore.contains(U); }))
6612 ValuesToIgnore.insert(Op);
6613
6614 VecValuesToIgnore.insert(Op);
6615 append_range(DeadOps, Op->operands());
6616 }
6617
6618 // Ignore type-promoting instructions we identified during reduction
6619 // detection.
6620 for (const auto &Reduction : Legal->getReductionVars()) {
6621 const RecurrenceDescriptor &RedDes = Reduction.second;
6622 const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
6623 VecValuesToIgnore.insert_range(Casts);
6624 }
6625 // Ignore type-casting instructions we identified during induction
6626 // detection.
6627 for (const auto &Induction : Legal->getInductionVars()) {
6628 const InductionDescriptor &IndDes = Induction.second;
6629 VecValuesToIgnore.insert_range(IndDes.getCastInsts());
6630 }
6631}
6632
6634 // Avoid duplicating work finding in-loop reductions.
6635 if (!InLoopReductions.empty())
6636 return;
6637
6638 for (const auto &Reduction : Legal->getReductionVars()) {
6639 PHINode *Phi = Reduction.first;
6640 const RecurrenceDescriptor &RdxDesc = Reduction.second;
6641
6642 // Multi-use reductions (e.g., used in FindLastIV patterns) are handled
6643 // separately and should not be considered for in-loop reductions.
6644 if (RdxDesc.hasUsesOutsideReductionChain())
6645 continue;
6646
6647 // We don't collect reductions that are type promoted (yet).
6648 if (RdxDesc.getRecurrenceType() != Phi->getType())
6649 continue;
6650
6651 // In-loop AnyOf and FindIV reductions are not yet supported.
6652 RecurKind Kind = RdxDesc.getRecurrenceKind();
6655 continue;
6656
6657 // If the target would prefer this reduction to happen "in-loop", then we
6658 // want to record it as such.
6659 if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
6660 !TTI.preferInLoopReduction(Kind, Phi->getType()))
6661 continue;
6662
6663 // Check that we can correctly put the reductions into the loop, by
6664 // finding the chain of operations that leads from the phi to the loop
6665 // exit value.
6666 SmallVector<Instruction *, 4> ReductionOperations =
6667 RdxDesc.getReductionOpChain(Phi, TheLoop);
6668 bool InLoop = !ReductionOperations.empty();
6669
6670 if (InLoop) {
6671 InLoopReductions.insert(Phi);
6672 // Add the elements to InLoopReductionImmediateChains for cost modelling.
6673 Instruction *LastChain = Phi;
6674 for (auto *I : ReductionOperations) {
6675 InLoopReductionImmediateChains[I] = LastChain;
6676 LastChain = I;
6677 }
6678 }
6679 LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
6680 << " reduction for phi: " << *Phi << "\n");
6681 }
6682}
6683
6684// This function will select a scalable VF if the target supports scalable
6685// vectors and a fixed one otherwise.
6686// TODO: we could return a pair of values that specify the max VF and
6687// min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
6688// `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
6689// doesn't have a cost model that can choose which plan to execute if
6690// more than one is generated.
6693 unsigned WidestType;
6694 std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
6695
6697 TTI.enableScalableVectorization()
6700
6701 TypeSize RegSize = TTI.getRegisterBitWidth(RegKind);
6702 unsigned N = RegSize.getKnownMinValue() / WidestType;
6703 return ElementCount::get(N, RegSize.isScalable());
6704}
6705
6708 ElementCount VF = UserVF;
6709 // Outer loop handling: They may require CFG and instruction level
6710 // transformations before even evaluating whether vectorization is profitable.
6711 // Since we cannot modify the incoming IR, we need to build VPlan upfront in
6712 // the vectorization pipeline.
6713 if (!OrigLoop->isInnermost()) {
6714 // If the user doesn't provide a vectorization factor, determine a
6715 // reasonable one.
6716 if (UserVF.isZero()) {
6717 VF = determineVPlanVF(TTI, CM);
6718 LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
6719
6720 // Make sure we have a VF > 1 for stress testing.
6721 if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
6722 LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
6723 << "overriding computed VF.\n");
6724 VF = ElementCount::getFixed(4);
6725 }
6726 } else if (UserVF.isScalable() && !TTI.supportsScalableVectors() &&
6728 LLVM_DEBUG(dbgs() << "LV: Not vectorizing. Scalable VF requested, but "
6729 << "not supported by the target.\n");
6731 "Scalable vectorization requested but not supported by the target",
6732 "the scalable user-specified vectorization width for outer-loop "
6733 "vectorization cannot be used because the target does not support "
6734 "scalable vectors.",
6735 "ScalableVFUnfeasible", ORE, OrigLoop);
6737 }
6738 assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
6740 "VF needs to be a power of two");
6741 LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
6742 << "VF " << VF << " to build VPlans.\n");
6743 buildVPlans(VF, VF);
6744
6745 if (VPlans.empty())
6747
6748 // For VPlan build stress testing, we bail out after VPlan construction.
6751
6752 return {VF, 0 /*Cost*/, 0 /* ScalarCost */};
6753 }
6754
6755 LLVM_DEBUG(
6756 dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
6757 "VPlan-native path.\n");
6759}
6760
6761void LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
6762 assert(OrigLoop->isInnermost() && "Inner loop expected.");
6763 CM.collectValuesToIgnore();
6764 CM.collectElementTypesForWidening();
6765
6766 FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
6767 if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
6768 return;
6769
6770 // Invalidate interleave groups if all blocks of loop will be predicated.
6771 if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
6773 LLVM_DEBUG(
6774 dbgs()
6775 << "LV: Invalidate all interleaved groups due to fold-tail by masking "
6776 "which requires masked-interleaved support.\n");
6777 if (CM.InterleaveInfo.invalidateGroups())
6778 // Invalidating interleave groups also requires invalidating all decisions
6779 // based on them, which includes widening decisions and uniform and scalar
6780 // values.
6781 CM.invalidateCostModelingDecisions();
6782 }
6783
6784 if (CM.foldTailByMasking())
6785 Legal->prepareToFoldTailByMasking();
6786
6787 ElementCount MaxUserVF =
6788 UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
6789 if (UserVF) {
6790 if (!ElementCount::isKnownLE(UserVF, MaxUserVF)) {
6792 "UserVF ignored because it may be larger than the maximal safe VF",
6793 "InvalidUserVF", ORE, OrigLoop);
6794 } else {
6796 "VF needs to be a power of two");
6797 // Collect the instructions (and their associated costs) that will be more
6798 // profitable to scalarize.
6799 CM.collectInLoopReductions();
6800 if (CM.selectUserVectorizationFactor(UserVF)) {
6801 LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
6802 buildVPlansWithVPRecipes(UserVF, UserVF);
6804 return;
6805 }
6806 reportVectorizationInfo("UserVF ignored because of invalid costs.",
6807 "InvalidCost", ORE, OrigLoop);
6808 }
6809 }
6810
6811 // Collect the Vectorization Factor Candidates.
6812 SmallVector<ElementCount> VFCandidates;
6813 for (auto VF = ElementCount::getFixed(1);
6814 ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
6815 VFCandidates.push_back(VF);
6816 for (auto VF = ElementCount::getScalable(1);
6817 ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
6818 VFCandidates.push_back(VF);
6819
6820 CM.collectInLoopReductions();
6821 for (const auto &VF : VFCandidates) {
6822 // Collect Uniform and Scalar instructions after vectorization with VF.
6823 CM.collectNonVectorizedAndSetWideningDecisions(VF);
6824 }
6825
6826 buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
6827 buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
6828
6830}
6831
6833 ElementCount VF) const {
6834 InstructionCost Cost = CM.getInstructionCost(UI, VF);
6835 if (Cost.isValid() && ForceTargetInstructionCost.getNumOccurrences())
6837 return Cost;
6838}
6839
6841 ElementCount VF) const {
6842 return CM.isUniformAfterVectorization(I, VF);
6843}
6844
6845bool VPCostContext::skipCostComputation(Instruction *UI, bool IsVector) const {
6846 return CM.ValuesToIgnore.contains(UI) ||
6847 (IsVector && CM.VecValuesToIgnore.contains(UI)) ||
6848 SkipCostComputation.contains(UI);
6849}
6850
6852 return CM.getPredBlockCostDivisor(CostKind, BB);
6853}
6854
6856LoopVectorizationPlanner::precomputeCosts(VPlan &Plan, ElementCount VF,
6857 VPCostContext &CostCtx) const {
6859 // Cost modeling for inductions is inaccurate in the legacy cost model
6860 // compared to the recipes that are generated. To match here initially during
6861 // VPlan cost model bring up directly use the induction costs from the legacy
6862 // cost model. Note that we do this as pre-processing; the VPlan may not have
6863 // any recipes associated with the original induction increment instruction
6864 // and may replace truncates with VPWidenIntOrFpInductionRecipe. We precompute
6865 // the cost of induction phis and increments (both that are represented by
6866 // recipes and those that are not), to avoid distinguishing between them here,
6867 // and skip all recipes that represent induction phis and increments (the
6868 // former case) later on, if they exist, to avoid counting them twice.
6869 // Similarly we pre-compute the cost of any optimized truncates.
6870 // TODO: Switch to more accurate costing based on VPlan.
6871 for (const auto &[IV, IndDesc] : Legal->getInductionVars()) {
6873 IV->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
6874 SmallVector<Instruction *> IVInsts = {IVInc};
6875 for (unsigned I = 0; I != IVInsts.size(); I++) {
6876 for (Value *Op : IVInsts[I]->operands()) {
6877 auto *OpI = dyn_cast<Instruction>(Op);
6878 if (Op == IV || !OpI || !OrigLoop->contains(OpI) || !Op->hasOneUse())
6879 continue;
6880 IVInsts.push_back(OpI);
6881 }
6882 }
6883 IVInsts.push_back(IV);
6884 for (User *U : IV->users()) {
6885 auto *CI = cast<Instruction>(U);
6886 if (!CostCtx.CM.isOptimizableIVTruncate(CI, VF))
6887 continue;
6888 IVInsts.push_back(CI);
6889 }
6890
6891 // If the vector loop gets executed exactly once with the given VF, ignore
6892 // the costs of comparison and induction instructions, as they'll get
6893 // simplified away.
6894 // TODO: Remove this code after stepping away from the legacy cost model and
6895 // adding code to simplify VPlans before calculating their costs.
6896 auto TC = getSmallConstantTripCount(PSE.getSE(), OrigLoop);
6897 if (TC == VF && !CM.foldTailByMasking())
6898 addFullyUnrolledInstructionsToIgnore(OrigLoop, Legal->getInductionVars(),
6899 CostCtx.SkipCostComputation);
6900
6901 for (Instruction *IVInst : IVInsts) {
6902 if (CostCtx.skipCostComputation(IVInst, VF.isVector()))
6903 continue;
6904 InstructionCost InductionCost = CostCtx.getLegacyCost(IVInst, VF);
6905 LLVM_DEBUG({
6906 dbgs() << "Cost of " << InductionCost << " for VF " << VF
6907 << ": induction instruction " << *IVInst << "\n";
6908 });
6909 Cost += InductionCost;
6910 CostCtx.SkipCostComputation.insert(IVInst);
6911 }
6912 }
6913
6914 /// Compute the cost of all exiting conditions of the loop using the legacy
6915 /// cost model. This is to match the legacy behavior, which adds the cost of
6916 /// all exit conditions. Note that this over-estimates the cost, as there will
6917 /// be a single condition to control the vector loop.
6919 CM.TheLoop->getExitingBlocks(Exiting);
6920 SetVector<Instruction *> ExitInstrs;
6921 // Collect all exit conditions.
6922 for (BasicBlock *EB : Exiting) {
6923 auto *Term = dyn_cast<BranchInst>(EB->getTerminator());
6924 if (!Term || CostCtx.skipCostComputation(Term, VF.isVector()))
6925 continue;
6926 if (auto *CondI = dyn_cast<Instruction>(Term->getOperand(0))) {
6927 ExitInstrs.insert(CondI);
6928 }
6929 }
6930 // Compute the cost of all instructions only feeding the exit conditions.
6931 for (unsigned I = 0; I != ExitInstrs.size(); ++I) {
6932 Instruction *CondI = ExitInstrs[I];
6933 if (!OrigLoop->contains(CondI) ||
6934 !CostCtx.SkipCostComputation.insert(CondI).second)
6935 continue;
6936 InstructionCost CondICost = CostCtx.getLegacyCost(CondI, VF);
6937 LLVM_DEBUG({
6938 dbgs() << "Cost of " << CondICost << " for VF " << VF
6939 << ": exit condition instruction " << *CondI << "\n";
6940 });
6941 Cost += CondICost;
6942 for (Value *Op : CondI->operands()) {
6943 auto *OpI = dyn_cast<Instruction>(Op);
6944 if (!OpI || CostCtx.skipCostComputation(OpI, VF.isVector()) ||
6945 any_of(OpI->users(), [&ExitInstrs](User *U) {
6946 return !ExitInstrs.contains(cast<Instruction>(U));
6947 }))
6948 continue;
6949 ExitInstrs.insert(OpI);
6950 }
6951 }
6952
6953 // Pre-compute the costs for branches except for the backedge, as the number
6954 // of replicate regions in a VPlan may not directly match the number of
6955 // branches, which would lead to different decisions.
6956 // TODO: Compute cost of branches for each replicate region in the VPlan,
6957 // which is more accurate than the legacy cost model.
6958 for (BasicBlock *BB : OrigLoop->blocks()) {
6959 if (CostCtx.skipCostComputation(BB->getTerminator(), VF.isVector()))
6960 continue;
6961 CostCtx.SkipCostComputation.insert(BB->getTerminator());
6962 if (BB == OrigLoop->getLoopLatch())
6963 continue;
6964 auto BranchCost = CostCtx.getLegacyCost(BB->getTerminator(), VF);
6965 Cost += BranchCost;
6966 }
6967
6968 // Pre-compute costs for instructions that are forced-scalar or profitable to
6969 // scalarize. Their costs will be computed separately in the legacy cost
6970 // model.
6971 for (Instruction *ForcedScalar : CM.ForcedScalars[VF]) {
6972 if (CostCtx.skipCostComputation(ForcedScalar, VF.isVector()))
6973 continue;
6974 CostCtx.SkipCostComputation.insert(ForcedScalar);
6975 InstructionCost ForcedCost = CostCtx.getLegacyCost(ForcedScalar, VF);
6976 LLVM_DEBUG({
6977 dbgs() << "Cost of " << ForcedCost << " for VF " << VF
6978 << ": forced scalar " << *ForcedScalar << "\n";
6979 });
6980 Cost += ForcedCost;
6981 }
6982 for (const auto &[Scalarized, ScalarCost] : CM.InstsToScalarize[VF]) {
6983 if (CostCtx.skipCostComputation(Scalarized, VF.isVector()))
6984 continue;
6985 CostCtx.SkipCostComputation.insert(Scalarized);
6986 LLVM_DEBUG({
6987 dbgs() << "Cost of " << ScalarCost << " for VF " << VF
6988 << ": profitable to scalarize " << *Scalarized << "\n";
6989 });
6990 Cost += ScalarCost;
6991 }
6992
6993 return Cost;
6994}
6995
6996InstructionCost LoopVectorizationPlanner::cost(VPlan &Plan,
6997 ElementCount VF) const {
6998 VPCostContext CostCtx(CM.TTI, *CM.TLI, Plan, CM, CM.CostKind, PSE, OrigLoop);
6999 InstructionCost Cost = precomputeCosts(Plan, VF, CostCtx);
7000
7001 // Now compute and add the VPlan-based cost.
7002 Cost += Plan.cost(VF, CostCtx);
7003#ifndef NDEBUG
7004 unsigned EstimatedWidth = estimateElementCount(VF, CM.getVScaleForTuning());
7005 LLVM_DEBUG(dbgs() << "Cost for VF " << VF << ": " << Cost
7006 << " (Estimated cost per lane: ");
7007 if (Cost.isValid()) {
7008 double CostPerLane = double(Cost.getValue()) / EstimatedWidth;
7009 LLVM_DEBUG(dbgs() << format("%.1f", CostPerLane));
7010 } else /* No point dividing an invalid cost - it will still be invalid */
7011 LLVM_DEBUG(dbgs() << "Invalid");
7012 LLVM_DEBUG(dbgs() << ")\n");
7013#endif
7014 return Cost;
7015}
7016
7017#ifndef NDEBUG
7018/// Return true if the original loop \ TheLoop contains any instructions that do
7019/// not have corresponding recipes in \p Plan and are not marked to be ignored
7020/// in \p CostCtx. This means the VPlan contains simplification that the legacy
7021/// cost-model did not account for.
7023 VPCostContext &CostCtx,
7024 Loop *TheLoop,
7025 ElementCount VF) {
7026 // First collect all instructions for the recipes in Plan.
7027 auto GetInstructionForCost = [](const VPRecipeBase *R) -> Instruction * {
7028 if (auto *S = dyn_cast<VPSingleDefRecipe>(R))
7029 return dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
7030 if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(R))
7031 return &WidenMem->getIngredient();
7032 return nullptr;
7033 };
7034
7035 // Check if a select for a safe divisor was hoisted to the pre-header. If so,
7036 // the select doesn't need to be considered for the vector loop cost; go with
7037 // the more accurate VPlan-based cost model.
7038 for (VPRecipeBase &R : *Plan.getVectorPreheader()) {
7039 auto *VPI = dyn_cast<VPInstruction>(&R);
7040 if (!VPI || VPI->getOpcode() != Instruction::Select)
7041 continue;
7042
7043 if (auto *WR = dyn_cast_or_null<VPWidenRecipe>(VPI->getSingleUser())) {
7044 switch (WR->getOpcode()) {
7045 case Instruction::UDiv:
7046 case Instruction::SDiv:
7047 case Instruction::URem:
7048 case Instruction::SRem:
7049 return true;
7050 default:
7051 break;
7052 }
7053 }
7054 }
7055
7056 DenseSet<Instruction *> SeenInstrs;
7057 auto Iter = vp_depth_first_deep(Plan.getVectorLoopRegion()->getEntry());
7059 for (VPRecipeBase &R : *VPBB) {
7060 if (auto *IR = dyn_cast<VPInterleaveRecipe>(&R)) {
7061 auto *IG = IR->getInterleaveGroup();
7062 unsigned NumMembers = IG->getNumMembers();
7063 for (unsigned I = 0; I != NumMembers; ++I) {
7064 if (Instruction *M = IG->getMember(I))
7065 SeenInstrs.insert(M);
7066 }
7067 continue;
7068 }
7069 // Unused FOR splices are removed by VPlan transforms, so the VPlan-based
7070 // cost model won't cost it whilst the legacy will.
7071 if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R)) {
7072 using namespace VPlanPatternMatch;
7073 if (none_of(FOR->users(),
7074 match_fn(m_VPInstruction<
7076 return true;
7077 }
7078 // The VPlan-based cost model is more accurate for partial reductions and
7079 // comparing against the legacy cost isn't desirable.
7080 if (auto *VPR = dyn_cast<VPReductionRecipe>(&R))
7081 if (VPR->isPartialReduction())
7082 return true;
7083
7084 // The VPlan-based cost model can analyze if recipes are scalar
7085 // recursively, but the legacy cost model cannot.
7086 if (auto *WidenMemR = dyn_cast<VPWidenMemoryRecipe>(&R)) {
7087 auto *AddrI = dyn_cast<Instruction>(
7088 getLoadStorePointerOperand(&WidenMemR->getIngredient()));
7089 if (AddrI && vputils::isSingleScalar(WidenMemR->getAddr()) !=
7090 CostCtx.isLegacyUniformAfterVectorization(AddrI, VF))
7091 return true;
7092
7093 if (WidenMemR->isReverse()) {
7094 // If the stored value of a reverse store is invariant, LICM will
7095 // hoist the reverse operation to the preheader. In this case, the
7096 // result of the VPlan-based cost model will diverge from that of
7097 // the legacy model.
7098 if (auto *StoreR = dyn_cast<VPWidenStoreRecipe>(WidenMemR))
7099 if (StoreR->getStoredValue()->isDefinedOutsideLoopRegions())
7100 return true;
7101
7102 if (auto *StoreR = dyn_cast<VPWidenStoreEVLRecipe>(WidenMemR))
7103 if (StoreR->getStoredValue()->isDefinedOutsideLoopRegions())
7104 return true;
7105 }
7106 }
7107
7108 // The legacy cost model costs non-header phis with a scalar VF as a phi,
7109 // but scalar unrolled VPlans will have VPBlendRecipes which emit selects.
7110 if (isa<VPBlendRecipe>(&R) &&
7111 vputils::onlyFirstLaneUsed(R.getVPSingleValue()))
7112 return true;
7113
7114 /// If a VPlan transform folded a recipe to one producing a single-scalar,
7115 /// but the original instruction wasn't uniform-after-vectorization in the
7116 /// legacy cost model, the legacy cost overestimates the actual cost.
7117 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
7118 if (RepR->isSingleScalar() &&
7120 RepR->getUnderlyingInstr(), VF))
7121 return true;
7122 }
7123 if (Instruction *UI = GetInstructionForCost(&R)) {
7124 // If we adjusted the predicate of the recipe, the cost in the legacy
7125 // cost model may be different.
7126 using namespace VPlanPatternMatch;
7127 CmpPredicate Pred;
7128 if (match(&R, m_Cmp(Pred, m_VPValue(), m_VPValue())) &&
7129 cast<VPRecipeWithIRFlags>(R).getPredicate() !=
7130 cast<CmpInst>(UI)->getPredicate())
7131 return true;
7132 SeenInstrs.insert(UI);
7133 }
7134 }
7135 }
7136
7137 // Return true if the loop contains any instructions that are not also part of
7138 // the VPlan or are skipped for VPlan-based cost computations. This indicates
7139 // that the VPlan contains extra simplifications.
7140 return any_of(TheLoop->blocks(), [&SeenInstrs, &CostCtx,
7141 TheLoop](BasicBlock *BB) {
7142 return any_of(*BB, [&SeenInstrs, &CostCtx, TheLoop, BB](Instruction &I) {
7143 // Skip induction phis when checking for simplifications, as they may not
7144 // be lowered directly be lowered to a corresponding PHI recipe.
7145 if (isa<PHINode>(&I) && BB == TheLoop->getHeader() &&
7146 CostCtx.CM.Legal->isInductionPhi(cast<PHINode>(&I)))
7147 return false;
7148 return !SeenInstrs.contains(&I) && !CostCtx.skipCostComputation(&I, true);
7149 });
7150 });
7151}
7152#endif
7153
7155 if (VPlans.empty())
7157 // If there is a single VPlan with a single VF, return it directly.
7158 VPlan &FirstPlan = *VPlans[0];
7159 if (VPlans.size() == 1 && size(FirstPlan.vectorFactors()) == 1)
7160 return {*FirstPlan.vectorFactors().begin(), 0, 0};
7161
7162 LLVM_DEBUG(dbgs() << "LV: Computing best VF using cost kind: "
7163 << (CM.CostKind == TTI::TCK_RecipThroughput
7164 ? "Reciprocal Throughput\n"
7165 : CM.CostKind == TTI::TCK_Latency
7166 ? "Instruction Latency\n"
7167 : CM.CostKind == TTI::TCK_CodeSize ? "Code Size\n"
7168 : CM.CostKind == TTI::TCK_SizeAndLatency
7169 ? "Code Size and Latency\n"
7170 : "Unknown\n"));
7171
7173 assert(hasPlanWithVF(ScalarVF) &&
7174 "More than a single plan/VF w/o any plan having scalar VF");
7175
7176 // TODO: Compute scalar cost using VPlan-based cost model.
7177 InstructionCost ScalarCost = CM.expectedCost(ScalarVF);
7178 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ScalarCost << ".\n");
7179 VectorizationFactor ScalarFactor(ScalarVF, ScalarCost, ScalarCost);
7180 VectorizationFactor BestFactor = ScalarFactor;
7181
7182 bool ForceVectorization = Hints.getForce() == LoopVectorizeHints::FK_Enabled;
7183 if (ForceVectorization) {
7184 // Ignore scalar width, because the user explicitly wants vectorization.
7185 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
7186 // evaluation.
7187 BestFactor.Cost = InstructionCost::getMax();
7188 }
7189
7190 for (auto &P : VPlans) {
7191 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
7192 P->vectorFactors().end());
7193
7195 if (any_of(VFs, [this](ElementCount VF) {
7196 return CM.shouldConsiderRegPressureForVF(VF);
7197 }))
7198 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI, CM.ValuesToIgnore);
7199
7200 for (unsigned I = 0; I < VFs.size(); I++) {
7201 ElementCount VF = VFs[I];
7202 if (VF.isScalar())
7203 continue;
7204 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
7205 LLVM_DEBUG(
7206 dbgs()
7207 << "LV: Not considering vector loop of width " << VF
7208 << " because it will not generate any vector instructions.\n");
7209 continue;
7210 }
7211 if (CM.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
7212 LLVM_DEBUG(
7213 dbgs()
7214 << "LV: Not considering vector loop of width " << VF
7215 << " because it would cause replicated blocks to be generated,"
7216 << " which isn't allowed when optimizing for size.\n");
7217 continue;
7218 }
7219
7220 InstructionCost Cost = cost(*P, VF);
7221 VectorizationFactor CurrentFactor(VF, Cost, ScalarCost);
7222
7223 if (CM.shouldConsiderRegPressureForVF(VF) &&
7224 RUs[I].exceedsMaxNumRegs(TTI, ForceTargetNumVectorRegs)) {
7225 LLVM_DEBUG(dbgs() << "LV(REG): Not considering vector loop of width "
7226 << VF << " because it uses too many registers\n");
7227 continue;
7228 }
7229
7230 if (isMoreProfitable(CurrentFactor, BestFactor, P->hasScalarTail()))
7231 BestFactor = CurrentFactor;
7232
7233 // If profitable add it to ProfitableVF list.
7234 if (isMoreProfitable(CurrentFactor, ScalarFactor, P->hasScalarTail()))
7235 ProfitableVFs.push_back(CurrentFactor);
7236 }
7237 }
7238
7239#ifndef NDEBUG
7240 // Select the optimal vectorization factor according to the legacy cost-model.
7241 // This is now only used to verify the decisions by the new VPlan-based
7242 // cost-model and will be retired once the VPlan-based cost-model is
7243 // stabilized.
7244 VectorizationFactor LegacyVF = selectVectorizationFactor();
7245 VPlan &BestPlan = getPlanFor(BestFactor.Width);
7246
7247 // Pre-compute the cost and use it to check if BestPlan contains any
7248 // simplifications not accounted for in the legacy cost model. If that's the
7249 // case, don't trigger the assertion, as the extra simplifications may cause a
7250 // different VF to be picked by the VPlan-based cost model.
7251 VPCostContext CostCtx(CM.TTI, *CM.TLI, BestPlan, CM, CM.CostKind, CM.PSE,
7252 OrigLoop);
7253 precomputeCosts(BestPlan, BestFactor.Width, CostCtx);
7254 // Verify that the VPlan-based and legacy cost models agree, except for
7255 // * VPlans with early exits,
7256 // * VPlans with additional VPlan simplifications,
7257 // * EVL-based VPlans with gather/scatters (the VPlan-based cost model uses
7258 // vp_scatter/vp_gather).
7259 // The legacy cost model doesn't properly model costs for such loops.
7260 bool UsesEVLGatherScatter =
7262 BestPlan.getVectorLoopRegion()->getEntry())),
7263 [](VPBasicBlock *VPBB) {
7264 return any_of(*VPBB, [](VPRecipeBase &R) {
7265 return isa<VPWidenLoadEVLRecipe, VPWidenStoreEVLRecipe>(&R) &&
7266 !cast<VPWidenMemoryRecipe>(&R)->isConsecutive();
7267 });
7268 });
7269 assert(
7270 (BestFactor.Width == LegacyVF.Width || BestPlan.hasEarlyExit() ||
7271 !Legal->getLAI()->getSymbolicStrides().empty() || UsesEVLGatherScatter ||
7273 getPlanFor(BestFactor.Width), CostCtx, OrigLoop, BestFactor.Width) ||
7275 getPlanFor(LegacyVF.Width), CostCtx, OrigLoop, LegacyVF.Width)) &&
7276 " VPlan cost model and legacy cost model disagreed");
7277 assert((BestFactor.Width.isScalar() || BestFactor.ScalarCost > 0) &&
7278 "when vectorizing, the scalar cost must be computed.");
7279#endif
7280
7281 LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << BestFactor.Width << ".\n");
7282 return BestFactor;
7283}
7284
7285/// Search \p Start's users for a recipe satisfying \p Pred, looking through
7286/// recipes with definitions.
7287template <typename PredT>
7288static VPRecipeBase *findRecipe(VPValue *Start, PredT Pred) {
7289 SetVector<VPValue *> Worklist;
7290 Worklist.insert(Start);
7291 for (unsigned I = 0; I != Worklist.size(); ++I) {
7292 VPValue *Cur = Worklist[I];
7293 auto *R = Cur->getDefiningRecipe();
7294 // TODO: Skip live-ins once no degenerate reductions (ones with constant
7295 // backedge values) are generated.
7296 if (R && Pred(R))
7297 return R;
7298 for (VPUser *U : Cur->users()) {
7299 for (VPValue *V : cast<VPRecipeBase>(U)->definedValues())
7300 Worklist.insert(V);
7301 }
7302 }
7303 return nullptr;
7304}
7305
7307 using namespace VPlanPatternMatch;
7309 "RdxResult must be ComputeFindIVResult");
7310 VPValue *StartVPV = RdxResult->getOperand(0);
7311 match(StartVPV, m_Freeze(m_VPValue(StartVPV)));
7312 return StartVPV->getLiveInIRValue();
7313}
7314
7315// If \p EpiResumePhiR is resume VPPhi for a reduction when vectorizing the
7316// epilog loop, fix the reduction's scalar PHI node by adding the incoming value
7317// from the main vector loop.
7319 VPPhi *EpiResumePhiR, PHINode &EpiResumePhi, BasicBlock *BypassBlock) {
7320 // Get the VPInstruction computing the reduction result in the middle block.
7321 // The first operand may not be from the middle block if it is not connected
7322 // to the scalar preheader. In that case, there's nothing to fix.
7323 VPValue *Incoming = EpiResumePhiR->getOperand(0);
7326 auto *EpiRedResult = dyn_cast<VPInstruction>(Incoming);
7327 if (!EpiRedResult ||
7328 (EpiRedResult->getOpcode() != VPInstruction::ComputeAnyOfResult &&
7329 EpiRedResult->getOpcode() != VPInstruction::ComputeReductionResult &&
7330 EpiRedResult->getOpcode() != VPInstruction::ComputeFindIVResult))
7331 return;
7332
7333 // Find the reduction phi by searching users of the backedge value.
7334 VPValue *BackedgeVal =
7335 EpiRedResult->getOperand(EpiRedResult->getNumOperands() - 1);
7336 auto *EpiRedHeaderPhi = cast_if_present<VPReductionPHIRecipe>(
7338 if (!EpiRedHeaderPhi) {
7339 match(BackedgeVal,
7341 VPlanPatternMatch::m_VPValue(BackedgeVal),
7343 EpiRedHeaderPhi = cast<VPReductionPHIRecipe>(
7345 }
7346
7347 RecurKind Kind = EpiRedHeaderPhi->getRecurrenceKind();
7348 Value *MainResumeValue;
7349 if (auto *VPI = dyn_cast<VPInstruction>(EpiRedHeaderPhi->getStartValue())) {
7350 assert((VPI->getOpcode() == VPInstruction::Broadcast ||
7351 VPI->getOpcode() == VPInstruction::ReductionStartVector) &&
7352 "unexpected start recipe");
7353 MainResumeValue = VPI->getOperand(0)->getUnderlyingValue();
7354 } else
7355 MainResumeValue = EpiRedHeaderPhi->getStartValue()->getUnderlyingValue();
7357 [[maybe_unused]] Value *StartV =
7358 EpiRedResult->getOperand(0)->getLiveInIRValue();
7359 auto *Cmp = cast<ICmpInst>(MainResumeValue);
7360 assert(Cmp->getPredicate() == CmpInst::ICMP_NE &&
7361 "AnyOf expected to start with ICMP_NE");
7362 assert(Cmp->getOperand(1) == StartV &&
7363 "AnyOf expected to start by comparing main resume value to original "
7364 "start value");
7365 MainResumeValue = Cmp->getOperand(0);
7367 Value *StartV = getStartValueFromReductionResult(EpiRedResult);
7368 Value *SentinelV = EpiRedResult->getOperand(1)->getLiveInIRValue();
7369 using namespace llvm::PatternMatch;
7370 Value *Cmp, *OrigResumeV, *CmpOp;
7371 [[maybe_unused]] bool IsExpectedPattern =
7372 match(MainResumeValue,
7373 m_Select(m_OneUse(m_Value(Cmp)), m_Specific(SentinelV),
7374 m_Value(OrigResumeV))) &&
7376 m_Value(CmpOp))) &&
7377 ((CmpOp == StartV && isGuaranteedNotToBeUndefOrPoison(CmpOp))));
7378 assert(IsExpectedPattern && "Unexpected reduction resume pattern");
7379 MainResumeValue = OrigResumeV;
7380 }
7381 PHINode *MainResumePhi = cast<PHINode>(MainResumeValue);
7382
7383 // When fixing reductions in the epilogue loop we should already have
7384 // created a bc.merge.rdx Phi after the main vector body. Ensure that we carry
7385 // over the incoming values correctly.
7386 EpiResumePhi.setIncomingValueForBlock(
7387 BypassBlock, MainResumePhi->getIncomingValueForBlock(BypassBlock));
7388}
7389
7391 ElementCount BestVF, unsigned BestUF, VPlan &BestVPlan,
7392 InnerLoopVectorizer &ILV, DominatorTree *DT, bool VectorizingEpilogue) {
7393 assert(BestVPlan.hasVF(BestVF) &&
7394 "Trying to execute plan with unsupported VF");
7395 assert(BestVPlan.hasUF(BestUF) &&
7396 "Trying to execute plan with unsupported UF");
7397 if (BestVPlan.hasEarlyExit())
7398 ++LoopsEarlyExitVectorized;
7399 // TODO: Move to VPlan transform stage once the transition to the VPlan-based
7400 // cost model is complete for better cost estimates.
7403 BestVPlan);
7406 bool HasBranchWeights =
7407 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator());
7408 if (HasBranchWeights) {
7409 std::optional<unsigned> VScale = CM.getVScaleForTuning();
7411 BestVPlan, BestVF, VScale);
7412 }
7413
7414 // Checks are the same for all VPlans, added to BestVPlan only for
7415 // compactness.
7416 attachRuntimeChecks(BestVPlan, ILV.RTChecks, HasBranchWeights);
7417
7418 // Retrieving VectorPH now when it's easier while VPlan still has Regions.
7419 VPBasicBlock *VectorPH = cast<VPBasicBlock>(BestVPlan.getVectorPreheader());
7420
7421 VPlanTransforms::optimizeForVFAndUF(BestVPlan, BestVF, BestUF, PSE);
7424 if (BestVPlan.getEntry()->getSingleSuccessor() ==
7425 BestVPlan.getScalarPreheader()) {
7426 // TODO: The vector loop would be dead, should not even try to vectorize.
7427 ORE->emit([&]() {
7428 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationDead",
7429 OrigLoop->getStartLoc(),
7430 OrigLoop->getHeader())
7431 << "Created vector loop never executes due to insufficient trip "
7432 "count.";
7433 });
7435 }
7436
7438 BestVPlan, BestVF,
7439 TTI.getRegisterBitWidth(BestVF.isScalable()
7443
7445 // Regions are dissolved after optimizing for VF and UF, which completely
7446 // removes unneeded loop regions first.
7448 // Expand BranchOnTwoConds after dissolution, when latch has direct access to
7449 // its successors.
7451 // Canonicalize EVL loops after regions are dissolved.
7455 BestVPlan, VectorPH, CM.foldTailByMasking(),
7456 CM.requiresScalarEpilogue(BestVF.isVector()));
7457 VPlanTransforms::materializeVFAndVFxUF(BestVPlan, VectorPH, BestVF);
7458 VPlanTransforms::cse(BestVPlan);
7460
7461 // 0. Generate SCEV-dependent code in the entry, including TripCount, before
7462 // making any changes to the CFG.
7463 DenseMap<const SCEV *, Value *> ExpandedSCEVs =
7464 VPlanTransforms::expandSCEVs(BestVPlan, *PSE.getSE());
7465 if (!ILV.getTripCount()) {
7466 ILV.setTripCount(BestVPlan.getTripCount()->getLiveInIRValue());
7467 } else {
7468 assert(VectorizingEpilogue && "should only re-use the existing trip "
7469 "count during epilogue vectorization");
7470 }
7471
7472 // Perform the actual loop transformation.
7473 VPTransformState State(&TTI, BestVF, LI, DT, ILV.AC, ILV.Builder, &BestVPlan,
7474 OrigLoop->getParentLoop(),
7475 Legal->getWidestInductionType());
7476
7477#ifdef EXPENSIVE_CHECKS
7478 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
7479#endif
7480
7481 // 1. Set up the skeleton for vectorization, including vector pre-header and
7482 // middle block. The vector loop is created during VPlan execution.
7483 State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7485 State.CFG.PrevBB->getSingleSuccessor(), &BestVPlan);
7487
7488 assert(verifyVPlanIsValid(BestVPlan, true /*VerifyLate*/) &&
7489 "final VPlan is invalid");
7490
7491 // After vectorization, the exit blocks of the original loop will have
7492 // additional predecessors. Invalidate SCEVs for the exit phis in case SE
7493 // looked through single-entry phis.
7494 ScalarEvolution &SE = *PSE.getSE();
7495 for (VPIRBasicBlock *Exit : BestVPlan.getExitBlocks()) {
7496 if (!Exit->hasPredecessors())
7497 continue;
7498 for (VPRecipeBase &PhiR : Exit->phis())
7500 &cast<VPIRPhi>(PhiR).getIRPhi());
7501 }
7502 // Forget the original loop and block dispositions.
7503 SE.forgetLoop(OrigLoop);
7505
7507
7508 //===------------------------------------------------===//
7509 //
7510 // Notice: any optimization or new instruction that go
7511 // into the code below should also be implemented in
7512 // the cost-model.
7513 //
7514 //===------------------------------------------------===//
7515
7516 // Retrieve loop information before executing the plan, which may remove the
7517 // original loop, if it becomes unreachable.
7518 MDNode *LID = OrigLoop->getLoopID();
7519 unsigned OrigLoopInvocationWeight = 0;
7520 std::optional<unsigned> OrigAverageTripCount =
7521 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
7522
7523 BestVPlan.execute(&State);
7524
7525 // 2.6. Maintain Loop Hints
7526 // Keep all loop hints from the original loop on the vector loop (we'll
7527 // replace the vectorizer-specific hints below).
7528 VPBasicBlock *HeaderVPBB = vputils::getFirstLoopHeader(BestVPlan, State.VPDT);
7529 // Add metadata to disable runtime unrolling a scalar loop when there
7530 // are no runtime checks about strides and memory. A scalar loop that is
7531 // rarely used is not worth unrolling.
7532 bool DisableRuntimeUnroll = !ILV.RTChecks.hasChecks() && !BestVF.isScalar();
7534 HeaderVPBB ? LI->getLoopFor(State.CFG.VPBB2IRBB.lookup(HeaderVPBB))
7535 : nullptr,
7536 HeaderVPBB, BestVPlan, VectorizingEpilogue, LID, OrigAverageTripCount,
7537 OrigLoopInvocationWeight,
7538 estimateElementCount(BestVF * BestUF, CM.getVScaleForTuning()),
7539 DisableRuntimeUnroll);
7540
7541 // 3. Fix the vectorized code: take care of header phi's, live-outs,
7542 // predication, updating analyses.
7543 ILV.fixVectorizedLoop(State);
7544
7546
7547 return ExpandedSCEVs;
7548}
7549
7550//===--------------------------------------------------------------------===//
7551// EpilogueVectorizerMainLoop
7552//===--------------------------------------------------------------------===//
7553
7554/// This function is partially responsible for generating the control flow
7555/// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7557 BasicBlock *ScalarPH = createScalarPreheader("");
7558 BasicBlock *VectorPH = ScalarPH->getSinglePredecessor();
7559
7560 // Generate the code to check the minimum iteration count of the vector
7561 // epilogue (see below).
7562 EPI.EpilogueIterationCountCheck =
7563 emitIterationCountCheck(VectorPH, ScalarPH, true);
7564 EPI.EpilogueIterationCountCheck->setName("iter.check");
7565
7566 VectorPH = cast<BranchInst>(EPI.EpilogueIterationCountCheck->getTerminator())
7567 ->getSuccessor(1);
7568 // Generate the iteration count check for the main loop, *after* the check
7569 // for the epilogue loop, so that the path-length is shorter for the case
7570 // that goes directly through the vector epilogue. The longer-path length for
7571 // the main loop is compensated for, by the gain from vectorizing the larger
7572 // trip count. Note: the branch will get updated later on when we vectorize
7573 // the epilogue.
7574 EPI.MainLoopIterationCountCheck =
7575 emitIterationCountCheck(VectorPH, ScalarPH, false);
7576
7577 return cast<BranchInst>(EPI.MainLoopIterationCountCheck->getTerminator())
7578 ->getSuccessor(1);
7579}
7580
7582 LLVM_DEBUG({
7583 dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7584 << "Main Loop VF:" << EPI.MainLoopVF
7585 << ", Main Loop UF:" << EPI.MainLoopUF
7586 << ", Epilogue Loop VF:" << EPI.EpilogueVF
7587 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7588 });
7589}
7590
7593 dbgs() << "intermediate fn:\n"
7594 << *OrigLoop->getHeader()->getParent() << "\n";
7595 });
7596}
7597
7599 BasicBlock *VectorPH, BasicBlock *Bypass, bool ForEpilogue) {
7600 assert(Bypass && "Expected valid bypass basic block.");
7603 Value *CheckMinIters = createIterationCountCheck(
7604 VectorPH, ForEpilogue ? EPI.EpilogueVF : EPI.MainLoopVF,
7605 ForEpilogue ? EPI.EpilogueUF : EPI.MainLoopUF);
7606
7607 BasicBlock *const TCCheckBlock = VectorPH;
7608 if (!ForEpilogue)
7609 TCCheckBlock->setName("vector.main.loop.iter.check");
7610
7611 // Create new preheader for vector loop.
7612 VectorPH = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7613 static_cast<DominatorTree *>(nullptr), LI, nullptr,
7614 "vector.ph");
7615 if (ForEpilogue) {
7616 // Save the trip count so we don't have to regenerate it in the
7617 // vec.epilog.iter.check. This is safe to do because the trip count
7618 // generated here dominates the vector epilog iter check.
7619 EPI.TripCount = Count;
7620 } else {
7622 }
7623
7624 BranchInst &BI = *BranchInst::Create(Bypass, VectorPH, CheckMinIters);
7625 if (hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator()))
7626 setBranchWeights(BI, MinItersBypassWeights, /*IsExpected=*/false);
7627 ReplaceInstWithInst(TCCheckBlock->getTerminator(), &BI);
7628
7629 // When vectorizing the main loop, its trip-count check is placed in a new
7630 // block, whereas the overall trip-count check is placed in the VPlan entry
7631 // block. When vectorizing the epilogue loop, its trip-count check is placed
7632 // in the VPlan entry block.
7633 if (!ForEpilogue)
7634 introduceCheckBlockInVPlan(TCCheckBlock);
7635 return TCCheckBlock;
7636}
7637
7638//===--------------------------------------------------------------------===//
7639// EpilogueVectorizerEpilogueLoop
7640//===--------------------------------------------------------------------===//
7641
7642/// This function creates a new scalar preheader, using the previous one as
7643/// entry block to the epilogue VPlan. The minimum iteration check is being
7644/// represented in VPlan.
7646 BasicBlock *NewScalarPH = createScalarPreheader("vec.epilog.");
7647 BasicBlock *OriginalScalarPH = NewScalarPH->getSinglePredecessor();
7648 OriginalScalarPH->setName("vec.epilog.iter.check");
7649 VPIRBasicBlock *NewEntry = Plan.createVPIRBasicBlock(OriginalScalarPH);
7650 VPBasicBlock *OldEntry = Plan.getEntry();
7651 for (auto &R : make_early_inc_range(*OldEntry)) {
7652 // Skip moving VPIRInstructions (including VPIRPhis), which are unmovable by
7653 // defining.
7654 if (isa<VPIRInstruction>(&R))
7655 continue;
7656 R.moveBefore(*NewEntry, NewEntry->end());
7657 }
7658
7659 VPBlockUtils::reassociateBlocks(OldEntry, NewEntry);
7660 Plan.setEntry(NewEntry);
7661 // OldEntry is now dead and will be cleaned up when the plan gets destroyed.
7662
7663 return OriginalScalarPH;
7664}
7665
7667 LLVM_DEBUG({
7668 dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7669 << "Epilogue Loop VF:" << EPI.EpilogueVF
7670 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7671 });
7672}
7673
7676 dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
7677 });
7678}
7679
7680VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(VPInstruction *VPI,
7681 VFRange &Range) {
7682 assert((VPI->getOpcode() == Instruction::Load ||
7683 VPI->getOpcode() == Instruction::Store) &&
7684 "Must be called with either a load or store");
7686
7687 auto WillWiden = [&](ElementCount VF) -> bool {
7689 CM.getWideningDecision(I, VF);
7691 "CM decision should be taken at this point.");
7693 return true;
7694 if (CM.isScalarAfterVectorization(I, VF) ||
7695 CM.isProfitableToScalarize(I, VF))
7696 return false;
7698 };
7699
7701 return nullptr;
7702
7703 VPValue *Mask = nullptr;
7704 if (Legal->isMaskRequired(I))
7705 Mask = getBlockInMask(Builder.getInsertBlock());
7706
7707 // Determine if the pointer operand of the access is either consecutive or
7708 // reverse consecutive.
7710 CM.getWideningDecision(I, Range.Start);
7712 bool Consecutive =
7714
7715 VPValue *Ptr = VPI->getOpcode() == Instruction::Load ? VPI->getOperand(0)
7716 : VPI->getOperand(1);
7717 if (Consecutive) {
7720 VPSingleDefRecipe *VectorPtr;
7721 if (Reverse) {
7722 // When folding the tail, we may compute an address that we don't in the
7723 // original scalar loop: drop the GEP no-wrap flags in this case.
7724 // Otherwise preserve existing flags without no-unsigned-wrap, as we will
7725 // emit negative indices.
7726 GEPNoWrapFlags Flags =
7727 CM.foldTailByMasking() || !GEP
7729 : GEP->getNoWrapFlags().withoutNoUnsignedWrap();
7730 VectorPtr = new VPVectorEndPointerRecipe(
7731 Ptr, &Plan.getVF(), getLoadStoreType(I),
7732 /*Stride*/ -1, Flags, VPI->getDebugLoc());
7733 } else {
7734 VectorPtr = new VPVectorPointerRecipe(Ptr, getLoadStoreType(I),
7735 GEP ? GEP->getNoWrapFlags()
7737 VPI->getDebugLoc());
7738 }
7739 Builder.insert(VectorPtr);
7740 Ptr = VectorPtr;
7741 }
7742
7743 if (VPI->getOpcode() == Instruction::Load) {
7744 auto *Load = cast<LoadInst>(I);
7745 auto *LoadR = new VPWidenLoadRecipe(*Load, Ptr, Mask, Consecutive, Reverse,
7746 *VPI, Load->getDebugLoc());
7747 if (Reverse) {
7748 Builder.insert(LoadR);
7749 return new VPInstruction(VPInstruction::Reverse, LoadR, {}, {},
7750 LoadR->getDebugLoc());
7751 }
7752 return LoadR;
7753 }
7754
7755 StoreInst *Store = cast<StoreInst>(I);
7756 VPValue *StoredVal = VPI->getOperand(0);
7757 if (Reverse)
7758 StoredVal = Builder.createNaryOp(VPInstruction::Reverse, StoredVal,
7759 Store->getDebugLoc());
7760 return new VPWidenStoreRecipe(*Store, Ptr, StoredVal, Mask, Consecutive,
7761 Reverse, *VPI, Store->getDebugLoc());
7762}
7763
7765VPRecipeBuilder::tryToOptimizeInductionTruncate(VPInstruction *VPI,
7766 VFRange &Range) {
7767 auto *I = cast<TruncInst>(VPI->getUnderlyingInstr());
7768 // Optimize the special case where the source is a constant integer
7769 // induction variable. Notice that we can only optimize the 'trunc' case
7770 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
7771 // (c) other casts depend on pointer size.
7772
7773 // Determine whether \p K is a truncation based on an induction variable that
7774 // can be optimized.
7775 auto IsOptimizableIVTruncate =
7776 [&](Instruction *K) -> std::function<bool(ElementCount)> {
7777 return [=](ElementCount VF) -> bool {
7778 return CM.isOptimizableIVTruncate(K, VF);
7779 };
7780 };
7781
7783 IsOptimizableIVTruncate(I), Range))
7784 return nullptr;
7785
7787 VPI->getOperand(0)->getDefiningRecipe());
7788 PHINode *Phi = WidenIV->getPHINode();
7789 VPIRValue *Start = WidenIV->getStartValue();
7790 const InductionDescriptor &IndDesc = WidenIV->getInductionDescriptor();
7791
7792 // It is always safe to copy over the NoWrap and FastMath flags. In
7793 // particular, when folding tail by masking, the masked-off lanes are never
7794 // used, so it is safe.
7795 VPIRFlags Flags = vputils::getFlagsFromIndDesc(IndDesc);
7796 VPValue *Step =
7798 return new VPWidenIntOrFpInductionRecipe(
7799 Phi, Start, Step, &Plan.getVF(), IndDesc, I, Flags, VPI->getDebugLoc());
7800}
7801
7802VPSingleDefRecipe *VPRecipeBuilder::tryToWidenCall(VPInstruction *VPI,
7803 VFRange &Range) {
7804 CallInst *CI = cast<CallInst>(VPI->getUnderlyingInstr());
7806 [this, CI](ElementCount VF) {
7807 return CM.isScalarWithPredication(CI, VF);
7808 },
7809 Range);
7810
7811 if (IsPredicated)
7812 return nullptr;
7813
7815 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
7816 ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
7817 ID == Intrinsic::pseudoprobe ||
7818 ID == Intrinsic::experimental_noalias_scope_decl))
7819 return nullptr;
7820
7822 VPI->op_begin() + CI->arg_size());
7823
7824 // Is it beneficial to perform intrinsic call compared to lib call?
7825 bool ShouldUseVectorIntrinsic =
7827 [&](ElementCount VF) -> bool {
7828 return CM.getCallWideningDecision(CI, VF).Kind ==
7830 },
7831 Range);
7832 if (ShouldUseVectorIntrinsic)
7833 return new VPWidenIntrinsicRecipe(*CI, ID, Ops, CI->getType(), *VPI, *VPI,
7834 VPI->getDebugLoc());
7835
7836 Function *Variant = nullptr;
7837 std::optional<unsigned> MaskPos;
7838 // Is better to call a vectorized version of the function than to to scalarize
7839 // the call?
7840 auto ShouldUseVectorCall = LoopVectorizationPlanner::getDecisionAndClampRange(
7841 [&](ElementCount VF) -> bool {
7842 // The following case may be scalarized depending on the VF.
7843 // The flag shows whether we can use a usual Call for vectorized
7844 // version of the instruction.
7845
7846 // If we've found a variant at a previous VF, then stop looking. A
7847 // vectorized variant of a function expects input in a certain shape
7848 // -- basically the number of input registers, the number of lanes
7849 // per register, and whether there's a mask required.
7850 // We store a pointer to the variant in the VPWidenCallRecipe, so
7851 // once we have an appropriate variant it's only valid for that VF.
7852 // This will force a different vplan to be generated for each VF that
7853 // finds a valid variant.
7854 if (Variant)
7855 return false;
7856 LoopVectorizationCostModel::CallWideningDecision Decision =
7857 CM.getCallWideningDecision(CI, VF);
7859 Variant = Decision.Variant;
7860 MaskPos = Decision.MaskPos;
7861 return true;
7862 }
7863
7864 return false;
7865 },
7866 Range);
7867 if (ShouldUseVectorCall) {
7868 if (MaskPos.has_value()) {
7869 // We have 2 cases that would require a mask:
7870 // 1) The block needs to be predicated, either due to a conditional
7871 // in the scalar loop or use of an active lane mask with
7872 // tail-folding, and we use the appropriate mask for the block.
7873 // 2) No mask is required for the block, but the only available
7874 // vector variant at this VF requires a mask, so we synthesize an
7875 // all-true mask.
7876 VPValue *Mask = Legal->isMaskRequired(CI)
7877 ? getBlockInMask(Builder.getInsertBlock())
7878 : Plan.getTrue();
7879
7880 Ops.insert(Ops.begin() + *MaskPos, Mask);
7881 }
7882
7883 Ops.push_back(VPI->getOperand(VPI->getNumOperands() - 1));
7884 return new VPWidenCallRecipe(CI, Variant, Ops, *VPI, *VPI,
7885 VPI->getDebugLoc());
7886 }
7887
7888 return nullptr;
7889}
7890
7891bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
7893 !isa<StoreInst>(I) && "Instruction should have been handled earlier");
7894 // Instruction should be widened, unless it is scalar after vectorization,
7895 // scalarization is profitable or it is predicated.
7896 auto WillScalarize = [this, I](ElementCount VF) -> bool {
7897 return CM.isScalarAfterVectorization(I, VF) ||
7898 CM.isProfitableToScalarize(I, VF) ||
7899 CM.isScalarWithPredication(I, VF);
7900 };
7902 Range);
7903}
7904
7905VPWidenRecipe *VPRecipeBuilder::tryToWiden(VPInstruction *VPI) {
7906 auto *I = VPI->getUnderlyingInstr();
7907 switch (VPI->getOpcode()) {
7908 default:
7909 return nullptr;
7910 case Instruction::SDiv:
7911 case Instruction::UDiv:
7912 case Instruction::SRem:
7913 case Instruction::URem: {
7914 // If not provably safe, use a select to form a safe divisor before widening the
7915 // div/rem operation itself. Otherwise fall through to general handling below.
7916 if (CM.isPredicatedInst(I)) {
7918 VPValue *Mask = getBlockInMask(Builder.getInsertBlock());
7919 VPValue *One = Plan.getConstantInt(I->getType(), 1u);
7920 auto *SafeRHS =
7921 Builder.createSelect(Mask, Ops[1], One, VPI->getDebugLoc());
7922 Ops[1] = SafeRHS;
7923 return new VPWidenRecipe(*I, Ops, *VPI, *VPI, VPI->getDebugLoc());
7924 }
7925 [[fallthrough]];
7926 }
7927 case Instruction::Add:
7928 case Instruction::And:
7929 case Instruction::AShr:
7930 case Instruction::FAdd:
7931 case Instruction::FCmp:
7932 case Instruction::FDiv:
7933 case Instruction::FMul:
7934 case Instruction::FNeg:
7935 case Instruction::FRem:
7936 case Instruction::FSub:
7937 case Instruction::ICmp:
7938 case Instruction::LShr:
7939 case Instruction::Mul:
7940 case Instruction::Or:
7941 case Instruction::Select:
7942 case Instruction::Shl:
7943 case Instruction::Sub:
7944 case Instruction::Xor:
7945 case Instruction::Freeze:
7946 return new VPWidenRecipe(*I, VPI->operands(), *VPI, *VPI,
7947 VPI->getDebugLoc());
7948 case Instruction::ExtractValue: {
7949 SmallVector<VPValue *> NewOps(VPI->operands());
7950 auto *EVI = cast<ExtractValueInst>(I);
7951 assert(EVI->getNumIndices() == 1 && "Expected one extractvalue index");
7952 unsigned Idx = EVI->getIndices()[0];
7953 NewOps.push_back(Plan.getConstantInt(32, Idx));
7954 return new VPWidenRecipe(*I, NewOps, *VPI, *VPI, VPI->getDebugLoc());
7955 }
7956 };
7957}
7958
7959VPHistogramRecipe *VPRecipeBuilder::tryToWidenHistogram(const HistogramInfo *HI,
7960 VPInstruction *VPI) {
7961 // FIXME: Support other operations.
7962 unsigned Opcode = HI->Update->getOpcode();
7963 assert((Opcode == Instruction::Add || Opcode == Instruction::Sub) &&
7964 "Histogram update operation must be an Add or Sub");
7965
7967 // Bucket address.
7968 HGramOps.push_back(VPI->getOperand(1));
7969 // Increment value.
7970 HGramOps.push_back(getVPValueOrAddLiveIn(HI->Update->getOperand(1)));
7971
7972 // In case of predicated execution (due to tail-folding, or conditional
7973 // execution, or both), pass the relevant mask.
7974 if (Legal->isMaskRequired(HI->Store))
7975 HGramOps.push_back(getBlockInMask(Builder.getInsertBlock()));
7976
7977 return new VPHistogramRecipe(Opcode, HGramOps, VPI->getDebugLoc());
7978}
7979
7981 VFRange &Range) {
7982 auto *I = VPI->getUnderlyingInstr();
7984 [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
7985 Range);
7986
7987 bool IsPredicated = CM.isPredicatedInst(I);
7988
7989 // Even if the instruction is not marked as uniform, there are certain
7990 // intrinsic calls that can be effectively treated as such, so we check for
7991 // them here. Conservatively, we only do this for scalable vectors, since
7992 // for fixed-width VFs we can always fall back on full scalarization.
7993 if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
7994 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
7995 case Intrinsic::assume:
7996 case Intrinsic::lifetime_start:
7997 case Intrinsic::lifetime_end:
7998 // For scalable vectors if one of the operands is variant then we still
7999 // want to mark as uniform, which will generate one instruction for just
8000 // the first lane of the vector. We can't scalarize the call in the same
8001 // way as for fixed-width vectors because we don't know how many lanes
8002 // there are.
8003 //
8004 // The reasons for doing it this way for scalable vectors are:
8005 // 1. For the assume intrinsic generating the instruction for the first
8006 // lane is still be better than not generating any at all. For
8007 // example, the input may be a splat across all lanes.
8008 // 2. For the lifetime start/end intrinsics the pointer operand only
8009 // does anything useful when the input comes from a stack object,
8010 // which suggests it should always be uniform. For non-stack objects
8011 // the effect is to poison the object, which still allows us to
8012 // remove the call.
8013 IsUniform = true;
8014 break;
8015 default:
8016 break;
8017 }
8018 }
8019 VPValue *BlockInMask = nullptr;
8020 if (!IsPredicated) {
8021 // Finalize the recipe for Instr, first if it is not predicated.
8022 LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8023 } else {
8024 LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8025 // Instructions marked for predication are replicated and a mask operand is
8026 // added initially. Masked replicate recipes will later be placed under an
8027 // if-then construct to prevent side-effects. Generate recipes to compute
8028 // the block mask for this region.
8029 BlockInMask = getBlockInMask(Builder.getInsertBlock());
8030 }
8031
8032 // Note that there is some custom logic to mark some intrinsics as uniform
8033 // manually above for scalable vectors, which this assert needs to account for
8034 // as well.
8035 assert((Range.Start.isScalar() || !IsUniform || !IsPredicated ||
8036 (Range.Start.isScalable() && isa<IntrinsicInst>(I))) &&
8037 "Should not predicate a uniform recipe");
8038 auto *Recipe =
8039 new VPReplicateRecipe(I, VPI->operands(), IsUniform, BlockInMask, *VPI,
8040 *VPI, VPI->getDebugLoc());
8041 return Recipe;
8042}
8043
8044/// Find all possible partial reductions in the loop and track all of those that
8045/// are valid so recipes can be formed later.
8047 // Find all possible partial reductions, grouping chains by their PHI. This
8048 // grouping allows invalidating the whole chain, if any link is not a valid
8049 // partial reduction.
8052 ChainsByPhi;
8053 for (const auto &[Phi, RdxDesc] : Legal->getReductionVars()) {
8054 if (Instruction *RdxExitInstr = RdxDesc.getLoopExitInstr())
8055 getScaledReductions(Phi, RdxExitInstr, Range, ChainsByPhi[Phi]);
8056 }
8057
8058 // A partial reduction is invalid if any of its extends are used by
8059 // something that isn't another partial reduction. This is because the
8060 // extends are intended to be lowered along with the reduction itself.
8061
8062 // Build up a set of partial reduction ops for efficient use checking.
8063 SmallPtrSet<User *, 4> PartialReductionOps;
8064 for (const auto &[_, Chains] : ChainsByPhi)
8065 for (const auto &[PartialRdx, _] : Chains)
8066 PartialReductionOps.insert(PartialRdx.ExtendUser);
8067
8068 auto ExtendIsOnlyUsedByPartialReductions =
8069 [&PartialReductionOps](Instruction *Extend) {
8070 return all_of(Extend->users(), [&](const User *U) {
8071 return PartialReductionOps.contains(U);
8072 });
8073 };
8074
8075 // Check if each use of a chain's two extends is a partial reduction
8076 // and only add those that don't have non-partial reduction users.
8077 for (const auto &[_, Chains] : ChainsByPhi) {
8078 for (const auto &[Chain, Scale] : Chains) {
8079 if (ExtendIsOnlyUsedByPartialReductions(Chain.ExtendA) &&
8080 (!Chain.ExtendB ||
8081 ExtendIsOnlyUsedByPartialReductions(Chain.ExtendB)))
8082 ScaledReductionMap.try_emplace(Chain.Reduction, Scale);
8083 }
8084 }
8085
8086 // Check that all partial reductions in a chain are only used by other
8087 // partial reductions with the same scale factor. Otherwise we end up creating
8088 // users of scaled reductions where the types of the other operands don't
8089 // match.
8090 for (const auto &[Phi, Chains] : ChainsByPhi) {
8091 for (const auto &[Chain, Scale] : Chains) {
8092 auto AllUsersPartialRdx = [ScaleVal = Scale, RdxPhi = Phi,
8093 this](const User *U) {
8094 auto *UI = cast<Instruction>(U);
8095 if (isa<PHINode>(UI) && UI->getParent() == OrigLoop->getHeader())
8096 return UI == RdxPhi;
8097 return ScaledReductionMap.lookup_or(UI, 0) == ScaleVal ||
8098 !OrigLoop->contains(UI->getParent());
8099 };
8100
8101 // If any partial reduction entry for the phi is invalid, invalidate the
8102 // whole chain.
8103 if (!all_of(Chain.Reduction->users(), AllUsersPartialRdx)) {
8104 for (const auto &[Chain, _] : Chains)
8105 ScaledReductionMap.erase(Chain.Reduction);
8106 break;
8107 }
8108 }
8109 }
8110}
8111
8112bool VPRecipeBuilder::getScaledReductions(
8113 Instruction *PHI, Instruction *RdxExitInstr, VFRange &Range,
8114 SmallVectorImpl<std::pair<PartialReductionChain, unsigned>> &Chains) {
8115 if (!CM.TheLoop->contains(RdxExitInstr))
8116 return false;
8117
8118 auto *Update = dyn_cast<BinaryOperator>(RdxExitInstr);
8119 if (!Update)
8120 return false;
8121
8122 Value *Op = Update->getOperand(0);
8123 Value *PhiOp = Update->getOperand(1);
8124 if (Op == PHI)
8125 std::swap(Op, PhiOp);
8126
8127 using namespace llvm::PatternMatch;
8128 // If Op is an extend, then it's still a valid partial reduction if the
8129 // extended mul fulfills the other requirements.
8130 // For example, reduce.add(ext(mul(ext(A), ext(B)))) is still a valid partial
8131 // reduction since the inner extends will be widened. We already have oneUse
8132 // checks on the inner extends so widening them is safe.
8133 std::optional<TTI::PartialReductionExtendKind> OuterExtKind = std::nullopt;
8134 if (match(Op, m_ZExtOrSExt(m_Mul(m_Value(), m_Value())))) {
8135 auto *Cast = cast<CastInst>(Op);
8136 OuterExtKind = TTI::getPartialReductionExtendKind(Cast->getOpcode());
8137 Op = Cast->getOperand(0);
8138 }
8139
8140 // Try and get a scaled reduction from the first non-phi operand.
8141 // If one is found, we use the discovered reduction instruction in
8142 // place of the accumulator for costing.
8143 if (auto *OpInst = dyn_cast<Instruction>(Op)) {
8144 if (getScaledReductions(PHI, OpInst, Range, Chains)) {
8145 PHI = Chains.rbegin()->first.Reduction;
8146
8147 Op = Update->getOperand(0);
8148 PhiOp = Update->getOperand(1);
8149 if (Op == PHI)
8150 std::swap(Op, PhiOp);
8151 }
8152 }
8153 if (PhiOp != PHI)
8154 return false;
8155
8156 // If the update is a binary operator, check both of its operands to see if
8157 // they are extends. Otherwise, see if the update comes directly from an
8158 // extend.
8159 Instruction *Exts[2] = {nullptr};
8160 BinaryOperator *ExtendUser = dyn_cast<BinaryOperator>(Op);
8161 std::optional<unsigned> BinOpc;
8162 Type *ExtOpTypes[2] = {nullptr};
8164
8165 auto CollectExtInfo = [this, OuterExtKind, &Exts, &ExtOpTypes,
8166 &ExtKinds](SmallVectorImpl<Value *> &Ops) -> bool {
8167 for (const auto &[I, OpI] : enumerate(Ops)) {
8168 const APInt *C;
8169 if (I > 0 && match(OpI, m_APInt(C)) &&
8170 canConstantBeExtended(C, ExtOpTypes[0], ExtKinds[0])) {
8171 ExtOpTypes[I] = ExtOpTypes[0];
8172 ExtKinds[I] = ExtKinds[0];
8173 continue;
8174 }
8175 Value *ExtOp;
8176 if (!match(OpI, m_ZExtOrSExt(m_Value(ExtOp))))
8177 return false;
8178 Exts[I] = cast<Instruction>(OpI);
8179
8180 // TODO: We should be able to support live-ins.
8181 if (!CM.TheLoop->contains(Exts[I]))
8182 return false;
8183
8184 ExtOpTypes[I] = ExtOp->getType();
8185 ExtKinds[I] = TTI::getPartialReductionExtendKind(Exts[I]);
8186 // The outer extend kind must be the same as the inner extends, so that
8187 // they can be folded together.
8188 if (OuterExtKind.has_value() && OuterExtKind.value() != ExtKinds[I])
8189 return false;
8190 }
8191 return true;
8192 };
8193
8194 if (ExtendUser) {
8195 if (!ExtendUser->hasOneUse())
8196 return false;
8197
8198 // Use the side-effect of match to replace BinOp only if the pattern is
8199 // matched, we don't care at this point whether it actually matched.
8200 match(ExtendUser, m_Neg(m_BinOp(ExtendUser)));
8201
8202 SmallVector<Value *> Ops(ExtendUser->operands());
8203 if (!CollectExtInfo(Ops))
8204 return false;
8205
8206 BinOpc = std::make_optional(ExtendUser->getOpcode());
8207 } else if (match(Update, m_Add(m_Value(), m_Value()))) {
8208 // We already know the operands for Update are Op and PhiOp.
8210 if (!CollectExtInfo(Ops))
8211 return false;
8212
8213 ExtendUser = Update;
8214 BinOpc = std::nullopt;
8215 } else
8216 return false;
8217
8218 PartialReductionChain Chain(RdxExitInstr, Exts[0], Exts[1], ExtendUser);
8219
8220 TypeSize PHISize = PHI->getType()->getPrimitiveSizeInBits();
8221 TypeSize ASize = ExtOpTypes[0]->getPrimitiveSizeInBits();
8222 if (!PHISize.hasKnownScalarFactor(ASize))
8223 return false;
8224 unsigned TargetScaleFactor = PHISize.getKnownScalarFactor(ASize);
8225
8227 [&](ElementCount VF) {
8228 InstructionCost Cost = TTI->getPartialReductionCost(
8229 Update->getOpcode(), ExtOpTypes[0], ExtOpTypes[1],
8230 PHI->getType(), VF, ExtKinds[0], ExtKinds[1], BinOpc,
8231 CM.CostKind);
8232 return Cost.isValid();
8233 },
8234 Range)) {
8235 Chains.emplace_back(Chain, TargetScaleFactor);
8236 return true;
8237 }
8238
8239 return false;
8240}
8241
8244 VFRange &Range) {
8245 assert(!R->isPhi() && "phis must be handled earlier");
8246 // First, check for specific widening recipes that deal with optimizing
8247 // truncates, calls and memory operations.
8248
8249 VPRecipeBase *Recipe;
8250 auto *VPI = cast<VPInstruction>(R);
8251 if (VPI->getOpcode() == Instruction::Trunc &&
8252 (Recipe = tryToOptimizeInductionTruncate(VPI, Range)))
8253 return Recipe;
8254
8255 // All widen recipes below deal only with VF > 1.
8257 [&](ElementCount VF) { return VF.isScalar(); }, Range))
8258 return nullptr;
8259
8260 if (VPI->getOpcode() == Instruction::Call)
8261 return tryToWidenCall(VPI, Range);
8262
8263 Instruction *Instr = R->getUnderlyingInstr();
8264 if (VPI->getOpcode() == Instruction::Store)
8265 if (auto HistInfo = Legal->getHistogramInfo(cast<StoreInst>(Instr)))
8266 return tryToWidenHistogram(*HistInfo, VPI);
8267
8268 if (VPI->getOpcode() == Instruction::Load ||
8269 VPI->getOpcode() == Instruction::Store)
8270 return tryToWidenMemory(VPI, Range);
8271
8272 if (std::optional<unsigned> ScaleFactor = getScalingForReduction(Instr))
8273 return tryToCreatePartialReduction(VPI, ScaleFactor.value());
8274
8275 if (!shouldWiden(Instr, Range))
8276 return nullptr;
8277
8278 if (VPI->getOpcode() == Instruction::GetElementPtr)
8279 return new VPWidenGEPRecipe(cast<GetElementPtrInst>(Instr), R->operands(),
8280 *VPI, VPI->getDebugLoc());
8281
8282 if (Instruction::isCast(VPI->getOpcode())) {
8283 auto *CI = cast<CastInst>(Instr);
8284 auto *CastR = cast<VPInstructionWithType>(VPI);
8285 return new VPWidenCastRecipe(CI->getOpcode(), VPI->getOperand(0),
8286 CastR->getResultType(), CI, *VPI, *VPI,
8287 VPI->getDebugLoc());
8288 }
8289
8290 return tryToWiden(VPI);
8291}
8292
8295 unsigned ScaleFactor) {
8296 assert(Reduction->getNumOperands() == 2 &&
8297 "Unexpected number of operands for partial reduction");
8298
8299 VPValue *BinOp = Reduction->getOperand(0);
8300 VPValue *Accumulator = Reduction->getOperand(1);
8301 VPRecipeBase *BinOpRecipe = BinOp->getDefiningRecipe();
8302 if (isa<VPReductionPHIRecipe>(BinOpRecipe) ||
8303 (isa<VPReductionRecipe>(BinOpRecipe) &&
8304 cast<VPReductionRecipe>(BinOpRecipe)->isPartialReduction()))
8305 std::swap(BinOp, Accumulator);
8306
8307 if (auto *RedPhiR = dyn_cast<VPReductionPHIRecipe>(Accumulator))
8308 RedPhiR->setVFScaleFactor(ScaleFactor);
8309
8310 assert(ScaleFactor ==
8311 vputils::getVFScaleFactor(Accumulator->getDefiningRecipe()) &&
8312 "all accumulators in chain must have same scale factor");
8313
8314 auto *ReductionI = Reduction->getUnderlyingInstr();
8315 if (Reduction->getOpcode() == Instruction::Sub) {
8317 Ops.push_back(Plan.getConstantInt(ReductionI->getType(), 0));
8318 Ops.push_back(BinOp);
8319 BinOp = new VPWidenRecipe(*ReductionI, Ops, VPIRFlags(*ReductionI),
8320 VPIRMetadata(), ReductionI->getDebugLoc());
8321 Builder.insert(BinOp->getDefiningRecipe());
8322 }
8323
8324 VPValue *Cond = nullptr;
8325 if (CM.blockNeedsPredicationForAnyReason(ReductionI->getParent()))
8326 Cond = getBlockInMask(Builder.getInsertBlock());
8327
8328 return new VPReductionRecipe(
8329 RecurKind::Add, FastMathFlags(), ReductionI, Accumulator, BinOp, Cond,
8330 RdxUnordered{/*VFScaleFactor=*/ScaleFactor}, ReductionI->getDebugLoc());
8331}
8332
8333void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8334 ElementCount MaxVF) {
8335 if (ElementCount::isKnownGT(MinVF, MaxVF))
8336 return;
8337
8338 assert(OrigLoop->isInnermost() && "Inner loop expected.");
8339
8340 const LoopAccessInfo *LAI = Legal->getLAI();
8342 OrigLoop, LI, DT, PSE.getSE());
8343 if (!LAI->getRuntimePointerChecking()->getChecks().empty() &&
8345 // Only use noalias metadata when using memory checks guaranteeing no
8346 // overlap across all iterations.
8347 LVer.prepareNoAliasMetadata();
8348 }
8349
8350 // Create initial base VPlan0, to serve as common starting point for all
8351 // candidates built later for specific VF ranges.
8352 auto VPlan0 = VPlanTransforms::buildVPlan0(
8353 OrigLoop, *LI, Legal->getWidestInductionType(),
8354 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()), PSE, &LVer);
8355
8356 // Create recipes for header phis.
8358 *VPlan0, PSE, *OrigLoop, Legal->getInductionVars(),
8359 Legal->getReductionVars(), Legal->getFixedOrderRecurrences(),
8360 CM.getInLoopReductions(), Hints.allowReordering());
8361
8362 auto MaxVFTimes2 = MaxVF * 2;
8363 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
8364 VFRange SubRange = {VF, MaxVFTimes2};
8365 if (auto Plan = tryToBuildVPlanWithVPRecipes(
8366 std::unique_ptr<VPlan>(VPlan0->duplicate()), SubRange, &LVer)) {
8367 // Now optimize the initial VPlan.
8368 VPlanTransforms::hoistPredicatedLoads(*Plan, PSE, OrigLoop);
8369 VPlanTransforms::sinkPredicatedStores(*Plan, PSE, OrigLoop);
8371 *Plan, CM.getMinimalBitwidths());
8373 // TODO: try to put addExplicitVectorLength close to addActiveLaneMask
8374 if (CM.foldTailWithEVL()) {
8376 *Plan, CM.getMaxSafeElements());
8378 }
8379 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8380 VPlans.push_back(std::move(Plan));
8381 }
8382 VF = SubRange.End;
8383 }
8384}
8385
8386VPlanPtr LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(
8387 VPlanPtr Plan, VFRange &Range, LoopVersioning *LVer) {
8388
8389 using namespace llvm::VPlanPatternMatch;
8390 SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8391
8392 // ---------------------------------------------------------------------------
8393 // Build initial VPlan: Scan the body of the loop in a topological order to
8394 // visit each basic block after having visited its predecessor basic blocks.
8395 // ---------------------------------------------------------------------------
8396
8397 bool RequiresScalarEpilogueCheck =
8399 [this](ElementCount VF) {
8400 return !CM.requiresScalarEpilogue(VF.isVector());
8401 },
8402 Range);
8403 VPlanTransforms::handleEarlyExits(*Plan, Legal->hasUncountableEarlyExit());
8404 VPlanTransforms::addMiddleCheck(*Plan, RequiresScalarEpilogueCheck,
8405 CM.foldTailByMasking());
8406
8408
8409 // Don't use getDecisionAndClampRange here, because we don't know the UF
8410 // so this function is better to be conservative, rather than to split
8411 // it up into different VPlans.
8412 // TODO: Consider using getDecisionAndClampRange here to split up VPlans.
8413 bool IVUpdateMayOverflow = false;
8414 for (ElementCount VF : Range)
8415 IVUpdateMayOverflow |= !isIndvarOverflowCheckKnownFalse(&CM, VF);
8416
8417 TailFoldingStyle Style = CM.getTailFoldingStyle(IVUpdateMayOverflow);
8418 // Use NUW for the induction increment if we proved that it won't overflow in
8419 // the vector loop or when not folding the tail. In the later case, we know
8420 // that the canonical induction increment will not overflow as the vector trip
8421 // count is >= increment and a multiple of the increment.
8422 VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
8423 bool HasNUW = !IVUpdateMayOverflow || Style == TailFoldingStyle::None;
8424 if (!HasNUW) {
8425 auto *IVInc =
8426 LoopRegion->getExitingBasicBlock()->getTerminator()->getOperand(0);
8427 assert(match(IVInc,
8428 m_VPInstruction<Instruction::Add>(
8429 m_Specific(LoopRegion->getCanonicalIV()), m_VPValue())) &&
8430 "Did not find the canonical IV increment");
8431 cast<VPRecipeWithIRFlags>(IVInc)->dropPoisonGeneratingFlags();
8432 }
8433
8434 // ---------------------------------------------------------------------------
8435 // Pre-construction: record ingredients whose recipes we'll need to further
8436 // process after constructing the initial VPlan.
8437 // ---------------------------------------------------------------------------
8438
8439 // For each interleave group which is relevant for this (possibly trimmed)
8440 // Range, add it to the set of groups to be later applied to the VPlan and add
8441 // placeholders for its members' Recipes which we'll be replacing with a
8442 // single VPInterleaveRecipe.
8443 for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8444 auto ApplyIG = [IG, this](ElementCount VF) -> bool {
8445 bool Result = (VF.isVector() && // Query is illegal for VF == 1
8446 CM.getWideningDecision(IG->getInsertPos(), VF) ==
8448 // For scalable vectors, the interleave factors must be <= 8 since we
8449 // require the (de)interleaveN intrinsics instead of shufflevectors.
8450 assert((!Result || !VF.isScalable() || IG->getFactor() <= 8) &&
8451 "Unsupported interleave factor for scalable vectors");
8452 return Result;
8453 };
8454 if (!getDecisionAndClampRange(ApplyIG, Range))
8455 continue;
8456 InterleaveGroups.insert(IG);
8457 }
8458
8459 // ---------------------------------------------------------------------------
8460 // Predicate and linearize the top-level loop region.
8461 // ---------------------------------------------------------------------------
8462 auto BlockMaskCache = VPlanTransforms::introduceMasksAndLinearize(
8463 *Plan, CM.foldTailByMasking());
8464
8465 // ---------------------------------------------------------------------------
8466 // Construct wide recipes and apply predication for original scalar
8467 // VPInstructions in the loop.
8468 // ---------------------------------------------------------------------------
8469 VPRecipeBuilder RecipeBuilder(*Plan, OrigLoop, TLI, &TTI, Legal, CM, Builder,
8470 BlockMaskCache);
8471 // TODO: Handle partial reductions with EVL tail folding.
8472 if (!CM.foldTailWithEVL())
8473 RecipeBuilder.collectScaledReductions(Range);
8474
8475 // Scan the body of the loop in a topological order to visit each basic block
8476 // after having visited its predecessor basic blocks.
8477 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
8478 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> RPOT(
8479 HeaderVPBB);
8480
8481 auto *MiddleVPBB = Plan->getMiddleBlock();
8482 VPBasicBlock::iterator MBIP = MiddleVPBB->getFirstNonPhi();
8483 // Mapping from VPValues in the initial plan to their widened VPValues. Needed
8484 // temporarily to update created block masks.
8485 DenseMap<VPValue *, VPValue *> Old2New;
8486
8487 // Collect blocks that need predication for in-loop reduction recipes.
8488 DenseSet<BasicBlock *> BlocksNeedingPredication;
8489 for (BasicBlock *BB : OrigLoop->blocks())
8490 if (CM.blockNeedsPredicationForAnyReason(BB))
8491 BlocksNeedingPredication.insert(BB);
8492
8494 *Plan, BlockMaskCache, BlocksNeedingPredication, Range.Start);
8495
8496 // Now process all other blocks and instructions.
8497 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
8498 // Convert input VPInstructions to widened recipes.
8499 for (VPRecipeBase &R : make_early_inc_range(
8500 make_range(VPBB->getFirstNonPhi(), VPBB->end()))) {
8501 // Skip recipes that do not need transforming.
8503 continue;
8504 auto *VPI = cast<VPInstruction>(&R);
8505 if (!VPI->getUnderlyingValue())
8506 continue;
8507
8508 // TODO: Gradually replace uses of underlying instruction by analyses on
8509 // VPlan. Migrate code relying on the underlying instruction from VPlan0
8510 // to construct recipes below to not use the underlying instruction.
8512 Builder.setInsertPoint(VPI);
8513
8514 // The stores with invariant address inside the loop will be deleted, and
8515 // in the exit block, a uniform store recipe will be created for the final
8516 // invariant store of the reduction.
8517 StoreInst *SI;
8518 if ((SI = dyn_cast<StoreInst>(Instr)) &&
8519 Legal->isInvariantAddressOfReduction(SI->getPointerOperand())) {
8520 // Only create recipe for the final invariant store of the reduction.
8521 if (Legal->isInvariantStoreOfReduction(SI)) {
8522 auto *Recipe = new VPReplicateRecipe(
8523 SI, R.operands(), true /* IsUniform */, nullptr /*Mask*/, *VPI,
8524 *VPI, VPI->getDebugLoc());
8525 Recipe->insertBefore(*MiddleVPBB, MBIP);
8526 }
8527 R.eraseFromParent();
8528 continue;
8529 }
8530
8531 VPRecipeBase *Recipe =
8532 RecipeBuilder.tryToCreateWidenNonPhiRecipe(VPI, Range);
8533 if (!Recipe)
8534 Recipe =
8535 RecipeBuilder.handleReplication(cast<VPInstruction>(VPI), Range);
8536
8537 RecipeBuilder.setRecipe(Instr, Recipe);
8538 if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) && isa<TruncInst>(Instr)) {
8539 // Optimized a truncate to VPWidenIntOrFpInductionRecipe. It needs to be
8540 // moved to the phi section in the header.
8541 Recipe->insertBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8542 } else {
8543 Builder.insert(Recipe);
8544 }
8545 if (Recipe->getNumDefinedValues() == 1) {
8546 VPI->replaceAllUsesWith(Recipe->getVPSingleValue());
8547 Old2New[VPI] = Recipe->getVPSingleValue();
8548 } else {
8549 assert(Recipe->getNumDefinedValues() == 0 &&
8550 "Unexpected multidef recipe");
8551 R.eraseFromParent();
8552 }
8553 }
8554 }
8555
8556 // replaceAllUsesWith above may invalidate the block masks. Update them here.
8557 // TODO: Include the masks as operands in the predicated VPlan directly
8558 // to remove the need to keep a map of masks beyond the predication
8559 // transform.
8560 RecipeBuilder.updateBlockMaskCache(Old2New);
8561 for (VPValue *Old : Old2New.keys())
8562 Old->getDefiningRecipe()->eraseFromParent();
8563
8564 assert(isa<VPRegionBlock>(LoopRegion) &&
8565 !LoopRegion->getEntryBasicBlock()->empty() &&
8566 "entry block must be set to a VPRegionBlock having a non-empty entry "
8567 "VPBasicBlock");
8568
8569 // TODO: We can't call runPass on these transforms yet, due to verifier
8570 // failures.
8572 DenseMap<VPValue *, VPValue *> IVEndValues;
8573 VPlanTransforms::updateScalarResumePhis(*Plan, IVEndValues);
8574
8575 // ---------------------------------------------------------------------------
8576 // Transform initial VPlan: Apply previously taken decisions, in order, to
8577 // bring the VPlan to its final state.
8578 // ---------------------------------------------------------------------------
8579
8580 addReductionResultComputation(Plan, RecipeBuilder, Range.Start);
8581
8582 // Apply mandatory transformation to handle reductions with multiple in-loop
8583 // uses if possible, bail out otherwise.
8585 *Plan))
8586 return nullptr;
8587 // Apply mandatory transformation to handle FP maxnum/minnum reduction with
8588 // NaNs if possible, bail out otherwise.
8590 *Plan))
8591 return nullptr;
8592
8593 // Create whole-vector selects for find-last recurrences.
8595 *Plan))
8596 return nullptr;
8597
8598 // Transform recipes to abstract recipes if it is legal and beneficial and
8599 // clamp the range for better cost estimation.
8600 // TODO: Enable following transform when the EVL-version of extended-reduction
8601 // and mulacc-reduction are implemented.
8602 if (!CM.foldTailWithEVL()) {
8603 VPCostContext CostCtx(CM.TTI, *CM.TLI, *Plan, CM, CM.CostKind, CM.PSE,
8604 OrigLoop);
8606 CostCtx, Range);
8607 }
8608
8609 for (ElementCount VF : Range)
8610 Plan->addVF(VF);
8611 Plan->setName("Initial VPlan");
8612
8613 // Interleave memory: for each Interleave Group we marked earlier as relevant
8614 // for this VPlan, replace the Recipes widening its memory instructions with a
8615 // single VPInterleaveRecipe at its insertion point.
8617 InterleaveGroups, RecipeBuilder,
8618 CM.isScalarEpilogueAllowed());
8619
8620 // Replace VPValues for known constant strides.
8622 Legal->getLAI()->getSymbolicStrides());
8623
8624 auto BlockNeedsPredication = [this](BasicBlock *BB) {
8625 return Legal->blockNeedsPredication(BB);
8626 };
8628 BlockNeedsPredication);
8629
8630 // Sink users of fixed-order recurrence past the recipe defining the previous
8631 // value and introduce FirstOrderRecurrenceSplice VPInstructions.
8633 *Plan, Builder))
8634 return nullptr;
8635
8636 if (useActiveLaneMask(Style)) {
8637 // TODO: Move checks to VPlanTransforms::addActiveLaneMask once
8638 // TailFoldingStyle is visible there.
8639 bool ForControlFlow = useActiveLaneMaskForControlFlow(Style);
8640 bool WithoutRuntimeCheck =
8642 VPlanTransforms::addActiveLaneMask(*Plan, ForControlFlow,
8643 WithoutRuntimeCheck);
8644 }
8645 VPlanTransforms::optimizeInductionExitUsers(*Plan, IVEndValues, PSE);
8646
8647 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8648 return Plan;
8649}
8650
8651VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan(VFRange &Range) {
8652 // Outer loop handling: They may require CFG and instruction level
8653 // transformations before even evaluating whether vectorization is profitable.
8654 // Since we cannot modify the incoming IR, we need to build VPlan upfront in
8655 // the vectorization pipeline.
8656 assert(!OrigLoop->isInnermost());
8657 assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
8658
8659 auto Plan = VPlanTransforms::buildVPlan0(
8660 OrigLoop, *LI, Legal->getWidestInductionType(),
8661 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()), PSE);
8662
8664 *Plan, PSE, *OrigLoop, Legal->getInductionVars(),
8665 MapVector<PHINode *, RecurrenceDescriptor>(),
8666 SmallPtrSet<const PHINode *, 1>(), SmallPtrSet<PHINode *, 1>(),
8667 /*AllowReordering=*/false);
8669 /*HasUncountableExit*/ false);
8670 VPlanTransforms::addMiddleCheck(*Plan, /*RequiresScalarEpilogue*/ true,
8671 /*TailFolded*/ false);
8672
8674
8675 for (ElementCount VF : Range)
8676 Plan->addVF(VF);
8677
8679 return nullptr;
8680
8681 // TODO: IVEndValues are not used yet in the native path, to optimize exit
8682 // values.
8683 // TODO: We can't call runPass on the transform yet, due to verifier
8684 // failures.
8685 DenseMap<VPValue *, VPValue *> IVEndValues;
8686 VPlanTransforms::updateScalarResumePhis(*Plan, IVEndValues);
8687
8688 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8689 return Plan;
8690}
8691
8692void LoopVectorizationPlanner::addReductionResultComputation(
8693 VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
8694 using namespace VPlanPatternMatch;
8695 VPTypeAnalysis TypeInfo(*Plan);
8696 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
8697 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
8699 VPBasicBlock *LatchVPBB = VectorLoopRegion->getExitingBasicBlock();
8700 Builder.setInsertPoint(&*std::prev(std::prev(LatchVPBB->end())));
8701 VPBasicBlock::iterator IP = MiddleVPBB->getFirstNonPhi();
8702 for (VPRecipeBase &R :
8703 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8704 VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
8705 if (!PhiR)
8706 continue;
8707
8708 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(
8710 Type *PhiTy = TypeInfo.inferScalarType(PhiR);
8711 // If tail is folded by masking, introduce selects between the phi
8712 // and the users outside the vector region of each reduction, at the
8713 // beginning of the dedicated latch block.
8714 auto *OrigExitingVPV = PhiR->getBackedgeValue();
8715 auto *NewExitingVPV = PhiR->getBackedgeValue();
8716 // Don't output selects for partial reductions because they have an output
8717 // with fewer lanes than the VF. So the operands of the select would have
8718 // different numbers of lanes. Partial reductions mask the input instead.
8719 auto *RR = dyn_cast<VPReductionRecipe>(OrigExitingVPV->getDefiningRecipe());
8720 if (!PhiR->isInLoop() && CM.foldTailByMasking() &&
8721 (!RR || !RR->isPartialReduction())) {
8722 VPValue *Cond = RecipeBuilder.getBlockInMask(PhiR->getParent());
8723 std::optional<FastMathFlags> FMFs =
8724 PhiTy->isFloatingPointTy()
8725 ? std::make_optional(RdxDesc.getFastMathFlags())
8726 : std::nullopt;
8727 NewExitingVPV =
8728 Builder.createSelect(Cond, OrigExitingVPV, PhiR, {}, "", FMFs);
8729 OrigExitingVPV->replaceUsesWithIf(NewExitingVPV, [](VPUser &U, unsigned) {
8730 return isa<VPInstruction>(&U) &&
8731 (cast<VPInstruction>(&U)->getOpcode() ==
8733 cast<VPInstruction>(&U)->getOpcode() ==
8735 cast<VPInstruction>(&U)->getOpcode() ==
8737 });
8738 if (CM.usePredicatedReductionSelect())
8739 PhiR->setOperand(1, NewExitingVPV);
8740 }
8741
8742 // We want code in the middle block to appear to execute on the location of
8743 // the scalar loop's latch terminator because: (a) it is all compiler
8744 // generated, (b) these instructions are always executed after evaluating
8745 // the latch conditional branch, and (c) other passes may add new
8746 // predecessors which terminate on this line. This is the easiest way to
8747 // ensure we don't accidentally cause an extra step back into the loop while
8748 // debugging.
8749 DebugLoc ExitDL = OrigLoop->getLoopLatch()->getTerminator()->getDebugLoc();
8750
8751 // TODO: At the moment ComputeReductionResult also drives creation of the
8752 // bc.merge.rdx phi nodes, hence it needs to be created unconditionally here
8753 // even for in-loop reductions, until the reduction resume value handling is
8754 // also modeled in VPlan.
8755 VPInstruction *FinalReductionResult;
8756 VPBuilder::InsertPointGuard Guard(Builder);
8757 Builder.setInsertPoint(MiddleVPBB, IP);
8758 RecurKind RecurrenceKind = PhiR->getRecurrenceKind();
8759 // For AnyOf reductions, find the select among PhiR's users. This is used
8760 // both to find NewVal for ComputeAnyOfResult and to adjust the reduction.
8761 VPRecipeBase *AnyOfSelect = nullptr;
8762 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
8763 AnyOfSelect = cast<VPRecipeBase>(*find_if(PhiR->users(), [](VPUser *U) {
8764 return match(U, m_Select(m_VPValue(), m_VPValue(), m_VPValue()));
8765 }));
8766 }
8768 VPValue *Start = PhiR->getStartValue();
8769 VPValue *Sentinel = Plan->getOrAddLiveIn(RdxDesc.getSentinelValue());
8770 RecurKind MinMaxKind;
8771 bool IsSigned =
8774 MinMaxKind = IsSigned ? RecurKind::SMax : RecurKind::UMax;
8775 else
8776 MinMaxKind = IsSigned ? RecurKind::SMin : RecurKind::UMin;
8777 VPIRFlags Flags(MinMaxKind, /*IsOrdered=*/false, /*IsInLoop=*/false,
8778 FastMathFlags());
8779 FinalReductionResult =
8780 Builder.createNaryOp(VPInstruction::ComputeFindIVResult,
8781 {Start, Sentinel, NewExitingVPV}, Flags, ExitDL);
8782 } else if (AnyOfSelect) {
8783 VPValue *Start = PhiR->getStartValue();
8784 // NewVal is the non-phi operand of the select.
8785 VPValue *NewVal = AnyOfSelect->getOperand(1) == PhiR
8786 ? AnyOfSelect->getOperand(2)
8787 : AnyOfSelect->getOperand(1);
8788 FinalReductionResult =
8789 Builder.createNaryOp(VPInstruction::ComputeAnyOfResult,
8790 {Start, NewVal, NewExitingVPV}, ExitDL);
8791 } else {
8792 FastMathFlags FMFs =
8794 ? RdxDesc.getFastMathFlags()
8795 : FastMathFlags();
8796 VPIRFlags Flags(RecurrenceKind, PhiR->isOrdered(), PhiR->isInLoop(),
8797 FMFs);
8798 FinalReductionResult =
8799 Builder.createNaryOp(VPInstruction::ComputeReductionResult,
8800 {NewExitingVPV}, Flags, ExitDL);
8801 }
8802 // If the vector reduction can be performed in a smaller type, we truncate
8803 // then extend the loop exit value to enable InstCombine to evaluate the
8804 // entire expression in the smaller type.
8805 if (MinVF.isVector() && PhiTy != RdxDesc.getRecurrenceType() &&
8807 assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
8809 "Unexpected truncated min-max recurrence!");
8810 Type *RdxTy = RdxDesc.getRecurrenceType();
8811 VPWidenCastRecipe *Trunc;
8812 Instruction::CastOps ExtendOpc =
8813 RdxDesc.isSigned() ? Instruction::SExt : Instruction::ZExt;
8814 VPWidenCastRecipe *Extnd;
8815 {
8816 VPBuilder::InsertPointGuard Guard(Builder);
8817 Builder.setInsertPoint(
8818 NewExitingVPV->getDefiningRecipe()->getParent(),
8819 std::next(NewExitingVPV->getDefiningRecipe()->getIterator()));
8820 Trunc =
8821 Builder.createWidenCast(Instruction::Trunc, NewExitingVPV, RdxTy);
8822 Extnd = Builder.createWidenCast(ExtendOpc, Trunc, PhiTy);
8823 }
8824 if (PhiR->getOperand(1) == NewExitingVPV)
8825 PhiR->setOperand(1, Extnd->getVPSingleValue());
8826
8827 // Update ComputeReductionResult with the truncated exiting value and
8828 // extend its result. Operand 0 provides the values to be reduced.
8829 FinalReductionResult->setOperand(0, Trunc);
8830 FinalReductionResult =
8831 Builder.createScalarCast(ExtendOpc, FinalReductionResult, PhiTy, {});
8832 }
8833
8834 // Update all users outside the vector region. Also replace redundant
8835 // extracts.
8836 for (auto *U : to_vector(OrigExitingVPV->users())) {
8837 auto *Parent = cast<VPRecipeBase>(U)->getParent();
8838 if (FinalReductionResult == U || Parent->getParent())
8839 continue;
8840 U->replaceUsesOfWith(OrigExitingVPV, FinalReductionResult);
8841
8842 // Look through ExtractLastPart.
8844 U = cast<VPInstruction>(U)->getSingleUser();
8845
8848 cast<VPInstruction>(U)->replaceAllUsesWith(FinalReductionResult);
8849 }
8850
8851 // Adjust AnyOf reductions; replace the reduction phi for the selected value
8852 // with a boolean reduction phi node to check if the condition is true in
8853 // any iteration. The final value is selected by the final
8854 // ComputeReductionResult.
8855 if (AnyOfSelect) {
8856 VPValue *Cmp = AnyOfSelect->getOperand(0);
8857 // If the compare is checking the reduction PHI node, adjust it to check
8858 // the start value.
8859 if (VPRecipeBase *CmpR = Cmp->getDefiningRecipe())
8860 CmpR->replaceUsesOfWith(PhiR, PhiR->getStartValue());
8861 Builder.setInsertPoint(AnyOfSelect);
8862
8863 // If the true value of the select is the reduction phi, the new value is
8864 // selected if the negated condition is true in any iteration.
8865 if (AnyOfSelect->getOperand(1) == PhiR)
8866 Cmp = Builder.createNot(Cmp);
8867 VPValue *Or = Builder.createOr(PhiR, Cmp);
8868 AnyOfSelect->getVPSingleValue()->replaceAllUsesWith(Or);
8869 // Delete AnyOfSelect now that it has invalid types.
8870 ToDelete.push_back(AnyOfSelect);
8871
8872 // Convert the reduction phi to operate on bools.
8873 PhiR->setOperand(0, Plan->getFalse());
8874 continue;
8875 }
8876
8878 RdxDesc.getRecurrenceKind())) {
8879 // Adjust the start value for FindFirstIV/FindLastIV recurrences to use
8880 // the sentinel value after generating the ResumePhi recipe, which uses
8881 // the original start value.
8882 PhiR->setOperand(0, Plan->getOrAddLiveIn(RdxDesc.getSentinelValue()));
8883 }
8884 RecurKind RK = RdxDesc.getRecurrenceKind();
8889 VPBuilder PHBuilder(Plan->getVectorPreheader());
8890 VPValue *Iden = Plan->getOrAddLiveIn(
8891 getRecurrenceIdentity(RK, PhiTy, RdxDesc.getFastMathFlags()));
8892 // If the PHI is used by a partial reduction, set the scale factor.
8893 unsigned ScaleFactor =
8894 RecipeBuilder.getScalingForReduction(RdxDesc.getLoopExitInstr())
8895 .value_or(1);
8896 auto *ScaleFactorVPV = Plan->getConstantInt(32, ScaleFactor);
8897 VPValue *StartV = PHBuilder.createNaryOp(
8899 {PhiR->getStartValue(), Iden, ScaleFactorVPV},
8900 PhiTy->isFloatingPointTy() ? RdxDesc.getFastMathFlags()
8901 : FastMathFlags());
8902 PhiR->setOperand(0, StartV);
8903 }
8904 }
8905 for (VPRecipeBase *R : ToDelete)
8906 R->eraseFromParent();
8907
8909}
8910
8911void LoopVectorizationPlanner::attachRuntimeChecks(
8912 VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const {
8913 const auto &[SCEVCheckCond, SCEVCheckBlock] = RTChecks.getSCEVChecks();
8914 if (SCEVCheckBlock && SCEVCheckBlock->hasNPredecessors(0)) {
8915 assert((!CM.OptForSize ||
8916 CM.Hints->getForce() == LoopVectorizeHints::FK_Enabled) &&
8917 "Cannot SCEV check stride or overflow when optimizing for size");
8918 VPlanTransforms::attachCheckBlock(Plan, SCEVCheckCond, SCEVCheckBlock,
8919 HasBranchWeights);
8920 }
8921 const auto &[MemCheckCond, MemCheckBlock] = RTChecks.getMemRuntimeChecks();
8922 if (MemCheckBlock && MemCheckBlock->hasNPredecessors(0)) {
8923 // VPlan-native path does not do any analysis for runtime checks
8924 // currently.
8925 assert((!EnableVPlanNativePath || OrigLoop->isInnermost()) &&
8926 "Runtime checks are not supported for outer loops yet");
8927
8928 if (CM.OptForSize) {
8929 assert(
8930 CM.Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
8931 "Cannot emit memory checks when optimizing for size, unless forced "
8932 "to vectorize.");
8933 ORE->emit([&]() {
8934 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
8935 OrigLoop->getStartLoc(),
8936 OrigLoop->getHeader())
8937 << "Code-size may be reduced by not forcing "
8938 "vectorization, or by source-code modifications "
8939 "eliminating the need for runtime checks "
8940 "(e.g., adding 'restrict').";
8941 });
8942 }
8943 VPlanTransforms::attachCheckBlock(Plan, MemCheckCond, MemCheckBlock,
8944 HasBranchWeights);
8945 }
8946}
8947
8949 VPlan &Plan, ElementCount VF, unsigned UF,
8950 ElementCount MinProfitableTripCount) const {
8951 // vscale is not necessarily a power-of-2, which means we cannot guarantee
8952 // an overflow to zero when updating induction variables and so an
8953 // additional overflow check is required before entering the vector loop.
8954 bool IsIndvarOverflowCheckNeededForVF =
8955 VF.isScalable() && !TTI.isVScaleKnownToBeAPowerOfTwo() &&
8956 !isIndvarOverflowCheckKnownFalse(&CM, VF, UF) &&
8957 CM.getTailFoldingStyle() !=
8959 const uint32_t *BranchWeigths =
8960 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator())
8962 : nullptr;
8964 Plan, VF, UF, MinProfitableTripCount,
8965 CM.requiresScalarEpilogue(VF.isVector()), CM.foldTailByMasking(),
8966 IsIndvarOverflowCheckNeededForVF, OrigLoop, BranchWeigths,
8967 OrigLoop->getLoopPredecessor()->getTerminator()->getDebugLoc(), PSE);
8968}
8969
8971 assert(!State.Lane && "VPDerivedIVRecipe being replicated.");
8972
8973 // Fast-math-flags propagate from the original induction instruction.
8974 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
8975 if (FPBinOp)
8976 State.Builder.setFastMathFlags(FPBinOp->getFastMathFlags());
8977
8978 Value *Step = State.get(getStepValue(), VPLane(0));
8979 Value *Index = State.get(getOperand(1), VPLane(0));
8980 Value *DerivedIV = emitTransformedIndex(
8981 State.Builder, Index, getStartValue()->getLiveInIRValue(), Step, Kind,
8983 DerivedIV->setName(Name);
8984 State.set(this, DerivedIV, VPLane(0));
8985}
8986
8987// Determine how to lower the scalar epilogue, which depends on 1) optimising
8988// for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
8989// predication, and 4) a TTI hook that analyses whether the loop is suitable
8990// for predication.
8992 Function *F, Loop *L, LoopVectorizeHints &Hints, bool OptForSize,
8995 // 1) OptSize takes precedence over all other options, i.e. if this is set,
8996 // don't look at hints or options, and don't request a scalar epilogue.
8997 if (F->hasOptSize() ||
8998 (OptForSize && Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9000
9001 // 2) If set, obey the directives
9002 if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9010 };
9011 }
9012
9013 // 3) If set, obey the hints
9014 switch (Hints.getPredicate()) {
9019 };
9020
9021 // 4) if the TTI hook indicates this is profitable, request predication.
9022 TailFoldingInfo TFI(TLI, &LVL, IAI);
9023 if (TTI->preferPredicateOverEpilogue(&TFI))
9025
9027}
9028
9029// Process the loop in the VPlan-native vectorization path. This path builds
9030// VPlan upfront in the vectorization pipeline, which allows to apply
9031// VPlan-to-VPlan transformations from the very beginning without modifying the
9032// input LLVM IR.
9038 std::function<BlockFrequencyInfo &()> GetBFI, bool OptForSize,
9039 LoopVectorizeHints &Hints, LoopVectorizationRequirements &Requirements) {
9040
9042 LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9043 return false;
9044 }
9045 assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9046 Function *F = L->getHeader()->getParent();
9047 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9048
9050 getScalarEpilogueLowering(F, L, Hints, OptForSize, TTI, TLI, *LVL, &IAI);
9051
9052 LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE,
9053 GetBFI, F, &Hints, IAI, OptForSize);
9054 // Use the planner for outer loop vectorization.
9055 // TODO: CM is not used at this point inside the planner. Turn CM into an
9056 // optional argument if we don't need it in the future.
9057 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, LVL, CM, IAI, PSE, Hints,
9058 ORE);
9059
9060 // Get user vectorization factor.
9061 ElementCount UserVF = Hints.getWidth();
9062
9064
9065 // Plan how to best vectorize, return the best VF and its cost.
9066 const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9067
9068 // If we are stress testing VPlan builds, do not attempt to generate vector
9069 // code. Masked vector code generation support will follow soon.
9070 // Also, do not attempt to vectorize if no vector code will be produced.
9072 return false;
9073
9074 VPlan &BestPlan = LVP.getPlanFor(VF.Width);
9075
9076 {
9077 GeneratedRTChecks Checks(PSE, DT, LI, TTI, CM.CostKind);
9078 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, /*UF=*/1, &CM,
9079 Checks, BestPlan);
9080 LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9081 << L->getHeader()->getParent()->getName() << "\"\n");
9082 LVP.addMinimumIterationCheck(BestPlan, VF.Width, /*UF=*/1,
9084
9085 LVP.executePlan(VF.Width, /*UF=*/1, BestPlan, LB, DT, false);
9086 }
9087
9088 reportVectorization(ORE, L, VF, 1);
9089
9090 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9091 return true;
9092}
9093
9094// Emit a remark if there are stores to floats that required a floating point
9095// extension. If the vectorized loop was generated with floating point there
9096// will be a performance penalty from the conversion overhead and the change in
9097// the vector width.
9100 for (BasicBlock *BB : L->getBlocks()) {
9101 for (Instruction &Inst : *BB) {
9102 if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9103 if (S->getValueOperand()->getType()->isFloatTy())
9104 Worklist.push_back(S);
9105 }
9106 }
9107 }
9108
9109 // Traverse the floating point stores upwards searching, for floating point
9110 // conversions.
9113 while (!Worklist.empty()) {
9114 auto *I = Worklist.pop_back_val();
9115 if (!L->contains(I))
9116 continue;
9117 if (!Visited.insert(I).second)
9118 continue;
9119
9120 // Emit a remark if the floating point store required a floating
9121 // point conversion.
9122 // TODO: More work could be done to identify the root cause such as a
9123 // constant or a function return type and point the user to it.
9124 if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9125 ORE->emit([&]() {
9126 return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9127 I->getDebugLoc(), L->getHeader())
9128 << "floating point conversion changes vector width. "
9129 << "Mixed floating point precision requires an up/down "
9130 << "cast that will negatively impact performance.";
9131 });
9132
9133 for (Use &Op : I->operands())
9134 if (auto *OpI = dyn_cast<Instruction>(Op))
9135 Worklist.push_back(OpI);
9136 }
9137}
9138
9139/// For loops with uncountable early exits, find the cost of doing work when
9140/// exiting the loop early, such as calculating the final exit values of
9141/// variables used outside the loop.
9142/// TODO: This is currently overly pessimistic because the loop may not take
9143/// the early exit, but better to keep this conservative for now. In future,
9144/// it might be possible to relax this by using branch probabilities.
9146 VPlan &Plan, ElementCount VF) {
9147 InstructionCost Cost = 0;
9148 for (auto *ExitVPBB : Plan.getExitBlocks()) {
9149 for (auto *PredVPBB : ExitVPBB->getPredecessors()) {
9150 // If the predecessor is not the middle.block, then it must be the
9151 // vector.early.exit block, which may contain work to calculate the exit
9152 // values of variables used outside the loop.
9153 if (PredVPBB != Plan.getMiddleBlock()) {
9154 LLVM_DEBUG(dbgs() << "Calculating cost of work in exit block "
9155 << PredVPBB->getName() << ":\n");
9156 Cost += PredVPBB->cost(VF, CostCtx);
9157 }
9158 }
9159 }
9160 return Cost;
9161}
9162
9163/// This function determines whether or not it's still profitable to vectorize
9164/// the loop given the extra work we have to do outside of the loop:
9165/// 1. Perform the runtime checks before entering the loop to ensure it's safe
9166/// to vectorize.
9167/// 2. In the case of loops with uncountable early exits, we may have to do
9168/// extra work when exiting the loop early, such as calculating the final
9169/// exit values of variables used outside the loop.
9170/// 3. The middle block.
9171static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks,
9172 VectorizationFactor &VF, Loop *L,
9174 VPCostContext &CostCtx, VPlan &Plan,
9176 std::optional<unsigned> VScale) {
9177 InstructionCost TotalCost = Checks.getCost();
9178 if (!TotalCost.isValid())
9179 return false;
9180
9181 // Add on the cost of any work required in the vector early exit block, if
9182 // one exists.
9183 TotalCost += calculateEarlyExitCost(CostCtx, Plan, VF.Width);
9184
9185 TotalCost += Plan.getMiddleBlock()->cost(VF.Width, CostCtx);
9186
9187 // When interleaving only scalar and vector cost will be equal, which in turn
9188 // would lead to a divide by 0. Fall back to hard threshold.
9189 if (VF.Width.isScalar()) {
9190 // TODO: Should we rename VectorizeMemoryCheckThreshold?
9191 if (TotalCost > VectorizeMemoryCheckThreshold) {
9192 LLVM_DEBUG(
9193 dbgs()
9194 << "LV: Interleaving only is not profitable due to runtime checks\n");
9195 return false;
9196 }
9197 return true;
9198 }
9199
9200 // The scalar cost should only be 0 when vectorizing with a user specified
9201 // VF/IC. In those cases, runtime checks should always be generated.
9202 uint64_t ScalarC = VF.ScalarCost.getValue();
9203 if (ScalarC == 0)
9204 return true;
9205
9206 // First, compute the minimum iteration count required so that the vector
9207 // loop outperforms the scalar loop.
9208 // The total cost of the scalar loop is
9209 // ScalarC * TC
9210 // where
9211 // * TC is the actual trip count of the loop.
9212 // * ScalarC is the cost of a single scalar iteration.
9213 //
9214 // The total cost of the vector loop is
9215 // RtC + VecC * (TC / VF) + EpiC
9216 // where
9217 // * RtC is the sum of the costs cost of
9218 // - the generated runtime checks
9219 // - performing any additional work in the vector.early.exit block for
9220 // loops with uncountable early exits.
9221 // - the middle block, if ExpectedTC <= VF.Width.
9222 // * VecC is the cost of a single vector iteration.
9223 // * TC is the actual trip count of the loop
9224 // * VF is the vectorization factor
9225 // * EpiCost is the cost of the generated epilogue, including the cost
9226 // of the remaining scalar operations.
9227 //
9228 // Vectorization is profitable once the total vector cost is less than the
9229 // total scalar cost:
9230 // RtC + VecC * (TC / VF) + EpiC < ScalarC * TC
9231 //
9232 // Now we can compute the minimum required trip count TC as
9233 // VF * (RtC + EpiC) / (ScalarC * VF - VecC) < TC
9234 //
9235 // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
9236 // the computations are performed on doubles, not integers and the result
9237 // is rounded up, hence we get an upper estimate of the TC.
9238 unsigned IntVF = estimateElementCount(VF.Width, VScale);
9239 uint64_t RtC = TotalCost.getValue();
9240 uint64_t Div = ScalarC * IntVF - VF.Cost.getValue();
9241 uint64_t MinTC1 = Div == 0 ? 0 : divideCeil(RtC * IntVF, Div);
9242
9243 // Second, compute a minimum iteration count so that the cost of the
9244 // runtime checks is only a fraction of the total scalar loop cost. This
9245 // adds a loop-dependent bound on the overhead incurred if the runtime
9246 // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
9247 // * TC. To bound the runtime check to be a fraction 1/X of the scalar
9248 // cost, compute
9249 // RtC < ScalarC * TC * (1 / X) ==> RtC * X / ScalarC < TC
9250 uint64_t MinTC2 = divideCeil(RtC * 10, ScalarC);
9251
9252 // Now pick the larger minimum. If it is not a multiple of VF and a scalar
9253 // epilogue is allowed, choose the next closest multiple of VF. This should
9254 // partly compensate for ignoring the epilogue cost.
9255 uint64_t MinTC = std::max(MinTC1, MinTC2);
9256 if (SEL == CM_ScalarEpilogueAllowed)
9257 MinTC = alignTo(MinTC, IntVF);
9259
9260 LLVM_DEBUG(
9261 dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
9262 << VF.MinProfitableTripCount << "\n");
9263
9264 // Skip vectorization if the expected trip count is less than the minimum
9265 // required trip count.
9266 if (auto ExpectedTC = getSmallBestKnownTC(PSE, L)) {
9267 if (ElementCount::isKnownLT(*ExpectedTC, VF.MinProfitableTripCount)) {
9268 LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
9269 "trip count < minimum profitable VF ("
9270 << *ExpectedTC << " < " << VF.MinProfitableTripCount
9271 << ")\n");
9272
9273 return false;
9274 }
9275 }
9276 return true;
9277}
9278
9280 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9282 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9284
9285/// Prepare \p MainPlan for vectorizing the main vector loop during epilogue
9286/// vectorization. Remove ResumePhis from \p MainPlan for inductions that
9287/// don't have a corresponding wide induction in \p EpiPlan.
9288static void preparePlanForMainVectorLoop(VPlan &MainPlan, VPlan &EpiPlan) {
9289 // Collect PHI nodes of widened phis in the VPlan for the epilogue. Those
9290 // will need their resume-values computed in the main vector loop. Others
9291 // can be removed from the main VPlan.
9292 SmallPtrSet<PHINode *, 2> EpiWidenedPhis;
9293 for (VPRecipeBase &R :
9296 continue;
9297 EpiWidenedPhis.insert(
9298 cast<PHINode>(R.getVPSingleValue()->getUnderlyingValue()));
9299 }
9300 for (VPRecipeBase &R :
9301 make_early_inc_range(MainPlan.getScalarHeader()->phis())) {
9302 auto *VPIRInst = cast<VPIRPhi>(&R);
9303 if (EpiWidenedPhis.contains(&VPIRInst->getIRPhi()))
9304 continue;
9305 // There is no corresponding wide induction in the epilogue plan that would
9306 // need a resume value. Remove the VPIRInst wrapping the scalar header phi
9307 // together with the corresponding ResumePhi. The resume values for the
9308 // scalar loop will be created during execution of EpiPlan.
9309 VPRecipeBase *ResumePhi = VPIRInst->getOperand(0)->getDefiningRecipe();
9310 VPIRInst->eraseFromParent();
9311 ResumePhi->eraseFromParent();
9312 }
9314
9315 using namespace VPlanPatternMatch;
9316 // When vectorizing the epilogue, FindFirstIV & FindLastIV reductions can
9317 // introduce multiple uses of undef/poison. If the reduction start value may
9318 // be undef or poison it needs to be frozen and the frozen start has to be
9319 // used when computing the reduction result. We also need to use the frozen
9320 // value in the resume phi generated by the main vector loop, as this is also
9321 // used to compute the reduction result after the epilogue vector loop.
9322 auto AddFreezeForFindLastIVReductions = [](VPlan &Plan,
9323 bool UpdateResumePhis) {
9324 VPBuilder Builder(Plan.getEntry());
9325 for (VPRecipeBase &R : *Plan.getMiddleBlock()) {
9326 auto *VPI = dyn_cast<VPInstruction>(&R);
9327 if (!VPI || VPI->getOpcode() != VPInstruction::ComputeFindIVResult)
9328 continue;
9329 VPValue *OrigStart = VPI->getOperand(0);
9331 continue;
9332 VPInstruction *Freeze =
9333 Builder.createNaryOp(Instruction::Freeze, {OrigStart}, {}, "fr");
9334 VPI->setOperand(0, Freeze);
9335 if (UpdateResumePhis)
9336 OrigStart->replaceUsesWithIf(Freeze, [Freeze](VPUser &U, unsigned) {
9337 return Freeze != &U && isa<VPPhi>(&U);
9338 });
9339 }
9340 };
9341 AddFreezeForFindLastIVReductions(MainPlan, true);
9342 AddFreezeForFindLastIVReductions(EpiPlan, false);
9343
9344 VPBasicBlock *MainScalarPH = MainPlan.getScalarPreheader();
9345 VPValue *VectorTC = &MainPlan.getVectorTripCount();
9346 // If there is a suitable resume value for the canonical induction in the
9347 // scalar (which will become vector) epilogue loop, use it and move it to the
9348 // beginning of the scalar preheader. Otherwise create it below.
9349 auto ResumePhiIter =
9350 find_if(MainScalarPH->phis(), [VectorTC](VPRecipeBase &R) {
9351 return match(&R, m_VPInstruction<Instruction::PHI>(m_Specific(VectorTC),
9352 m_ZeroInt()));
9353 });
9354 VPPhi *ResumePhi = nullptr;
9355 if (ResumePhiIter == MainScalarPH->phis().end()) {
9356 VPBuilder ScalarPHBuilder(MainScalarPH, MainScalarPH->begin());
9357 ResumePhi = ScalarPHBuilder.createScalarPhi(
9358 {VectorTC,
9360 {}, "vec.epilog.resume.val");
9361 } else {
9362 ResumePhi = cast<VPPhi>(&*ResumePhiIter);
9363 if (MainScalarPH->begin() == MainScalarPH->end())
9364 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->end());
9365 else if (&*MainScalarPH->begin() != ResumePhi)
9366 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->begin());
9367 }
9368 // Add a user to to make sure the resume phi won't get removed.
9369 VPBuilder(MainScalarPH)
9371}
9372
9373/// Prepare \p Plan for vectorizing the epilogue loop. That is, re-use expanded
9374/// SCEVs from \p ExpandedSCEVs and set resume values for header recipes. Some
9375/// reductions require creating new instructions to compute the resume values.
9376/// They are collected in a vector and returned. They must be moved to the
9377/// preheader of the vector epilogue loop, after created by the execution of \p
9378/// Plan.
9380 VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs,
9382 ScalarEvolution &SE) {
9383 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
9384 VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
9385 Header->setName("vec.epilog.vector.body");
9386
9387 VPCanonicalIVPHIRecipe *IV = VectorLoop->getCanonicalIV();
9388 // When vectorizing the epilogue loop, the canonical induction needs to be
9389 // adjusted by the value after the main vector loop. Find the resume value
9390 // created during execution of the main VPlan. It must be the first phi in the
9391 // loop preheader. Use the value to increment the canonical IV, and update all
9392 // users in the loop region to use the adjusted value.
9393 // FIXME: Improve modeling for canonical IV start values in the epilogue
9394 // loop.
9395 using namespace llvm::PatternMatch;
9396 PHINode *EPResumeVal = &*L->getLoopPreheader()->phis().begin();
9397 for (Value *Inc : EPResumeVal->incoming_values()) {
9398 if (match(Inc, m_SpecificInt(0)))
9399 continue;
9400 assert(!EPI.VectorTripCount &&
9401 "Must only have a single non-zero incoming value");
9402 EPI.VectorTripCount = Inc;
9403 }
9404 // If we didn't find a non-zero vector trip count, all incoming values
9405 // must be zero, which also means the vector trip count is zero. Pick the
9406 // first zero as vector trip count.
9407 // TODO: We should not choose VF * UF so the main vector loop is known to
9408 // be dead.
9409 if (!EPI.VectorTripCount) {
9410 assert(EPResumeVal->getNumIncomingValues() > 0 &&
9411 all_of(EPResumeVal->incoming_values(),
9412 [](Value *Inc) { return match(Inc, m_SpecificInt(0)); }) &&
9413 "all incoming values must be 0");
9414 EPI.VectorTripCount = EPResumeVal->getOperand(0);
9415 }
9416 VPValue *VPV = Plan.getOrAddLiveIn(EPResumeVal);
9417 assert(all_of(IV->users(),
9418 [](const VPUser *U) {
9419 return isa<VPScalarIVStepsRecipe>(U) ||
9420 isa<VPDerivedIVRecipe>(U) ||
9421 cast<VPRecipeBase>(U)->isScalarCast() ||
9422 cast<VPInstruction>(U)->getOpcode() ==
9423 Instruction::Add;
9424 }) &&
9425 "the canonical IV should only be used by its increment or "
9426 "ScalarIVSteps when resetting the start value");
9427 VPBuilder Builder(Header, Header->getFirstNonPhi());
9428 VPInstruction *Add = Builder.createNaryOp(Instruction::Add, {IV, VPV});
9429 IV->replaceAllUsesWith(Add);
9430 Add->setOperand(0, IV);
9431
9433 SmallVector<Instruction *> InstsToMove;
9434 // Ensure that the start values for all header phi recipes are updated before
9435 // vectorizing the epilogue loop. Skip the canonical IV, which has been
9436 // handled above.
9437 for (VPRecipeBase &R : drop_begin(Header->phis())) {
9438 Value *ResumeV = nullptr;
9439 // TODO: Move setting of resume values to prepareToExecute.
9440 if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
9441 // Find the reduction result by searching users of the phi or its backedge
9442 // value.
9443 auto IsReductionResult = [](VPRecipeBase *R) {
9444 auto *VPI = dyn_cast<VPInstruction>(R);
9445 return VPI &&
9449 };
9450 auto *RdxResult = cast<VPInstruction>(
9451 findRecipe(ReductionPhi->getBackedgeValue(), IsReductionResult));
9452 assert(
9453 (is_contained(RdxResult->operands(),
9454 ReductionPhi->getBackedgeValue()) ||
9455 (isa<VPWidenCastRecipe>(ReductionPhi->getBackedgeValue()) &&
9456 is_contained(RdxResult->operands(), ReductionPhi->getBackedgeValue()
9457 ->getDefiningRecipe()
9458 ->getOperand(0))) ||
9459 RdxResult->getOpcode() == VPInstruction::ComputeFindIVResult) &&
9460 "expected to find reduction result via backedge");
9461
9462 ResumeV = cast<PHINode>(ReductionPhi->getUnderlyingInstr())
9463 ->getIncomingValueForBlock(L->getLoopPreheader());
9464 RecurKind RK = ReductionPhi->getRecurrenceKind();
9466 Value *StartV = RdxResult->getOperand(0)->getLiveInIRValue();
9467 // VPReductionPHIRecipes for AnyOf reductions expect a boolean as
9468 // start value; compare the final value from the main vector loop
9469 // to the start value.
9470 BasicBlock *PBB = cast<Instruction>(ResumeV)->getParent();
9471 IRBuilder<> Builder(PBB, PBB->getFirstNonPHIIt());
9472 ResumeV = Builder.CreateICmpNE(ResumeV, StartV);
9473 if (auto *I = dyn_cast<Instruction>(ResumeV))
9474 InstsToMove.push_back(I);
9476 Value *StartV = getStartValueFromReductionResult(RdxResult);
9477 ToFrozen[StartV] = cast<PHINode>(ResumeV)->getIncomingValueForBlock(
9479
9480 // VPReductionPHIRecipe for FindFirstIV/FindLastIV reductions requires
9481 // an adjustment to the resume value. The resume value is adjusted to
9482 // the sentinel value when the final value from the main vector loop
9483 // equals the start value. This ensures correctness when the start value
9484 // might not be less than the minimum value of a monotonically
9485 // increasing induction variable.
9486 BasicBlock *ResumeBB = cast<Instruction>(ResumeV)->getParent();
9487 IRBuilder<> Builder(ResumeBB, ResumeBB->getFirstNonPHIIt());
9488 Value *Cmp = Builder.CreateICmpEQ(ResumeV, ToFrozen[StartV]);
9489 if (auto *I = dyn_cast<Instruction>(Cmp))
9490 InstsToMove.push_back(I);
9491 Value *Sentinel = RdxResult->getOperand(1)->getLiveInIRValue();
9492 ResumeV = Builder.CreateSelect(Cmp, Sentinel, ResumeV);
9493 if (auto *I = dyn_cast<Instruction>(ResumeV))
9494 InstsToMove.push_back(I);
9495 } else {
9496 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
9497 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9498 if (auto *VPI = dyn_cast<VPInstruction>(PhiR->getStartValue())) {
9500 "unexpected start value");
9501 VPI->setOperand(0, StartVal);
9502 continue;
9503 }
9504 }
9505 } else {
9506 // Retrieve the induction resume values for wide inductions from
9507 // their original phi nodes in the scalar loop.
9508 PHINode *IndPhi = cast<VPWidenInductionRecipe>(&R)->getPHINode();
9509 // Hook up to the PHINode generated by a ResumePhi recipe of main
9510 // loop VPlan, which feeds the scalar loop.
9511 ResumeV = IndPhi->getIncomingValueForBlock(L->getLoopPreheader());
9512 }
9513 assert(ResumeV && "Must have a resume value");
9514 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
9515 cast<VPHeaderPHIRecipe>(&R)->setStartValue(StartVal);
9516 }
9517
9518 // For some VPValues in the epilogue plan we must re-use the generated IR
9519 // values from the main plan. Replace them with live-in VPValues.
9520 // TODO: This is a workaround needed for epilogue vectorization and it
9521 // should be removed once induction resume value creation is done
9522 // directly in VPlan.
9523 for (auto &R : make_early_inc_range(*Plan.getEntry())) {
9524 // Re-use frozen values from the main plan for Freeze VPInstructions in the
9525 // epilogue plan. This ensures all users use the same frozen value.
9526 auto *VPI = dyn_cast<VPInstruction>(&R);
9527 if (VPI && VPI->getOpcode() == Instruction::Freeze) {
9529 ToFrozen.lookup(VPI->getOperand(0)->getLiveInIRValue())));
9530 continue;
9531 }
9532
9533 // Re-use the trip count and steps expanded for the main loop, as
9534 // skeleton creation needs it as a value that dominates both the scalar
9535 // and vector epilogue loops
9536 auto *ExpandR = dyn_cast<VPExpandSCEVRecipe>(&R);
9537 if (!ExpandR)
9538 continue;
9539 VPValue *ExpandedVal =
9540 Plan.getOrAddLiveIn(ExpandedSCEVs.lookup(ExpandR->getSCEV()));
9541 ExpandR->replaceAllUsesWith(ExpandedVal);
9542 if (Plan.getTripCount() == ExpandR)
9543 Plan.resetTripCount(ExpandedVal);
9544 ExpandR->eraseFromParent();
9545 }
9546
9547 auto VScale = CM.getVScaleForTuning();
9548 unsigned MainLoopStep =
9549 estimateElementCount(EPI.MainLoopVF * EPI.MainLoopUF, VScale);
9550 unsigned EpilogueLoopStep =
9551 estimateElementCount(EPI.EpilogueVF * EPI.EpilogueUF, VScale);
9553 Plan, EPI.TripCount, EPI.VectorTripCount,
9555 EPI.EpilogueUF, MainLoopStep, EpilogueLoopStep, SE);
9556
9557 return InstsToMove;
9558}
9559
9560// Generate bypass values from the additional bypass block. Note that when the
9561// vectorized epilogue is skipped due to iteration count check, then the
9562// resume value for the induction variable comes from the trip count of the
9563// main vector loop, passed as the second argument.
9565 PHINode *OrigPhi, const InductionDescriptor &II, IRBuilder<> &BypassBuilder,
9566 const SCEV2ValueTy &ExpandedSCEVs, Value *MainVectorTripCount,
9567 Instruction *OldInduction) {
9568 Value *Step = getExpandedStep(II, ExpandedSCEVs);
9569 // For the primary induction the additional bypass end value is known.
9570 // Otherwise it is computed.
9571 Value *EndValueFromAdditionalBypass = MainVectorTripCount;
9572 if (OrigPhi != OldInduction) {
9573 auto *BinOp = II.getInductionBinOp();
9574 // Fast-math-flags propagate from the original induction instruction.
9576 BypassBuilder.setFastMathFlags(BinOp->getFastMathFlags());
9577
9578 // Compute the end value for the additional bypass.
9579 EndValueFromAdditionalBypass =
9580 emitTransformedIndex(BypassBuilder, MainVectorTripCount,
9581 II.getStartValue(), Step, II.getKind(), BinOp);
9582 EndValueFromAdditionalBypass->setName("ind.end");
9583 }
9584 return EndValueFromAdditionalBypass;
9585}
9586
9588 VPlan &BestEpiPlan,
9590 const SCEV2ValueTy &ExpandedSCEVs,
9591 Value *MainVectorTripCount) {
9592 // Fix reduction resume values from the additional bypass block.
9593 BasicBlock *PH = L->getLoopPreheader();
9594 for (auto *Pred : predecessors(PH)) {
9595 for (PHINode &Phi : PH->phis()) {
9596 if (Phi.getBasicBlockIndex(Pred) != -1)
9597 continue;
9598 Phi.addIncoming(Phi.getIncomingValueForBlock(BypassBlock), Pred);
9599 }
9600 }
9601 auto *ScalarPH = cast<VPIRBasicBlock>(BestEpiPlan.getScalarPreheader());
9602 if (ScalarPH->hasPredecessors()) {
9603 // If ScalarPH has predecessors, we may need to update its reduction
9604 // resume values.
9605 for (const auto &[R, IRPhi] :
9606 zip(ScalarPH->phis(), ScalarPH->getIRBasicBlock()->phis())) {
9608 BypassBlock);
9609 }
9610 }
9611
9612 // Fix induction resume values from the additional bypass block.
9613 IRBuilder<> BypassBuilder(BypassBlock, BypassBlock->getFirstInsertionPt());
9614 for (const auto &[IVPhi, II] : LVL.getInductionVars()) {
9615 auto *Inc = cast<PHINode>(IVPhi->getIncomingValueForBlock(PH));
9617 IVPhi, II, BypassBuilder, ExpandedSCEVs, MainVectorTripCount,
9618 LVL.getPrimaryInduction());
9619 // TODO: Directly add as extra operand to the VPResumePHI recipe.
9620 Inc->setIncomingValueForBlock(BypassBlock, V);
9621 }
9622}
9623
9624/// Connect the epilogue vector loop generated for \p EpiPlan to the main vector
9625// loop, after both plans have executed, updating branches from the iteration
9626// and runtime checks of the main loop, as well as updating various phis. \p
9627// InstsToMove contains instructions that need to be moved to the preheader of
9628// the epilogue vector loop.
9630 VPlan &EpiPlan, Loop *L, EpilogueLoopVectorizationInfo &EPI,
9632 DenseMap<const SCEV *, Value *> &ExpandedSCEVs, GeneratedRTChecks &Checks,
9633 ArrayRef<Instruction *> InstsToMove) {
9634 BasicBlock *VecEpilogueIterationCountCheck =
9635 cast<VPIRBasicBlock>(EpiPlan.getEntry())->getIRBasicBlock();
9636
9637 BasicBlock *VecEpiloguePreHeader =
9638 cast<BranchInst>(VecEpilogueIterationCountCheck->getTerminator())
9639 ->getSuccessor(1);
9640 // Adjust the control flow taking the state info from the main loop
9641 // vectorization into account.
9643 "expected this to be saved from the previous pass.");
9644 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
9646 VecEpilogueIterationCountCheck, VecEpiloguePreHeader);
9647
9649 VecEpilogueIterationCountCheck},
9651 VecEpiloguePreHeader}});
9652
9653 BasicBlock *ScalarPH =
9654 cast<VPIRBasicBlock>(EpiPlan.getScalarPreheader())->getIRBasicBlock();
9656 VecEpilogueIterationCountCheck, ScalarPH);
9657 DTU.applyUpdates(
9659 VecEpilogueIterationCountCheck},
9661
9662 // Adjust the terminators of runtime check blocks and phis using them.
9663 BasicBlock *SCEVCheckBlock = Checks.getSCEVChecks().second;
9664 BasicBlock *MemCheckBlock = Checks.getMemRuntimeChecks().second;
9665 if (SCEVCheckBlock) {
9666 SCEVCheckBlock->getTerminator()->replaceUsesOfWith(
9667 VecEpilogueIterationCountCheck, ScalarPH);
9668 DTU.applyUpdates({{DominatorTree::Delete, SCEVCheckBlock,
9669 VecEpilogueIterationCountCheck},
9670 {DominatorTree::Insert, SCEVCheckBlock, ScalarPH}});
9671 }
9672 if (MemCheckBlock) {
9673 MemCheckBlock->getTerminator()->replaceUsesOfWith(
9674 VecEpilogueIterationCountCheck, ScalarPH);
9675 DTU.applyUpdates(
9676 {{DominatorTree::Delete, MemCheckBlock, VecEpilogueIterationCountCheck},
9677 {DominatorTree::Insert, MemCheckBlock, ScalarPH}});
9678 }
9679
9680 // The vec.epilog.iter.check block may contain Phi nodes from inductions
9681 // or reductions which merge control-flow from the latch block and the
9682 // middle block. Update the incoming values here and move the Phi into the
9683 // preheader.
9684 SmallVector<PHINode *, 4> PhisInBlock(
9685 llvm::make_pointer_range(VecEpilogueIterationCountCheck->phis()));
9686
9687 for (PHINode *Phi : PhisInBlock) {
9688 Phi->moveBefore(VecEpiloguePreHeader->getFirstNonPHIIt());
9689 Phi->replaceIncomingBlockWith(
9690 VecEpilogueIterationCountCheck->getSinglePredecessor(),
9691 VecEpilogueIterationCountCheck);
9692
9693 // If the phi doesn't have an incoming value from the
9694 // EpilogueIterationCountCheck, we are done. Otherwise remove the
9695 // incoming value and also those from other check blocks. This is needed
9696 // for reduction phis only.
9697 if (none_of(Phi->blocks(), [&](BasicBlock *IncB) {
9698 return EPI.EpilogueIterationCountCheck == IncB;
9699 }))
9700 continue;
9701 Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
9702 if (SCEVCheckBlock)
9703 Phi->removeIncomingValue(SCEVCheckBlock);
9704 if (MemCheckBlock)
9705 Phi->removeIncomingValue(MemCheckBlock);
9706 }
9707
9708 auto IP = VecEpiloguePreHeader->getFirstNonPHIIt();
9709 for (auto *I : InstsToMove)
9710 I->moveBefore(IP);
9711
9712 // VecEpilogueIterationCountCheck conditionally skips over the epilogue loop
9713 // after executing the main loop. We need to update the resume values of
9714 // inductions and reductions during epilogue vectorization.
9715 fixScalarResumeValuesFromBypass(VecEpilogueIterationCountCheck, L, EpiPlan,
9716 LVL, ExpandedSCEVs, EPI.VectorTripCount);
9717}
9718
9720 assert((EnableVPlanNativePath || L->isInnermost()) &&
9721 "VPlan-native path is not enabled. Only process inner loops.");
9722
9723 LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
9724 << L->getHeader()->getParent()->getName() << "' from "
9725 << L->getLocStr() << "\n");
9726
9727 LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
9728
9729 LLVM_DEBUG(
9730 dbgs() << "LV: Loop hints:"
9731 << " force="
9733 ? "disabled"
9735 ? "enabled"
9736 : "?"))
9737 << " width=" << Hints.getWidth()
9738 << " interleave=" << Hints.getInterleave() << "\n");
9739
9740 // Function containing loop
9741 Function *F = L->getHeader()->getParent();
9742
9743 // Looking at the diagnostic output is the only way to determine if a loop
9744 // was vectorized (other than looking at the IR or machine code), so it
9745 // is important to generate an optimization remark for each loop. Most of
9746 // these messages are generated as OptimizationRemarkAnalysis. Remarks
9747 // generated as OptimizationRemark and OptimizationRemarkMissed are
9748 // less verbose reporting vectorized loops and unvectorized loops that may
9749 // benefit from vectorization, respectively.
9750
9751 if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9752 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9753 return false;
9754 }
9755
9756 PredicatedScalarEvolution PSE(*SE, *L);
9757
9758 // Query this against the original loop and save it here because the profile
9759 // of the original loop header may change as the transformation happens.
9760 bool OptForSize = llvm::shouldOptimizeForSize(
9761 L->getHeader(), PSI,
9762 PSI && PSI->hasProfileSummary() ? &GetBFI() : nullptr,
9764
9765 // Check if it is legal to vectorize the loop.
9766 LoopVectorizationRequirements Requirements;
9767 LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, F, *LAIs, LI, ORE,
9768 &Requirements, &Hints, DB, AC,
9769 /*AllowRuntimeSCEVChecks=*/!OptForSize, AA);
9771 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9772 Hints.emitRemarkWithHints();
9773 return false;
9774 }
9775
9777 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
9778 "early exit is not enabled",
9779 "UncountableEarlyExitLoopsDisabled", ORE, L);
9780 return false;
9781 }
9782
9783 if (!LVL.getPotentiallyFaultingLoads().empty()) {
9784 reportVectorizationFailure("Auto-vectorization of loops with potentially "
9785 "faulting load is not supported",
9786 "PotentiallyFaultingLoadsNotSupported", ORE, L);
9787 return false;
9788 }
9789
9790 // Entrance to the VPlan-native vectorization path. Outer loops are processed
9791 // here. They may require CFG and instruction level transformations before
9792 // even evaluating whether vectorization is profitable. Since we cannot modify
9793 // the incoming IR, we need to build VPlan upfront in the vectorization
9794 // pipeline.
9795 if (!L->isInnermost())
9796 return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
9797 ORE, GetBFI, OptForSize, Hints,
9798 Requirements);
9799
9800 assert(L->isInnermost() && "Inner loop expected.");
9801
9802 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
9803 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
9804
9805 // If an override option has been passed in for interleaved accesses, use it.
9806 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
9807 UseInterleaved = EnableInterleavedMemAccesses;
9808
9809 // Analyze interleaved memory accesses.
9810 if (UseInterleaved)
9812
9813 if (LVL.hasUncountableEarlyExit()) {
9814 BasicBlock *LoopLatch = L->getLoopLatch();
9815 if (IAI.requiresScalarEpilogue() ||
9817 [LoopLatch](BasicBlock *BB) { return BB != LoopLatch; })) {
9818 reportVectorizationFailure("Auto-vectorization of early exit loops "
9819 "requiring a scalar epilogue is unsupported",
9820 "UncountableEarlyExitUnsupported", ORE, L);
9821 return false;
9822 }
9823 }
9824
9825 // Check the function attributes and profiles to find out if this function
9826 // should be optimized for size.
9828 getScalarEpilogueLowering(F, L, Hints, OptForSize, TTI, TLI, LVL, &IAI);
9829
9830 // Check the loop for a trip count threshold: vectorize loops with a tiny trip
9831 // count by optimizing for size, to minimize overheads.
9832 auto ExpectedTC = getSmallBestKnownTC(PSE, L);
9833 if (ExpectedTC && ExpectedTC->isFixed() &&
9834 ExpectedTC->getFixedValue() < TinyTripCountVectorThreshold) {
9835 LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
9836 << "This loop is worth vectorizing only if no scalar "
9837 << "iteration overheads are incurred.");
9839 LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
9840 else {
9841 LLVM_DEBUG(dbgs() << "\n");
9842 // Predicate tail-folded loops are efficient even when the loop
9843 // iteration count is low. However, setting the epilogue policy to
9844 // `CM_ScalarEpilogueNotAllowedLowTripLoop` prevents vectorizing loops
9845 // with runtime checks. It's more effective to let
9846 // `isOutsideLoopWorkProfitable` determine if vectorization is
9847 // beneficial for the loop.
9850 }
9851 }
9852
9853 // Check the function attributes to see if implicit floats or vectors are
9854 // allowed.
9855 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9857 "Can't vectorize when the NoImplicitFloat attribute is used",
9858 "loop not vectorized due to NoImplicitFloat attribute",
9859 "NoImplicitFloat", ORE, L);
9860 Hints.emitRemarkWithHints();
9861 return false;
9862 }
9863
9864 // Check if the target supports potentially unsafe FP vectorization.
9865 // FIXME: Add a check for the type of safety issue (denormal, signaling)
9866 // for the target we're vectorizing for, to make sure none of the
9867 // additional fp-math flags can help.
9868 if (Hints.isPotentiallyUnsafe() &&
9869 TTI->isFPVectorizationPotentiallyUnsafe()) {
9871 "Potentially unsafe FP op prevents vectorization",
9872 "loop not vectorized due to unsafe FP support.",
9873 "UnsafeFP", ORE, L);
9874 Hints.emitRemarkWithHints();
9875 return false;
9876 }
9877
9878 bool AllowOrderedReductions;
9879 // If the flag is set, use that instead and override the TTI behaviour.
9880 if (ForceOrderedReductions.getNumOccurrences() > 0)
9881 AllowOrderedReductions = ForceOrderedReductions;
9882 else
9883 AllowOrderedReductions = TTI->enableOrderedReductions();
9884 if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
9885 ORE->emit([&]() {
9886 auto *ExactFPMathInst = Requirements.getExactFPInst();
9887 return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
9888 ExactFPMathInst->getDebugLoc(),
9889 ExactFPMathInst->getParent())
9890 << "loop not vectorized: cannot prove it is safe to reorder "
9891 "floating-point operations";
9892 });
9893 LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
9894 "reorder floating-point operations\n");
9895 Hints.emitRemarkWithHints();
9896 return false;
9897 }
9898
9899 // Use the cost model.
9900 LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
9901 GetBFI, F, &Hints, IAI, OptForSize);
9902 // Use the planner for vectorization.
9903 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, &LVL, CM, IAI, PSE, Hints,
9904 ORE);
9905
9906 // Get user vectorization factor and interleave count.
9907 ElementCount UserVF = Hints.getWidth();
9908 unsigned UserIC = Hints.getInterleave();
9909 if (UserIC > 1 && !LVL.isSafeForAnyVectorWidth())
9910 UserIC = 1;
9911
9912 // Plan how to best vectorize.
9913 LVP.plan(UserVF, UserIC);
9915 unsigned IC = 1;
9916
9917 if (ORE->allowExtraAnalysis(LV_NAME))
9919
9920 GeneratedRTChecks Checks(PSE, DT, LI, TTI, CM.CostKind);
9921 if (LVP.hasPlanWithVF(VF.Width)) {
9922 // Select the interleave count.
9923 IC = LVP.selectInterleaveCount(LVP.getPlanFor(VF.Width), VF.Width, VF.Cost);
9924
9925 unsigned SelectedIC = std::max(IC, UserIC);
9926 // Optimistically generate runtime checks if they are needed. Drop them if
9927 // they turn out to not be profitable.
9928 if (VF.Width.isVector() || SelectedIC > 1) {
9929 Checks.create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC,
9930 *ORE);
9931
9932 // Bail out early if either the SCEV or memory runtime checks are known to
9933 // fail. In that case, the vector loop would never execute.
9934 using namespace llvm::PatternMatch;
9935 if (Checks.getSCEVChecks().first &&
9936 match(Checks.getSCEVChecks().first, m_One()))
9937 return false;
9938 if (Checks.getMemRuntimeChecks().first &&
9939 match(Checks.getMemRuntimeChecks().first, m_One()))
9940 return false;
9941 }
9942
9943 // Check if it is profitable to vectorize with runtime checks.
9944 bool ForceVectorization =
9946 VPCostContext CostCtx(CM.TTI, *CM.TLI, LVP.getPlanFor(VF.Width), CM,
9947 CM.CostKind, CM.PSE, L);
9948 if (!ForceVectorization &&
9949 !isOutsideLoopWorkProfitable(Checks, VF, L, PSE, CostCtx,
9950 LVP.getPlanFor(VF.Width), SEL,
9951 CM.getVScaleForTuning())) {
9952 ORE->emit([&]() {
9954 DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
9955 L->getHeader())
9956 << "loop not vectorized: cannot prove it is safe to reorder "
9957 "memory operations";
9958 });
9959 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
9960 Hints.emitRemarkWithHints();
9961 return false;
9962 }
9963 }
9964
9965 // Identify the diagnostic messages that should be produced.
9966 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
9967 bool VectorizeLoop = true, InterleaveLoop = true;
9968 if (VF.Width.isScalar()) {
9969 LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
9970 VecDiagMsg = {
9971 "VectorizationNotBeneficial",
9972 "the cost-model indicates that vectorization is not beneficial"};
9973 VectorizeLoop = false;
9974 }
9975
9976 if (UserIC == 1 && Hints.getInterleave() > 1) {
9978 "UserIC should only be ignored due to unsafe dependencies");
9979 LLVM_DEBUG(dbgs() << "LV: Ignoring user-specified interleave count.\n");
9980 IntDiagMsg = {"InterleavingUnsafe",
9981 "Ignoring user-specified interleave count due to possibly "
9982 "unsafe dependencies in the loop."};
9983 InterleaveLoop = false;
9984 } else if (!LVP.hasPlanWithVF(VF.Width) && UserIC > 1) {
9985 // Tell the user interleaving was avoided up-front, despite being explicitly
9986 // requested.
9987 LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
9988 "interleaving should be avoided up front\n");
9989 IntDiagMsg = {"InterleavingAvoided",
9990 "Ignoring UserIC, because interleaving was avoided up front"};
9991 InterleaveLoop = false;
9992 } else if (IC == 1 && UserIC <= 1) {
9993 // Tell the user interleaving is not beneficial.
9994 LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
9995 IntDiagMsg = {
9996 "InterleavingNotBeneficial",
9997 "the cost-model indicates that interleaving is not beneficial"};
9998 InterleaveLoop = false;
9999 if (UserIC == 1) {
10000 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10001 IntDiagMsg.second +=
10002 " and is explicitly disabled or interleave count is set to 1";
10003 }
10004 } else if (IC > 1 && UserIC == 1) {
10005 // Tell the user interleaving is beneficial, but it explicitly disabled.
10006 LLVM_DEBUG(dbgs() << "LV: Interleaving is beneficial but is explicitly "
10007 "disabled.\n");
10008 IntDiagMsg = {"InterleavingBeneficialButDisabled",
10009 "the cost-model indicates that interleaving is beneficial "
10010 "but is explicitly disabled or interleave count is set to 1"};
10011 InterleaveLoop = false;
10012 }
10013
10014 // If there is a histogram in the loop, do not just interleave without
10015 // vectorizing. The order of operations will be incorrect without the
10016 // histogram intrinsics, which are only used for recipes with VF > 1.
10017 if (!VectorizeLoop && InterleaveLoop && LVL.hasHistograms()) {
10018 LLVM_DEBUG(dbgs() << "LV: Not interleaving without vectorization due "
10019 << "to histogram operations.\n");
10020 IntDiagMsg = {
10021 "HistogramPreventsScalarInterleaving",
10022 "Unable to interleave without vectorization due to constraints on "
10023 "the order of histogram operations"};
10024 InterleaveLoop = false;
10025 }
10026
10027 // Override IC if user provided an interleave count.
10028 IC = UserIC > 0 ? UserIC : IC;
10029
10030 // FIXME: Enable interleaving for FindLast reductions.
10031 if (any_of(LVL.getReductionVars().values(), [](auto &RdxDesc) {
10032 return RecurrenceDescriptor::isFindLastRecurrenceKind(
10033 RdxDesc.getRecurrenceKind());
10034 })) {
10035 LLVM_DEBUG(dbgs() << "LV: Not interleaving due to FindLast reduction.\n");
10036 IntDiagMsg = {"FindLastPreventsScalarInterleaving",
10037 "Unable to interleave due to FindLast reduction."};
10038 InterleaveLoop = false;
10039 IC = 1;
10040 }
10041
10042 // Emit diagnostic messages, if any.
10043 const char *VAPassName = Hints.vectorizeAnalysisPassName();
10044 if (!VectorizeLoop && !InterleaveLoop) {
10045 // Do not vectorize or interleaving the loop.
10046 ORE->emit([&]() {
10047 return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10048 L->getStartLoc(), L->getHeader())
10049 << VecDiagMsg.second;
10050 });
10051 ORE->emit([&]() {
10052 return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10053 L->getStartLoc(), L->getHeader())
10054 << IntDiagMsg.second;
10055 });
10056 return false;
10057 }
10058
10059 if (!VectorizeLoop && InterleaveLoop) {
10060 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10061 ORE->emit([&]() {
10062 return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10063 L->getStartLoc(), L->getHeader())
10064 << VecDiagMsg.second;
10065 });
10066 } else if (VectorizeLoop && !InterleaveLoop) {
10067 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10068 << ") in " << L->getLocStr() << '\n');
10069 ORE->emit([&]() {
10070 return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10071 L->getStartLoc(), L->getHeader())
10072 << IntDiagMsg.second;
10073 });
10074 } else if (VectorizeLoop && InterleaveLoop) {
10075 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10076 << ") in " << L->getLocStr() << '\n');
10077 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10078 }
10079
10080 // Report the vectorization decision.
10081 if (VF.Width.isScalar()) {
10082 using namespace ore;
10083 assert(IC > 1);
10084 ORE->emit([&]() {
10085 return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10086 L->getHeader())
10087 << "interleaved loop (interleaved count: "
10088 << NV("InterleaveCount", IC) << ")";
10089 });
10090 } else {
10091 // Report the vectorization decision.
10092 reportVectorization(ORE, L, VF, IC);
10093 }
10094 if (ORE->allowExtraAnalysis(LV_NAME))
10096
10097 // If we decided that it is *legal* to interleave or vectorize the loop, then
10098 // do it.
10099
10100 VPlan &BestPlan = LVP.getPlanFor(VF.Width);
10101 // Consider vectorizing the epilogue too if it's profitable.
10102 VectorizationFactor EpilogueVF =
10104 if (EpilogueVF.Width.isVector()) {
10105 std::unique_ptr<VPlan> BestMainPlan(BestPlan.duplicate());
10106
10107 // The first pass vectorizes the main loop and creates a scalar epilogue
10108 // to be vectorized by executing the plan (potentially with a different
10109 // factor) again shortly afterwards.
10110 VPlan &BestEpiPlan = LVP.getPlanFor(EpilogueVF.Width);
10111 BestEpiPlan.getMiddleBlock()->setName("vec.epilog.middle.block");
10112 BestEpiPlan.getVectorPreheader()->setName("vec.epilog.ph");
10113 preparePlanForMainVectorLoop(*BestMainPlan, BestEpiPlan);
10114 EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1,
10115 BestEpiPlan);
10116 EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TTI, AC, EPI, &CM,
10117 Checks, *BestMainPlan);
10118 auto ExpandedSCEVs = LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF,
10119 *BestMainPlan, MainILV, DT, false);
10120 ++LoopsVectorized;
10121
10122 // Second pass vectorizes the epilogue and adjusts the control flow
10123 // edges from the first pass.
10124 EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TTI, AC, EPI, &CM,
10125 Checks, BestEpiPlan);
10127 BestEpiPlan, L, ExpandedSCEVs, EPI, CM, *PSE.getSE());
10128 LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV, DT,
10129 true);
10130 connectEpilogueVectorLoop(BestEpiPlan, L, EPI, DT, LVL, ExpandedSCEVs,
10131 Checks, InstsToMove);
10132 ++LoopsEpilogueVectorized;
10133 } else {
10134 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, IC, &CM, Checks,
10135 BestPlan);
10136 // TODO: Move to general VPlan pipeline once epilogue loops are also
10137 // supported.
10140 IC, PSE);
10141 LVP.addMinimumIterationCheck(BestPlan, VF.Width, IC,
10143
10144 LVP.executePlan(VF.Width, IC, BestPlan, LB, DT, false);
10145 ++LoopsVectorized;
10146 }
10147
10148 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
10149 "DT not preserved correctly");
10150 assert(!verifyFunction(*F, &dbgs()));
10151
10152 return true;
10153}
10154
10156
10157 // Don't attempt if
10158 // 1. the target claims to have no vector registers, and
10159 // 2. interleaving won't help ILP.
10160 //
10161 // The second condition is necessary because, even if the target has no
10162 // vector registers, loop vectorization may still enable scalar
10163 // interleaving.
10164 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10165 TTI->getMaxInterleaveFactor(ElementCount::getFixed(1)) < 2)
10166 return LoopVectorizeResult(false, false);
10167
10168 bool Changed = false, CFGChanged = false;
10169
10170 // The vectorizer requires loops to be in simplified form.
10171 // Since simplification may add new inner loops, it has to run before the
10172 // legality and profitability checks. This means running the loop vectorizer
10173 // will simplify all loops, regardless of whether anything end up being
10174 // vectorized.
10175 for (const auto &L : *LI)
10176 Changed |= CFGChanged |=
10177 simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10178
10179 // Build up a worklist of inner-loops to vectorize. This is necessary as
10180 // the act of vectorizing or partially unrolling a loop creates new loops
10181 // and can invalidate iterators across the loops.
10182 SmallVector<Loop *, 8> Worklist;
10183
10184 for (Loop *L : *LI)
10185 collectSupportedLoops(*L, LI, ORE, Worklist);
10186
10187 LoopsAnalyzed += Worklist.size();
10188
10189 // Now walk the identified inner loops.
10190 while (!Worklist.empty()) {
10191 Loop *L = Worklist.pop_back_val();
10192
10193 // For the inner loops we actually process, form LCSSA to simplify the
10194 // transform.
10195 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10196
10197 Changed |= CFGChanged |= processLoop(L);
10198
10199 if (Changed) {
10200 LAIs->clear();
10201
10202#ifndef NDEBUG
10203 if (VerifySCEV)
10204 SE->verify();
10205#endif
10206 }
10207 }
10208
10209 // Process each loop nest in the function.
10210 return LoopVectorizeResult(Changed, CFGChanged);
10211}
10212
10215 LI = &AM.getResult<LoopAnalysis>(F);
10216 // There are no loops in the function. Return before computing other
10217 // expensive analyses.
10218 if (LI->empty())
10219 return PreservedAnalyses::all();
10228 AA = &AM.getResult<AAManager>(F);
10229
10230 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10231 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10232 GetBFI = [&AM, &F]() -> BlockFrequencyInfo & {
10234 };
10235 LoopVectorizeResult Result = runImpl(F);
10236 if (!Result.MadeAnyChange)
10237 return PreservedAnalyses::all();
10239
10240 if (isAssignmentTrackingEnabled(*F.getParent())) {
10241 for (auto &BB : F)
10243 }
10244
10245 PA.preserve<LoopAnalysis>();
10249
10250 if (Result.MadeCFGChange) {
10251 // Making CFG changes likely means a loop got vectorized. Indicate that
10252 // extra simplification passes should be run.
10253 // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10254 // be run if runtime checks have been added.
10257 } else {
10259 }
10260 return PA;
10261}
10262
10264 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10265 static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10266 OS, MapClassName2PassName);
10267
10268 OS << '<';
10269 OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10270 OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10271 OS << '>';
10272}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static unsigned getIntrinsicID(const SDNode *N)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
AMDGPU Lower Kernel Arguments
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
@ PostInc
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, TargetLibraryInfo &TLI)
Definition CostModel.cpp:74
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
#define _
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 Constant * getTrue(Type *Ty)
For a boolean type or a vector of boolean type, return true or a vector with every element true.
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:81
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 cl::opt< bool > WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true), cl::desc("Widen the loop induction variables, if possible, so " "overflow checks won't reject flattening"))
static const char * VerboseDebug
#define LV_NAME
This file defines the LoopVectorizationLegality class.
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 Type * maybeVectorizeType(Type *Ty, ElementCount VF)
static ElementCount determineVPlanVF(const TargetTransformInfo &TTI, LoopVectorizationCostModel &CM)
static ElementCount getSmallConstantTripCount(ScalarEvolution *SE, const Loop *L)
A version of ScalarEvolution::getSmallConstantTripCount that returns an ElementCount to include loops...
static cl::opt< unsigned > VectorizeMemoryCheckThreshold("vectorize-memory-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum allowed number of runtime memory checks"))
static void preparePlanForMainVectorLoop(VPlan &MainPlan, VPlan &EpiPlan)
Prepare MainPlan for vectorizing the main vector loop during epilogue vectorization.
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 void debugVectorizationMessage(const StringRef Prefix, const StringRef DebugMsg, Instruction *I)
Write a DebugMsg about vectorization to the debug output stream.
static cl::opt< bool > EnableCondStoresVectorization("enable-cond-stores-vec", cl::init(true), cl::Hidden, cl::desc("Enable if predication of stores during vectorization."))
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 Value * emitTransformedIndex(IRBuilderBase &B, Value *Index, Value *StartValue, Value *Step, InductionDescriptor::InductionKind InductionKind, const BinaryOperator *InductionBinOp)
Compute the transformed value of Index at offset StartValue using step StepValue.
static DebugLoc getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or its operands.
static Value * createInductionAdditionalBypassValues(PHINode *OrigPhi, const InductionDescriptor &II, IRBuilder<> &BypassBuilder, const SCEV2ValueTy &ExpandedSCEVs, Value *MainVectorTripCount, Instruction *OldInduction)
static void fixReductionScalarResumeWhenVectorizingEpilog(VPPhi *EpiResumePhiR, PHINode &EpiResumePhi, BasicBlock *BypassBlock)
static Value * getStartValueFromReductionResult(VPInstruction *RdxResult)
static cl::opt< bool > ForceTargetSupportsScalableVectors("force-target-supports-scalable-vectors", cl::init(false), cl::Hidden, cl::desc("Pretend that scalable vectors are supported, even if the target does " "not support them. This flag should only be used for testing."))
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
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 bool processLoopInVPlanNativePath(Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, LoopVectorizationLegality *LVL, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, std::function< BlockFrequencyInfo &()> GetBFI, bool OptForSize, LoopVectorizeHints &Hints, LoopVectorizationRequirements &Requirements)
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."))
static unsigned estimateElementCount(ElementCount VF, std::optional< unsigned > VScale)
This function attempts to return a value that represents the ElementCount at runtime.
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 cl::opt< bool > UseWiderVFIfCallVariantsPresent("vectorizer-maximize-bandwidth-for-vector-calls", cl::init(true), cl::Hidden, cl::desc("Try wider VFs if they enable the use of vector variants"))
static std::optional< unsigned > getMaxVScale(const Function &F, const TargetTransformInfo &TTI)
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 void connectEpilogueVectorLoop(VPlan &EpiPlan, Loop *L, EpilogueLoopVectorizationInfo &EPI, DominatorTree *DT, LoopVectorizationLegality &LVL, DenseMap< const SCEV *, Value * > &ExpandedSCEVs, GeneratedRTChecks &Checks, ArrayRef< Instruction * > InstsToMove)
Connect the epilogue vector loop generated for EpiPlan to the main vector.
static bool planContainsAdditionalSimplifications(VPlan &Plan, VPCostContext &CostCtx, Loop *TheLoop, ElementCount VF)
Return true if the original loop \ TheLoop contains any instructions that do not have corresponding r...
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::DataAndControlFlowWithoutRuntimeCheck, "data-and-control-without-rt-check", "Similar to data-and-control, but remove the runtime check"), clEnumValN(TailFoldingStyle::DataWithEVL, "data-with-evl", "Use predicated EVL instructions for tail folding. If EVL " "is unsupported, fallback to data-without-lane-mask.")))
static ScalarEpilogueLowering getScalarEpilogueLowering(Function *F, Loop *L, LoopVectorizeHints &Hints, bool OptForSize, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, LoopVectorizationLegality &LVL, InterleavedAccessInfo *IAI)
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 cl::opt< bool > PreferInLoopReductions("prefer-inloop-reductions", cl::init(false), cl::Hidden, cl::desc("Prefer in-loop vector reductions, " "overriding the targets preference."))
static SmallVector< Instruction * > preparePlanForEpilogueVectorLoop(VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationCostModel &CM, ScalarEvolution &SE)
Prepare Plan for vectorizing the epilogue loop.
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
static cl::opt< bool > EnableLoadStoreRuntimeInterleave("enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, cl::desc("Enable runtime interleaving until load/store ports are saturated"))
static cl::opt< bool > VPlanBuildStressTest("vplan-build-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 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 std::optional< ElementCount > getSmallBestKnownTC(PredicatedScalarEvolution &PSE, Loop *L, bool CanUseConstantMax=true)
Returns "best known" trip count, which is either a valid positive trip count or std::nullopt when an ...
static Value * getExpandedStep(const InductionDescriptor &ID, const SCEV2ValueTy &ExpandedSCEVs)
Return the expanded step for ID using ExpandedSCEVs to look up SCEV expansion results.
static bool useActiveLaneMask(TailFoldingStyle Style)
static bool hasReplicatorRegion(VPlan &Plan)
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 cl::opt< PreferPredicateTy::Option > PreferPredicateOverEpilogue("prefer-predicate-over-epilogue", cl::init(PreferPredicateTy::ScalarEpilogue), cl::Hidden, cl::desc("Tail-folding and predication preferences over creating a scalar " "epilogue loop."), cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue, "scalar-epilogue", "Don't tail-predicate loops, create scalar epilogue"), clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue, "predicate-else-scalar-epilogue", "prefer tail-folding, create scalar epilogue if tail " "folding fails."), clEnumValN(PreferPredicateTy::PredicateOrDontVectorize, "predicate-dont-vectorize", "prefers tail-folding, don't attempt vectorization if " "tail-folding fails.")))
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< 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 VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
static cl::opt< cl::boolOrDefault > ForceSafeDivisor("force-widen-divrem-via-safe-divisor", cl::Hidden, cl::desc("Override cost based safe divisor widening for div/rem instructions"))
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,...
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)
static 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 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.
static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks, VectorizationFactor &VF, Loop *L, PredicatedScalarEvolution &PSE, VPCostContext &CostCtx, VPlan &Plan, ScalarEpilogueLowering SEL, std::optional< unsigned > VScale)
This function determines whether or not it's still profitable to vectorize the loop given the extra w...
static void fixScalarResumeValuesFromBypass(BasicBlock *BypassBlock, Loop *L, VPlan &BestEpiPlan, LoopVectorizationLegality &LVL, const SCEV2ValueTy &ExpandedSCEVs, Value *MainVectorTripCount)
static cl::opt< bool > MaximizeBandwidth("vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden, cl::desc("Maximize bandwidth when selecting vectorization factor which " "will be determined by the smallest type in loop."))
static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I, DebugLoc DL={})
Create an analysis remark that explains why vectorization failed.
#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.
#define T
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 BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore, Value *FlagsOp)
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore, Value *FlagsOp)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
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={})
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:114
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
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.
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:
static const char PassName[]
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
A manager for alias analyses.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1549
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1521
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
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:539
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
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 const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
BinaryOps getOpcode() const
Definition InstrTypes.h:374
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional or Unconditional Branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
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...
Value * getArgOperand(unsigned i) const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
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.
Definition InstrTypes.h:982
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:789
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
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:123
static DebugLoc getTemporary()
Definition DebugLoc.h:160
static DebugLoc getUnknown()
Definition DebugLoc.h:161
An analysis that produces DemandedBits for a function.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:256
iterator end()
Definition DenseMap.h:81
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:169
void insert_range(Range &&R)
Inserts range of 'std::pair<KeyT, ValueT>' values into the map.
Definition DenseMap.h:294
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
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:164
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 introduceCheckBlockInVPlan(BasicBlock *CheckIRBB)
Introduces a new VPIRBasicBlock for CheckIRBB to Plan between the vector preheader and its predecesso...
BasicBlock * emitIterationCountCheck(BasicBlock *VectorPH, BasicBlock *Bypass, bool ForEpilogue)
Emits an iteration count bypass check once for the main loop (when ForEpilogue is false) and once for...
Value * createIterationCountCheck(BasicBlock *VectorPH, ElementCount VF, unsigned UF) const
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)
BasicBlock * createVectorizedLoopSkeleton() final
Implements the interface for creating a vectorized skeleton using the main loop strategy (i....
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:22
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:209
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:765
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
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
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:345
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2762
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...
InductionKind
This enum represents the kinds of inductions that we support.
@ IK_NoInduction
Not an induction variable.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
InnerLoopAndEpilogueVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, 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...
Value * TripCount
Trip count of the original loop.
const TargetTransformInfo * TTI
Target Transform Info.
LoopVectorizationCostModel * Cost
The profitablity analysis.
Value * getTripCount() const
Returns the original loop trip count.
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 setTripCount(Value *TC)
Used to set the trip count after ILV's construction and after the preheader block has been executed.
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.
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
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:318
LLVM_ABI APInt getMask() const
For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
Definition Type.cpp:342
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
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.
Drive the analysis of memory accesses in the loop.
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
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.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
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.
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.
SmallPtrSet< Type *, 16 > ElementTypesInLoop
All element types found in the loop.
bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment, unsigned AddressSpace) const
Returns true if the target machine supports masked load operation for the given DataType and kind of ...
void collectElementTypesForWidening()
Collect all element types in the loop for which widening is needed.
bool canVectorizeReductions(ElementCount VF) const
Returns true if the target machine supports all of the reduction variables found for the given VF.
bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment, unsigned AddressSpace) const
Returns true if the target machine supports masked store operation for the given DataType and kind of...
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.
void collectInLoopReductions()
Split reductions into those that happen in the loop, and those that happen outside.
BlockFrequencyInfo & getBFI()
Returns the BlockFrequencyInfo for the function if cached, otherwise fetches it via GetBFI.
std::pair< unsigned, unsigned > getSmallestAndWidestTypes()
bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be uniform after vectorization.
void collectNonVectorizedAndSetWideningDecisions(ElementCount VF)
Collect values that will not be widened, including Uniforms, Scalars, and Instructions to Scalarize f...
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
const LoopVectorizeHints * Hints
Loop Vectorize Hint.
std::optional< unsigned > getMaxSafeElements() const
Return maximum safe number of elements to be processed per vector iteration, which do not prevent sto...
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.
DemandedBits * DB
Demanded bits analysis.
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 OptForSize
Whether this loop should be optimized for size based on function attribute or profile information.
bool useMaxBandwidth(TargetTransformInfo::RegisterKind RegKind)
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)
bool shouldConsiderRegPressureForVF(ElementCount VF)
Loop * TheLoop
The loop that we evaluate.
TTI::TargetCostKind CostKind
The kind of cost that we are calculating.
TailFoldingStyle getTailFoldingStyle(bool IVUpdateMayOverflow=true) const
Returns the TailFoldingStyle that is best for the current loop.
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 setVectorizedCallDecision(ElementCount VF)
A call may be vectorized in different ways depending on whether we have vectorized variants available...
void invalidateCostModelingDecisions()
Invalidates decisions already taken by the cost model.
bool isAccessInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleaved access group.
bool selectUserVectorizationFactor(ElementCount UserVF)
Setup cost-based decisions for user vectorization factor.
std::optional< unsigned > getVScaleForTuning() const
Return the value of vscale used for tuning the cost model.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
bool preferPredicatedLoop() const
Returns true if tail-folding is preferred over a scalar epilogue.
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 isInLoopReduction(PHINode *Phi) const
Returns true if the Phi is part of an inloop reduction.
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 ...
const MapVector< Instruction *, uint64_t > & getMinimalBitwidths() const
CallWideningDecision getCallWideningDecision(CallInst *CI, ElementCount VF) const
bool isLegalGatherOrScatter(Value *V, ElementCount VF)
Returns true if the target machine can represent V as a masked gather or scatter operation.
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 usePredicatedReductionSelect() const
Returns true if the predicated reduction select should be used to set the incoming value for the redu...
bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const
Returns true if the instructions in this block requires predication for any reason,...
void setCallWideningDecision(CallInst *CI, ElementCount VF, InstWidening Kind, Function *Variant, Intrinsic::ID IID, std::optional< unsigned > MaskPos, InstructionCost Cost)
void setTailFoldingStyles(bool IsScalableVF, unsigned UserIC)
Selects and saves TailFoldingStyle for 2 options - if IV update may overflow or not.
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.
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...
bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const
Returns true if we should use strict in-order reductions for the given RdxDesc.
bool isDivRemScalarWithPredication(InstructionCost ScalarCost, InstructionCost SafeDivisorCost) const
Given costs for both strategies, return true if the scalar predication lowering should be used for di...
std::function< BlockFrequencyInfo &()> GetBFI
A function to lazily fetch BlockFrequencyInfo.
LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, std::function< BlockFrequencyInfo &()> GetBFI, const Function *F, const LoopVectorizeHints *Hints, InterleavedAccessInfo &IAI, bool OptForSize)
InstructionCost expectedCost(ElementCount VF)
Returns the expected execution cost.
void setCostBasedWideningDecision(ElementCount VF)
Memory access instruction may be vectorized in more than one way.
InstWidening getWideningDecision(Instruction *I, ElementCount VF) const
Return the cost model decision for the given instruction I and vector width VF.
FixedScalableVFPair MaxPermissibleVFWithoutMaxBW
The highest VF possible for this loop, without using MaxBandwidth.
const SmallPtrSetImpl< PHINode * > & getInLoopReductions() const
Returns the set of in-loop reduction PHIs.
bool isScalarEpilogueAllowed() const
Returns true if a scalar epilogue is not allowed due to optsize or a loop hint annotation.
InstructionCost getWideningCost(Instruction *I, ElementCount VF)
Return the vectorization cost for the given instruction I and vector width VF.
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.
const SmallPtrSetImpl< const Instruction * > & getPotentiallyFaultingLoads() const
Returns potentially faulting loads.
bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
PHINode * getPrimaryInduction()
Returns the primary induction variable.
const SmallVector< BasicBlock *, 4 > & getCountableExitingBlocks() const
Returns all exiting blocks with a countable exit, i.e.
const InductionList & getInductionVars() const
Returns the induction variables found in the loop.
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
bool hasUncountableEarlyExit() const
Returns true if the loop has exactly one uncountable early exit, 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.
VectorizationFactor selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC)
VPlan & getPlanFor(ElementCount VF) const
Return the VPlan for VF.
Definition VPlan.cpp:1584
VectorizationFactor planInVPlanNativePath(ElementCount UserVF)
Use the VPlan-native path to plan how to best vectorize, return the best VF and its cost.
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:1635
void buildVPlans(ElementCount MinVF, ElementCount MaxVF)
Build VPlans for power-of-2 VF's between MinVF and MaxVF inclusive, according to the information gath...
Definition VPlan.cpp:1568
VectorizationFactor computeBestVF()
Compute and return the most profitable vectorization factor.
DenseMap< const SCEV *, Value * > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, InnerLoopVectorizer &LB, DominatorTree *DT, bool VectorizingEpilogue)
Generate the IR code for the vectorized loop captured in VPlan BestPlan according to the best selecte...
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:1549
void printPlans(raw_ostream &O)
Definition VPlan.cpp:1713
void plan(ElementCount UserVF, unsigned UserIC)
Build VPlans for the specified UserVF and UserIC if they are non-zero or all applicable candidate VFs...
void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount) const
Create a check to Plan to see if the vector loop should be executed based on its trip count.
bool hasPlanWithVF(ElementCount VF) const
Look through the existing plans and return true if we have one with vectorization factor VF.
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.
bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
bool allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
void emitRemarkWithHints() const
Dumps all the hint information.
const char * vectorizeAnalysisPassName() const
If hints are provided that force vectorization, use the AlwaysPrint pass name to force the frontend t...
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition LoopInfo.cpp:67
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:632
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:61
Metadata node.
Definition Metadata.h:1078
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:124
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.
op_range incoming_values()
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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.
static bool isFMulAddIntrinsic(Instruction *I)
Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
FastMathFlags getFastMathFlags() const
static bool isSignedRecurrenceKind(RecurKind Kind)
Returns true if recurrece kind is a signed redux kind.
Instruction * getLoopExitInstr() const
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
Type * getRecurrenceType() const
Returns the type of the recurrence.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
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,...
unsigned getMinWidthCastToRecurrenceTypeInBits() const
Returns the minimum width used by the recurrence in bits.
LLVM_ABI SmallVector< Instruction *, 4 > getReductionOpChain(PHINode *Phi, Loop *L) const
Attempts to find a chain of operations from Phi to LoopExitInst that can be treated as a set of reduc...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindLastIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
bool isSigned() const
Returns true if all source operands of the recurrence are SExtInsts.
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
static LLVM_ABI bool isFloatingPointRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating point kind.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
Value * getSentinelValue() const
Returns the sentinel value for FindFirstIV & FindLastIV recurrences to replace the start value.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
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.
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(const SCEV *LHS, const SCEV *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)
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 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 * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &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, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:176
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:262
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI std::optional< unsigned > getVScaleForTuning() const
LLVM_ABI InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}) const
Estimate the overhead of scalarizing an instruction.
LLVM_ABI bool supportsEfficientVectorElementLoadStore() const
If target has efficient vector element load/store instructions, it can return true here so that inser...
LLVM_ABI bool prefersVectorizedAddressing() const
Return true if target doesn't mind addresses in vectors.
LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const
LLVM_ABI bool preferFixedOverScalableIfEqualCost(bool IsEpilogue) const
LLVM_ABI InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, bool UseMaskForCond=false, bool UseMaskForGaps=false) const
LLVM_ABI InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, ArrayRef< int > Mask={}, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) const
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
LLVM_ABI bool isElementTypeLegalForScalableVector(Type *Ty) const
LLVM_ABI ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
LLVM_ABI InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const
LLVM_ABI bool supportsScalableVectors() const
@ TCC_Free
Expected to fold away in lowering.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const
LLVM_ABI InstructionCost getOperandsScalarizationOverhead(ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing operands with the given types.
@ 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.
LLVM_ABI InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ None
The cast is not used with a load/store of any kind.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class implements a switch-like dispatch statement for a value of 'T' using dyn_cast functionalit...
Definition TypeSwitch.h:89
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
Definition TypeSwitch.h:98
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
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:74
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4009
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4036
iterator end()
Definition VPlan.h:4046
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4044
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4097
InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override
Return the cost of this VPBasicBlock.
Definition VPlan.cpp:775
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:228
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:635
bool empty() const
Definition VPlan.h:4055
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:81
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:198
void setName(const Twine &newName)
Definition VPlan.h:166
size_t getNumSuccessors() const
Definition VPlan.h:219
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
Definition VPlan.h:322
size_t getNumPredecessors() const
Definition VPlan.h:220
VPlan * getPlan()
Definition VPlan.cpp:173
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:178
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:209
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:198
static auto blocksOnly(const T &Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:221
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition VPlanUtils.h:242
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:173
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition VPlanUtils.h:199
VPlan-based builder utility analogous to IRBuilder.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL, const Twine &Name="")
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
Canonical scalar induction phi of the vector loop.
Definition VPlan.h:3595
VPIRValue * getStartValue() const
Returns the start value of the canonical induction.
Definition VPlan.h:3616
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:477
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:450
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPIRValue * getStartValue() const
Definition VPlan.h:3810
VPValue * getStepValue() const
Definition VPlan.h:3811
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2075
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2118
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2107
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:1830
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4162
Class to record and manage LLVM IR flags.
Definition VPlan.h:608
Helper to manage IR metadata for recipes.
Definition VPlan.h:1032
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1086
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1133
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1191
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1182
unsigned getOpcode() const
Definition VPlan.h:1246
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:2733
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
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:1427
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:387
VPBasicBlock * getParent()
Definition VPlan.h:408
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:479
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.
VPValue * getBlockInMask(VPBasicBlock *VPBB) const
Returns the entry mask for block VPBB or null if the mask is all-true.
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...
VPValue * getVPValueOrAddLiveIn(Value *V)
VPRecipeBase * tryToCreatePartialReduction(VPInstruction *Reduction, unsigned ScaleFactor)
Create and return a partial reduction recipe for a reduction instruction along with binary operation ...
std::optional< unsigned > getScalingForReduction(const Instruction *ExitInst)
void collectScaledReductions(VFRange &Range)
Find all possible partial reductions in the loop and track all of those that are valid so recipes can...
VPReplicateRecipe * handleReplication(VPInstruction *VPI, VFRange &Range)
Build a VPReplicationRecipe for VPI.
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2525
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2528
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2522
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:2826
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4197
const VPBlockBase * getEntry() const
Definition VPlan.h:4233
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the region.
Definition VPlan.h:4295
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:2982
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition VPlan.h:531
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:594
An analysis for type-inference for VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:253
operand_range operands()
Definition VPlanValue.h:321
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:297
unsigned getNumOperands() const
Definition VPlanValue.h:291
operand_iterator op_begin()
Definition VPlanValue.h:317
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:292
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:47
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:133
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:119
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:74
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1385
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:1389
user_range users()
Definition VPlanValue.h:128
A recipe to compute a pointer to the last element of each part of a widened memory access for widened...
Definition VPlan.h:1934
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1625
A recipe for handling GEP instructions.
Definition VPlan.h:1871
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2221
A recipe for widened phis.
Definition VPlan.h:2357
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1577
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4327
bool hasVF(ElementCount VF) const
Definition VPlan.h:4524
VPBasicBlock * getEntry()
Definition VPlan.h:4416
VPValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4506
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4474
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:4531
bool hasUF(unsigned UF) const
Definition VPlan.h:4542
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4464
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4503
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:4566
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1022
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:4680
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1004
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:4488
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4441
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4455
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:916
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4460
VPBasicBlock * getVectorPreheader()
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4421
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:1164
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:166
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
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 const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
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:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS.multiplyCoefficientBy(X) will result in a value whos...
Definition TypeSize.h:269
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
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS.multiplyCoefficientBy(X) will result in a value whose quantity matches ou...
Definition TypeSize.h:277
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 LeafTy multiplyCoefficientBy(ScalarTy RHS) const
Definition TypeSize.h:256
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.
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.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
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
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Definition DwarfDebug.h:189
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
OneOps_match< OpTy, Instruction::Freeze > m_Freeze(const OpTy &Op)
Matches FreezeInst.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
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)
bind_ty< 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.
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.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
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.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
class_match< const SCEVVScale > m_SCEVVScale()
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
specificloop_ty m_SpecificLoop(const Loop *L)
cst_pred_ty< is_specific_signed_cst > m_scev_SpecificSInt(int64_t V)
Match an SCEV constant with a plain signed integer (sign-extended value will be matched)
SCEVAffineAddRec_match< Op0_t, Op1_t, class_match< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
bind_ty< 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)
class_match< const SCEV > m_SCEV()
AllRecipe_match< Instruction::Select, Op0_t, Op1_t, Op2_t > m_Select(const Op0_t &Op0, const Op1_t &Op1, const Op2_t &Op2)
match_combine_or< AllRecipe_match< Instruction::ZExt, Op0_t >, AllRecipe_match< Instruction::SExt, Op0_t > > m_ZExtOrSExt(const Op0_t &Op0)
VPInstruction_match< VPInstruction::ExtractLastLane, Op0_t > m_ExtractLastLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore 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.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
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,...
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
VPIRFlags getFlagsFromIndDesc(const InductionDescriptor &ID)
Extracts and returns NoWrap and FastMath flags from the induction binop in ID.
Definition VPlanUtils.h:93
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
unsigned getVFScaleFactor(VPRecipeBase *R)
Get the VF scaling factor applied to the recipe's output, if the recipe has one.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:532
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:829
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:
static void reportVectorization(OptimizationRemarkEmitter *ORE, Loop *TheLoop, VectorizationFactor VF, unsigned IC)
Report successful vectorization of the loop.
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:1737
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.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1667
LLVM_ABI_FOR_TEST bool verifyVPlanIsValid(const VPlan &Plan, bool VerifyLate=false)
Verify invariants for general VPlans.
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2544
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:2198
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:632
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
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:216
LLVM_ABI bool VerifySCEV
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:243
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...
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:337
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
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:1744
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
Definition CFG.h:149
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:1634
LLVM_ABI_FOR_TEST cl::opt< bool > EnableWideActiveLaneMask
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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:1751
LLVM_ABI cl::opt< bool > EnableLoopVectorization
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:421
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
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.
LLVM_ABI void llvm_unreachable_internal(const char *msg=nullptr, const char *file=nullptr, unsigned line=0)
This function calls abort(), and prints the optional message to stderr.
bool canConstantBeExtended(const APInt *C, Type *NarrowType, TTI::PartialReductionExtendKind ExtKind)
Check if a constant CI can be safely treated as having been extended from a narrower type with the gi...
Definition VPlan.cpp:1726
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:1835
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
cl::opt< unsigned > ForceTargetInstructionCost
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
TargetTransformInfo TTI
static void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I=nullptr, DebugLoc DL={})
Reports an informative message: print Msg for debugging purposes as well as an optimization remark.
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Or
Bitwise or logical OR of integers.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
LLVM_ABI void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
DWARFExpression::Operation Op
ScalarEpilogueLowering
@ CM_ScalarEpilogueNotAllowedLowTripLoop
@ CM_ScalarEpilogueNotNeededUsePredicate
@ CM_ScalarEpilogueNotAllowedOptSize
@ CM_ScalarEpilogueAllowed
@ CM_ScalarEpilogueNotAllowedUsePredicate
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 >
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1407
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
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:1770
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:1945
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:119
@ DataAndControlFlowWithoutRuntimeCheck
Use predicate to control both data and control flow, but modify the trip count so that a runtime over...
@ 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:592
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:330
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:77
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI MapVector< Instruction *, uint64_t > computeMinimumValueSizes(ArrayRef< BasicBlock * > Blocks, DemandedBits &DB, const TargetTransformInfo *TTI=nullptr)
Compute a map of integer instructions to their minimum legal type size.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:466
LLVM_ABI cl::opt< bool > EnableLoopInterleaving
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
An information struct used to provide DenseMap with the various necessary components for a given valu...
Encapsulate information regarding vectorization of a loop and its epilogue.
EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF, ElementCount EVF, unsigned EUF, VPlan &EpiloguePlan)
A class that represents two vectorization factors (initialized with 0 by default).
static FixedScalableVFPair getNone()
This holds details about a histogram operation – a load -> update -> store sequence where each lane i...
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
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:70
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2446
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.
std::optional< unsigned > getParamIndexForOptionalMask() const
Instruction Set Architecture.
Encapsulates information needed to describe a parameter.
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.
unsigned getPredBlockCostDivisor(BasicBlock *BB) const
LoopVectorizationCostModel & CM
bool isLegacyUniformAfterVectorization(Instruction *I, ElementCount VF) const
Return true if I is considered uniform-after-vectorization in the legacy cost model for VF.
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...
TargetTransformInfo::TargetCostKind CostKind
SmallPtrSet< Instruction *, 8 > SkipCostComputation
A struct that represents some properties of the register usage of a loop.
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
static LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlan &Plan, const TargetLibraryInfo &TLI)
Replaces the VPInstructions in Plan with corresponding widen recipes.
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 bool handleMultiUseReductions(VPlan &Plan)
Try to legalize reductions with multiple in-loop uses.
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, DebugLoc IVDL, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static void optimizeInductionExitUsers(VPlan &Plan, DenseMap< VPValue *, VPValue * > &EndValues, PredicatedScalarEvolution &PSE)
If there's a single exit block, optimize its phi recipes that use exiting IV values by feeding them p...
static void materializeBackedgeTakenCount(VPlan &Plan, VPBasicBlock *VectorPH)
Materialize the backedge-taken count to be computed explicitly using VPInstructions.
static LLVM_ABI_FOR_TEST void handleEarlyExits(VPlan &Plan, bool HasUncountableExit)
Update Plan to account for all early exits.
static void canonicalizeEVLLoops(VPlan &Plan)
Transform EVL loops to use variable-length stepping after region dissolution.
static void createInLoopReductionRecipes(VPlan &Plan, const DenseMap< VPBasicBlock *, VPValue * > &BlockMaskCache, const DenseSet< BasicBlock * > &BlocksNeedingPredication, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
static void dropPoisonGeneratingRecipes(VPlan &Plan, const std::function< bool(BasicBlock *)> &BlockNeedsPredication)
Drop poison flags from recipes that may generate a poison value that is used after vectorization,...
static void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, bool CheckNeededWithTailFolding, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE)
static void createInterleaveGroups(VPlan &Plan, const SmallPtrSetImpl< const InterleaveGroup< Instruction > * > &InterleaveGroups, VPRecipeBuilder &RecipeBuilder, const bool &ScalarEpilogueAllowed)
static bool runPass(bool(*Transform)(VPlan &, ArgsTy...), VPlan &Plan, typename std::remove_reference< ArgsTy >::type &...Args)
Helper to run a VPlan transform Transform on VPlan, forwarding extra arguments to the transform.
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 bool handleFindLastReductions(VPlan &Plan)
Check if Plan contains any FindLast reductions.
static void narrowInterleaveGroups(VPlan &Plan, ElementCount VF, TypeSize VectorRegWidth)
Try to convert a plan with interleave groups with VF elements to a plan with the interleave groups re...
static void unrollByUF(VPlan &Plan, unsigned UF)
Explicitly unroll Plan by UF.
static DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand VPExpandSCEVRecipes in Plan's entry block.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static void expandBranchOnTwoConds(VPlan &Plan)
Expand BranchOnTwoConds instructions into explicit CFG with BranchOnCond instructions.
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 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 addExitUsersForFirstOrderRecurrences(VPlan &Plan, VFRange &Range)
Handle users in the exit block for first order reductions in the original exit block.
static void createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, const MapVector< PHINode *, InductionDescriptor > &Inductions, const MapVector< PHINode *, RecurrenceDescriptor > &Reductions, const SmallPtrSetImpl< const PHINode * > &FixedOrderRecurrences, const SmallPtrSetImpl< PHINode * > &InLoopReductions, bool AllowReordering)
Replace VPPhi recipes in Plan's header with corresponding VPHeaderPHIRecipe subclasses for inductions...
static DenseMap< VPBasicBlock *, VPValue * > introduceMasksAndLinearize(VPlan &Plan, bool FoldTail)
Predicate and linearize the control-flow in the only loop region of Plan.
static void addExplicitVectorLength(VPlan &Plan, const std::optional< unsigned > &MaxEVLSafeElements)
Add a VPEVLBasedIVPHIRecipe and related recipes to Plan and replaces all uses except the canonical IV...
static void optimizeEVLMasks(VPlan &Plan)
Optimize recipes which use an EVL-based header mask to VP intrinsics, for example:
static void replaceSymbolicStrides(VPlan &Plan, PredicatedScalarEvolution &PSE, const DenseMap< Value *, const SCEV * > &StridesMap)
Replace symbolic strides from StridesMap in Plan with constants when possible.
static bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum or FMinNum reductions.
static void removeBranchOnConst(VPlan &Plan)
Remove BranchOnCond recipes with true or false conditions together with removing dead edges to their ...
static LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
Wrap runtime check block CheckBlock in a VPIRBB and Cond in a VPValue and connect the block to Plan,...
static void materializeVectorTripCount(VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking, bool RequiresScalarEpilogue)
Materialize vector trip count computations to a set of VPInstructions.
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 void replicateByVF(VPlan &Plan, ElementCount VF)
Replace each replicating VPReplicateRecipe and VPInstruction outside of any replicate region in Plan ...
static void clearReductionWrapFlags(VPlan &Plan)
Clear NSW/NUW flags from reduction instructions if necessary.
static void cse(VPlan &Plan)
Perform common-subexpression-elimination on Plan.
static void addActiveLaneMask(VPlan &Plan, bool UseActiveLaneMaskForControlFlow, bool DataAndControlFlowWithoutRuntimeCheck)
Replace (ICMP_ULE, wide canonical IV, backedge-taken-count) checks with an (active-lane-mask recipe,...
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 bool adjustFixedOrderRecurrences(VPlan &Plan, VPBuilder &Builder)
Try to have all users of fixed-order recurrences appear after the recipe defining their previous valu...
static void optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Optimize Plan based on BestVF and BestUF.
static void materializeVFAndVFxUF(VPlan &Plan, VPBasicBlock *VectorPH, ElementCount VF)
Materialize VF and VFxUF to be computed explicitly using VPInstructions.
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, Value *TripCount, 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 updateScalarResumePhis(VPlan &Plan, DenseMap< VPValue *, VPValue * > &IVEndValues)
Update the resume phis in the scalar preheader after creating wide recipes for first-order recurrence...
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan, bool RequiresScalarEpilogueCheck, bool TailFolded)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class.
InstructionCost Cost
Cost of the loop with that width.
ElementCount MinProfitableTripCount
The minimum trip count required to make vectorization profitable, e.g.
ElementCount Width
Vector width with best cost.
InstructionCost ScalarCost
Cost of the scalar loop.
static VectorizationFactor Disabled()
Width 1 means no vectorization, cost 0 means uncomputed cost.
static LLVM_ABI bool HoistRuntimeChecks